instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public final CurrencyConversionContext getInvoiceCurrencyConversionCtx()
{
if (invoiceCurrencyConversionCtx == null)
{
final I_C_Invoice invoice = getC_Invoice();
Check.assumeNotNull(invoice, "invoice not null");
final ICurrencyBL currencyConversionBL = Services.get(ICurrencyBL.class);
invoiceCurrencyConversionCtx = currencyConversionBL.createCurrencyConversionContext(
LocalDateAndOrgId.ofTimestamp(invoice.getDateAcct(), OrgId.ofRepoId(invoice.getAD_Org_ID()), services::getTimeZone),
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(invoice.getAD_Client_ID()));
}
return invoiceCurrencyConversionCtx;
}
public final CurrencyConversionContext getPaymentCurrencyConversionCtx()
{
if (paymentCurrencyConversionCtx == null)
{
final I_C_Payment payment = getC_Payment();
final I_C_CashLine cashLine = getC_CashLine();
if (payment != null)
{
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
paymentCurrencyConversionCtx = paymentBL.extractCurrencyConversionContext(payment);
}
else if (cashLine != null)
{
final ICurrencyBL currencyConversionBL = Services.get(ICurrencyBL.class);
final I_C_Cash cashJournal = cashLine.getC_Cash();
paymentCurrencyConversionCtx = currencyConversionBL.createCurrencyConversionContext(
InstantAndOrgId.ofTimestamp(cashJournal.getDateAcct(), OrgId.ofRepoId(cashLine.getAD_Org_ID())),
null, // C_ConversionType_ID - default
ClientId.ofRepoId(cashLine.getAD_Client_ID()));
}
else
{
throw new IllegalStateException("Allocation line does not have a payment or a cash line set: " + this);
}
}
return paymentCurrencyConversionCtx;
}
public final boolean hasPaymentDocument()
{
return getC_Payment() != null || getC_CashLine() != null;
}
public final OrgId getPaymentOrgId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return OrgId.ofRepoId(payment.getAD_Org_ID());
}
|
final I_C_CashLine cashLine = getC_CashLine();
if (cashLine != null)
{
return OrgId.ofRepoId(cashLine.getAD_Org_ID());
}
return getOrgId();
}
public final BPartnerId getPaymentBPartnerId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return BPartnerId.ofRepoId(payment.getC_BPartner_ID());
}
return getBPartnerId();
}
@Nullable
public final BPartnerLocationId getPaymentBPartnerLocationId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return BPartnerLocationId.ofRepoIdOrNull(payment.getC_BPartner_ID(), payment.getC_BPartner_Location_ID());
}
return getBPartnerLocationId();
}
public boolean isPaymentReceipt()
{
Check.assumeNotNull(paymentReceipt, "payment document exists");
return paymentReceipt;
}
} // DocLine_Allocation
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Allocation.java
| 1
|
请完成以下Java代码
|
public final class QuickInputPath
{
public static final QuickInputPath of(final String windowIdStr //
, final String documentIdStr //
, final String tabIdStr //
, final String quickInputIdStr //
)
{
final DocumentPath rootDocumentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), documentIdStr);
final DetailId detailId = DetailId.fromJson(tabIdStr);
final DocumentId quickInputId = DocumentId.of(quickInputIdStr);
return new QuickInputPath(rootDocumentPath, detailId, quickInputId);
}
private final DocumentPath rootDocumentPath;
private final DetailId detailId;
private final DocumentId quickInputId;
private transient Integer _hashCode;
private QuickInputPath(final DocumentPath rootDocumentPath, final DetailId detailId, final DocumentId quickInputId)
{
this.rootDocumentPath = rootDocumentPath;
this.detailId = detailId;
this.quickInputId = quickInputId;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(rootDocumentPath)
.add("detailId", detailId)
.add("quickInputId", quickInputId)
.toString();
}
@Override
public int hashCode()
{
if (_hashCode == null)
{
_hashCode = Objects.hash(rootDocumentPath, detailId, quickInputId);
}
return _hashCode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
|
else if (obj instanceof QuickInputPath)
{
final QuickInputPath other = (QuickInputPath)obj;
return Objects.equals(rootDocumentPath, other.rootDocumentPath)
&& Objects.equals(detailId, other.detailId)
&& Objects.equals(quickInputId, other.quickInputId);
}
else
{
return false;
}
}
public DocumentPath getRootDocumentPath()
{
return rootDocumentPath;
}
public DetailId getDetailId()
{
return detailId;
}
public DocumentId getQuickInputId()
{
return quickInputId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputPath.java
| 1
|
请完成以下Java代码
|
public int getAD_ImpFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ImpFormat_ID);
}
@Override
public void setC_DataImport_ID (final int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, C_DataImport_ID);
}
@Override
public int getC_DataImport_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DataImport_ID);
}
/**
* DataImport_ConfigType AD_Reference_ID=541535
* Reference name: C_DataImport_ConfigType
*/
public static final int DATAIMPORT_CONFIGTYPE_AD_Reference_ID=541535;
/** Standard = S */
public static final String DATAIMPORT_CONFIGTYPE_Standard = "S";
/** Bank Statement Import = BSI */
public static final String DATAIMPORT_CONFIGTYPE_BankStatementImport = "BSI";
@Override
public void setDataImport_ConfigType (final java.lang.String DataImport_ConfigType)
{
set_Value (COLUMNNAME_DataImport_ConfigType, DataImport_ConfigType);
}
|
@Override
public java.lang.String getDataImport_ConfigType()
{
return get_ValueAsString(COLUMNNAME_DataImport_ConfigType);
}
@Override
public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDesc(String desc) {
this.desc = desc;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Long getBignumber() {
return bignumber;
}
public void setBignumber(Long bignumber) {
|
this.bignumber = bignumber;
}
public Integer getTest1() {
return test1;
}
public void setTest1(Integer test1) {
this.test1 = test1;
}
public Integer getTest2() {
return test2;
}
public void setTest2(Integer test2) {
this.test2 = test2;
}
}
|
repos\SpringBoot-Learning-master\1.x\Chapter2-1-1\src\main\java\com\didispace\service\BlogProperties.java
| 2
|
请完成以下Java代码
|
public ResponseEntity<JsonResponseUpsert> putProductPriceByPriceListVersionIdentifier(
@ApiParam(required = true, value = PRICE_LIST_VERSION_IDENTIFIER)
@PathVariable("priceListVersionIdentifier") //
@NonNull final String priceListVersionIdentifier,
@RequestBody @NonNull final JsonRequestProductPriceUpsert request)
{
final JsonResponseUpsert responseUpsert = productPriceRestService.upsertProductPrices(priceListVersionIdentifier, request);
return ResponseEntity.ok().body(responseUpsert);
}
@ApiOperation("Create or update product price to the latest price list version of the given price list identifier")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully processed the request"),
@ApiResponse(code = 401, message = "You are not authorized to consume this resource"),
@ApiResponse(code = 403, message = "Accessing a related resource is forbidden"),
@ApiResponse(code = 422, message = "The request body could not be processed")
})
@PutMapping("/priceList/{priceListIdentifier}/productPrices")
public ResponseEntity<JsonResponseUpsert> putProductPriceByPriceListIdentifier(
@ApiParam(required = true, value = PRICE_LIST_IDENTIFIER)
@PathVariable("priceListIdentifier")
@NonNull final String priceListIdentifier,
@RequestBody @NonNull final JsonRequestProductPriceUpsert request)
{
final JsonResponseUpsert responseUpsert = productPriceRestService.upsertProductPricesForPriceList(priceListIdentifier, request);
return ResponseEntity.ok().body(responseUpsert);
}
@ApiOperation("Search product prices by a given `JsonProductPriceSearchRequest`")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully processed the request"),
@ApiResponse(code = 401, message = "You are not authorized to consume this resource"),
|
@ApiResponse(code = 403, message = "Accessing a related resource is forbidden"),
@ApiResponse(code = 422, message = "The request body could not be processed")
})
@PostMapping("{orgCode}/product/search")
public ResponseEntity<?> productPriceSearch(
@PathVariable("orgCode") @Nullable final String orgCode,
@RequestBody @NonNull final JsonRequestProductPriceQuery request)
{
try
{
final JsonResponseProductPriceQuery result = productPriceRestService.productPriceSearch(request, orgCode);
return ResponseEntity.ok(result);
}
catch (final Exception ex)
{
return ResponseEntity
.status(HttpStatus.UNPROCESSABLE_ENTITY)
.body(ex.getMessage());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\PricesRestController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
OrderLineItems orderLineItems = (OrderLineItems)o;
return Objects.equals(this.itemId, orderLineItems.itemId) &&
Objects.equals(this.lineItemId, orderLineItems.lineItemId);
}
@Override
public int hashCode()
{
return Objects.hash(itemId, lineItemId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class OrderLineItems {\n");
sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n");
|
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderLineItems.java
| 2
|
请完成以下Java代码
|
public void setReferenceNo (java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
/** Get Referenznummer.
@return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/
@Override
public java.lang.String getReferenceNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo);
}
/** Set Bewegungs-Betrag.
@param TrxAmt
Betrag einer Transaktion
*/
@Override
public void setTrxAmt (java.math.BigDecimal TrxAmt)
{
|
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
/** Get Bewegungs-Betrag.
@return Betrag einer Transaktion
*/
@Override
public java.math.BigDecimal getTrxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TrxAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_BankStatementLine_Ref.java
| 1
|
请完成以下Java代码
|
public class ArchiveSetDataRequest
{
private int sessionId;
// NOTE: this goes to AD_Archive.AD_Table_ID=754, Record_ID=this.adArchiveId
private int adArchiveId;
private byte[] data;
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + adArchiveId;
result = prime * result + Arrays.hashCode(data);
result = prime * result + sessionId;
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final ArchiveSetDataRequest other = (ArchiveSetDataRequest)obj;
if (adArchiveId != other.adArchiveId)
{
return false;
}
if (!Arrays.equals(data, other.data))
|
{
return false;
}
if (sessionId != other.sessionId)
{
return false;
}
return true;
}
public int getSessionId()
{
return sessionId;
}
public void setSessionId(final int sessionId)
{
this.sessionId = sessionId;
}
public int getAdArchiveId()
{
return adArchiveId;
}
public void setAdArchiveId(final int adArchiveId)
{
this.adArchiveId = adArchiveId;
}
public byte[] getData()
{
return data;
}
public void setData(final byte[] data)
{
this.data = data;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive.api\src\main\java\de\metas\document\archive\esb\api\ArchiveSetDataRequest.java
| 1
|
请完成以下Java代码
|
public Criteria andTypeIn(List<Integer> values) {
addCriterion("type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<Integer> values) {
addCriterion("type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(Integer value1, Integer value2) {
addCriterion("type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(Integer value1, Integer value2) {
addCriterion("type not between", value1, value2, "type");
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\PmsCommentReplayExample.java
| 1
|
请完成以下Java代码
|
public void setLine_PrintColor_ID (int Line_PrintColor_ID)
{
if (Line_PrintColor_ID < 1)
set_Value (COLUMNNAME_Line_PrintColor_ID, null);
else
set_Value (COLUMNNAME_Line_PrintColor_ID, Integer.valueOf(Line_PrintColor_ID));
}
/** Get Line Color.
@return Table line color
*/
public int getLine_PrintColor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line_PrintColor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Line Stroke.
@param LineStroke
Width of the Line Stroke
*/
public void setLineStroke (BigDecimal LineStroke)
{
set_Value (COLUMNNAME_LineStroke, LineStroke);
}
/** Get Line Stroke.
@return Width of the Line Stroke
*/
public BigDecimal getLineStroke ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineStroke);
if (bd == null)
return Env.ZERO;
return bd;
}
/** LineStrokeType AD_Reference_ID=312 */
public static final int LINESTROKETYPE_AD_Reference_ID=312;
/** Solid Line = S */
public static final String LINESTROKETYPE_SolidLine = "S";
/** Dashed Line = D */
public static final String LINESTROKETYPE_DashedLine = "D";
/** Dotted Line = d */
public static final String LINESTROKETYPE_DottedLine = "d";
/** Dash-Dotted Line = 2 */
public static final String LINESTROKETYPE_Dash_DottedLine = "2";
/** Set Line Stroke Type.
@param LineStrokeType
|
Type of the Line Stroke
*/
public void setLineStrokeType (String LineStrokeType)
{
set_Value (COLUMNNAME_LineStrokeType, LineStrokeType);
}
/** Get Line Stroke Type.
@return Type of the Line Stroke
*/
public String getLineStrokeType ()
{
return (String)get_Value(COLUMNNAME_LineStrokeType);
}
/** 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_AD_PrintTableFormat.java
| 1
|
请完成以下Java代码
|
public class ConfigurationPropertiesReportEndpointWebExtension {
private final ConfigurationPropertiesReportEndpoint delegate;
private final Show showValues;
private final Set<String> roles;
public ConfigurationPropertiesReportEndpointWebExtension(ConfigurationPropertiesReportEndpoint delegate,
Show showValues, Set<String> roles) {
this.delegate = delegate;
this.showValues = showValues;
this.roles = roles;
}
@ReadOperation
public ConfigurationPropertiesDescriptor configurationProperties(SecurityContext securityContext) {
boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles);
return this.delegate.getConfigurationProperties(showUnsanitized);
}
|
@ReadOperation
public WebEndpointResponse<ConfigurationPropertiesDescriptor> configurationPropertiesWithPrefix(
SecurityContext securityContext, @Selector String prefix) {
boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles);
ConfigurationPropertiesDescriptor configurationProperties = this.delegate.getConfigurationProperties(prefix,
showUnsanitized);
boolean foundMatchingBeans = configurationProperties.getContexts()
.values()
.stream()
.anyMatch((context) -> !context.getBeans().isEmpty());
return (foundMatchingBeans) ? new WebEndpointResponse<>(configurationProperties, WebEndpointResponse.STATUS_OK)
: new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\context\properties\ConfigurationPropertiesReportEndpointWebExtension.java
| 1
|
请完成以下Java代码
|
protected I_M_ReceiptSchedule getM_ReceiptSchedule()
{
Check.assumeNotNull(_receiptSchedule, "receiptSchedule not null");
return _receiptSchedule;
}
@Override
public ReceiptScheduleAllocBuilder setM_ReceiptSchedule(@NonNull final I_M_ReceiptSchedule receiptSchedule)
{
this._receiptSchedule = receiptSchedule;
return this;
}
private I_M_InOutLine getM_InOutLine()
{
return _receiptLine;
}
@Override
public ReceiptScheduleAllocBuilder setM_InOutLine(@Nullable final I_M_InOutLine receiptLine)
{
this._receiptLine = receiptLine;
return this;
}
private StockQtyAndUOMQty getQtyToAllocate()
{
Check.assumeNotNull(_qtyToAllocate, "qtyToAllocate not null");
return _qtyToAllocate;
}
@Override
public ReceiptScheduleAllocBuilder setQtyToAllocate(@NonNull final StockQtyAndUOMQty qtyToAllocate)
{
this._qtyToAllocate = qtyToAllocate;
return this;
}
|
@Override
public ReceiptScheduleAllocBuilder setQtyWithIssues(@NonNull final StockQtyAndUOMQty qtyWithIssues)
{
this._qtyWithIssues = qtyWithIssues;
return this;
}
private StockQtyAndUOMQty getQtyWithIssues()
{
if (_qtyWithIssues == null)
{
return _qtyToAllocate.toZero();
}
return _qtyWithIssues;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleAllocBuilder.java
| 1
|
请完成以下Java代码
|
public void setFrom(@NonNull final I_C_Order from)
{
setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation());
}
@Override
public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
|
}
@Override
public OrderMainLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderMainLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
public void setLocationAndResetRenderedAddress(@Nullable final BPartnerLocationAndCaptureId from)
{
setC_BPartner_Location_ID(from != null ? from.getBPartnerLocationRepoId() : -1);
setC_BPartner_Location_Value_ID(from != null ? from.getLocationCaptureRepoId() : -1);
setBPartnerAddress(null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderMainLocationAdapter.java
| 1
|
请完成以下Java代码
|
public void setQtyDeliveredCatch (final @Nullable BigDecimal QtyDeliveredCatch)
{
set_Value (COLUMNNAME_QtyDeliveredCatch, QtyDeliveredCatch);
}
@Override
public BigDecimal getQtyDeliveredCatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredCatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
|
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_QtyPicked.java
| 1
|
请完成以下Java代码
|
public class ApiRequestMapper
{
@NonNull
public ApiRequest map(@NonNull final CachedBodyHttpServletRequest cachedBodyHttpServletRequest)
{
return ApiRequest.builder()
.body(getRequestBody(cachedBodyHttpServletRequest))
.fullPath(getFullPath(cachedBodyHttpServletRequest))
.headers(getHeaders(cachedBodyHttpServletRequest))
.httpMethod(cachedBodyHttpServletRequest.getMethod())
.remoteAddr(cachedBodyHttpServletRequest.getRemoteAddr())
.remoteHost(cachedBodyHttpServletRequest.getRemoteHost())
.requestURI(cachedBodyHttpServletRequest.getRequestURI())
.build();
}
@NonNull
public String getFullPath(@NonNull final HttpServletRequest requestWrapper)
{
String fullPath = requestWrapper.getRequestURL().toString();
if (requestWrapper.getQueryString() != null)
{
fullPath += "?" + requestWrapper.getQueryString();
}
return fullPath;
}
@NonNull
private ImmutableMultimap<String, String> getHeaders(@NonNull final HttpServletRequest request)
{
final ImmutableMultimap.Builder<String, String> requestHeaders = ImmutableMultimap.builder();
final Enumeration<String> allHeaderNames = request.getHeaderNames();
while (allHeaderNames != null && allHeaderNames.hasMoreElements())
{
final String currentHeaderName = allHeaderNames.nextElement();
requestHeaders.putAll(currentHeaderName, Collections.list(request.getHeaders(currentHeaderName)));
}
return requestHeaders.build();
}
@Nullable
private String getRequestBody(@NonNull final CachedBodyHttpServletRequest requestWrapper)
{
try
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
|
if (requestWrapper.getContentLength() <= 0)
{
return null;
}
final Object body = objectMapper.readValue(requestWrapper.getInputStream(), Object.class);
return toJson(body);
}
catch (final IOException e)
{
throw new AdempiereException("Failed to parse request body!", e);
}
}
@Nullable
private String toJson(@Nullable final Object obj)
{
if (obj == null)
{
return null;
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(obj);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Failed to parse object!", e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiRequestMapper.java
| 1
|
请完成以下Java代码
|
public class Payment {
private String type;
private String amount;
public Payment() {
}
public Payment(String type, String amount) {
this.type = type;
this.amount = amount;
}
public String getType() {
|
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
|
repos\tutorials-master\mapstruct-3\src\main\java\com\baeldung\entity\Payment.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getBusinessKey() {
return businessKey;
}
public Map<String, Object> getVariables() {
return variables;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLinkedProcessInstanceId() {
|
return linkedProcessInstanceId;
}
public void setLinkedProcessInstanceId(String linkedProcessInstanceId) {
this.linkedProcessInstanceId = linkedProcessInstanceId;
}
public String getLinkedProcessInstanceType() {
return linkedProcessInstanceType;
}
public void setLinkedProcessInstanceType(String linkedProcessInstanceType) {
this.linkedProcessInstanceType = linkedProcessInstanceType;
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\StartProcessPayload.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setTaxedAmount(BigDecimal value) {
this.taxedAmount = value;
}
/**
* The tax rate.
*
* @return
* possible object is
* {@link TaxRateType }
*
*/
public TaxRateType getTaxRate() {
return taxRate;
}
/**
* Sets the value of the taxRate property.
*
* @param value
* allowed object is
* {@link TaxRateType }
*
*/
public void setTaxRate(TaxRateType value) {
this.taxRate = value;
}
/**
* The tax amount. Calculated using: taxed amount x tax rate = tax amount.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
/**
* The tax amount in the domestic currency. The domestic currency != invoice currency.
*
* @return
* possible object is
* {@link DomesticAmountType }
*
*/
public DomesticAmountType getDomesticAmount() {
return domesticAmount;
}
/**
* Sets the value of the domesticAmount property.
*
|
* @param value
* allowed object is
* {@link DomesticAmountType }
*
*/
public void setDomesticAmount(DomesticAmountType value) {
this.domesticAmount = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemType.java
| 2
|
请完成以下Java代码
|
public Mono<Authentication> convert(PayloadExchange exchange) {
return Mono
.fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(),
AuthenticationPayloadExchangeConverter.COMPOSITE_METADATA_MIME_TYPE))
.flatMap((metadata) -> Mono.justOrEmpty(authentication(metadata)));
}
private @Nullable Authentication authentication(Map<String, Object> metadata) {
byte[] authenticationMetadata = (byte[]) metadata.get("authentication");
if (authenticationMetadata == null) {
return null;
}
ByteBuf rawAuthentication = ByteBufAllocator.DEFAULT.buffer();
try {
rawAuthentication.writeBytes(authenticationMetadata);
if (!AuthMetadataCodec.isWellKnownAuthType(rawAuthentication)) {
return null;
}
WellKnownAuthType wellKnownAuthType = AuthMetadataCodec.readWellKnownAuthType(rawAuthentication);
if (WellKnownAuthType.SIMPLE.equals(wellKnownAuthType)) {
return simple(rawAuthentication);
}
if (WellKnownAuthType.BEARER.equals(wellKnownAuthType)) {
return bearer(rawAuthentication);
}
throw new IllegalArgumentException("Unknown Mime Type " + wellKnownAuthType);
}
finally {
rawAuthentication.release();
}
}
|
private Authentication simple(ByteBuf rawAuthentication) {
ByteBuf rawUsername = AuthMetadataCodec.readUsername(rawAuthentication);
String username = rawUsername.toString(StandardCharsets.UTF_8);
ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication);
String password = rawPassword.toString(StandardCharsets.UTF_8);
return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
}
private Authentication bearer(ByteBuf rawAuthentication) {
char[] rawToken = AuthMetadataCodec.readBearerTokenAsCharArray(rawAuthentication);
String token = new String(rawToken);
return new BearerTokenAuthenticationToken(token);
}
private static MetadataExtractor createDefaultExtractor() {
DefaultMetadataExtractor result = new DefaultMetadataExtractor(new ByteArrayDecoder());
result.metadataToExtract(AUTHENTICATION_MIME_TYPE, byte[].class, "authentication");
return result;
}
}
|
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authentication\AuthenticationPayloadExchangeConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String profileDisplay(Model model, HttpServletRequest request) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.getUserByUsername(username);
if (user != null) {
model.addAttribute("userid", user.getId());
model.addAttribute("username", user.getUsername());
model.addAttribute("email", user.getEmail());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
} else {
model.addAttribute("msg", "User not found");
}
return "updateProfile";
}
//for Learning purpose of model
@GetMapping("/test")
public String Test(Model model)
{
System.out.println("test page");
model.addAttribute("author","jay gajera");
model.addAttribute("id",40);
List<String> friends = new ArrayList<String>();
model.addAttribute("f",friends);
friends.add("xyz");
friends.add("abc");
return "test";
}
|
// for learning purpose of model and view ( how data is pass to view)
@GetMapping("/test2")
public ModelAndView Test2()
{
System.out.println("test page");
//create modelandview object
ModelAndView mv=new ModelAndView();
mv.addObject("name","jay gajera 17");
mv.addObject("id",40);
mv.setViewName("test2");
List<Integer> list=new ArrayList<Integer>();
list.add(10);
list.add(25);
mv.addObject("marks",list);
return mv;
}
// @GetMapping("carts")
// public ModelAndView getCartDetail()
// {
// ModelAndView mv= new ModelAndView();
// List<Cart>carts = cartService.getCarts();
// }
}
|
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\controller\UserController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SpringAsyncExecutor springAsyncExecutor(TaskExecutor applicationTaskExecutor) {
return new SpringAsyncExecutor(applicationTaskExecutor, springRejectedJobsHandler());
}
@Bean
public SpringRejectedJobsHandler springRejectedJobsHandler() {
return new SpringCallerRunsRejectedJobsHandler();
}
protected Set<Class<?>> getCustomMybatisMapperClasses(List<String> customMyBatisMappers) {
Set<Class<?>> mybatisMappers = new HashSet<>();
for (String customMybatisMapperClassName : customMyBatisMappers) {
try {
Class customMybatisClass = Class.forName(customMybatisMapperClassName);
mybatisMappers.add(customMybatisClass);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class " + customMybatisMapperClassName + " has not been found.", e);
}
}
return mybatisMappers;
}
@Bean
public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) {
return super.springProcessEngineBean(configuration);
}
@Bean
@ConditionalOnMissingBean
@Override
public RuntimeService runtimeServiceBean(ProcessEngine processEngine) {
return super.runtimeServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public RepositoryService repositoryServiceBean(ProcessEngine processEngine) {
return super.repositoryServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public TaskService taskServiceBean(ProcessEngine processEngine) {
return super.taskServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public HistoryService historyServiceBean(ProcessEngine processEngine) {
|
return super.historyServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public ManagementService managementServiceBeanBean(ProcessEngine processEngine) {
return super.managementServiceBeanBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) {
return super.integrationContextManagerBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) {
return super.integrationContextServiceBean(processEngine);
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public HitPolicyEntry getHitPolicyEntry() {
return HIT_POLICY;
}
public DmnDecisionTableEvaluationEvent apply(DmnDecisionTableEvaluationEvent decisionTableEvaluationEvent) {
List<DmnEvaluatedDecisionRule> matchingRules = decisionTableEvaluationEvent.getMatchingRules();
if (!matchingRules.isEmpty()) {
if (allOutputsAreEqual(matchingRules)) {
DmnEvaluatedDecisionRule firstMatchingRule = matchingRules.get(0);
((DmnDecisionTableEvaluationEventImpl) decisionTableEvaluationEvent).setMatchingRules(Collections.singletonList(firstMatchingRule));
} else {
throw LOG.anyHitPolicyRequiresThatAllOutputsAreEqual(matchingRules);
}
}
return decisionTableEvaluationEvent;
}
protected boolean allOutputsAreEqual(List<DmnEvaluatedDecisionRule> matchingRules) {
Map<String, DmnEvaluatedOutput> firstOutputEntries = matchingRules.get(0).getOutputEntries();
if (firstOutputEntries == null) {
for (int i = 1; i < matchingRules.size(); i++) {
if (matchingRules.get(i).getOutputEntries() != null) {
|
return false;
}
}
} else {
for (int i = 1; i < matchingRules.size(); i++) {
if (!firstOutputEntries.equals(matchingRules.get(i).getOutputEntries())) {
return false;
}
}
}
return true;
}
@Override
public String toString() {
return "AnyHitPolicyHandler{}";
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\AnyHitPolicyHandler.java
| 1
|
请完成以下Java代码
|
public String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setSEPA_Export_ID (final int SEPA_Export_ID)
{
if (SEPA_Export_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, SEPA_Export_ID);
}
@Override
public int getSEPA_Export_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_ID);
}
@Override
public void setSEPA_Export_Line_ID (final int SEPA_Export_Line_ID)
{
if (SEPA_Export_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, SEPA_Export_Line_ID);
}
@Override
public int getSEPA_Export_Line_ID()
{
|
return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_ID);
}
@Override
public void setSEPA_Export_Line_Ref_ID (final int SEPA_Export_Line_Ref_ID)
{
if (SEPA_Export_Line_Ref_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, SEPA_Export_Line_Ref_ID);
}
@Override
public int getSEPA_Export_Line_Ref_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_Ref_ID);
}
@Override
public void setStructuredRemittanceInfo (final @Nullable String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
@Override
public String getStructuredRemittanceInfo()
{
return get_ValueAsString(COLUMNNAME_StructuredRemittanceInfo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line_Ref.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JmxManagedProcessApplication getValue() {
return this;
}
public void setProcessesXmls(List<ProcessesXml> processesXmls) {
this.processesXmls = processesXmls;
}
public List<ProcessesXml> getProcessesXmls() {
return processesXmls;
}
public void setDeploymentMap(Map<String, DeployedProcessArchive> processArchiveDeploymentMap) {
this.deploymentMap = processArchiveDeploymentMap;
}
public Map<String, DeployedProcessArchive> getProcessArchiveDeploymentMap() {
return deploymentMap;
}
public List<String> getDeploymentIds() {
List<String> deploymentIds = new ArrayList<String>();
for (DeployedProcessArchive registration : deploymentMap.values()) {
|
deploymentIds.addAll(registration.getAllDeploymentIds());
}
return deploymentIds;
}
public List<String> getDeploymentNames() {
return new ArrayList<String>(deploymentMap.keySet());
}
public ProcessApplicationInfoImpl getProcessApplicationInfo() {
return processApplicationInfo;
}
public ProcessApplicationReference getProcessApplicationReference() {
return processApplicationReference;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedProcessApplication.java
| 2
|
请完成以下Java代码
|
public void setCurrentTime(Date currentTime) {
Calendar time = null;
if (currentTime != null) {
time = new GregorianCalendar();
time.setTime(currentTime);
}
setCurrentCalendar(time);
}
@Override
public void setCurrentCalendar(Calendar currentTime) {
CURRENT_TIME = currentTime;
}
@Override
public void reset() {
CURRENT_TIME = null;
}
@Override
public Date getCurrentTime() {
return CURRENT_TIME == null ? new Date() : CURRENT_TIME.getTime();
}
|
@Override
public Calendar getCurrentCalendar() {
return CURRENT_TIME == null ? new GregorianCalendar() : (Calendar) CURRENT_TIME.clone();
}
@Override
public Calendar getCurrentCalendar(TimeZone timeZone) {
return TimeZoneUtil.convertToTimeZone(getCurrentCalendar(), timeZone);
}
@Override
public TimeZone getCurrentTimeZone() {
return getCurrentCalendar().getTimeZone();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\DefaultClockImpl.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractObjectArrayToJsonConverter implements ObjectArrayToJsonConverter {
protected static final String BEGIN_ARRAY = "[";
protected static final String EMPTY_STRING = "";
protected static final String END_ARRAY = "]";
protected static final String JSON_OBJECT_SEPARATOR = ", ";
private ObjectToJsonConverter converter = newObjectToJsonConverter();
// TODO configure via an SPI
private @NonNull ObjectToJsonConverter newObjectToJsonConverter() {
return new JSONFormatterPdxToJsonConverter();
}
/**
* Returns a reference to the configured {@link ObjectToJsonConverter} used to convert
* individual {@link Object Objects} into {@link String JSON}.
*
* @return a reference to the configured {@link ObjectToJsonConverter}; never {@literal null}.
* @see org.springframework.geode.data.json.converter.ObjectToJsonConverter
*/
protected @NonNull ObjectToJsonConverter getObjectToJsonConverter() {
return this.converter;
}
/**
* Converts the given {@link Iterable} of {@link Object Objects} into a {@link String JSON} array.
*
* @param iterable {@link Iterable} containing the {@link Object Objects} to convert into {@link String JSON};
* must not be {@literal null}.
* @return the {@link String JSON} generated from the given {@link Iterable} of {@link Object Objects};
* never {@literal null}.
* @throws IllegalArgumentException if {@link Iterable} is {@literal null}.
* @see #getObjectToJsonConverter()
* @see java.lang.Iterable
*/
@Override
public @NonNull String convert(@NonNull Iterable<?> iterable) {
Assert.notNull(iterable, "Iterable must not be null");
StringBuilder json = new StringBuilder(BEGIN_ARRAY);
|
ObjectToJsonConverter converter = getObjectToJsonConverter();
boolean addComma = false;
for (Object value : CollectionUtils.nullSafeIterable(iterable)) {
json.append(addComma ? JSON_OBJECT_SEPARATOR : EMPTY_STRING);
json.append(converter.convert(value));
addComma = true;
}
json.append(END_ARRAY);
return json.toString();
}
/**
* Converts the {@link Map#values() values} from the given {@link Map} into {@link String JSON}.
*
* @param <K> {@link Class} type of the {@link Map#keySet() keys}.
* @param <V> {@link Class} type of the {@link Map#values() values}.
* @param map {@link Map} containing the {@link Map#values() values} to convert into {@link String JSON}.
* @return {@link String JSON} generated from the {@link Map#values() values} in the given {@link Map}.
* @see #convert(Iterable)
* @see java.util.Map
*/
public @NonNull <K, V> String convert(@Nullable Map<K, V> map) {
return convert(CollectionUtils.nullSafeMap(map).values());
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\AbstractObjectArrayToJsonConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryRecipientExtensionType getDeliveryRecipientExtension() {
return deliveryRecipientExtension;
}
/**
* Sets the value of the deliveryRecipientExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryRecipientExtensionType }
*
*/
public void setDeliveryRecipientExtension(at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryRecipientExtensionType value) {
this.deliveryRecipientExtension = value;
}
/**
* Gets the value of the erpelDeliveryRecipientExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelDeliveryRecipientExtension() {
|
return erpelDeliveryRecipientExtension;
}
/**
* Sets the value of the erpelDeliveryRecipientExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelDeliveryRecipientExtension(CustomType value) {
this.erpelDeliveryRecipientExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\DeliveryRecipientExtensionType.java
| 2
|
请完成以下Java代码
|
private void setGroupNoToOrderLine(final I_C_OrderLine compensationLinePO)
{
if (compensationLinePO.getC_Order_CompensationGroup_ID() <= 0)
{
compensationLinePO.setC_Order_CompensationGroup_ID(groupId.getOrderCompensationGroupId());
}
else if (compensationLinePO.getC_Order_CompensationGroup_ID() != groupId.getOrderCompensationGroupId())
{
throw new AdempiereException("Order line has already another groupNo set: " + compensationLinePO)
.setParameter("expectedGroupId", groupId.getOrderCompensationGroupId())
.appendParametersToMessage();
}
}
private void setActivityToOrderLine(final I_C_OrderLine compensationLinePO)
{
compensationLinePO.setC_Activity_ID(ActivityId.toRepoId(activityId));
}
public I_C_OrderLine getOrderLineByIdIfPresent(final OrderLineId orderLineId)
{
return orderLinesById.get(orderLineId);
}
public void deleteAllNotIn(final Collection<OrderLineId> orderLineIdsToSkipDeleting)
{
if (!performDatabaseChanges)
{
return;
}
final List<I_C_OrderLine> orderLinesToDelete = orderLinesById.values()
.stream()
.filter(orderLine -> !orderLineIdsToSkipDeleting.contains(OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())))
.collect(ImmutableList.toImmutableList());
orderLinesToDelete.forEach(this::deleteOrderLineRecord);
}
private void deleteOrderLineRecord(final I_C_OrderLine orderLine)
|
{
ATTR_IsRepoUpdate.setValue(orderLine, Boolean.TRUE);
try
{
delete(orderLine);
}
finally
{
ATTR_IsRepoUpdate.reset(orderLine);
}
}
static boolean isRepositoryUpdate(final I_C_OrderLine orderLine)
{
return ATTR_IsRepoUpdate.isSet(orderLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderLinesStorage.java
| 1
|
请完成以下Java代码
|
public void setReportUri(String reportUri) {
try {
this.reportUri = new URI(reportUri);
updateHpkpHeaderValue();
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException(ex);
}
}
private void updateHpkpHeaderValue() {
String headerValue = "max-age=" + this.maxAgeInSeconds;
for (Map.Entry<String, String> pin : this.pins.entrySet()) {
headerValue += " ; pin-" + pin.getValue() + "=\"" + pin.getKey() + "\"";
}
if (this.reportUri != null) {
headerValue += " ; report-uri=\"" + this.reportUri.toString() + "\"";
}
if (this.includeSubDomains) {
|
headerValue += " ; includeSubDomains";
}
this.hpkpHeaderValue = headerValue;
}
private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\HpkpHeaderWriter.java
| 1
|
请完成以下Java代码
|
public int getM_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID);
}
@Override
public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID)
{
if (M_HU_PI_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID);
}
@Override
public int getM_HU_PI_Version_ID()
|
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Version.java
| 1
|
请完成以下Java代码
|
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Window getAD_Window() throws RuntimeException
{
return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name)
.getPO(getAD_Window_ID(), get_TrxName()); }
/** Set Window.
@param AD_Window_ID
Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Window.
@return Data entry or display window
*/
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Attribute.
@param Attribute Attribute */
public void setAttribute (String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
/** Get Attribute.
@return Attribute */
public String getAttribute ()
{
return (String)get_Value(COLUMNNAME_Attribute);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getAttribute());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Preference.java
| 1
|
请完成以下Java代码
|
public FactLine getSingleLineByAccountId(final AccountId accountId)
{
final MAccount account = services.getAccountById(accountId);
FactLine lineFound = null;
for (FactLine line : m_lines)
{
if (ElementValueId.equals(line.getAccountId(), account.getElementValueId()))
{
if (lineFound == null)
{
lineFound = line;
}
else
{
throw new AdempiereException("More than one fact line found for AccountId: " + accountId.getRepoId() + ": " + lineFound + ", " + line);
}
}
}
if (lineFound == null)
{
throw new AdempiereException("No fact line found for AccountId: " + accountId.getRepoId() + " in " + m_lines);
}
return lineFound;
}
public void save()
{
final FactTrxStrategy factTrxLinesStrategy = getFactTrxLinesStrategyEffective();
if (factTrxLinesStrategy != null)
{
factTrxLinesStrategy
.createFactTrxLines(m_lines)
.forEach(this::saveNew);
}
else
{
m_lines.forEach(this::saveNew);
}
}
private void saveNew(FactLine line) {services.saveNew(line);}
private void saveNew(final FactTrxLines factTrxLines)
|
{
//
// Case: 1 debit line, one or more credit lines
if (factTrxLines.getType() == FactTrxLinesType.Debit)
{
final FactLine drLine = factTrxLines.getDebitLine();
saveNew(drLine);
factTrxLines.forEachCreditLine(crLine -> {
crLine.setCounterpart_Fact_Acct_ID(drLine.getIdNotNull());
saveNew(crLine);
});
}
//
// Case: 1 credit line, one or more debit lines
else if (factTrxLines.getType() == FactTrxLinesType.Credit)
{
final FactLine crLine = factTrxLines.getCreditLine();
saveNew(crLine);
factTrxLines.forEachDebitLine(drLine -> {
drLine.setCounterpart_Fact_Acct_ID(crLine.getIdOrNull());
saveNew(drLine);
});
}
//
// Case: no debit lines, no credit lines
else if (factTrxLines.getType() == FactTrxLinesType.EmptyOrZero)
{
// nothing to do
}
else
{
throw new AdempiereException("Unknown type: " + factTrxLines.getType());
}
//
// also save the zero lines, if they are here
factTrxLines.forEachZeroLine(this::saveNew);
}
public void forEach(final Consumer<FactLine> consumer)
{
m_lines.forEach(consumer);
}
} // Fact
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Fact.java
| 1
|
请完成以下Java代码
|
static class ElasticsearchDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements ElasticsearchConnectionDetails {
private final ElasticsearchEnvironment environment;
private final List<Node> nodes;
ElasticsearchDockerComposeConnectionDetails(RunningService service) {
super(service);
this.environment = new ElasticsearchEnvironment(service.env());
this.nodes = List.of(new Node(service.host(), service.ports().get(ELASTICSEARCH_PORT), Protocol.HTTP,
getUsername(), getPassword()));
}
@Override
public String getUsername() {
|
return "elastic";
}
@Override
public @Nullable String getPassword() {
return this.environment.getPassword();
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\docker\compose\ElasticsearchDockerComposeConnectionDetailsFactory.java
| 1
|
请完成以下Java代码
|
public void setPeriodNo (int PeriodNo)
{
set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo));
}
/** Get Period No.
@return Unique Period Number
*/
public int getPeriodNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** PeriodType AD_Reference_ID=115 */
public static final int PERIODTYPE_AD_Reference_ID=115;
/** Standard Calendar Period = S */
public static final String PERIODTYPE_StandardCalendarPeriod = "S";
/** Adjustment Period = A */
public static final String PERIODTYPE_AdjustmentPeriod = "A";
/** Set Period Type.
@param PeriodType
Period Type
*/
public void setPeriodType (String PeriodType)
{
set_ValueNoCheck (COLUMNNAME_PeriodType, PeriodType);
}
/** Get Period Type.
@return Period Type
*/
public String getPeriodType ()
{
return (String)get_Value(COLUMNNAME_PeriodType);
}
/** Set Process Now.
@param Processing Process Now */
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 Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java
| 1
|
请完成以下Java代码
|
public LeaveRequestState nextState() {
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
return Escalated;
}
@Override
public String responsiblePerson() {
return "Employee";
}
},
Escalated {
@Override
public LeaveRequestState nextState() {
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
return Approved;
}
@Override
public String responsiblePerson() {
return "Team Leader";
}
},
Approved {
@Override
public LeaveRequestState nextState() {
|
System.out.println("Approving the Leave Request.");
return this;
}
@Override
public String responsiblePerson() {
return "Department Manager";
}
};
public abstract String responsiblePerson();
public abstract LeaveRequestState nextState();
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\enumstatemachine\LeaveRequestState.java
| 1
|
请完成以下Java代码
|
public void onCompleted() {
log.info("[{}] Stream was closed and completed successfully!", edgeKey);
}
};
}
@Override
public void disconnect(boolean onError) throws InterruptedException {
if (!onError) {
try {
if (inputStream != null) {
inputStream.onCompleted();
}
} catch (Exception e) {
log.error("Exception during onCompleted", e);
}
}
if (channel != null) {
channel.shutdown();
int attempt = 0;
do {
try {
channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Channel await termination was interrupted", e);
}
if (attempt > 5) {
log.warn("We had reached maximum of termination attempts. Force closing channel");
try {
channel.shutdownNow();
} catch (Exception e) {
log.error("Exception during shutdownNow", e);
}
break;
}
attempt++;
} while (!channel.isTerminated());
}
}
@Override
public void sendUplinkMsg(UplinkMsg msg) {
uplinkMsgLock.lock();
try {
|
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE)
.setUplinkMsg(msg)
.build());
} finally {
uplinkMsgLock.unlock();
}
}
@Override
public void sendSyncRequestMsg(boolean fullSyncRequired) {
uplinkMsgLock.lock();
try {
SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder()
.setFullSync(fullSyncRequired)
.build();
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE)
.setSyncRequestMsg(syncRequestMsg)
.build());
} finally {
uplinkMsgLock.unlock();
}
}
@Override
public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) {
uplinkMsgLock.lock();
try {
this.inputStream.onNext(RequestMsg.newBuilder()
.setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE)
.setDownlinkResponseMsg(downlinkResponseMsg)
.build());
} finally {
uplinkMsgLock.unlock();
}
}
}
|
repos\thingsboard-master\common\edge-api\src\main\java\org\thingsboard\edge\rpc\EdgeGrpcClient.java
| 1
|
请完成以下Java代码
|
public Builder tenantId(TenantId tenantId) {
this.tenantId = tenantId;
return this;
}
public Builder entityId(EntityId entityId) {
this.entityId = entityId;
return this;
}
public Builder keys(List<String> keys) {
this.keys = keys;
return this;
}
public Builder deleteHistoryQueries(List<DeleteTsKvQuery> deleteHistoryQueries) {
this.deleteHistoryQueries = deleteHistoryQueries;
return this;
}
public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = previousCalculatedFieldIds;
return this;
}
public Builder tbMsgId(UUID tbMsgId) {
|
this.tbMsgId = tbMsgId;
return this;
}
public Builder tbMsgType(TbMsgType tbMsgType) {
this.tbMsgType = tbMsgType;
return this;
}
public Builder callback(FutureCallback<List<String>> callback) {
this.callback = callback;
return this;
}
public TimeseriesDeleteRequest build() {
return new TimeseriesDeleteRequest(tenantId, entityId, keys, deleteHistoryQueries, previousCalculatedFieldIds, tbMsgId, tbMsgType, callback);
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\TimeseriesDeleteRequest.java
| 1
|
请完成以下Java代码
|
public class IntervalTree
{
/**
* 根节点
*/
private IntervalNode rootNode = null;
/**
* 构造线段树
*
* @param intervals
*/
public IntervalTree(List<Intervalable> intervals)
{
this.rootNode = new IntervalNode(intervals);
}
/**
* 从区间列表中移除重叠的区间
*
* @param intervals
* @return
*/
public List<Intervalable> removeOverlaps(List<Intervalable> intervals)
{
// 排序,按照先大小后左端点的顺序
Collections.sort(intervals, new IntervalableComparatorBySize());
Set<Intervalable> removeIntervals = new TreeSet<Intervalable>();
for (Intervalable interval : intervals)
{
// 如果区间已经被移除了,就忽略它
if (removeIntervals.contains(interval))
{
continue;
}
// 否则就移除它
removeIntervals.addAll(findOverlaps(interval));
}
// 移除所有的重叠区间
|
for (Intervalable removeInterval : removeIntervals)
{
intervals.remove(removeInterval);
}
// 排序,按照左端顺序
Collections.sort(intervals, new IntervalableComparatorByPosition());
return intervals;
}
/**
* 寻找重叠区间
*
* @param interval 与这个区间重叠
* @return 重叠的区间列表
*/
public List<Intervalable> findOverlaps(Intervalable interval)
{
return rootNode.findOverlaps(interval);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\IntervalTree.java
| 1
|
请完成以下Java代码
|
private static final class HostIdentifier implements IHostIdentifier
{
private final String hostName;
private final String hostAddress;
private transient String _toString;
private transient Integer _hashcode;
private HostIdentifier(final String hostName, final String hostAddress)
{
this.hostAddress = hostAddress;
this.hostName = hostName;
}
@Override
public String toString()
{
if (_toString == null)
{
_toString = (hostName != null ? hostName : "") + "/" + hostAddress;
}
return _toString;
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = Objects.hash(hostName, hostAddress);
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
|
return true;
}
if (obj instanceof HostIdentifier)
{
final HostIdentifier other = (HostIdentifier)obj;
return Objects.equals(hostName, other.hostName)
&& Objects.equals(hostAddress, other.hostAddress);
}
else
{
return false;
}
}
@Override
public String getIP()
{
return hostAddress;
}
@Override
public String getHostName()
{
return hostName;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\net\NetUtils.java
| 1
|
请完成以下Java代码
|
public static RSAPublicKey readX509PublicKeySecondApproach(File file) throws IOException {
try (FileReader keyReader = new FileReader(file)) {
PEMParser pemParser = new PEMParser(keyReader);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject());
return (RSAPublicKey) converter.getPublicKey(publicKeyInfo);
}
}
public static RSAPrivateKey readPKCS8PrivateKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
KeyFactory factory = KeyFactory.getInstance("RSA");
try (FileReader keyReader = new FileReader(file);
PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
|
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return (RSAPrivateKey) factory.generatePrivate(privKeySpec);
}
}
public static RSAPrivateKey readPKCS8PrivateKeySecondApproach(File file) throws IOException {
try (FileReader keyReader = new FileReader(file)) {
PEMParser pemParser = new PEMParser(keyReader);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(pemParser.readObject());
return (RSAPrivateKey) converter.getPrivateKey(privateKeyInfo);
}
}
}
|
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\pem\BouncyCastlePemUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private synchronized boolean checkIfBatchIsDone()
{
if (wpProgress == null || !isEnqueueingDone)
{
return false;
}
if (wpProgress.isProcessedSuccessfully())
{
Loggables.withLogger(logger, Level.INFO).addLog("AsyncBatchId={} completed successfully. ", batchId.getRepoId());
this.completableFuture.complete(null);
return true;
}
else if (wpProgress.isProcessedWithError())
{
this.completableFuture.completeExceptionally(new AdempiereException("WorkPackage completed with an exception")
.appendParametersToMessage()
.setParameter("AsyncBatchId", batchId.getRepoId()));
return true;
}
return false;
}
@NonNull
private static WorkPackagesProgress getWPsProgress(@NonNull final AsyncBatchNotifyRequest request)
{
return WorkPackagesProgress.builder()
.noOfProcessedWPs(request.getNoOfProcessedWPs())
.noOfEnqueuedWPs(request.getNoOfEnqueuedWPs())
.noOfErrorWPs(request.getNoOfErrorWPs())
.build();
}
private static class WorkPackagesProgress
{
@NonNull
Integer noOfEnqueuedWPs;
@NonNull
Integer noOfProcessedWPs;
@NonNull
Integer noOfErrorWPs;
@Builder
|
public WorkPackagesProgress(
@NonNull final Integer noOfEnqueuedWPs,
@Nullable final Integer noOfProcessedWPs,
@Nullable final Integer noOfErrorWPs)
{
this.noOfEnqueuedWPs = noOfEnqueuedWPs;
this.noOfProcessedWPs = CoalesceUtil.coalesceNotNull(noOfProcessedWPs, 0);
this.noOfErrorWPs = CoalesceUtil.coalesceNotNull(noOfErrorWPs, 0);
Check.assumeGreaterThanZero(noOfEnqueuedWPs, "noOfEnqueuedWPs");
Check.assumeGreaterOrEqualToZero(this.noOfProcessedWPs, this.noOfErrorWPs);
}
public boolean isProcessedSuccessfully()
{
return noOfErrorWPs == 0 && noOfProcessedWPs >= noOfEnqueuedWPs;
}
public boolean isProcessedWithError()
{
return noOfErrorWPs > 0 && (noOfProcessedWPs + noOfErrorWPs >= noOfEnqueuedWPs);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\service\AsyncBatchObserver.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public EventSubscriptionBuilder activityId(String activityId) {
this.activityId = activityId;
return this;
}
@Override
public EventSubscriptionBuilder subScopeId(String subScopeId) {
this.subScopeId = subScopeId;
return this;
}
@Override
public EventSubscriptionBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public EventSubscriptionBuilder scopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
return this;
}
@Override
public EventSubscriptionBuilder scopeDefinitionKey(String scopeDefinitionKey) {
this.scopeDefinitionKey = scopeDefinitionKey;
return this;
}
@Override
public EventSubscriptionBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public EventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
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 HUEditorViewBuilder orderBy(@NonNull final DocumentQueryOrderBy orderBy)
{
if (orderBys == null)
{
orderBys = new ArrayList<>();
}
orderBys.add(orderBy);
return this;
}
public HUEditorViewBuilder orderBys(@NonNull final DocumentQueryOrderByList orderBys)
{
this.orderBys = new ArrayList<>(orderBys.toList());
return this;
}
public HUEditorViewBuilder clearOrderBys()
{
this.orderBys = null;
return this;
}
private DocumentQueryOrderByList getOrderBys()
{
return DocumentQueryOrderByList.ofList(orderBys);
}
public HUEditorViewBuilder setParameter(final String name, @Nullable final Object value)
{
if (value == null)
{
if (parameters != null)
{
parameters.remove(name);
}
}
else
{
if (parameters == null)
{
parameters = new LinkedHashMap<>();
}
parameters.put(name, value);
}
return this;
}
public HUEditorViewBuilder setParameters(final Map<String, Object> parameters)
{
parameters.forEach(this::setParameter);
return this;
}
ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
@Nullable
public <T> T getParameter(@NonNull final String name)
{
if (parameters == null)
{
return null;
}
|
@SuppressWarnings("unchecked") final T value = (T)parameters.get(name);
return value;
}
public void assertParameterSet(final String name)
{
final Object value = getParameter(name);
if (value == null)
{
throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this);
}
}
public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository)
{
this.huEditorViewRepository = huEditorViewRepository;
return this;
}
HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context)
{
final ViewId viewId = getViewId();
final DocumentFilterList stickyFilters = getStickyFilters();
final DocumentFilterList filters = getFilters();
if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters))
{
return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
else
{
return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
}
public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters)
{
this.useAutoFilters = useAutoFilters;
return this;
}
public boolean isUseAutoFilters()
{
return useAutoFilters;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java
| 1
|
请完成以下Java代码
|
public Integer getThreadNum() {
return threadNum;
}
public void setThreadNum(Integer threadNum) {
this.threadNum = threadNum;
}
public Long getPassQps() {
return passQps;
}
public void setPassQps(Long passQps) {
this.passQps = passQps;
}
public Long getBlockQps() {
return blockQps;
}
public void setBlockQps(Long blockQps) {
this.blockQps = blockQps;
}
public Long getTotalQps() {
return totalQps;
}
public void setTotalQps(Long totalQps) {
this.totalQps = totalQps;
}
public Long getAverageRt() {
return averageRt;
}
public void setAverageRt(Long averageRt) {
this.averageRt = averageRt;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public Long getOneMinutePass() {
return oneMinutePass;
|
}
public void setOneMinutePass(Long oneMinutePass) {
this.oneMinutePass = oneMinutePass;
}
public Long getOneMinuteBlock() {
return oneMinuteBlock;
}
public void setOneMinuteBlock(Long oneMinuteBlock) {
this.oneMinuteBlock = oneMinuteBlock;
}
public Long getOneMinuteException() {
return oneMinuteException;
}
public void setOneMinuteException(Long oneMinuteException) {
this.oneMinuteException = oneMinuteException;
}
public Long getOneMinuteTotal() {
return oneMinuteTotal;
}
public void setOneMinuteTotal(Long oneMinuteTotal) {
this.oneMinuteTotal = oneMinuteTotal;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public List<ResourceTreeNode> getChildren() {
return children;
}
public void setChildren(List<ResourceTreeNode> children) {
this.children = children;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
| 1
|
请完成以下Java代码
|
public class SalesPurchaseWatchDog implements IIterateResultHandler
{
private static final transient Logger logger = LogManager.getLogger(SalesPurchaseWatchDog.class);
private ITableRecordReference lastSalesReference;
private Date lastSalesReferenceSeen;
private ITableRecordReference lastPurchaseReference;
private Date lastPurchaseReferenceSeen;
private ITableRecordReference lastHUReference;
private Date lastHUReferenceSeen;
@Override
public AddResult onRecordAdded(
final ITableRecordReference r,
final AddResult preliminaryResult)
{
final PlainContextAware ctx = PlainContextAware.newWithThreadInheritedTrx(Env.getCtx());
final Object model = r.getModel(ctx);
final String tableName = r.getTableName();
if (tableName.startsWith("M_HU") && !tableName.startsWith("M_HU_Assign"))
{
lastHUReference = r;
lastHUReferenceSeen = de.metas.common.util.time.SystemTime.asDate();
}
else
{
setSalesOrPurchaseReference(r, model);
}
if (getNotNullReferenceCount() > 1)
{
Loggables.withLogger(logger, Level.WARN).addLog("Records which do not fit together are added to the same result.\n"
+ "Signaling the crawler to stop! The records are:\n"
+ "IsSOTrx=true, seen at {}: {}\n"
+ "IsSOTrx=false, seen at {}: {}\n"
+ "HU-record, seen at {}: {}\n",
lastSalesReferenceSeen, lastSalesReference, lastPurchaseReferenceSeen, lastPurchaseReference, lastHUReferenceSeen, lastHUReference);
return AddResult.STOP;
}
return preliminaryResult;
}
private int getNotNullReferenceCount()
{
int result = 0;
if (lastHUReference != null)
{
result++;
}
if (lastSalesReference != null)
{
result++;
}
if (lastPurchaseReference != null)
{
result++;
}
return result;
}
/**
* If the given model has {@code IsSOTrx} or {@code SOTrx}, then this method set the respective members within this class.
*
* @param r
* @param model
*/
|
private void setSalesOrPurchaseReference(
final ITableRecordReference r,
final Object model)
{
final String soTrxColName1 = "IsSOTrx";
final String soTrxColName2 = "SOTrx";
if (!InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName1) && !InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName2))
{
return;
}
final Boolean soTrx = CoalesceUtil.coalesceSuppliers(
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName1),
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName2));
if (soTrx == null)
{
return;
}
if (soTrx)
{
lastSalesReference = r;
lastSalesReferenceSeen = de.metas.common.util.time.SystemTime.asDate();
}
else
{
lastPurchaseReference = r;
lastPurchaseReferenceSeen = SystemTime.asDate();
}
}
@Override
public String toString()
{
return "SalesPurchaseWatchDog [lastSalesReference=" + lastSalesReference + ", lastPurchaseReference=" + lastPurchaseReference + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\SalesPurchaseWatchDog.java
| 1
|
请完成以下Java代码
|
private I_M_HU_PI_Attribute getByAttributeIdOrNull(final AttributeId attributeId)
{
return attributesByAttributeId.get(attributeId);
}
public PIAttributes addIfAbsent(@NonNull final PIAttributes from)
{
if (from.isEmpty())
{
return this;
}
if (this.isEmpty())
{
return from;
}
final LinkedHashMap<AttributeId, I_M_HU_PI_Attribute> piAttributesNew = new LinkedHashMap<>(attributesByAttributeId);
from.attributesByAttributeId.forEach(piAttributesNew::putIfAbsent);
return of(piAttributesNew.values());
}
public int getSeqNoByAttributeId(final AttributeId attributeId, final int seqNoIfNotFound)
{
final I_M_HU_PI_Attribute piAttribute = getByAttributeIdOrNull(attributeId);
if (piAttribute == null)
{
|
return seqNoIfNotFound;
}
return piAttribute.getSeqNo();
}
public ImmutableSet<AttributeId> getAttributeIds()
{
return attributesByAttributeId.keySet();
}
public boolean isEmpty()
{
return attributesByAttributeId.isEmpty();
}
public boolean isUseInASI(@NonNull final AttributeId attributeId)
{
return getByAttributeId(attributeId).isUseInASI();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\PIAttributes.java
| 1
|
请完成以下Java代码
|
public void setTableColumnFixedWidthCallback(ITableColumnWidthCallback tableColumnFixedWidthCallback)
{
if (this.tableColumnFixedWidthCallback == tableColumnFixedWidthCallback)
{
return;
}
// Avoid common development errors
// i.e. current tableColumnFixedWidthCallback is set back to null
if (tableColumnFixedWidthCallback == null)
{
throw new IllegalArgumentException("Cannot set tableColumnFixedWidthCallback back to null");
}
this.tableColumnFixedWidthCallback = tableColumnFixedWidthCallback;
}
private int getFixedWidth(final TableColumn column)
{
if (tableColumnFixedWidthCallback == null)
{
return -1;
}
return tableColumnFixedWidthCallback.getWidth(column);
}
/**
* Class used to store column attributes when the column it is hidden. We need those informations to restore the column in case it is unhide.
*/
private final class ColumnAttributes
{
protected TableCellEditor cellEditor;
protected TableCellRenderer cellRenderer;
// protected Object headerValue;
protected int minWidth;
protected int maxWidth;
protected int preferredWidth;
}
@Override
public Object getModelValueAt(int rowIndexModel, int columnIndexModel)
{
return getModel().getValueAt(rowIndexModel, columnIndexModel);
}
|
private ITableColorProvider colorProvider = new DefaultTableColorProvider();
@Override
public void setColorProvider(final ITableColorProvider colorProvider)
{
Check.assumeNotNull(colorProvider, "colorProvider not null");
this.colorProvider = colorProvider;
}
@Override
public ITableColorProvider getColorProvider()
{
return colorProvider;
}
@Override
public void setModel(final TableModel dataModel)
{
super.setModel(dataModel);
if (modelRowSorter == null)
{
// i.e. we are in JTable constructor and modelRowSorter was not yet set
// => do nothing
}
else if (!modelRowSorter.isEnabled())
{
setupViewRowSorter();
}
}
private final void setupViewRowSorter()
{
final TableModel model = getModel();
viewRowSorter.setModel(model);
if (modelRowSorter != null)
{
viewRowSorter.setSortKeys(modelRowSorter.getSortKeys());
}
setRowSorter(viewRowSorter);
viewRowSorter.sort();
}
} // CTable
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTable.java
| 1
|
请完成以下Java代码
|
private static final class ProcessPreconditionsResolutionSupplier implements Supplier<ProcessPreconditionsResolution>
{
private final IProcessPreconditionsContext preconditionsContext;
private final ProcessDescriptor processDescriptor;
@Builder
private ProcessPreconditionsResolutionSupplier(
@NonNull final IProcessPreconditionsContext preconditionsContext,
@NonNull final ProcessDescriptor processDescriptor)
{
this.preconditionsContext = preconditionsContext;
this.processDescriptor = processDescriptor;
}
@Override
public ProcessPreconditionsResolution get()
{
return processDescriptor.checkPreconditionsApplicable(preconditionsContext);
}
}
private static final class ProcessParametersCallout
{
private static void forwardValueToCurrentProcessInstance(final ICalloutField calloutField)
{
final JavaProcess processInstance = JavaProcess.currentInstance();
final String parameterName = calloutField.getColumnName();
final IRangeAwareParams source = createSource(calloutField);
// Ask the instance to load the parameter
processInstance.loadParameterValueNoFail(parameterName, source);
}
private static IRangeAwareParams createSource(final ICalloutField calloutField)
{
final String parameterName = calloutField.getColumnName();
final Object fieldValue = calloutField.getValue();
if (fieldValue instanceof LookupValue)
{
final Object idObj = ((LookupValue)fieldValue).getId();
return ProcessParams.ofValueObject(parameterName, idObj);
}
|
else if (fieldValue instanceof DateRangeValue)
{
final DateRangeValue dateRange = (DateRangeValue)fieldValue;
return ProcessParams.of(
parameterName,
TimeUtil.asDate(dateRange.getFrom()),
TimeUtil.asDate(dateRange.getTo()));
}
else
{
return ProcessParams.ofValueObject(parameterName, fieldValue);
}
}
}
private static final class ProcessParametersDataBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder
{
public static final ProcessParametersDataBindingDescriptorBuilder instance = new ProcessParametersDataBindingDescriptorBuilder();
private static final DocumentEntityDataBindingDescriptor dataBinding = () -> ADProcessParametersRepository.instance;
@Override
public DocumentEntityDataBindingDescriptor getOrBuild()
{
return dataBinding;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessDescriptorsFactory.java
| 1
|
请完成以下Java代码
|
public class BaseRuleChainProcessor extends BaseEdgeProcessor {
@Autowired
private DataValidator<RuleChain> ruleChainValidator;
protected Pair<Boolean, Boolean> saveOrUpdateRuleChain(TenantId tenantId, RuleChainId ruleChainId, RuleChainUpdateMsg ruleChainUpdateMsg, RuleChainType ruleChainType) {
boolean created = false;
RuleChain ruleChainFromDb = edgeCtx.getRuleChainService().findRuleChainById(tenantId, ruleChainId);
if (ruleChainFromDb == null) {
created = true;
}
RuleChain ruleChain = JacksonUtil.fromString(ruleChainUpdateMsg.getEntity(), RuleChain.class, true);
if (ruleChain == null) {
throw new RuntimeException("[{" + tenantId + "}] ruleChainUpdateMsg {" + ruleChainUpdateMsg + "} cannot be converted to rule chain");
}
boolean isRoot = ruleChain.isRoot();
if (RuleChainType.CORE.equals(ruleChainType)) {
ruleChain.setRoot(false);
} else {
ruleChain.setRoot(ruleChainFromDb == null ? false : ruleChainFromDb.isRoot());
}
ruleChain.setType(ruleChainType);
ruleChainValidator.validate(ruleChain, RuleChain::getTenantId);
if (created) {
|
ruleChain.setId(ruleChainId);
}
edgeCtx.getRuleChainService().saveRuleChain(ruleChain, true, false);
return Pair.of(created, isRoot);
}
protected void saveOrUpdateRuleChainMetadata(TenantId tenantId, RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg) {
RuleChainMetaData ruleChainMetadata = JacksonUtil.fromString(ruleChainMetadataUpdateMsg.getEntity(), RuleChainMetaData.class, true);
if (ruleChainMetadata == null) {
throw new RuntimeException("[{" + tenantId + "}] ruleChainMetadataUpdateMsg {" + ruleChainMetadataUpdateMsg + "} cannot be converted to rule chain metadata");
}
if (!ruleChainMetadata.getNodes().isEmpty()) {
ruleChainMetadata.setVersion(null);
for (RuleNode ruleNode : ruleChainMetadata.getNodes()) {
ruleNode.setRuleChainId(null);
ruleNode.setId(null);
}
edgeCtx.getRuleChainService().saveRuleChainMetaData(tenantId, ruleChainMetadata, Function.identity(), true);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\rule\BaseRuleChainProcessor.java
| 1
|
请完成以下Java代码
|
private int getNotNullReferenceCount()
{
int result = 0;
if (lastHUReference != null)
{
result++;
}
if (lastSalesReference != null)
{
result++;
}
if (lastPurchaseReference != null)
{
result++;
}
return result;
}
/**
* If the given model has {@code IsSOTrx} or {@code SOTrx}, then this method set the respective members within this class.
*
* @param r
* @param model
*/
private void setSalesOrPurchaseReference(
final ITableRecordReference r,
final Object model)
{
final String soTrxColName1 = "IsSOTrx";
final String soTrxColName2 = "SOTrx";
if (!InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName1) && !InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName2))
|
{
return;
}
final Boolean soTrx = CoalesceUtil.coalesceSuppliers(
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName1),
() -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName2));
if (soTrx == null)
{
return;
}
if (soTrx)
{
lastSalesReference = r;
lastSalesReferenceSeen = de.metas.common.util.time.SystemTime.asDate();
}
else
{
lastPurchaseReference = r;
lastPurchaseReferenceSeen = SystemTime.asDate();
}
}
@Override
public String toString()
{
return "SalesPurchaseWatchDog [lastSalesReference=" + lastSalesReference + ", lastPurchaseReference=" + lastPurchaseReference + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\SalesPurchaseWatchDog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void customizePropertySources(MutablePropertySources propertySources) {
Map<String, Object> dubboScanProperties = getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX);
propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties));
}
};
ConfigurationPropertySources.attach(propertyResolver);
return propertyResolver;
}
/**
* The bean is used to scan the packages of Dubbo Service classes
*
* @param environment {@link Environment} instance
* @return non-null {@link Set}
* @since 2.7.8
|
*/
@ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME)
@Bean(name = BASE_PACKAGES_BEAN_NAME)
public Set<String> dubboBasePackages(ConfigurableEnvironment environment) {
PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment);
return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
}
@ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class)
@Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME)
@Scope(scopeName = SCOPE_PROTOTYPE)
public ConfigurationBeanBinder relaxedDubboConfigBinder() {
return new BinderDubboConfigBinder();
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboRelaxedBinding2AutoConfiguration.java
| 2
|
请完成以下Java代码
|
public ProcessEngine buildProcessEngine() {
// Disable schema creation/validation by setting it to null.
// We'll do it manually, see buildProcessEngine() method (hence why it's copied first)
String originalDatabaseSchemaUpdate = this.databaseSchemaUpdate;
this.databaseSchemaUpdate = null;
// Also, we shouldn't start the async executor until *after* the schema's have been created
boolean originalIsAutoActivateAsyncExecutor = this.asyncExecutorActivate;
this.asyncExecutorActivate = false;
ProcessEngine processEngine = super.buildProcessEngine();
// Reset to original values
this.databaseSchemaUpdate = originalDatabaseSchemaUpdate;
this.asyncExecutorActivate = originalIsAutoActivateAsyncExecutor;
// Create tenant schema
for (String tenantId : tenantInfoHolder.getAllTenants()) {
createTenantSchema(tenantId);
}
// Start async executor
if (asyncExecutor != null && originalIsAutoActivateAsyncExecutor) {
asyncExecutor.start();
}
booted = true;
return processEngine;
}
protected void createTenantSchema(String tenantId) {
logger.info("creating/validating database schema for tenant " + tenantId);
tenantInfoHolder.setCurrentTenantId(tenantId);
getCommandExecutor().execute(getSchemaCommandConfig(), new ExecuteSchemaOperationCommand(databaseSchemaUpdate));
tenantInfoHolder.clearCurrentTenantId();
}
|
protected void createTenantAsyncJobExecutor(String tenantId) {
((TenantAwareAsyncExecutor) asyncExecutor).addTenantAsyncExecutor(
tenantId,
isAsyncExecutorActivate() && booted
);
}
@Override
public CommandInterceptor createTransactionInterceptor() {
return null;
}
@Override
protected void postProcessEngineInitialisation() {
// empty here. will be done in registerTenant
}
@Override
public UserGroupManager getUserGroupManager() {
return null; //no external identity provider supplied
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\multitenant\MultiSchemaMultiTenantProcessEngineConfiguration.java
| 1
|
请完成以下Java代码
|
public SimpleDateFormat getDateFormat()
{
return (SimpleDateFormat)getDateFormatInternal().clone();
}
private SimpleDateFormat getDateFormatInternal()
{
SimpleDateFormat dateFormat = dateFormatHolder.get();
if(dateFormat == null)
{
dateFormat = new SimpleDateFormat(pattern);
dateFormatHolder.set(dateFormat);
}
return dateFormat;
}
/**
* @see SimpleDateFormat#format(Date)
*/
public String format(final Date date)
{
return getDateFormatInternal().format(date);
}
/**
* @see SimpleDateFormat#format(Object)
*/
public Object format(final Object value)
{
return getDateFormatInternal().format(value);
|
}
/**
* @see SimpleDateFormat#parse(String)
*/
public Date parse(final String source) throws ParseException
{
return getDateFormatInternal().parse(source);
}
/**
* @see SimpleDateFormat#parseObject(String)
*/
public Object parseObject(final String source) throws ParseException
{
return getDateFormatInternal().parseObject(source);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\SimpleDateFormatThreadLocal.java
| 1
|
请完成以下Java代码
|
public String getDisplayName()
{
if (_displayName == null)
{
final List<String> publisherNames = new ArrayList<>(publishers.size());
for (final IRfQResponsePublisher publisher : publishers)
{
publisherNames.add(publisher.getDisplayName());
}
_displayName = "composite["
+ Joiner.on(", ").skipNulls().join(publisherNames)
+ "]";
}
return _displayName;
}
@Override
public void publish(final RfQResponsePublisherRequest request)
{
Check.assumeNotNull(request, "request not null");
for (final IRfQResponsePublisher publisher : publishers)
{
try
{
publisher.publish(request);
onSuccess(publisher, request);
}
catch (final Exception ex)
{
onException(publisher, request, ex);
}
}
}
|
private void onSuccess(final IRfQResponsePublisher publisher, final RfQResponsePublisherRequest request)
{
final ILoggable loggable = Loggables.get();
loggable.addLog("OK - " + publisher.getDisplayName() + ": " + request.getSummary());
}
private void onException(final IRfQResponsePublisher publisher, final RfQResponsePublisherRequest request, final Exception ex)
{
final ILoggable loggable = Loggables.get();
loggable.addLog("@Error@ - " + publisher.getDisplayName() + ": " + ex.getMessage());
logger.warn("Publishing failed: publisher={}, request={}", publisher, request, ex);
}
public void addRfQResponsePublisher(final IRfQResponsePublisher publisher)
{
Check.assumeNotNull(publisher, "publisher not null");
final boolean added = publishers.addIfAbsent(publisher);
if (!added)
{
logger.warn("Publisher {} was already added to {}", publisher, publishers);
return;
}
_displayName = null; // reset
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\CompositeRfQResponsePublisher.java
| 1
|
请完成以下Java代码
|
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
final int max = findMax(initialList);
final int numberOfBuckets = (int) Math.sqrt(initialList.size());
List<List<Integer>> buckets = new ArrayList<>();
for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>());
//distribute the data
for (int i : initialList) {
buckets.get(hash(i, max, numberOfBuckets)).add(i);
}
return buckets;
}
|
private int findMax(List<Integer> input){
int m = Integer.MIN_VALUE;
for (int i : input){
m = Math.max(i, m);
}
return m;
}
private static int hash(int i, int max, int numberOfBuckets) {
return (int) ((double) i / max * (numberOfBuckets - 1));
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\bucketsort\IntegerBucketSorter.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8088
spring.datasource.url=jdbc:sqlserver://172.24.4.35:1433;databaseName=SampleDB
spring.datasource.username=sa
spring.datasource.password=Y.sa
|
123456
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
|
repos\springboot-demo-master\sqlserver\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
@Override
public int getAD_Printer_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_ID);
}
@Override
public void setAD_Printer_Matching_ID (int AD_Printer_Matching_ID)
{
if (AD_Printer_Matching_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, Integer.valueOf(AD_Printer_Matching_ID));
}
@Override
public int getAD_Printer_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Matching_ID);
}
@Override
public void setAD_Tray_Matching_IncludedTab (java.lang.String AD_Tray_Matching_IncludedTab)
{
|
set_Value (COLUMNNAME_AD_Tray_Matching_IncludedTab, AD_Tray_Matching_IncludedTab);
}
@Override
public java.lang.String getAD_Tray_Matching_IncludedTab()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_Tray_Matching_IncludedTab);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Matching.java
| 1
|
请完成以下Java代码
|
public void changeAssignee(Task task, String assignee) {
TaskHelper.changeTaskAssignee((TaskEntity) task, assignee, cmmnEngineConfiguration);
}
@Override
public void changeOwner(Task task, String owner) {
TaskHelper.changeTaskOwner((TaskEntity) task, owner, cmmnEngineConfiguration);
}
@Override
public void addCandidateUser(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addCandidateUsers(Task task, List<IdentityLink> candidateUsers) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateUsers) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks, cmmnEngineConfiguration);
}
@Override
public void addCandidateGroup(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addCandidateGroups(Task task, List<IdentityLink> candidateGroups) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateGroups) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks, cmmnEngineConfiguration);
}
@Override
public void addUserIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
|
@Override
public void addGroupIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void deleteUserIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
@Override
public void deleteGroupIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cfg\DefaultTaskAssignmentManager.java
| 1
|
请完成以下Java代码
|
public I_AD_Alert getAD_Alert() throws RuntimeException
{
return (I_AD_Alert)MTable.get(getCtx(), I_AD_Alert.Table_Name)
.getPO(getAD_Alert_ID(), get_TrxName()); }
/** Set Alert.
@param AD_Alert_ID
Adempiere Alert
*/
public void setAD_Alert_ID (int AD_Alert_ID)
{
if (AD_Alert_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Alert_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Alert_ID, Integer.valueOf(AD_Alert_ID));
}
/** Get Alert.
@return Adempiere Alert
*/
public int getAD_Alert_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Alert_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Alert Recipient.
@param AD_AlertRecipient_ID
Recipient of the Alert Notification
*/
public void setAD_AlertRecipient_ID (int AD_AlertRecipient_ID)
{
if (AD_AlertRecipient_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_AlertRecipient_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_AlertRecipient_ID, Integer.valueOf(AD_AlertRecipient_ID));
}
/** Get Alert Recipient.
@return Recipient of the Alert Notification
*/
public int getAD_AlertRecipient_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_AlertRecipient_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Role getAD_Role() throws RuntimeException
{
return (I_AD_Role)MTable.get(getCtx(), I_AD_Role.Table_Name)
.getPO(getAD_Role_ID(), get_TrxName()); }
/** Set Role.
@param AD_Role_ID
Responsibility Role
*/
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertRecipient.java
| 1
|
请完成以下Java代码
|
public void serverStreamingRpc(ServerStreamingRequest request,
StreamObserver<ServerStreamingResponse> responseObserver) {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onNext(
ServerStreamingResponse.newBuilder().setMessage(request.getMessage()).build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<BidiStreamingRequest> bidiStreamingRpc(
StreamObserver<BidiStreamingResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(BidiStreamingRequest value) {
responseObserver.onNext(
|
BidiStreamingResponse.newBuilder().setMessage(value.getMessage()).build());
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onCompleted();
}
}
};
}
}
|
repos\grpc-spring-master\examples\grpc-observability\backend\src\main\java\net\devh\boot\grpc\examples\observability\backend\ExampleServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
ApplicationRunner runner(@Qualifier("YellowPages") Region<String, Person> yellowPages) {
return args -> {
assertThat(yellowPages).isNotNull();
assertThat(yellowPages.getName()).isEqualTo("YellowPages");
assertThat(yellowPages.getAttributes()).isNotNull();
assertThat(yellowPages.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.REPLICATE);
assertThat(yellowPages.getAttributes().getEnableSubscriptionConflation()).isTrue();
};
}
// end::application-runner[]
// tag::geode-configuration[]
@Configuration
static class GeodeConfiguration {
@Bean("YellowPages")
public ReplicatedRegionFactoryBean<String, Person> yellowPagesRegion(GemFireCache gemfireCache,
@Qualifier("YellowPagesAttributes") RegionAttributes<String, Person> exampleAttributes) {
ReplicatedRegionFactoryBean<String, Person> yellowPagesRegion =
new ReplicatedRegionFactoryBean<>();
yellowPagesRegion.setAttributes(exampleAttributes);
yellowPagesRegion.setCache(gemfireCache);
yellowPagesRegion.setClose(false);
yellowPagesRegion.setPersistent(false);
return yellowPagesRegion;
}
@Bean("YellowPagesAttributes")
public RegionAttributesFactoryBean<String, Person> exampleRegionAttributes() {
RegionAttributesFactoryBean<String, Person> yellowPagesRegionAttributes =
new RegionAttributesFactoryBean<>();
|
yellowPagesRegionAttributes.setEnableSubscriptionConflation(true);
return yellowPagesRegionAttributes;
}
}
// end::geode-configuration[]
// tag::locator-manager[]
@Configuration
@EnableLocator
@EnableManager(start = true)
@Profile("locator-manager")
static class LocatorManagerConfiguration { }
// end::locator-manager[]
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\server\BootGeodeNearCachingCacheServerApplication.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseResult<T> {
private static final int SUCCESS_CODE = 0;
private static final String SUCCESS_MESSAGE = "成功";
@ApiModelProperty(value = "响应码", name = "code", required = true, example = "" + SUCCESS_CODE)
private int code;
@ApiModelProperty(value = "响应消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
private String msg;
@ApiModelProperty(value = "响应数据", name = "data")
private T data;
private BaseResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
private BaseResult() {
this(SUCCESS_CODE, SUCCESS_MESSAGE);
}
private BaseResult(int code, String msg) {
this(code, msg, null);
}
private BaseResult(T data) {
this(SUCCESS_CODE, SUCCESS_MESSAGE, data);
}
public static <T> BaseResult<T> success() {
return new BaseResult<>();
}
public static <T> BaseResult<T> successWithData(T data) {
return new BaseResult<>(data);
}
public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) {
return new BaseResult<>(code, msg, null);
}
public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
return new BaseResult<>(param.getCode(), param.getMsg(), null);
}
public int getCode() {
return code;
}
public void setCode(int code) {
|
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static class ResponseParam {
private int code;
private String msg;
private ResponseParam(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseParam buildParam(int code, String msg) {
return new ResponseParam(code, msg);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Job parentJob() {
return jobBuilderFactory.get("parentJob")
.start(childJobOneStep())
.next(childJobTwoStep())
.build();
}
// 将任务转换为特殊的步骤
private Step childJobOneStep() {
return new JobStepBuilder(new StepBuilder("childJobOneStep"))
.job(childJobOne())
.launcher(jobLauncher)
.repository(jobRepository)
.transactionManager(platformTransactionManager)
.build();
}
// 将任务转换为特殊的步骤
private Step childJobTwoStep() {
return new JobStepBuilder(new StepBuilder("childJobTwoStep"))
.job(childJobTwo())
.launcher(jobLauncher)
.repository(jobRepository)
.transactionManager(platformTransactionManager)
.build();
}
// 子任务一
private Job childJobOne() {
|
return jobBuilderFactory.get("childJobOne")
.start(
stepBuilderFactory.get("childJobOneStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("子任务一执行步骤。。。");
return RepeatStatus.FINISHED;
}).build()
).build();
}
// 子任务二
private Job childJobTwo() {
return jobBuilderFactory.get("childJobTwo")
.start(
stepBuilderFactory.get("childJobTwoStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("子任务二执行步骤。。。");
return RepeatStatus.FINISHED;
}).build()
).build();
}
}
|
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\NestedJobDemo.java
| 2
|
请完成以下Java代码
|
public final void memberSuspect(DistributionManager manager, InternalDistributedMember member,
InternalDistributedMember suspectMember, String reason) {
MemberSuspectEvent event = new MemberSuspectEvent(manager)
.withMember(member)
.withReason(reason)
.withSuspect(suspectMember);
handleMemberSuspect(event);
}
public void handleMemberSuspect(MemberSuspectEvent event) { }
/**
* @inheritDoc
*/
@Override
public final void quorumLost(DistributionManager manager, Set<InternalDistributedMember> failedMembers,
List<InternalDistributedMember> remainingMembers) {
QuorumLostEvent event = new QuorumLostEvent(manager)
.withFailedMembers(failedMembers)
.withRemainingMembers(remainingMembers);
handleQuorumLost(event);
}
public void handleQuorumLost(QuorumLostEvent event) { }
/**
* Registers this {@link MembershipListener} with the given {@literal peer} {@link Cache}.
*
* @param peerCache {@literal peer} {@link Cache} on which to register this {@link MembershipListener}.
* @return this {@link MembershipListenerAdapter}.
* @see org.apache.geode.cache.Cache
|
*/
@SuppressWarnings("unchecked")
public T register(Cache peerCache) {
Optional.ofNullable(peerCache)
.map(Cache::getDistributedSystem)
.filter(InternalDistributedSystem.class::isInstance)
.map(InternalDistributedSystem.class::cast)
.map(InternalDistributedSystem::getDistributionManager)
.ifPresent(distributionManager -> distributionManager
.addMembershipListener(this));
return (T) this;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipListenerAdapter.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8769
spring:
application:
name: sc-admin-server
security:
user:
name: "admin"
password: "admin"
mail:
host: smtp.163.com
username: xxxx@163.com
password: xxxx
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
boot:
admin:
notify:
mail:
from: xxxx@163.com
to: xxxx@qq.com
eureka:
client:
registryFetchIntervalSeconds: 5
service-url:
defaultZone: ${EUREKA_SERVICE_URL:http://localhost:8761}/eureka/
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health
metadata-map:
user.name: ${spring.security.us
|
er.name}
user.password: ${spring.security.user.password}
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
health:
db:
enabled: false
mail:
enabled: false
redis:
enabled: false
mongo:
enabled: false
|
repos\SpringBootLearning-master (1)\springboot-admin\sc-admin-server\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
private Object getSessionMutex(HttpSession session) {
if (session == null) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "HttpSession is missing");
}
Object mutex = session.getAttribute(CsrfConstants.CSRF_SESSION_MUTEX);
if (mutex == null) {
mutex = session;
}
return mutex;
}
private boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private String getRequestedPath(HttpServletRequest request) {
String path = request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
|
return path;
}
private Set<String> parseURLs(String urlString) {
Set<String> urlSet = new HashSet<>();
if (urlString != null && !urlString.isEmpty()) {
String values[] = urlString.split(",");
for (String value : values) {
urlSet.add(value.trim());
}
}
return urlSet;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\CsrfPreventionFilter.java
| 1
|
请完成以下Java代码
|
public class CyclicBarrierTest {
public static void main(String[] args) {
Random random = new Random();
Map<String, Long> map = new ConcurrentHashMap<>();
CyclicBarrier cyclicBarrier = new CyclicBarrier(4, () -> {
System.out.println(Thread.currentThread().getName() + " 3所有线程到达屏障的时候,优先执行barrierAction线程。。。。。。。");
System.out.println(Thread.currentThread().getName() + " 3" + JSON.toJSONString(map));
});
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
Thread.sleep(200 + random.nextInt(200));
System.out.println(Thread.currentThread().getName() + " 1等待所有线程到达屏障------------");
map.put(Thread.currentThread().getName(), Thread.currentThread().getId());
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + " 2所有线程到达屏障的时候,开始执行业务代码================");
} catch (Exception e) {
|
e.printStackTrace();
}
}).start();
}
try {
cyclicBarrier.await();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " 主线程完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\CyclicBarrierTest.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws JsonProcessingException
{
final KPIId kpiId = KPIId.ofRepoId(getRecord_ID());
kpisRepo.invalidateCache();
final KPI kpi = kpisRepo.getKPI(kpiId);
final KPIDataResult kpiData = KPIDataProvider.builder()
.kpiRepository(kpisRepo)
.esSystem(esSystem)
.sysConfigBL(sysConfigBL)
.kpiPermissionsProvider(new KPIPermissionsProvider(userRolePermissionsDAO))
|
.build()
.getKPIData(KPIDataRequest.builder()
.kpiId(kpiId)
.timeRangeDefaults(kpi.getTimeRangeDefaults())
.context(KPIDataContext.ofEnvProperties(getCtx())
.toBuilder()
.from(p_DateFrom)
.to(p_DateTo)
.build())
.build());
final String jsonData = jsonObjectMapper.writeValueAsString(kpiData);
log.info("jsonData:\n {}", jsonData);
return jsonData;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\process\WEBUI_KPI_TestQuery.java
| 1
|
请完成以下Java代码
|
public int getC_MediatedCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_MediatedCommissionSettings_ID);
}
@Override
public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
|
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPointsPrecision (final int PointsPrecision)
{
set_Value (COLUMNNAME_PointsPrecision, PointsPrecision);
}
@Override
public int getPointsPrecision()
{
return get_ValueAsInt(COLUMNNAME_PointsPrecision);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_MediatedCommissionSettings.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 Start Date.
|
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java
| 1
|
请完成以下Java代码
|
protected final boolean isHUEditorView()
{
return isViewClass(HUEditorView.class);
}
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
protected final HUEditorView getView()
{
return super.getView(HUEditorView.class);
}
@Override
protected final HUEditorRow getSingleSelectedRow()
{
return HUEditorRow.cast(super.getSingleSelectedRow());
}
protected final Stream<HUEditorRow> streamSelectedRows(@NonNull final HUEditorRowFilter filter)
{
final DocumentIdsSelection selectedDocumentIds = getSelectedRowIds();
if (selectedDocumentIds.isEmpty())
{
return Stream.empty();
}
return getView().streamByIds(filter.andOnlyRowIds(selectedDocumentIds));
}
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
protected Stream<HUEditorRow> streamSelectedRows()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return getView().streamByIds(selectedRowIds);
}
protected final Stream<HuId> streamSelectedHUIds(@NonNull final Select select)
{
return streamSelectedHUIds(HUEditorRowFilter.select(select));
}
protected final Stream<HuId> streamSelectedHUIds(@NonNull final HUEditorRowFilter filter)
{
return streamSelectedRows(filter)
.map(HUEditorRow::getHuId)
.filter(Objects::nonNull);
}
/**
* Gets <b>all</b> selected {@link HUEditorRow}s and loads the top level-HUs from those.
|
* I.e. this method does not rely on {@link HUEditorRow#isTopLevel()}, but checks the underlying HU.
*/
protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final Select select)
{
return streamSelectedHUs(HUEditorRowFilter.select(select));
}
protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final HUEditorRowFilter filter)
{
final Stream<HuId> huIds = streamSelectedHUIds(filter);
return StreamUtils
.dice(huIds, 100)
.flatMap(huIdsChunk -> handlingUnitsRepo.getByIds(huIdsChunk).stream());
}
protected final void addHUIdsAndInvalidateView(Collection<HuId> huIds)
{
if (huIds.isEmpty())
{
return;
}
getView().addHUIdsAndInvalidate(huIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorProcessTemplate.java
| 1
|
请完成以下Java代码
|
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public void setCostAmount (final BigDecimal CostAmount)
{
set_Value (COLUMNNAME_CostAmount, CostAmount);
}
@Override
public BigDecimal getCostAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setCostAmountReceived (final BigDecimal CostAmountReceived)
{
set_Value (COLUMNNAME_CostAmountReceived, CostAmountReceived);
}
@Override
public BigDecimal getCostAmountReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmountReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setLineNetAmt (final BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt);
}
@Override
public BigDecimal getLineNetAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReceived (final BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
@Override
public BigDecimal getQtyReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getLegacyItemId()
{
return legacyItemId;
}
public void setLegacyItemId(String legacyItemId)
{
this.legacyItemId = legacyItemId;
}
public LegacyReference legacyTransactionId(String legacyTransactionId)
{
this.legacyTransactionId = legacyTransactionId;
return this;
}
/**
* The unique identifier of a sale/transaction in legacy/Trading API format. A 'transaction ID' is created once a buyer purchases a 'Buy It Now' item or if an auction listing ends with a winning bidder. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.
*
* @return legacyTransactionId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of a sale/transaction in legacy/Trading API format. A 'transaction ID' is created once a buyer purchases a 'Buy It Now' item or if an auction listing ends with a winning bidder. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.")
public String getLegacyTransactionId()
{
return legacyTransactionId;
}
public void setLegacyTransactionId(String legacyTransactionId)
{
this.legacyTransactionId = legacyTransactionId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
|
{
return false;
}
LegacyReference legacyReference = (LegacyReference)o;
return Objects.equals(this.legacyItemId, legacyReference.legacyItemId) &&
Objects.equals(this.legacyTransactionId, legacyReference.legacyTransactionId);
}
@Override
public int hashCode()
{
return Objects.hash(legacyItemId, legacyTransactionId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LegacyReference {\n");
sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n");
sb.append(" legacyTransactionId: ").append(toIndentedString(legacyTransactionId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LegacyReference.java
| 2
|
请完成以下Java代码
|
public final class WidgetsBundleEntity extends BaseVersionedEntity<WidgetsBundle> {
@Column(name = ModelConstants.WIDGETS_BUNDLE_TENANT_ID_PROPERTY)
private UUID tenantId;
@Column(name = ModelConstants.WIDGETS_BUNDLE_ALIAS_PROPERTY)
private String alias;
@Column(name = ModelConstants.WIDGETS_BUNDLE_TITLE_PROPERTY)
private String title;
@Column(name = ModelConstants.WIDGETS_BUNDLE_IMAGE_PROPERTY)
private String image;
@Column(name = ModelConstants.WIDGETS_BUNDLE_SCADA_PROPERTY)
private boolean scada;
@Column(name = ModelConstants.WIDGETS_BUNDLE_DESCRIPTION)
private String description;
@Column(name = ModelConstants.WIDGETS_BUNDLE_ORDER)
private Integer order;
@Column(name = ModelConstants.EXTERNAL_ID_PROPERTY)
private UUID externalId;
public WidgetsBundleEntity() {
super();
}
public WidgetsBundleEntity(WidgetsBundle widgetsBundle) {
super(widgetsBundle);
if (widgetsBundle.getTenantId() != null) {
this.tenantId = widgetsBundle.getTenantId().getId();
}
this.alias = widgetsBundle.getAlias();
this.title = widgetsBundle.getTitle();
this.image = widgetsBundle.getImage();
this.scada = widgetsBundle.isScada();
this.description = widgetsBundle.getDescription();
this.order = widgetsBundle.getOrder();
if (widgetsBundle.getExternalId() != null) {
this.externalId = widgetsBundle.getExternalId().getId();
}
|
}
@Override
public WidgetsBundle toData() {
WidgetsBundle widgetsBundle = new WidgetsBundle(new WidgetsBundleId(id));
widgetsBundle.setCreatedTime(createdTime);
widgetsBundle.setVersion(version);
if (tenantId != null) {
widgetsBundle.setTenantId(TenantId.fromUUID(tenantId));
}
widgetsBundle.setAlias(alias);
widgetsBundle.setTitle(title);
widgetsBundle.setImage(image);
widgetsBundle.setScada(scada);
widgetsBundle.setDescription(description);
widgetsBundle.setOrder(order);
if (externalId != null) {
widgetsBundle.setExternalId(new WidgetsBundleId(externalId));
}
return widgetsBundle;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\WidgetsBundleEntity.java
| 1
|
请完成以下Java代码
|
public class MybatisSentryPartInstanceDataManagerImpl extends AbstractCmmnDataManager<SentryPartInstanceEntity> implements SentryPartInstanceDataManager {
protected SentryPartByCaseInstanceIdEntityMatcher sentryPartByCaseInstanceIdEntityMatched
= new SentryPartByCaseInstanceIdEntityMatcher();
protected SentryPartByPlanItemInstanceIdEntityMatcher sentryPartByPlanItemInstanceIdEntityMatched
= new SentryPartByPlanItemInstanceIdEntityMatcher();
public MybatisSentryPartInstanceDataManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration) {
super(cmmnEngineConfiguration);
}
@Override
public Class<? extends SentryPartInstanceEntity> getManagedEntityClass() {
return SentryPartInstanceEntityImpl.class;
}
@Override
public SentryPartInstanceEntity create() {
return new SentryPartInstanceEntityImpl();
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceId(String caseInstanceId) {
return getList("selectSentryPartInstanceByCaseInstanceId", caseInstanceId, sentryPartByCaseInstanceIdEntityMatched);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(String caseInstanceId) {
return getList("selectSentryPartInstanceByCaseInstanceIdAndNullPlanItemInstanceId", caseInstanceId);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByPlanItemInstanceId(String planItemInstanceId) {
return getList("selectSentryPartInstanceByPlanItemInstanceId", planItemInstanceId, sentryPartByPlanItemInstanceIdEntityMatched);
}
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
bulkDelete("deleteSentryPartInstancesByCaseInstanceId", sentryPartByCaseInstanceIdEntityMatched, caseInstanceId);
}
|
public static class SentryPartByCaseInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) {
return sentryPartInstanceEntity.getPlanItemInstanceId() == null
&& sentryPartInstanceEntity.getCaseInstanceId().equals(param);
}
}
public static class SentryPartByPlanItemInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) {
return sentryPartInstanceEntity.getPlanItemInstanceId() != null
&& sentryPartInstanceEntity.getPlanItemInstanceId().equals(param);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisSentryPartInstanceDataManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class Jackson2ResourceConfigCustomizerConfiguration {
@Bean
ResourceConfigCustomizer jacksonResourceConfigCustomizer(
com.fasterxml.jackson.databind.ObjectMapper objectMapper) {
return (ResourceConfig config) -> {
config.register(JacksonFeature.class);
config.register(new ObjectMapperContextResolver(objectMapper), ContextResolver.class);
};
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector.class,
XmlElement.class })
static class JaxbJackson2ObjectMapperCustomizerConfiguration {
@Autowired
void addJaxbAnnotationIntrospector(com.fasterxml.jackson.databind.ObjectMapper objectMapper) {
com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector jaxbAnnotationIntrospector = new com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector(
objectMapper.getTypeFactory());
objectMapper.setAnnotationIntrospectors(
createPair(objectMapper.getSerializationConfig(), jaxbAnnotationIntrospector),
createPair(objectMapper.getDeserializationConfig(), jaxbAnnotationIntrospector));
}
private com.fasterxml.jackson.databind.AnnotationIntrospector createPair(
com.fasterxml.jackson.databind.cfg.MapperConfig<?> config,
com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector jaxbAnnotationIntrospector) {
return com.fasterxml.jackson.databind.AnnotationIntrospector.pair(config.getAnnotationIntrospector(),
jaxbAnnotationIntrospector);
}
}
|
private static final class ObjectMapperContextResolver
implements ContextResolver<com.fasterxml.jackson.databind.ObjectMapper> {
private final com.fasterxml.jackson.databind.ObjectMapper objectMapper;
private ObjectMapperContextResolver(com.fasterxml.jackson.databind.ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public com.fasterxml.jackson.databind.ObjectMapper getContext(Class<?> type) {
return this.objectMapper;
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\JerseyAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void abortAll(@NonNull final UserId responsibleId)
{
final List<DistributionJob> jobs = newLoader().loadByQuery(DistributionJobQueries.ddOrdersAssignedToUser(responsibleId));
if (jobs.isEmpty())
{
return;
}
abort().jobs(jobs).execute();
}
public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@NonNull final JsonGetNextEligiblePickFromLineRequest request, @NonNull final UserId callerId)
{
final DistributionJobId jobId = DistributionJobId.ofWFProcessId(request.getWfProcessId());
final DistributionJob job = getJobById(jobId);
job.assertCanEdit(callerId);
final HUQRCode huQRCode = huService.resolveHUQRCode(request.getHuQRCode());
final ProductId productId;
if (request.getProductScannedCode() != null)
{
productId = productService.getProductIdByScannedProductCode(request.getProductScannedCode());
huService.assetHUContainsProduct(huQRCode, productId);
}
else
{
productId = huService.getSingleProductId(huQRCode);
}
final DistributionJobLineId nextEligiblePickFromLineId;
if (request.getLineId() != null)
|
{
final DistributionJobLine line = job.getLineById(request.getLineId());
nextEligiblePickFromLineId = line.isEligibleForPicking() ? line.getId() : null;
}
else
{
nextEligiblePickFromLineId = job.getNextEligiblePickFromLineId(productId).orElse(null);
}
return JsonGetNextEligiblePickFromLineResponse.builder()
.lineId(nextEligiblePickFromLineId)
.build();
}
public void printMaterialInTransitReport(
@NonNull final UserId userId,
@NonNull final String adLanguage)
{
@NonNull final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId)
.map(LocatorQRCode::getLocatorId)
.orElseThrow(() -> new AdempiereException("No trolley found for user: " + userId));
ddOrderMoveScheduleService.printMaterialInTransitReport(inTransitLocatorId, adLanguage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionRestService.java
| 2
|
请完成以下Java代码
|
public String getSuggest() {
return suggest;
}
public void setSuggest(String suggest) {
this.suggest = suggest;
}
public Integer getBusinessSystemId() {
return businessSystemId;
}
public void setBusinessSystemId(Integer businessSystemId) {
this.businessSystemId = businessSystemId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOccurCount() {
return occurCount;
}
public void setOccurCount(Integer occurCount) {
this.occurCount = occurCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getResponsedTime() {
return responsedTime;
}
public void setResponsedTime(Date responsedTime) {
this.responsedTime = responsedTime;
}
public String getResponsedBy() {
return responsedBy;
}
public void setResponsedBy(String responsedBy) {
this.responsedBy = responsedBy;
}
public Date getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(Date resolvedTime) {
this.resolvedTime = resolvedTime;
}
public String getResolvedBy() {
return resolvedBy;
}
public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
}
public Date getClosedTime() {
|
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
}
|
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomsInvoiceLineId implements RepoIdAware
{
int repoId;
@NonNull
CustomsInvoiceId customsInvoiceId;
public static CustomsInvoiceLineId ofRepoId(@NonNull final CustomsInvoiceId customsInvoiceId, final int customsInvoiceLineid)
{
return new CustomsInvoiceLineId(customsInvoiceId, customsInvoiceLineid);
}
public static CustomsInvoiceLineId ofRepoId(final int customsInvoiceId, final int customsInvoiceLineId)
{
return new CustomsInvoiceLineId(CustomsInvoiceId.ofRepoId(customsInvoiceId), customsInvoiceLineId);
|
}
public static CustomsInvoiceLineId ofRepoIdOrNull(
@Nullable final CustomsInvoiceId customsInvoiceId,
final int customsInvoiceLineId)
{
return customsInvoiceId != null && customsInvoiceLineId > 0 ? ofRepoId(customsInvoiceId, customsInvoiceLineId) : null;
}
private CustomsInvoiceLineId(@NonNull final CustomsInvoiceId customsInvoiceId, final int customsInvoiceLineId)
{
this.repoId = Check.assumeGreaterThanZero(customsInvoiceLineId, "shipmentDeclarationLineId");
this.customsInvoiceId = customsInvoiceId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoiceLineId.java
| 2
|
请完成以下Java代码
|
public class RelyingPartyAuthenticationRequest implements Serializable {
@Serial
private static final long serialVersionUID = -928083091875202086L;
private final PublicKeyCredentialRequestOptions requestOptions;
private final PublicKeyCredential<AuthenticatorAssertionResponse> publicKey;
/**
* Creates a new instance.
* @param requestOptions the {@link PublicKeyCredentialRequestOptions}
* @param publicKey the {@link PublicKeyCredential}
*/
public RelyingPartyAuthenticationRequest(PublicKeyCredentialRequestOptions requestOptions,
PublicKeyCredential<AuthenticatorAssertionResponse> publicKey) {
Assert.notNull(requestOptions, "requestOptions cannot be null");
Assert.notNull(publicKey, "publicKey cannot be null");
this.requestOptions = requestOptions;
this.publicKey = publicKey;
}
/**
|
* Ges the request options.
* @return the request options.
*/
public PublicKeyCredentialRequestOptions getRequestOptions() {
return this.requestOptions;
}
/**
* Gets the public key.
* @return the public key.
*/
public PublicKeyCredential<AuthenticatorAssertionResponse> getPublicKey() {
return this.publicKey;
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\RelyingPartyAuthenticationRequest.java
| 1
|
请完成以下Java代码
|
public boolean isAcceptable()
{
return this.depth > 0 && this.emits != null;
}
/**
* 获取failure状态
* @return
*/
public State failure()
{
return this.failure;
}
/**
* 设置failure状态
* @param failState
*/
public void setFailure(State failState, int fail[])
{
this.failure = failState;
fail[index] = failState.index;
}
/**
* 转移到下一个状态
* @param character 希望按此字符转移
* @param ignoreRootState 是否忽略根节点,如果是根节点自己调用则应该是true,否则为false
* @return 转移结果
*/
private State nextState(Character character, boolean ignoreRootState)
{
State nextState = this.success.get(character);
if (!ignoreRootState && nextState == null && this.depth == 0)
{
nextState = this;
}
return nextState;
}
/**
* 按照character转移,根节点转移失败会返回自己(永远不会返回null)
* @param character
* @return
*/
public State nextState(Character character)
{
return nextState(character, false);
}
/**
* 按照character转移,任何节点转移失败会返回null
* @param character
* @return
*/
public State nextStateIgnoreRootState(Character character)
{
|
return nextState(character, true);
}
public State addState(Character character)
{
State nextState = nextStateIgnoreRootState(character);
if (nextState == null)
{
nextState = new State(this.depth + 1);
this.success.put(character, nextState);
}
return nextState;
}
public Collection<State> getStates()
{
return this.success.values();
}
public Collection<Character> getTransitions()
{
return this.success.keySet();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("State{");
sb.append("depth=").append(depth);
sb.append(", ID=").append(index);
sb.append(", emits=").append(emits);
sb.append(", success=").append(success.keySet());
sb.append(", failureID=").append(failure == null ? "-1" : failure.index);
sb.append(", failure=").append(failure);
sb.append('}');
return sb.toString();
}
/**
* 获取goto表
* @return
*/
public Map<Character, State> getSuccess()
{
return success;
}
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index = index;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\AhoCorasick\State.java
| 1
|
请完成以下Java代码
|
private void updateShipmentScheduleFromSubscriptionLine(
@NonNull final I_M_ShipmentSchedule shipmentSchedule,
@NonNull final I_C_SubscriptionProgress subscriptionLine)
{
final int tableId = InterfaceWrapperHelper.getTableId(I_C_SubscriptionProgress.class);
shipmentSchedule.setAD_Table_ID(tableId);
shipmentSchedule.setRecord_ID(subscriptionLine.getC_SubscriptionProgress_ID());
final I_C_Flatrate_Term term = subscriptionLine.getC_Flatrate_Term();
Check.assume(term.getM_Product_ID() > 0, term + " has M_Product_ID>0");
shipmentSchedule.setM_Product_ID(term.getM_Product_ID());
Services.get(IAttributeSetInstanceBL.class).cloneASI(term, shipmentSchedule);
shipmentSchedule.setProductDescription(null);
updateNewSchedWithValuesFromReferencedLine(shipmentSchedule);
final I_C_DocType doctypeForTerm = Services.get(IFlatrateBL.class).getDocTypeFor(term);
shipmentSchedule.setC_DocType_ID(doctypeForTerm.getC_DocType_ID());
shipmentSchedule.setDocSubType(doctypeForTerm.getDocSubType());
shipmentSchedule.setPriorityRule(X_M_ShipmentSchedule.PRIORITYRULE_High);
ShipmentScheduleDocumentLocationAdapterFactory
.mainLocationAdapter(shipmentSchedule)
.setFrom(ContractLocationHelper.extractDropShipLocation(subscriptionLine));
ShipmentScheduleDocumentLocationAdapterFactory
.billLocationAdapter(shipmentSchedule)
.setFrom(ContractLocationHelper.extractBillLocation(term));
// commented out because there is no BPartnerAddress field nor BillToAddress field
// final IDocumentLocation documentLocation = InterfaceWrapperHelper.create(shipmentSchedule, IDocumentLocation.class);
// documentLocationBL.updateRenderedAddressAndCapturedLocation(documentLocation);
shipmentSchedule.setDeliveryRule(term.getDeliveryRule());
shipmentSchedule.setDeliveryViaRule(term.getDeliveryViaRule());
|
shipmentSchedule.setQtyOrdered(subscriptionLine.getQty());
shipmentSchedule.setQtyOrdered_Calculated(subscriptionLine.getQty());
shipmentSchedule.setQtyReserved(subscriptionLine.getQty());
shipmentSchedule.setLineNetAmt(shipmentSchedule.getQtyReserved().multiply(term.getPriceActual()));
shipmentSchedule.setDateOrdered(subscriptionLine.getEventDate());
shipmentSchedule.setAD_Org_ID(subscriptionLine.getAD_Org_ID());
Check.assume(shipmentSchedule.getAD_Client_ID() == subscriptionLine.getAD_Client_ID(),
"The new M_ShipmentSchedule has the same AD_Client_ID as " + subscriptionLine + ", i.e." + shipmentSchedule.getAD_Client_ID() + " == " + subscriptionLine.getAD_Client_ID());
// only display item products
// note: at least for C_Subscription_Progress records, we won't even create records for non-items
final boolean display = Services.get(IProductBL.class).getProductType(ProductId.ofRepoId(term.getM_Product_ID())).isItem();
shipmentSchedule.setIsDisplayed(display);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\inoutcandidate\SubscriptionShipmentScheduleHandler.java
| 1
|
请完成以下Java代码
|
public Response doLogout(@PathParam("processEngineName") String engineName) {
final Authentications authentications = Authentications.getCurrent();
ProcessEngine processEngine = ProcessEngineUtil.lookupProcessEngine(engineName);
if(processEngine == null) {
throw LOGGER.invalidRequestEngineNotFoundForName(engineName);
}
// remove authentication for process engine
if(authentications != null) {
UserAuthentication removedAuthentication = authentications.removeByEngineName(engineName);
if(isWebappsAuthenticationLoggingEnabled(processEngine) && removedAuthentication != null) {
LOGGER.infoWebappLogout(removedAuthentication.getName());
}
}
return Response.ok().build();
}
|
protected Response unauthorized() {
return Response.status(Status.UNAUTHORIZED).build();
}
protected Response forbidden() {
return Response.status(Status.FORBIDDEN).build();
}
protected Response notFound() {
return Response.status(Status.NOT_FOUND).build();
}
private boolean isWebappsAuthenticationLoggingEnabled(ProcessEngine processEngine) {
return ((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).isWebappsAuthenticationLoggingEnabled();
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\UserAuthenticationResource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DomesticAmountType getDomesticAmount() {
return domesticAmount;
}
/**
* Sets the value of the domesticAmount property.
*
* @param value
* allowed object is
* {@link DomesticAmountType }
*
*/
public void setDomesticAmount(DomesticAmountType value) {
this.domesticAmount = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Amount for calculation the document's commission amount.
*
|
* @return
* possible object is
* {@link MonetaryAmountType }
*
*/
public MonetaryAmountType getCommissionBaseAmount() {
return commissionBaseAmount;
}
/**
* Sets the value of the commissionBaseAmount property.
*
* @param value
* allowed object is
* {@link MonetaryAmountType }
*
*/
public void setCommissionBaseAmount(MonetaryAmountType value) {
this.commissionBaseAmount = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ItemType.java
| 2
|
请完成以下Java代码
|
class GlassPane extends JComponent
{
private static final long serialVersionUID = -4416920279272513L;
GlassPane()
{
addMouseListener(new MouseAdapter()
{
});
addKeyListener(new KeyAdapter()
{
});
addFocusListener(new FocusAdapter()
{
});
}
}
/**
* A custom panel, only repaint when look and feel or theme changed.
* @author Low Heng Sin
*/
class PreviewPanel extends CPanel
{
/**
*
*/
private static final long serialVersionUID = 6028614986952449622L;
private boolean capture = true;
private LookAndFeel laf = null;
private MetalTheme theme = null;
private BufferedImage image;
@Override
public void paint(Graphics g)
{
if (capture) {
//capture preview image
image = (BufferedImage)createImage(this.getWidth(),this.getHeight());
super.paint(image.createGraphics());
g.drawImage(image, 0, 0, null);
|
capture = false;
if (laf != null)
{
//reset to original setting
if (laf instanceof MetalLookAndFeel)
AdempierePLAF.setCurrentMetalTheme((MetalLookAndFeel)laf, theme);
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
}
laf = null;
theme = null;
}
} else {
//draw captured preview image
if (image != null)
g.drawImage(image, 0, 0, null);
}
}
/**
* Refresh look and feel preview, reset to original setting after
* refresh.
* @param currentLaf Current Look and feel
* @param currentTheme Current Theme
*/
void refresh(LookAndFeel currentLaf, MetalTheme currentTheme)
{
this.laf = currentLaf;
this.theme = currentTheme;
capture = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\PLAFEditorPanel.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@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 setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem.java
| 1
|
请完成以下Java代码
|
private void assertAssigneeIsACandidateUser(String taskId, String assignee) {
List<String> userCandidates = userCandidates(taskId);
if (!userCandidates.contains(assignee)) {
throw new IllegalStateException(
"You cannot assign a task to " + assignee + " due it is not a candidate for it"
);
}
}
private void reassignTask(String taskId, String assignee) {
releaseTask(taskId);
taskService.claim(taskId, assignee);
}
private void releaseTask(String taskId) {
|
assertCanReleaseTask(taskId);
taskService.unclaim(taskId);
}
private void assertCanReleaseTask(String taskId) {
Task task = task(taskId);
if (task.getAssignee() == null || task.getAssignee().isEmpty()) {
throw new IllegalStateException("You cannot release a task that is not claimed");
}
String authenticatedUserId = securityManager.getAuthenticatedUserId();
if (!task.getAssignee().equals(authenticatedUserId)) {
throw new IllegalStateException("You cannot release a task where you are not the assignee");
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskRuntimeImpl.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=541435
* Reference name: DD_OrderLine_Schedule_Status
*/
public static final int STATUS_AD_Reference_ID=541435;
/** NotStarted = NS */
public static final String STATUS_NotStarted = "NS";
/** InProgress = IP */
|
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
| 1
|
请完成以下Java代码
|
private void validateExternalRequestHeaders(@NonNull final HttpHeadersWrapper requestHeaders)
{
final Integer pInstanceId = extractExternalRequestHeader(requestHeaders, HEADER_PINSTANCE_ID).orElse(null);
if (pInstanceId != null && pInstanceDAO.getByIdOrNull(PInstanceId.ofRepoId(pInstanceId)) == null)
{
throw new AdempiereException("No AD_PInstance record found for '" + HEADER_PINSTANCE_ID + "':" + pInstanceId);
}
final Integer externalSystemConfigId = extractExternalRequestHeader(requestHeaders, HEADER_EXTERNALSYSTEM_CONFIG_ID).orElse(null);
// TableRecordReference is used here in order to avoid circular dependencies that would emerge from using I_ExternalSystem_Config and it's repository
if (externalSystemConfigId != null && TableRecordReference.of("ExternalSystem_Config", externalSystemConfigId).getModel() == null)
{
throw new AdempiereException("No IExternalSystemChildConfigId record found for '" + HEADER_EXTERNALSYSTEM_CONFIG_ID + "':" + externalSystemConfigId);
}
}
@Value
@Builder
|
private static class FutureCompletionContext
{
@NonNull
ApiAuditLoggable apiAuditLoggable;
@NonNull
ApiRequestAudit apiRequestAudit;
@NonNull
OrgId orgId;
@NonNull
ApiAuditConfig apiAuditConfig;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ApiAuditService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringSecurityConfig {
@Autowired
private WebApplicationContext applicationContext;
@Autowired
private AuthenticationSuccessHandlerImpl successHandler;
@Autowired
private DataSource dataSource;
private CustomUserDetailsService userDetailsService;
@PostConstruct
public void completeSetup() {
userDetailsService = applicationContext.getBean(CustomUserDetailsService.class);
}
@Bean
public UserDetailsManager users(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(encoder());
authenticationManagerBuilder.authenticationProvider(authenticationProvider());
AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.setAuthenticationManager(authenticationManager);
return jdbcUserDetailsManager;
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().requestMatchers("/resources/**");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.requestMatchers("/login").permitAll())
.formLogin(httpSecurityFormLoginConfigurer ->
|
httpSecurityFormLoginConfigurer.permitAll().successHandler(successHandler))
.csrf(AbstractHttpConfigurer::disable);
return http.build();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(11);
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\SpringSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void persistAuthors() {
List<Author> authors = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
Author author = new Author();
author.setName("Name_" + i);
author.setGenre("Genre_" + i);
author.setAge(18 + i);
|
authors.add(author);
}
authorRepository.saveAll(authors);
}
@Transactional
public void updateAuthors() {
List<Author> authors = authorRepository.findAll();
authors.forEach(a -> a.setAge(a.getAge() + 1));
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchUpdateOrderSingleEntity\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderProductPK other = (OrderProductPK) obj;
if (order == null) {
if (other.order != null) {
return false;
}
|
} else if (!order.equals(other.order)) {
return false;
}
if (product == null) {
if (other.product != null) {
return false;
}
} else if (!product.equals(other.product)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\OrderProductPK.java
| 1
|
请完成以下Java代码
|
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
|
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getTime() {
return getStartTime();
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return (
"HistoricActivityInstanceEntity[id=" +
id +
", activityId=" +
activityId +
", activityName=" +
activityName +
"]"
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public @Nullable String getAccess() {
return this.access;
}
public void setAccess(String access) {
this.access = access;
}
public @Nullable String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public @Nullable String getMethod() {
return this.method;
}
@NullUnmarked
public void setMethod(String method) {
this.method = (method != null) ? method.toUpperCase(Locale.ENGLISH) : null;
}
private SecurityContext getContext() {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
String[] names = appContext.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = appContext.getBean(SecurityContextHolderStrategy.class);
return strategy.getContext();
}
return SecurityContextHolder.getContext();
}
|
@SuppressWarnings({ "unchecked", "rawtypes" })
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : handlers.values()) {
if (FilterInvocation.class
.equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
}
throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest()
.getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE);
if (privEvaluatorFromRequest != null) {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.isEmpty()) {
throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
}
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
}
|
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTag.java
| 1
|
请完成以下Java代码
|
public static FTPClient connect(String host, int port, String username, String password, String controlEncoding) throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(host, port);
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
ftpClient.login(username, password);
}
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
ftpClient.setControlEncoding(controlEncoding);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
return ftpClient;
}
public static void download(String ftpUrl, String localFilePath, String ftpUsername, String ftpPassword, String ftpControlEncoding) throws IOException {
String username = StringUtils.isEmpty(ftpUsername) ? ConfigConstants.getFtpUsername() : ftpUsername;
String password = StringUtils.isEmpty(ftpPassword) ? ConfigConstants.getFtpPassword() : ftpPassword;
String controlEncoding = StringUtils.isEmpty(ftpControlEncoding) ? ConfigConstants.getFtpControlEncoding() : ftpControlEncoding;
|
URL url = new URL(ftpUrl);
String host = url.getHost();
int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();
String remoteFilePath = url.getPath();
LOGGER.debug("FTP connection url:{}, username:{}, password:{}, controlEncoding:{}, localFilePath:{}", ftpUrl, username, password, controlEncoding, localFilePath);
FTPClient ftpClient = connect(host, port, username, password, controlEncoding);
OutputStream outputStream = Files.newOutputStream(Paths.get(localFilePath));
ftpClient.enterLocalPassiveMode();
boolean downloadResult = ftpClient.retrieveFile(new String(remoteFilePath.getBytes(controlEncoding), StandardCharsets.ISO_8859_1), outputStream);
LOGGER.debug("FTP download result {}", downloadResult);
outputStream.flush();
outputStream.close();
ftpClient.logout();
ftpClient.disconnect();
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\utils\FtpUtils.java
| 1
|
请完成以下Java代码
|
public BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final HuId huId)
{
return checkEligibleToAddAsSourceHUs(ImmutableSet.of(huId));
}
@NonNull
public BooleanWithReason checkEligibleToAddAsSourceHUs(@NonNull final Set<HuId> huIds)
{
final String notEligibleReason = handlingUnitsBL.getByIds(huIds)
.stream()
.map(this::checkEligibleToAddAsSourceHU)
.filter(BooleanWithReason::isFalse)
.map(BooleanWithReason::getReasonAsString)
.collect(Collectors.joining(" | "));
return Check.isBlank(notEligibleReason)
? BooleanWithReason.TRUE
: BooleanWithReason.falseBecause(notEligibleReason);
}
@NonNull
private BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final I_M_HU hu)
{
if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus()))
{
return BooleanWithReason.falseBecause("HU is not active");
}
if (!handlingUnitsBL.isTopLevel(hu))
{
return BooleanWithReason.falseBecause("HU is not top level");
}
return BooleanWithReason.TRUE;
}
|
public BooleanWithReason checkEligibleToAddToManufacturingOrder(@NonNull final PPOrderId ppOrderId)
{
final I_PP_Order ppOrder = ppOrderBL.getById(ppOrderId);
final DocStatus ppOrderDocStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus());
if (!ppOrderDocStatus.isCompleted())
{
return BooleanWithReason.falseBecause(MSG_ManufacturingOrderNotCompleted, ppOrder.getDocumentNo());
}
if (ppOrderIssueScheduleService.matchesByOrderId(ppOrderId))
{
return BooleanWithReason.falseBecause(MSG_ManufacturingJobAlreadyStarted, ppOrder.getDocumentNo());
}
return BooleanWithReason.TRUE;
}
@NonNull
public ImmutableSet<HuId> getSourceHUIds(@NonNull final PPOrderId ppOrderId)
{
return ppOrderSourceHURepository.getSourceHUIds(ppOrderId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHUService.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public List<Post> getPosts() {
return this.posts;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
|
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", posts=" + this.getPosts()
+ ")";
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ResourceQRCode
{
@NonNull ResourceId resourceId;
@Nullable String resourceType;
@NonNull String caption;
public static boolean equals(@Nullable final ResourceQRCode o1, @Nullable final ResourceQRCode o2)
{
return Objects.equals(o1, o2);
}
public String toGlobalQRCodeJsonString() {return ResourceQRCodeJsonConverter.toGlobalQRCodeJsonString(this);}
public static ResourceQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return ResourceQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);}
public static ResourceQRCode ofGlobalQRCodeJsonString(final String qrCodeString)
{
return ResourceQRCodeJsonConverter.fromGlobalQRCodeJsonString(qrCodeString);
}
public static ResourceQRCode ofResource(@NonNull final I_S_Resource record)
{
return ResourceQRCode.builder()
|
.resourceId(ResourceId.ofRepoId(record.getS_Resource_ID()))
.resourceType(record.getManufacturingResourceType())
.caption(record.getName())
.build();
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString())
.bottomText(caption)
.build();
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return ResourceQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\qrcode\ResourceQRCode.java
| 2
|
请完成以下Java代码
|
public boolean solve(int[][] board) {
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
if (board[row][column] == NO_VALUE) {
for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
board[row][column] = k;
if (isValid(board, row, column) && solve(board)) {
return true;
}
board[row][column] = NO_VALUE;
}
return false;
}
}
}
return true;
}
private boolean isValid(int[][] board, int row, int column) {
return rowConstraint(board, row) &&
columnConstraint(board, column) &&
subsectionConstraint(board, row, column);
}
private boolean subsectionConstraint(int[][] board, int row, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
if (!checkConstraint(board, r, constraint, c)) return false;
}
}
return true;
}
private boolean columnConstraint(int[][] board, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
if (!checkConstraint(board, row, constraint, column)) {
return false;
}
|
}
return true;
}
private boolean rowConstraint(int[][] board, int row) {
boolean[] constraint = new boolean[BOARD_SIZE];
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
if (!checkConstraint(board, row, constraint, column)) {
return false;
}
}
return true;
}
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
if (board[row][column] != NO_VALUE) {
if (!constraint[board[row][column] - 1]) {
constraint[board[row][column] - 1] = true;
} else {
return false;
}
}
return true;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\BacktrackingAlgorithm.java
| 1
|
请完成以下Java代码
|
public void actionPerformed (ActionEvent e)
{
JFileChooser fc = new JFileChooser("");
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int option = 0;
boolean save = m_data != null;
if (save)
option = fc.showSaveDialog(this);
else
option = fc.showOpenDialog(this);
if (option != JFileChooser.APPROVE_OPTION)
return;
File file = fc.getSelectedFile();
if (file == null)
return;
//
log.info(file.toString());
try
{
if (save)
{
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = (byte[])m_data;
os.write(buffer);
os.flush();
os.close();
log.info("Save to " + file + " #" + buffer.length);
}
else // load
{
FileInputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*8]; // 8kB
int length = -1;
while ((length = is.read(buffer)) != -1)
os.write(buffer, 0, length);
is.close();
byte[] data = os.toByteArray();
m_data = data;
log.info("Load from " + file + " #" + data.length);
os.close();
}
}
catch (Exception ex)
{
log.warn("Save=" + save, ex);
}
|
try
{
fireVetoableChange(m_columnName, null, m_data);
}
catch (PropertyVetoException pve) {}
} // actionPerformed
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VBinary
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VBinary.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.