instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>> implements SecurityConfigurer<O, B> {
private B securityBuilder;
private CompositeObjectPostProcessor objectPostProcessor = new CompositeObjectPostProcessor();
@Override
public void init(B builder) {
}
@Override
public void configure(B builder) {
}
/**
* Gets the {@link SecurityBuilder}. Cannot be null.
* @return the {@link SecurityBuilder}
* @throws IllegalStateException if {@link SecurityBuilder} is null
*/
protected final B getBuilder() {
Assert.state(this.securityBuilder != null, "securityBuilder cannot be null");
return this.securityBuilder;
}
/**
* Performs post processing of an object. The default is to delegate to the
* {@link ObjectPostProcessor}.
* @param object the Object to post process
* @return the possibly modified Object to use
*/
@SuppressWarnings("unchecked")
protected <T> T postProcess(T object) {
return (T) this.objectPostProcessor.postProcess(object);
}
/**
* Adds an {@link ObjectPostProcessor} to be used for this
* {@link SecurityConfigurerAdapter}. The default implementation does nothing to the
* object.
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
*/
public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#with(SecurityConfigurerAdapter, Customizer)}
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
/**
* An {@link ObjectPostProcessor} that delegates work to numerous
* {@link ObjectPostProcessor} implementations.
*
* @author Rob Winch | */
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors = new ArrayList<>();
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) {
for (ObjectPostProcessor opp : this.postProcessors) {
Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
}
return object;
}
/**
* Adds an {@link ObjectPostProcessor} to use
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\SecurityConfigurerAdapter.java | 2 |
请完成以下Java代码 | public void setC_Letter_ID (int C_Letter_ID)
{
if (C_Letter_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Letter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Letter_ID, Integer.valueOf(C_Letter_ID));
}
/** Get Letter.
@return Letter */
@Override
public int getC_Letter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Letter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zu druckende Mitgliederausweise.
@param IsMembershipBadgeToPrint Zu druckende Mitgliederausweise */
@Override
public void setIsMembershipBadgeToPrint (boolean IsMembershipBadgeToPrint)
{
set_Value (COLUMNNAME_IsMembershipBadgeToPrint, Boolean.valueOf(IsMembershipBadgeToPrint));
}
/** Get Zu druckende Mitgliederausweise.
@return Zu druckende Mitgliederausweise */
@Override
public boolean isMembershipBadgeToPrint ()
{
Object oo = get_Value(COLUMNNAME_IsMembershipBadgeToPrint);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Body.
@param LetterBody Body */
@Override
public void setLetterBody (java.lang.String LetterBody)
{
set_Value (COLUMNNAME_LetterBody, LetterBody);
}
/** Get Body.
@return Body */
@Override
public java.lang.String getLetterBody ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBody);
}
/** Set Body (parsed).
@param LetterBodyParsed Body (parsed) */
@Override
public void setLetterBodyParsed (java.lang.String LetterBodyParsed)
{
set_Value (COLUMNNAME_LetterBodyParsed, LetterBodyParsed);
}
/** Get Body (parsed). | @return Body (parsed) */
@Override
public java.lang.String getLetterBodyParsed ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBodyParsed);
}
/** Set Subject.
@param LetterSubject Subject */
@Override
public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java | 1 |
请完成以下Java代码 | public String toString()
{
return "ProductionMaterial ["
+ "product=" + product.getName()
+ ", qty=" + qty
+ ", uom=" + uom.getUOMSymbol()
+ "]";
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(product)
.append(qty)
.append(uom)
.toHashcode();
};
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final InvoicingItem other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(product, other.product)
.append(qty, other.qty)
.append(uom, other.uom)
.isEqual();
} | @Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicingItem.java | 1 |
请完成以下Java代码 | public void clearCurrentWindow()
{
this.currentWindowId = null;
this._currentWindowName = null;
}
@Nullable
public String getCurrentWindowName()
{
if (this._currentWindowName == null && this.currentWindowId != null)
{
this._currentWindowName = adWindowDAO.retrieveWindowName(currentWindowId).translate(adLanguage);
}
return this._currentWindowName;
}
public void collectError(@NonNull final String errorMessage)
{
errors.add(JsonWindowsHealthCheckResponse.Entry.builder() | .windowId(WindowId.of(currentWindowId))
.windowName(getCurrentWindowName())
.errorMessage(errorMessage)
.build());
}
public void collectError(@NonNull final Throwable exception)
{
errors.add(JsonWindowsHealthCheckResponse.Entry.builder()
.windowId(WindowId.of(currentWindowId))
.windowName(getCurrentWindowName())
.error(JsonErrors.ofThrowable(exception, adLanguage))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ErrorsCollector.java | 1 |
请完成以下Java代码 | public void setC_DocLine_Sort_Item_ID (int C_DocLine_Sort_Item_ID)
{
if (C_DocLine_Sort_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_Item_ID, Integer.valueOf(C_DocLine_Sort_Item_ID));
}
/** Get Document Line Sorting Preferences Item.
@return Document Line Sorting Preferences Item */
@Override
public int getC_DocLine_Sort_Item_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_Item_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocLine_Sort_Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void putProcessInfoParameter(final ProcessInfoParameter processParam)
{
if (processParam == null)
{
return;
}
// NOTE: just to be on the safe side, for each process info parameter we are setting the ParameterName even if it's a range parameter
final Object parameterValue = normalizeParameterValue(processParam.getParameter());
put(processParam.getParameterName(), parameterValue);
// If we are dealing with a range parameter we are setting ParameterName1 and ParameterName2 too.
final Object parameterValueTo = normalizeParameterValue(processParam.getParameter_To());
if (parameterValueTo != null)
{
put(processParam.getParameterName() + "1", parameterValue);
put(processParam.getParameterName() + "2", parameterValueTo);
}
}
private static Object normalizeParameterValue(final Object value)
{
if (TimeUtil.isDateOrTimeObject(value))
{
return TimeUtil.asTimestamp(value);
}
else
{
return value;
}
}
public void putPInstanceId(final PInstanceId pinstanceId)
{
map.put(PARAM_AD_PINSTANCE_ID, PInstanceId.toRepoId(pinstanceId));
}
public void putOutputType(final OutputType outputType)
{
put(PARAM_OUTPUTTYPE, outputType);
}
/**
* Gets desired output type
*
* @return {@link OutputType}; never returns null
*/
public OutputType getOutputTypeEffective()
{
final Object outputTypeObj = get(PARAM_OUTPUTTYPE);
if (outputTypeObj instanceof OutputType)
{
return (OutputType)outputTypeObj;
}
else if (outputTypeObj instanceof String)
{
return OutputType.valueOf(outputTypeObj.toString());
}
else
{
return OutputType.JasperPrint;
}
}
public void putReportLanguage(String adLanguage)
{
put(PARAM_REPORT_LANGUAGE, adLanguage);
}
/**
* Extracts {@link Language} parameter
*
* @return {@link Language}; never returns null
*/
public Language getReportLanguageEffective()
{
final Object languageObj = get(PARAM_REPORT_LANGUAGE); | Language currLang = null;
if (languageObj instanceof String)
{
currLang = Language.getLanguage((String)languageObj);
}
else if (languageObj instanceof Language)
{
currLang = (Language)languageObj;
}
if (currLang == null)
{
currLang = Env.getLanguage(Env.getCtx());
}
return currLang;
}
public void putLocale(@Nullable final Locale locale)
{
put(JRParameter.REPORT_LOCALE, locale);
}
@Nullable
public Locale getLocale()
{
return (Locale)get(JRParameter.REPORT_LOCALE);
}
public void putRecordId(final int recordId)
{
put(PARAM_RECORD_ID, recordId);
}
public void putTableId(final int tableId)
{
put(PARAM_AD_Table_ID, tableId);
}
public void putBarcodeURL(final String barcodeURL)
{
put(PARAM_BARCODE_URL, barcodeURL);
}
@Nullable
public String getBarcodeUrl()
{
final Object barcodeUrl = get(PARAM_BARCODE_URL);
return barcodeUrl != null ? barcodeUrl.toString() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class X_S_GithubConfig extends org.compiere.model.PO implements I_S_GithubConfig, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 835160211L;
/** Standard Constructor */
public X_S_GithubConfig (final Properties ctx, final int S_GithubConfig_ID, @Nullable final String trxName)
{
super (ctx, S_GithubConfig_ID, trxName);
}
/** Load Constructor */
public X_S_GithubConfig (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setConfig (final java.lang.String Config)
{
set_Value (COLUMNNAME_Config, Config);
}
@Override
public java.lang.String getConfig()
{
return get_ValueAsString(COLUMNNAME_Config);
}
@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 setS_GithubConfig_ID (final int S_GithubConfig_ID)
{
if (S_GithubConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, S_GithubConfig_ID);
}
@Override
public int getS_GithubConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_S_GithubConfig_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_GithubConfig.java | 2 |
请完成以下Java代码 | public class C_BPartner_SyncTo_GRS_HTTP extends C_BPartner_SyncTo_ExternalSystem
{
private final ExportBPartnerToGRSService exportToGRSService = SpringContextHolder.instance.getBean(ExportBPartnerToGRSService.class);
private static final String PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID = I_ExternalSystem_Config_GRSSignum.COLUMNNAME_ExternalSystem_Config_GRSSignum_ID;
@Param(parameterName = PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID)
private int externalSystemConfigGRSSignumId;
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.GRSSignum;
}
@Override
protected IExternalSystemChildConfigId getExternalSystemChildConfigId()
{ | return ExternalSystemGRSSignumConfigId.ofRepoId(externalSystemConfigGRSSignumId);
}
@Override
protected String getExternalSystemParam()
{
return PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID;
}
@Override
protected ExportToExternalSystemService getExportToBPartnerExternalSystem()
{
return exportToGRSService;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\export\bpartner\C_BPartner_SyncTo_GRS_HTTP.java | 1 |
请完成以下Java代码 | class DualPrintStream extends PrintStream {
private final PrintStream second;
public DualPrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
@Override
public void close() {
super.close();
second.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len); | }
@Override
public void write(int b) {
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
@Override
public boolean checkError() {
return super.checkError() && second.checkError();
}
} | repos\tutorials-master\core-java-modules\core-java-io-apis-3\src\main\java\com\baeldung\outputtofile\DualPrintStream.java | 1 |
请完成以下Java代码 | public void setMappingGroupKey (final @Nullable java.lang.String MappingGroupKey)
{
set_Value (COLUMNNAME_MappingGroupKey, MappingGroupKey);
}
@Override
public java.lang.String getMappingGroupKey()
{
return get_ValueAsString(COLUMNNAME_MappingGroupKey);
}
/**
* MappingRule AD_Reference_ID=542000
* Reference name: Mapping Regel
*/
public static final int MAPPINGRULE_AD_Reference_ID=542000;
/** ReceiverCountryCode = ReceiverCountryCode */
public static final String MAPPINGRULE_ReceiverCountryCode = "ReceiverCountryCode";
@Override
public void setMappingRule (final @Nullable java.lang.String MappingRule)
{
set_Value (COLUMNNAME_MappingRule, MappingRule);
}
@Override
public java.lang.String getMappingRule()
{
return get_ValueAsString(COLUMNNAME_MappingRule);
}
@Override
public void setMappingRuleValue (final @Nullable java.lang.String MappingRuleValue)
{
set_Value (COLUMNNAME_MappingRuleValue, MappingRuleValue);
}
@Override
public java.lang.String getMappingRuleValue()
{
return get_ValueAsString(COLUMNNAME_MappingRuleValue);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Shipper_Mapping_Config_ID (final int M_Shipper_Mapping_Config_ID)
{
if (M_Shipper_Mapping_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, M_Shipper_Mapping_Config_ID);
}
@Override
public int getM_Shipper_Mapping_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_Mapping_Config_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_Mapping_Config.java | 1 |
请完成以下Java代码 | private boolean isCompletelyDelivered(final ShipmentScheduleWithHU candidate)
{
final I_M_ShipmentSchedule shipmentSchedule = candidate.getM_ShipmentSchedule();
final BigDecimal qtyOrdered = shipmentScheduleEffectiveValuesBL.computeQtyOrdered(shipmentSchedule);
final BigDecimal qtyToDeliver = shipmentScheduleEffectiveValuesBL.getQtyToDeliverBD(shipmentSchedule);
final BigDecimal qtyDelivered = shipmentSchedule.getQtyDelivered();
final BigDecimal qtyDeliveredProjected = qtyDelivered.add(qtyToDeliver);
return qtyOrdered.compareTo(qtyDeliveredProjected) <= 0;
}
@ToString
private static class Order
{
@Getter
private final OrderId orderId;
private final Set<ShipmentScheduleId> shipmentScheduleIds = new HashSet<>();
@Getter
@Setter
private boolean completeOrderDeliveryRequired; | public Order(@NonNull final OrderId orderId)
{
this.orderId = orderId;
}
public void addShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
shipmentScheduleIds.add(shipmentScheduleId);
}
public Set<ShipmentScheduleId> getMissingShipmentScheduleIds(final Set<ShipmentScheduleId> allShipmentScheduleIds)
{
return Sets.difference(allShipmentScheduleIds, shipmentScheduleIds);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\CompleteOrderDeliveryRuleChecker.java | 1 |
请完成以下Java代码 | public int getAD_WorkflowProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WorkflowProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workflow Processorl Log.
@param AD_WorkflowProcessorLog_ID
Result of the execution of the Workflow Processor
*/
public void setAD_WorkflowProcessorLog_ID (int AD_WorkflowProcessorLog_ID)
{
if (AD_WorkflowProcessorLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WorkflowProcessorLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WorkflowProcessorLog_ID, Integer.valueOf(AD_WorkflowProcessorLog_ID));
}
/** Get Workflow Processorl Log.
@return Result of the execution of the Workflow Processor
*/
public int getAD_WorkflowProcessorLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WorkflowProcessorLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set BinaryData.
@param BinaryData
Binary Data
*/
public void setBinaryData (byte[] BinaryData)
{
set_Value (COLUMNNAME_BinaryData, BinaryData);
}
/** Get BinaryData.
@return Binary Data
*/
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Error.
@param IsError
An Error occured in the execution
*/
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Error.
@return An Error occured in the execution
*/
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reference.
@param Reference
Reference for this record | */
public void setReference (String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Reference.
@return Reference for this record
*/
public String getReference ()
{
return (String)get_Value(COLUMNNAME_Reference);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkflowProcessorLog.java | 1 |
请完成以下Java代码 | public String getMultiplier() {
return multiplier;
}
public void setMultiplier(String multiplier) {
this.multiplier = multiplier;
}
public String getRandom() {
return random;
}
public void setRandom(String random) {
this.random = random;
}
}
public static class TopicPartition {
protected String topic;
protected Collection<String> partitions;
public String getTopic() { | return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Collection<String> getPartitions() {
return partitions;
}
public void setPartitions(Collection<String> partitions) {
this.partitions = partitions;
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static boolean getSignVeryfy(Map<String, String> Params, String sign) {
//过滤空值、sign与sign_type参数
Map<String, String> sParaNew = AlipayCore.paraFilter(Params);
//获取待签名字符串
String preSignStr = AlipayCore.createLinkString(sParaNew);
//获得签名验证结果
boolean isSign = false;
if(SIGN_TYPE.equals("MD5") ) {
isSign = MD5.verify(preSignStr, sign, KEY, INPUT_CHARSET);
}
return isSign;
}
/**
* 获取远程服务器ATN结果,验证返回URL
* @param notify_id 通知校验ID
* @return 服务器ATN结果
* 验证结果集:
* invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空
* true 返回正确信息
* false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
*/
private static String verifyResponse(String notify_id) {
//获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
String veryfy_url = HTTPS_VERIFY_URL + "partner=" + PARTNER + "¬ify_id=" + notify_id;
return checkUrl(veryfy_url);
}
/**
* 获取远程服务器ATN结果
* @param urlvalue 指定URL路径地址
* @return 服务器ATN结果
* 验证结果集:
* invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空
* true 返回正确信息
* false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟 | */
private static String checkUrl(String urlvalue) {
String inputLine = "";
try {
URL url = new URL(urlvalue);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection
.getInputStream()));
inputLine = in.readLine().toString();
} catch (Exception e) {
e.printStackTrace();
inputLine = "";
}
return inputLine;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\AlipayNotify.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SecondaryConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource) | .properties(getVendorProperties())
.packages("com.neo.model")
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
} | repos\spring-boot-leaning-master\2.x_data\1-5 Spring Boot 下的(分布式)事务解决方案\spring-boot-multi-Jpa\src\main\java\com\neo\config\SecondaryConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CompletableFutureDemo {
public static void completableFutureMethod() {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 42;
});
System.out.println(future.join());
}
public static void chainingTaskExample() {
CompletableFuture<Integer> firstTask = CompletableFuture.supplyAsync(() -> {
return 42;
});
CompletableFuture<String> secondTask = firstTask.thenApply(result -> {
return "Result based on Task 1: " + result;
});
System.out.println(secondTask.join());
}
public static void exceptionHandlingExample() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Simulate a task that might throw an exception
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Success";
})
.exceptionally(ex -> { | System.err.println("Error in task: " + ex.getMessage());
// Can optionally return a default value
return "Error occurred";
});
future.thenAccept(result -> System.out.println("Result: " + result));
}
public static void timeoutExample() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.err.println("Task execution timed out!");
}
return "Task completed";
});
CompletableFuture<String> timeoutFuture = future.completeOnTimeout("Timed out!", 2, TimeUnit.SECONDS);
String result = timeoutFuture.join();
System.out.println("Result: " + result);
}
public static void main(String[] args) {
timeoutExample();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executorservicevscompletablefuture\CompletableFutureDemo.java | 2 |
请完成以下Java代码 | private final JTextComponent getTextComponent()
{
return _textComponent;
}
@Override
public void executeCopyPasteAction(final CopyPasteActionType actionType)
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return; // shall not happen
}
if (actionType == CopyPasteActionType.Cut)
{
textComponent.cut();
}
else if (actionType == CopyPasteActionType.Copy)
{
textComponent.copy();
}
else if (actionType == CopyPasteActionType.Paste)
{
textComponent.paste();
}
else if (actionType == CopyPasteActionType.SelectAll)
{
// NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus.
textComponent.requestFocus();
final Document doc = textComponent.getDocument();
if (doc != null)
{
textComponent.setCaretPosition(0);
textComponent.moveCaretPosition(doc.getLength());
}
}
}
@Override
public Action getCopyPasteAction(final CopyPasteActionType actionType)
{
final String swingActionMapName = actionType.getSwingActionMapName();
return getTextComponent().getActionMap().get(swingActionMapName);
}
@Override
public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke)
{
final JTextComponent textComponent = getTextComponent();
final String swingActionMapName = actionType.getSwingActionMapName();
textComponent.getActionMap().put(swingActionMapName, action);
if (keyStroke != null)
{
textComponent.getInputMap().put(keyStroke, action.getValue(Action.NAME));
} | }
@Override
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType)
{
if (actionType == CopyPasteActionType.Copy)
{
return hasTextToCopy();
}
else if (actionType == CopyPasteActionType.Cut)
{
return isEditable() && hasTextToCopy();
}
else if (actionType == CopyPasteActionType.Paste)
{
return isEditable();
}
else if (actionType == CopyPasteActionType.SelectAll)
{
return !isEmpty();
}
else
{
return false;
}
}
private final boolean isEditable()
{
final JTextComponent textComponent = getTextComponent();
return textComponent.isEditable() && textComponent.isEnabled();
}
private final boolean hasTextToCopy()
{
final JTextComponent textComponent = getTextComponent();
final String selectedText = textComponent.getSelectedText();
return selectedText != null && !selectedText.isEmpty();
}
private final boolean isEmpty()
{
final JTextComponent textComponent = getTextComponent();
final String text = textComponent.getText();
return Check.isEmpty(text, false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JTextComponentCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | public String postUser(ModelMap map,
@ModelAttribute @Valid User user,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
map.addAttribute("action", "create");
return "userForm";
}
userService.insertByUser(user);
return "redirect:/users/";
}
/**
* 显示需要更新用户表单
* 处理 "/users/{id}" 的 GET 请求,通过 URL 中的 id 值获取 User 信息
* URL 中的 id ,通过 @PathVariable 绑定参数
*/
@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
public String getUser(@PathVariable Long id, ModelMap map) {
map.addAttribute("user", userService.findById(id));
map.addAttribute("action", "update");
return "userForm";
}
/**
* 处理 "/users/{id}" 的 PUT 请求,用来更新 User 信息
*
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String putUser(ModelMap map,
@ModelAttribute @Valid User user, | BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
map.addAttribute("action", "update");
return "userForm";
}
userService.update(user);
return "redirect:/users/";
}
/**
* 处理 "/users/{id}" 的 GET 请求,用来删除 User 信息
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
userService.delete(id);
return "redirect:/users/";
}
} | repos\springboot-learning-example-master\chapter-4-spring-boot-validating-form-input\src\main\java\spring\boot\core\web\UserController.java | 1 |
请完成以下Java代码 | public final class RequestedUrlRedirectInvalidSessionStrategy implements InvalidSessionStrategy {
private final Log logger = LogFactory.getLog(getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private boolean createNewSession = true;
@Override
public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
String destinationUrl = ServletUriComponentsBuilder.fromRequest(request)
.host(null)
.scheme(null)
.port(null)
.toUriString();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Starting new session (if required) and redirecting to '" + destinationUrl + "'");
}
if (this.createNewSession) {
request.getSession();
}
this.redirectStrategy.sendRedirect(request, response, destinationUrl);
}
/**
* Determines whether a new session should be created before redirecting (to avoid
* possible looping issues where the same session ID is sent with the redirected
* request). Alternatively, ensure that the configured URL does not pass through the | * {@code SessionManagementFilter}.
* @param createNewSession defaults to {@code true}.
*/
public void setCreateNewSession(boolean createNewSession) {
this.createNewSession = createNewSession;
}
/**
* Sets the redirect strategy to use. The default is {@link DefaultRedirectStrategy}.
* @param redirectStrategy the redirect strategy to use.
* @since 6.2
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\RequestedUrlRedirectInvalidSessionStrategy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Config config(CasClient casClient) {
return new Config(casClient);
}
/**
* cas 客户端配置
* @param casConfig
* @return
*/
@Bean
public CasClient casClient(CasConfiguration casConfig){
CasClient casClient = new CasClient(casConfig);
//客户端回调地址
casClient.setCallbackUrl(projectUrl + "/callback?client_name=" + clientName);
casClient.setName(clientName);
return casClient;
} | /**
* 请求cas服务端配置
* @param casLogoutHandler
*/
@Bean
public CasConfiguration casConfig(){
final CasConfiguration configuration = new CasConfiguration();
//CAS server登录地址
configuration.setLoginUrl(casServerUrl + "/login");
configuration.setAcceptAnyProxy(true);
configuration.setPrefixUrl(casServerUrl + "/");
configuration.setLogoutHandler(new DefaultCasLogoutHandler<>());
return configuration;
}
} | repos\spring-boot-quick-master\quick-shiro-cas\src\main\java\com\shiro\config\Pac4jConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private CorsFilter getCorsFilter(ApplicationContext context) {
if (this.configurationSource != null) {
return new CorsFilter(this.configurationSource);
}
boolean containsCorsFilter = context.containsBeanDefinition(CORS_FILTER_BEAN_NAME);
if (containsCorsFilter) {
return context.getBean(CORS_FILTER_BEAN_NAME, CorsFilter.class);
}
boolean containsCorsSource = context.containsBean(CORS_CONFIGURATION_SOURCE_BEAN_NAME);
if (containsCorsSource) {
CorsConfigurationSource configurationSource = context.getBean(CORS_CONFIGURATION_SOURCE_BEAN_NAME,
CorsConfigurationSource.class);
return new CorsFilter(configurationSource);
}
return MvcCorsFilter.getMvcCorsFilter(context);
}
static class MvcCorsFilter {
private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector";
/**
* This needs to be isolated into a separate class as Spring MVC is an optional
* dependency and will potentially cause ClassLoading issues
* @param context | * @return
*/
private static CorsFilter getMvcCorsFilter(ApplicationContext context) {
if (context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) {
CorsConfigurationSource corsConfigurationSource = context
.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, CorsConfigurationSource.class);
return new CorsFilter(corsConfigurationSource);
}
throw new NoSuchBeanDefinitionException(CorsConfigurationSource.class,
"Failed to find a bean that implements `CorsConfigurationSource`. Please ensure that you are using "
+ "`@EnableWebMvc`, are publishing a `WebMvcConfigurer`, or are publishing a `CorsConfigurationSource` bean.");
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\CorsConfigurer.java | 2 |
请完成以下Java代码 | final class EventHtmlMessageFormat extends EventMessageFormatTemplate
{
public static final EventHtmlMessageFormat newInstance()
{
return new EventHtmlMessageFormat();
}
private EventHtmlMessageFormat()
{
super();
}
@Override
protected String formatTableRecordReference(final ITableRecordReference recordRef)
{
final Object suggestedWindowIdObj = getArgumentValue(Event.PROPERTY_SuggestedWindowId); | final int suggestedWindowId = (suggestedWindowIdObj instanceof Number) ? ((Number)suggestedWindowIdObj).intValue() : -1;
return new ADHyperlinkBuilder().createShowWindowHTML(recordRef, suggestedWindowId);
}
@Override
protected String formatText(final String text)
{
if (text == null || text.isEmpty())
{
return "";
}
return StringUtils.maskHTML(text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\EventHtmlMessageFormat.java | 1 |
请完成以下Java代码 | protected String getTabName()
{
return ExternalSystemType.Other.getValue();
}
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.Other;
}
@Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context)
{
throw new UnsupportedOperationException("getSelectedRecordCount unsupported for InvokeOtherAction!");
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
else if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(context.getSingleSelectedRecordId());
if (!ExternalSystemType.Other.getValue().equals(externalSystemConfigDAO.getParentTypeById(parentConfigId)))
{
return ProcessPreconditionsResolution.reject(); | }
final ExternalSystemOtherConfigId externalSystemOtherConfigId = ExternalSystemOtherConfigId.ofExternalSystemParentConfigId(parentConfigId);
final ExternalSystemParentConfig externalSystemParentConfig = externalSystemConfigDAO.getById(externalSystemOtherConfigId);
final ExternalSystemOtherConfig otherConfig = ExternalSystemOtherConfig.cast(externalSystemParentConfig.getChildConfig());
if (otherConfig.getParameters().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeOtherAction.java | 1 |
请完成以下Java代码 | public class InvoiceCandidateHandlerDAO implements IInvoiceCandidateHandlerDAO
{
@Cached(cacheName = I_C_ILCandHandler.Table_Name + "#All")
@Override
public List<I_C_ILCandHandler> retrieveAll(@CacheCtx final Properties ctx)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_C_ILCandHandler> queryBuilder = queryBL
.createQueryBuilder(I_C_ILCandHandler.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter() // only those handlers which are active
;
queryBuilder.orderBy()
.addColumn(I_C_ILCandHandler.COLUMN_C_ILCandHandler_ID); // to have a predictible order
return queryBuilder
.create()
.list(I_C_ILCandHandler.class);
}
@Override
public List<I_C_ILCandHandler> retrieveForTable(final Properties ctx, final String tableName)
{
final List<I_C_ILCandHandler> result = new ArrayList<>();
for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx))
{
if (tableName.equals(handlerDef.getTableName()))
{
result.add(handlerDef);
}
}
return result;
}
@Override
public I_C_ILCandHandler retrieveForClassOneOnly(final Properties ctx,
@NonNull final Class<? extends IInvoiceCandidateHandler> handlerClass)
{
final List<I_C_ILCandHandler> result = retrieveForClass(ctx, handlerClass);
//
// Retain only active handlers
for (final Iterator<I_C_ILCandHandler> it = result.iterator(); it.hasNext();)
{
final I_C_ILCandHandler handlerDef = it.next();
if (!handlerDef.isActive())
{
it.remove();
}
}
if (result.isEmpty())
{
throw new AdempiereException("@NotFound@ @C_ILCandHandler@ (@Classname@:" + handlerClass + ")");
}
else if (result.size() != 1)
{
throw new AdempiereException("@QueryMoreThanOneRecordsFound@ @C_ILCandHandler@ (@Classname@:" + handlerClass + "): " + result);
} | return result.get(0);
}
@Override
public List<I_C_ILCandHandler> retrieveForClass(
final Properties ctx,
@NonNull final Class<? extends IInvoiceCandidateHandler> clazz)
{
final String classname = clazz.getName();
final List<I_C_ILCandHandler> result = new ArrayList<>();
for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx))
{
if (classname.equals(handlerDef.getClassname()))
{
result.add(handlerDef);
}
}
return result;
}
@Override
public I_C_ILCandHandler retrieveFor(final I_C_Invoice_Candidate ic)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(ic);
for (final I_C_ILCandHandler handlerDef : retrieveAll(ctx))
{
if (ic.getC_ILCandHandler_ID() == handlerDef.getC_ILCandHandler_ID())
{
return handlerDef;
}
}
throw new AdempiereException("Missing C_ILCandHandler return for C_ILCandHandler_ID=" + ic.getC_ILCandHandler_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerDAO.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String[] getRoles() {
return roles;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
} | repos\spring-boot-quick-master\quick-oauth2\quick-oauth2-server\src\main\java\com\quick\auth\server\entity\Account.java | 1 |
请完成以下Java代码 | public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public LocalDateTime getCreated() {
return this.created;
}
public Long getInserted() {
return this.inserted;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setCreated(LocalDateTime created) {
this.created = created;
} | public void setInserted(Long inserted) {
this.inserted = inserted;
}
public Category withId(Long id) {
return this.id == id ? this : new Category(id, this.name, this.description, this.created, this.inserted);
}
@Override
public String toString() {
return "Category(id=" + this.getId() + ", name=" + this.getName() + ", description=" + this.getDescription()
+ ", created=" + this.getCreated() + ", inserted=" + this.getInserted() + ")";
}
} | repos\spring-data-examples-main\jdbc\aot-optimization\src\main\java\example\springdata\aot\Category.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Resolution.
@param R_Resolution_ID
Request Resolution
*/ | public void setR_Resolution_ID (int R_Resolution_ID)
{
if (R_Resolution_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Resolution_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Resolution_ID, Integer.valueOf(R_Resolution_ID));
}
/** Get Resolution.
@return Request Resolution
*/
public int getR_Resolution_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Resolution_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Resolution.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookQueryResolver {
private final BookRepository bookRepository;
public BookQueryResolver(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@QueryMapping
public BookPage books(@Argument int page, @Argument int size) {
Pageable pageable = PageRequest.of(page, size);
Page<Book> bookPage = bookRepository.findAll(pageable);
return new BookPage(bookPage);
}
@QueryMapping
public BookConnection booksByCursor(@Argument Optional<Long> cursor, @Argument int limit) {
List<Book> books;
if (cursor.isPresent()) { | books = bookRepository.findByIdGreaterThanOrderByIdAsc(cursor.get(), PageRequest.of(0, limit));
} else {
books = bookRepository.findAllByOrderByIdAsc(PageRequest.of(0, limit));
}
List<BookEdge> edges = books.stream()
.map(book -> new BookEdge(book, book.getId().toString()))
.collect(Collectors.toList());
String endCursor = books.isEmpty() ? null : books.get(books.size() - 1).getId().toString();
boolean hasNextPage = !books.isEmpty() && bookRepository.existsByIdGreaterThan(books.get(books.size() - 1).getId());
PageInfo pageInfo = new PageInfo(hasNextPage, endCursor);
return new BookConnection(edges, pageInfo);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\pagination\resolver\BookQueryResolver.java | 2 |
请完成以下Java代码 | public void unlock() {
this.lockOwner = null;
this.lockExpirationTime = null;
}
public abstract String getType();
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JobEntity other = (JobEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (exceptionByteArrayId != null) {
referenceIdAndClass.put(exceptionByteArrayId, ByteArrayEntity.class);
}
return referenceIdAndClass;
}
@Override
public Map<String, Class> getDependentEntities() {
return persistedDependentEntities;
}
@Override
public void postLoad() {
if (exceptionByteArrayId != null) {
persistedDependentEntities = new HashMap<>();
persistedDependentEntities.put(exceptionByteArrayId, ByteArrayEntity.class);
}
else {
persistedDependentEntities = Collections.EMPTY_MAP;
}
}
public String getLastFailureLogId() {
return lastFailureLogId;
}
public void setLastFailureLogId(String lastFailureLogId) { | this.lastFailureLogId = lastFailureLogId;
}
@Override
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", duedate=" + duedate
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ ", jobDefinitionId=" + jobDefinitionId
+ ", jobHandlerType=" + jobHandlerType
+ ", jobHandlerConfiguration=" + jobHandlerConfiguration
+ ", exceptionByteArray=" + exceptionByteArray
+ ", exceptionByteArrayId=" + exceptionByteArrayId
+ ", exceptionMessage=" + exceptionMessage
+ ", failedActivityId=" + failedActivityId
+ ", deploymentId=" + deploymentId
+ ", priority=" + priority
+ ", tenantId=" + tenantId
+ ", batchId=" + batchId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataController {
private final MessageProducer messageProducer;
private final MessageConsumer messageConsumer;
@Autowired
public DataController(MessageProducer messageProducer, MessageConsumer messageConsumer) {
this.messageProducer = messageProducer;
this.messageConsumer = messageConsumer;
}
@PostMapping("/send-message")
public ResponseEntity<Void> sendMessage(@RequestBody MessageRequest message) {
DataMessageAsyncEvent dataMessageEvent = new DataMessageAsyncEvent(message.getId(), message.getMessage());
messageProducer.sendMessage(new EventWrapper<>(dataMessageEvent)); | return ResponseEntity.ok().build();
}
@PostMapping("/send-message-and-get-response")
public ResponseEntity<MessageReply> sendMessageAndGetResponse(@RequestBody MessageRequest message) throws ExecutionException, InterruptedException {
long timestamp = System.nanoTime();
DataMessageAsyncEvent dataMessageEvent = new DataMessageAsyncEvent(message.getId(), message.getMessage());
Future<DataMessageAsyncEvent> future = messageConsumer.getFuture(dataMessageEvent.getId());
messageProducer.sendMessage(new EventWrapper<>(dataMessageEvent));
DataMessageAsyncEvent reply = future.get();
float duration = (System.nanoTime() - timestamp)/(1_000_000F);
return ResponseEntity.ok(new MessageReply(reply.getId(), reply.getMessage(), duration));
}
} | repos\spring-examples-java-17\spring-kafka\kafka-simple\src\main\java\itx\examples\spring\kafka\controller\DataController.java | 2 |
请完成以下Java代码 | public String getRuleKey() {
return ruleKey;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.rule_key
*
* @param ruleKey the value for rule.rule_key
*
* @mbggenerated
*/
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey == null ? null : ruleKey.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.version
*
* @return the value of rule.version
*
* @mbggenerated
*/
public String getVersion() {
return version;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.version
*
* @param version the value for rule.version
*
* @mbggenerated
*/
public void setVersion(String version) {
this.version = version == null ? null : version.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.content
*
* @return the value of rule.content
*
* @mbggenerated
*/
public String getContent() {
return content;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.content
*
* @param content the value for rule.content
*
* @mbggenerated
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.create_time
*
* @return the value of rule.create_time
*
* @mbggenerated
*/ | public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.create_time
*
* @param createTime the value for rule.create_time
*
* @mbggenerated
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column rule.update_time
*
* @return the value of rule.update_time
*
* @mbggenerated
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column rule.update_time
*
* @param updateTime the value for rule.update_time
*
* @mbggenerated
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\domain\model\Rule.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 1234
http2:
enabled: true
servlet:
context-path: /generator
#tomcat:
# remote-ip-header: x-forward-for
# uri-encoding: UTF-8
# max-threads: 10
# background-processor-delay: 30
# basedir: ${user.home}/tomcat/
undertow:
# 设置IO线程数, 它主要执行非阻塞的任务,它们会负责多个连接, 默认设置每个CPU核心一个线程
# 不要设置过大,如果过大,启动项目会报错:打开文件数过多
io-threads: 4
# 阻塞任务线程池, 当执行类似servlet请求阻塞IO操作, undertow会从这个线程池中取得线程
# 它的值设置取决于系统线程执行任务的阻塞系数,默认值是IO线程数*8
worker-threads: 64
# 以下的配置会影响buffer,这些buffer会用于服务器连接的IO操作,有点类似netty的池化内存管理
# 每块buffer的空间大小,越小的空间被利用越充分,不要设置太大,以免影响其他应用,合适即可
buffer-size: 1024
# 是否分配的直接内存(NIO直接分配的堆外内存)
direct-buffers: true
spring:
banner:
charset: UTF-8
web:
encoding:
force: true
charset: UTF-8
application:
name: spring-boot-code-generator
freemarker:
request-context-attribute: request
suffix: .html
content-type: text/html
enabled: true
cache: false
charset: UTF-8
allow-request-override: false
expose-request-attributes: true
expose-session-attributes: true
expose-spring-macro-helpers: true
settings:
number_format: 0.##
default_encoding: UTF-8
#template_loader: /templates/
#mvc:
# static-path-pattern: /statics/**
OEM:
version: 2025 September
header: SQL转Java JPA、MYBATIS实现类代码生成平台
keywords: sql转实体类,sql转DAO,SQL转service,SQL转JPA实现,SQL转MYBATIS实现
title: JAVA在线代码生成
slogan: 👐 Free your hands from boring CRUD—let the code write itself! ⚡
description: <p>💻 SpringBootCodeGenerator,又名 `大狼狗代码生成器`🐺🐶,支持 S | QL 一键转 JAVA/JPA/Mybatis/MybatisPlus 等多种模板,轻松搞定 CRUD,彻底解放双手 ✋!只需提供 DDL、SELECT SQL 或简单 JSON 👉 即可生成 生成JPA/JdbcTemplate/Mybatis/MybatisPlus/BeetlSQL/CommonMapper 等代码模板。</p><p>🔥🔥🔥 全新 JSqlParser 引擎上线,强力支持 DDL CREATE SQL与 SELECT SQL 解析!欢迎体验 & 反馈 💬!</p><p>👨💻 面向开发者的高效利器,已服务数万工程师,欢迎 Star ⭐、Fork 🍴、提 Issue 💬,一起打造更强大的代码生成平台!</p>
author: BEJSON.com
packageName: www.bejson.com
copyright: ✨ Powered by <a href="https://zhengkai.blog.csdn.net" target="_blank">Moshow郑锴</a>➕<a href="https://www.bejson.com/">BeJSON</a> — may the holy light guide your code, your coffee, and your commits! ⚡🧙♂️💻
returnUtilSuccess: ResponseUtil.success
returnUtilFailure: ResponseUtil.error
outputStr: www.bejson.com
mode: CDN | repos\SpringBootCodeGenerator-master\src\main\resources\application-bejson.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonWFActivity
{
@NonNull String activityId;
@NonNull String caption;
@NonNull String componentType;
@NonNull WFActivityStatus status;
@Nullable Boolean isAlwaysAvailableToUser;
@Nullable String userInstructions;
@Builder.Default
@NonNull Map<String, Object> componentProps = ImmutableMap.of();
static JsonWFActivity of(
@NonNull final WFActivity activity,
@NonNull final UIComponent uiComponent, | @NonNull final JsonOpts jsonOpts)
{
final String adLanguage = jsonOpts.getAdLanguage();
return builder()
.activityId(activity.getId().getAsString())
.caption(activity.getCaption().translate(adLanguage))
.componentType(uiComponent.getType().getAsString())
.status(activity.getStatus())
.isAlwaysAvailableToUser(uiComponent.getAlwaysAvailableToUser().toBooleanObject())
.userInstructions(activity.getUserInstructions())
.componentProps(uiComponent.getProperties().toJson(jsonOpts::convertValueToJson))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonWFActivity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CustomColumnRepository
{
private final CCache<Integer, RESTApiTableInfoMap> cache = CCache.<Integer, RESTApiTableInfoMap>builder()
.tableName(I_AD_Column.Table_Name)
.additionalTableNameToResetFor(I_AD_Table.Table_Name)
.initialCapacity(1)
.build();
@Nullable
public RESTApiTableInfo getByTableNameOrNull(final String tableName)
{
return getMap().getByTableNameOrNull(tableName);
}
private RESTApiTableInfoMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private RESTApiTableInfoMap retrieveMap()
{
final String sql = "SELECT "
+ " t." + I_AD_Table.COLUMNNAME_TableName
+ ", c." + I_AD_Column.COLUMNNAME_ColumnName
+ " FROM " + I_AD_Column.Table_Name + " c "
+ " INNER JOIN " + I_AD_Table.Table_Name + " t ON (t.AD_Table_ID=c.AD_Table_ID)"
+ " WHERE c." + I_AD_Column.COLUMNNAME_IsRestAPICustomColumn + "='Y'"
+ " AND c.IsActive='Y' AND t.IsActive='Y'"
+ " ORDER BY t." + I_AD_Table.COLUMNNAME_TableName + ", c." + I_AD_Column.COLUMNNAME_ColumnName;
final HashMap<String, RESTApiTableInfoBuilder> builders = new HashMap<>();
DB.forEachRow(sql, null, rs -> {
final String tableName = rs.getString(I_AD_Table.COLUMNNAME_TableName);
final String columnName = rs.getString(I_AD_Column.COLUMNNAME_ColumnName);
builders.computeIfAbsent(tableName, RESTApiTableInfo::newBuilderForTableName) | .customRestAPIColumnName(columnName);
});
return builders.values().stream()
.map(RESTApiTableInfoBuilder::build)
.collect(RESTApiTableInfoMap.collect());
}
@EqualsAndHashCode
@ToString
private static class RESTApiTableInfoMap
{
private final ImmutableMap<String, RESTApiTableInfo> byTableName;
private RESTApiTableInfoMap(final List<RESTApiTableInfo> list)
{
this.byTableName = Maps.uniqueIndex(list, RESTApiTableInfo::getTableName);
}
public static Collector<RESTApiTableInfo, ?, RESTApiTableInfoMap> collect()
{
return GuavaCollectors.collectUsingListAccumulator(RESTApiTableInfoMap::new);
}
@Nullable
private RESTApiTableInfo getByTableNameOrNull(final String tableName)
{
return this.byTableName.get(tableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnRepository.java | 2 |
请完成以下Spring Boot application配置 | # 基础配置
spring.datasource.druid.url=jdbc:mysql://localhost:3306/test
spring.datasource.druid.username=root
spring.datasource.druid.password=
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接池配置
spring.datasource.druid.initialSize=10
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.minIdle=1
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxOpenPreparedStatements=20
spring.datasource.druid.validationQuery=SELECT 1
spring.datasource.druid.validation-query-timeout=500
sp | ring.datasource.druid.filters=stat,wall
# 监控配置
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin | repos\SpringBoot-Learning-master\2.x\chapter3-3\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public Set<String> getAutoForward() {
return autoForward;
}
public void setAutoForward(Set<String> autoForward) {
this.autoForward = autoForward;
}
public Set<String> getSensitive() {
return sensitive;
}
public void setSensitive(Set<String> sensitive) {
this.sensitive = sensitive;
} | public Set<String> getSkipped() {
return skipped;
}
public void setSkipped(Set<String> skipped) {
this.skipped = skipped;
}
public HttpHeaders convertHeaders() {
HttpHeaders headers = new HttpHeaders();
for (String key : this.headers.keySet()) {
headers.set(key, this.headers.get(key));
}
return headers;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\config\ProxyExchangeWebMvcProperties.java | 2 |
请完成以下Java代码 | public void writeJExcel() throws IOException, WriteException {
WritableWorkbook workbook = null;
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
workbook = Workbook.createWorkbook(new File(fileLocation));
WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
headerFormat.setFont(font);
headerFormat.setBackground(Colour.LIGHT_BLUE);
headerFormat.setWrap(true);
Label headerLabel = new Label(0, 0, "Name", headerFormat);
sheet.setColumnView(0, 60);
sheet.addCell(headerLabel); | headerLabel = new Label(1, 0, "Age", headerFormat);
sheet.setColumnView(0, 40);
sheet.addCell(headerLabel);
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
sheet.addCell(cellLabel);
Number cellNumber = new Number(1, 2, 20, cellFormat);
sheet.addCell(cellNumber);
workbook.write();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
} | repos\tutorials-master\apache-poi\src\main\java\com\baeldung\jexcel\JExcelHelper.java | 1 |
请完成以下Java代码 | public void execute(CommandContext commandContext) {
CreateNewTimerJobCommand cmd = new CreateNewTimerJobCommand(jobId);
commandExecutor.execute(cmd);
}
protected class CreateNewTimerJobCommand implements Command<Void> {
protected String jobId;
public CreateNewTimerJobCommand(String jobId) {
this.jobId = jobId;
}
public Void execute(CommandContext commandContext) {
TimerEntity failedJob = (TimerEntity) commandContext
.getJobManager()
.findJobById(jobId); | Date newDueDate = failedJob.calculateNewDueDate();
if (newDueDate != null) {
failedJob.createNewTimerJob(newDueDate);
// update configuration of failed job
TimerJobConfiguration config = (TimerJobConfiguration) failedJob.getJobHandlerConfiguration();
config.setFollowUpJobCreated(true);
failedJob.setJobHandlerConfiguration(config);
}
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\RepeatingFailedJobListener.java | 1 |
请完成以下Java代码 | public class ExtensionElementsParser implements BpmnXMLConstants {
public void parse(
XMLStreamReader xtr,
List<SubProcess> activeSubProcessList,
Process activeProcess,
BpmnModel model
) throws Exception {
BaseElement parentElement = null;
if (!activeSubProcessList.isEmpty()) {
parentElement = activeSubProcessList.get(activeSubProcessList.size() - 1);
} else {
parentElement = activeProcess;
}
boolean readyWithChildElements = false;
while (readyWithChildElements == false && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (ELEMENT_EXECUTION_LISTENER.equals(xtr.getLocalName())) {
new ExecutionListenerParser().parseChildElement(xtr, parentElement, model);
} else if (ELEMENT_EVENT_LISTENER.equals(xtr.getLocalName())) { | new ActivitiEventListenerParser().parseChildElement(xtr, parentElement, model);
} else if (ELEMENT_POTENTIAL_STARTER.equals(xtr.getLocalName())) {
new PotentialStarterParser().parse(xtr, activeProcess);
} else {
ExtensionElement extensionElement = BpmnXMLUtil.parseExtensionElement(xtr);
if (parentElement != null) {
parentElement.addExtensionElement(extensionElement);
}
}
} else if (xtr.isEndElement()) {
if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\ExtensionElementsParser.java | 1 |
请完成以下Java代码 | public IAttributeValue getAttributeValueOrNull(final AttributeCode attributeCode)
{
return attributeValuesByCode.get(attributeCode);
}
public boolean hasAttribute(final AttributeCode attributeCode)
{
return attributesByCode.containsKey(attributeCode);
}
public boolean hasAttribute(final AttributeId attributeId)
{
return attributesById.containsKey(attributeId);
}
public Collection<I_M_Attribute> getAttributes()
{
return attributesByCode.values();
}
public I_M_Attribute getAttributeOrNull(final AttributeId attributeId)
{
return attributesById.get(attributeId);
} | public boolean hasAttributes()
{
return !attributesByCode.isEmpty();
}
public I_M_Attribute getAttributeByCodeOrNull(final AttributeCode attributeCode)
{
return attributesByCode.get(attributeCode);
}
public boolean isNull()
{
return this == NULL;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractAttributeStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<StageResponse> getStageOverview(@ApiParam(name = "caseInstanceId") @PathVariable String caseInstanceId) {
HistoricCaseInstance caseInstance = getHistoricCaseInstanceFromRequest(caseInstanceId);
return cmmnhistoryService.getStageOverview(caseInstance.getId());
}
@ApiOperation(value = "Migrate historic case instance", tags = { "History Case" }, nickname = "migrateHistoricCaseInstance")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the historiccase instance was found and migration was executed."),
@ApiResponse(code = 404, message = "Indicates the requested historic case instance was not found.")
})
@PostMapping(value = "/cmmn-history/historic-case-instances/{caseInstanceId}/migrate", produces = "application/json")
public void migrateHistoricCaseInstance(@ApiParam(name = "caseInstanceId") @PathVariable String caseInstanceId,
@RequestBody String migrationDocumentJson) {
HistoricCaseInstance caseInstance = getHistoricCaseInstanceFromRequestWithoutAccessCheck(caseInstanceId);
if (restApiInterceptor != null) {
restApiInterceptor.migrateHistoricCaseInstance(caseInstance, migrationDocumentJson);
}
HistoricCaseInstanceMigrationDocument migrationDocument = HistoricCaseInstanceMigrationDocumentConverter.convertFromJson(migrationDocumentJson);
cmmnMigrationService.migrateHistoricCaseInstance(caseInstanceId, migrationDocument);
}
protected Date getPlanItemInstanceEndTime(List<HistoricPlanItemInstance> stagePlanItemInstances, Stage stage) {
return getPlanItemInstance(stagePlanItemInstances, stage)
.map(HistoricPlanItemInstance::getEndedTime)
.orElse(null);
}
protected Optional<HistoricPlanItemInstance> getPlanItemInstance(List<HistoricPlanItemInstance> stagePlanItemInstances, Stage stage) {
HistoricPlanItemInstance planItemInstance = null; | for (HistoricPlanItemInstance p : stagePlanItemInstances) {
if (p.getPlanItemDefinitionId().equals(stage.getId())) {
if (p.getEndedTime() == null) {
planItemInstance = p; // one that's not ended yet has precedence
} else {
if (planItemInstance == null) {
planItemInstance = p;
}
}
}
}
return Optional.ofNullable(planItemInstance);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResource.java | 2 |
请完成以下Java代码 | public static FailedJobRetryConfiguration parseRetryIntervals(String retryIntervals) {
if (retryIntervals != null && !retryIntervals.isEmpty()) {
if (StringUtil.isExpression(retryIntervals)) {
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
Expression expression = expressionManager.createExpression(retryIntervals);
return new FailedJobRetryConfiguration(expression);
}
String[] intervals = StringUtil.split(retryIntervals, ",");
int retries = intervals.length + 1;
if (intervals.length == 1) {
try {
DurationHelper durationHelper = new DurationHelper(intervals[0]);
if (durationHelper.isRepeat()) {
retries = durationHelper.getTimes();
}
} catch (Exception e) {
LOG.logParsingRetryIntervals(intervals[0], e);
return null;
}
}
return new FailedJobRetryConfiguration(retries, Arrays.asList(intervals));
} else {
return null;
}
}
public static ProcessEngineDetails parseProcessEngineVersion(boolean trimSuffixEE) {
String version = ProductPropertiesUtil.getProductVersion();
return parseProcessEngineVersion(version, trimSuffixEE);
}
public static ProcessEngineDetails parseProcessEngineVersion(String version, boolean trimSuffixEE) {
String edition = ProcessEngineDetails.EDITION_COMMUNITY;
if (version.contains("-ee")) {
edition = ProcessEngineDetails.EDITION_ENTERPRISE;
if (trimSuffixEE) {
version = version.replace("-ee", ""); // trim `-ee` suffix | }
}
return new ProcessEngineDetails(version, edition);
}
public static String parseServerVendor(String applicationServerInfo) {
String serverVendor = "";
Pattern pattern = Pattern.compile("[\\sA-Za-z]+");
Matcher matcher = pattern.matcher(applicationServerInfo);
if (matcher.find()) {
try {
serverVendor = matcher.group();
} catch (IllegalStateException ignored) {
}
serverVendor = serverVendor.trim();
if (serverVendor.contains("WildFly")) {
return "WildFly";
}
}
return serverVendor;
}
public static JdkImpl parseJdkDetails() {
String jdkVendor = System.getProperty("java.vm.vendor");
if (jdkVendor != null && jdkVendor.contains("Oracle")
&& System.getProperty("java.vm.name").contains("OpenJDK")) {
jdkVendor = "OpenJDK";
}
String jdkVersion = System.getProperty("java.version");
JdkImpl jdk = new JdkImpl(jdkVersion, jdkVendor);
return jdk;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ParseUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Logger logger(JoinPoint joinPoint) {
return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint).error(
"Exception in {}() with cause = '{}' and exception = '{}'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint).error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? String.valueOf(e.getCause()) : "NULL"
);
}
} | /**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Logger log = logger(joinPoint);
if (log.isDebugEnabled()) {
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
throw e;
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\aop\logging\LoggingAspect.java | 2 |
请完成以下Java代码 | public boolean containsChannel(Channel channel) {
return this.channels.contains(channel);
}
public @Nullable Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public @Nullable Channel getChannel() {
return (!this.channels.isEmpty() ? this.channels.get(0) : null);
}
public void commitAll() throws AmqpException {
try {
for (Channel channel : this.channels) {
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
channel.basicAck(deliveryTag, false);
}
}
channel.txCommit();
}
}
catch (IOException e) {
throw new AmqpException("failed to commit RabbitMQ transaction", e);
}
}
public void closeAll() {
for (Channel channel : this.channels) {
try {
if (channel != ConsumerChannelRegistry.getConsumerChannel()) { // NOSONAR
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
}
catch (Exception ex) { | logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
for (Connection con : this.connections) { //NOSONAR
RabbitUtils.closeConnection(con);
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
}
RabbitUtils.rollbackIfNecessary(channel);
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, this.requeueOnRollback);
}
catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitResourceHolder.java | 1 |
请完成以下Java代码 | public void lock(LockExternalTaskDto lockExternalTaskDto) {
ExternalTaskService externalTaskService = engine.getExternalTaskService();
try {
externalTaskService
.lock(externalTaskId, lockExternalTaskDto.getWorkerId(), lockExternalTaskDto.getLockDuration());
} catch (NotFoundException e) {
throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist");
} catch (BadUserRequestException e) {
throw new RestException(Status.BAD_REQUEST, e, e.getMessage());
}
}
@Override
public void extendLock(ExtendLockOnExternalTaskDto extendLockDto) {
ExternalTaskService externalTaskService = engine.getExternalTaskService();
try {
externalTaskService.extendLock(externalTaskId, extendLockDto.getWorkerId(), extendLockDto.getNewDuration()); | } catch (NotFoundException e) {
throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist");
} catch (BadUserRequestException e) {
throw new RestException(Status.BAD_REQUEST, e, e.getMessage());
}
}
@Override
public void unlock() {
ExternalTaskService externalTaskService = engine.getExternalTaskService();
try {
externalTaskService.unlock(externalTaskId);
} catch (NotFoundException e) {
throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist");
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\externaltask\impl\ExternalTaskResourceImpl.java | 1 |
请完成以下Java代码 | public QueueBuilder stream() {
return withArgument("x-queue-type", "stream");
}
/**
* Set the delivery limit; only applies to quorum queues.
* @param limit the limit.
* @return the builder.
* @since 2.2.2
* @see #quorum()
*/
public QueueBuilder deliveryLimit(int limit) {
return withArgument("x-delivery-limit", limit);
}
/**
* Builds a final queue.
* @return the Queue instance.
*/
public Queue build() {
return new Queue(this.name, this.durable, this.exclusive, this.autoDelete, getArguments());
}
/**
* Overflow argument values.
*/
public enum Overflow {
/**
* Drop the oldest message.
*/
dropHead("drop-head"),
/**
* Reject the new message.
*/
rejectPublish("reject-publish");
private final String value;
Overflow(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
} | /**
* Locate the queue leader.
*
* @since 2.3.7
*
*/
public enum LeaderLocator {
/**
* Deploy on the node with the fewest queue leaders.
*/
minLeaders("min-masters"),
/**
* Deploy on the node we are connected to.
*/
clientLocal("client-local"),
/**
* Deploy on a random node.
*/
random("random");
private final String value;
LeaderLocator(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueBuilder.java | 1 |
请完成以下Java代码 | public void setParameter(String parameter) {
Assert.hasText(parameter, "Parameter name cannot be empty or null");
this.parameter = parameter;
}
public String getParameter() {
return this.parameter;
}
protected UserDetailsService getUserDetailsService() {
return this.userDetailsService;
}
public String getKey() {
return this.key;
}
public void setTokenValiditySeconds(int tokenValiditySeconds) {
this.tokenValiditySeconds = tokenValiditySeconds;
}
protected int getTokenValiditySeconds() {
return this.tokenValiditySeconds;
}
/**
* Whether the cookie should be flagged as secure or not. Secure cookies can only be
* sent over an HTTPS connection and thus cannot be accidentally submitted over HTTP
* where they could be intercepted.
* <p>
* By default the cookie will be secure if the request is secure. If you only want to
* use remember-me over HTTPS (recommended) you should set this property to
* {@code true}.
* @param useSecureCookie set to {@code true} to always user secure cookies,
* {@code false} to disable their use.
*/
public void setUseSecureCookie(boolean useSecureCookie) {
this.useSecureCookie = useSecureCookie;
}
protected AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() {
return this.authenticationDetailsSource;
}
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource cannot be null");
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* Sets the strategy to be used to validate the {@code UserDetails} object obtained
* for the user when processing a remember-me cookie to automatically log in a user.
* @param userDetailsChecker the strategy which will be passed the user object to
* allow it to be rejected if account should not be allowed to authenticate (if it is
* locked, for example). Defaults to a {@code AccountStatusUserDetailsChecker}
* instance.
*
*/
public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { | this.userDetailsChecker = userDetailsChecker;
}
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
this.authoritiesMapper = authoritiesMapper;
}
/**
* @since 5.5
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the {@link Consumer}, allowing customization of cookie.
* @param cookieCustomizer customize for cookie
* @since 6.4
*/
public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) {
Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null");
this.cookieCustomizer = cookieCustomizer;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\AbstractRememberMeServices.java | 1 |
请完成以下Java代码 | public int getC_Recurring_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurring Run.
@param C_Recurring_Run_ID
Recurring Document Run
*/
public void setC_Recurring_Run_ID (int C_Recurring_Run_ID)
{
if (C_Recurring_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, Integer.valueOf(C_Recurring_Run_ID));
}
/** Get Recurring Run.
@return Recurring Document Run
*/
public int getC_Recurring_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document Date.
@param DateDoc
Date of the Document
*/
public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date.
@return Date of the Document
*/
public Timestamp getDateDoc ()
{ | return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException
{
return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name)
.getPO(getGL_JournalBatch_ID(), get_TrxName()); }
/** Set Journal Batch.
@param GL_JournalBatch_ID
General Ledger Journal Batch
*/
public void setGL_JournalBatch_ID (int GL_JournalBatch_ID)
{
if (GL_JournalBatch_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID));
}
/** Get Journal Batch.
@return General Ledger Journal Batch
*/
public int getGL_JournalBatch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring_Run.java | 1 |
请完成以下Java代码 | public BalanceType getBalance() {
return balance;
}
/**
* Sets the value of the balance property.
*
* @param value
* allowed object is
* {@link BalanceType }
*
*/
public void setBalance(BalanceType value) {
this.balance = value;
}
/**
* Gets the value of the esr9 property.
*
* @return
* possible object is
* {@link Esr9Type }
*
*/
public Esr9Type getEsr9() {
return esr9;
}
/**
* Sets the value of the esr9 property.
*
* @param value
* allowed object is
* {@link Esr9Type }
*
*/
public void setEsr9(Esr9Type value) {
this.esr9 = value;
}
/**
* Gets the value of the esrRed property.
*
* @return
* possible object is
* {@link EsrRedType }
*
*/
public EsrRedType getEsrRed() {
return esrRed;
}
/**
* Sets the value of the esrRed property.
*
* @param value | * allowed object is
* {@link EsrRedType }
*
*/
public void setEsrRed(EsrRedType value) {
this.esrRed = value;
}
/**
* Gets the value of the esrQR property.
*
* @return
* possible object is
* {@link EsrQRType }
*
*/
public EsrQRType getEsrQR() {
return esrQR;
}
/**
* Sets the value of the esrQR property.
*
* @param value
* allowed object is
* {@link EsrQRType }
*
*/
public void setEsrQR(EsrQRType value) {
this.esrQR = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\ReimbursementType.java | 1 |
请完成以下Java代码 | public void onMessage(String message, Session session) {
log.info("收到来"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误", error);
}
/**
* 实现服务器主动推送
*/
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(SocketMsg socketMsg,@PathParam("sid") String sid) throws IOException {
String message = JSON.toJSONString(socketMsg);
log.info("推送消息到"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException ignored) { } | }
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebSocketServer that = (WebSocketServer) o;
return Objects.equals(session, that.session) &&
Objects.equals(sid, that.sid);
}
@Override
public int hashCode() {
return Objects.hash(session, sid);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\websocket\WebSocketServer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceChangedEvent
{
@JsonProperty("invoiceId")
InvoiceId invoiceId;
@JsonProperty("invoiceDate")
LocalDate invoiceDate;
@JsonProperty("bpartnerId")
BPartnerId bpartnerId;
@JsonProperty("soTrx")
SOTrx soTrx;
@JsonProperty("reversal")
boolean reversal;
@JsonProperty("productPrices")
@Getter(AccessLevel.NONE)
List<ProductPrice> productPrices;
@JsonIgnore
ImmutableMap<ProductId, ProductPrice> productPricesByProductId;
@Builder
@JsonCreator
private InvoiceChangedEvent(
@JsonProperty("invoiceId") @NonNull final InvoiceId invoiceId,
@JsonProperty("invoiceDate") @NonNull final LocalDate invoiceDate,
@JsonProperty("bpartnerId") @NonNull final BPartnerId bpartnerId,
@JsonProperty("soTrx") @NonNull final SOTrx soTrx,
@JsonProperty("reversal") final boolean reversal,
@JsonProperty("productPrices") @NonNull @Singular final List<ProductPrice> productPrices)
{
Check.assumeNotEmpty(productPrices, "productPrices is not empty");
this.invoiceId = invoiceId;
this.invoiceDate = invoiceDate;
this.bpartnerId = bpartnerId;
this.soTrx = soTrx;
this.reversal = reversal;
this.productPrices = ImmutableList.copyOf(productPrices); | this.productPricesByProductId = Maps.uniqueIndex(this.productPrices, ProductPrice::getProductId);
}
public Set<ProductId> getProductIds()
{
return productPricesByProductId.keySet();
}
public Money getProductPrice(@NonNull final ProductId productId)
{
final ProductPrice productPrice = productPricesByProductId.get(productId);
if (productPrice == null)
{
throw new AdempiereException("No product price found for " + productId + " in " + this);
}
return productPrice.getPrice();
}
@Value
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public static class ProductPrice
{
@JsonProperty("productId")
ProductId productId;
@JsonProperty("price")
Money price;
@Builder
@JsonCreator
private ProductPrice(
@JsonProperty("productId") @NonNull final ProductId productId,
@JsonProperty("price") @NonNull final Money price)
{
this.productId = productId;
this.price = price;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\InvoiceChangedEvent.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void onlyAllowPost(HttpHeaders headers) {
headers.setAllow(Collections.singleton(HttpMethod.POST));
}
@Configuration(proxyBeanMethods = false)
static class GraphQlEndpointCorsConfiguration implements WebFluxConfigurer {
final GraphQlProperties graphQlProperties;
final GraphQlCorsProperties corsProperties;
GraphQlEndpointCorsConfiguration(GraphQlProperties graphQlProps, GraphQlCorsProperties corsProps) {
this.graphQlProperties = graphQlProps;
this.corsProperties = corsProps;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
CorsConfiguration configuration = this.corsProperties.toCorsConfiguration();
if (configuration != null) {
registry.addMapping(this.graphQlProperties.getHttp().getPath()).combine(configuration);
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("spring.graphql.websocket.path")
static class WebSocketConfiguration {
@Bean
@ConditionalOnMissingBean
GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler,
GraphQlProperties properties, ServerCodecConfigurer configurer) {
return new GraphQlWebSocketHandler(webGraphQlHandler, configurer,
properties.getWebsocket().getConnectionInitTimeout(), properties.getWebsocket().getKeepAlive());
} | @Bean
HandlerMapping graphQlWebSocketEndpoint(GraphQlWebSocketHandler graphQlWebSocketHandler,
GraphQlProperties properties) {
String path = properties.getWebsocket().getPath();
Assert.state(path != null, "'path' must not be null");
logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path));
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setHandlerPredicate(new WebSocketUpgradeHandlerPredicate());
mapping.setUrlMap(Collections.singletonMap(path, graphQlWebSocketHandler));
mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean)
return mapping;
}
}
static class GraphiQlResourceHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphiql/index.html");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\reactive\GraphQlWebFluxAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public Object getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Object createdAt) {
this.createdAt = createdAt;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
} | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\configuration\AdvancedArticle.java | 2 |
请完成以下Java代码 | public class LicenseKeyDataImpl implements LicenseKeyData {
public static final String SERIALIZED_VALID_UNTIL = "valid-until";
public static final String SERIALIZED_IS_UNLIMITED = "unlimited";
protected String customer;
protected String type;
@SerializedName(value = SERIALIZED_VALID_UNTIL)
protected String validUntil;
@SerializedName(value = SERIALIZED_IS_UNLIMITED)
protected Boolean isUnlimited;
protected Map<String, String> features;
protected String raw;
public LicenseKeyDataImpl(String customer, String type, String validUntil, Boolean isUnlimited, Map<String, String> features, String raw) {
this.customer = customer;
this.type = type;
this.validUntil = validUntil;
this.isUnlimited = isUnlimited;
this.features = features;
this.raw = raw;
}
public static LicenseKeyDataImpl fromRawString(String rawLicense) {
String licenseKeyRawString = rawLicense.contains(";") ? rawLicense.split(";", 2)[1] : rawLicense;
return new LicenseKeyDataImpl(null, null, null, null, null, licenseKeyRawString);
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValidUntil() {
return validUntil;
}
public void setValidUntil(String validUntil) {
this.validUntil = validUntil; | }
public Boolean isUnlimited() {
return isUnlimited;
}
public void setUnlimited(Boolean isUnlimited) {
this.isUnlimited = isUnlimited;
}
public Map<String, String> getFeatures() {
return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\LicenseKeyDataImpl.java | 1 |
请完成以下Java代码 | private Step step1() {
return stepBuilderFactory.get("step1")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("execute step1。。。");
return RepeatStatus.FINISHED;
}).build();
}
private Step step2() {
return stepBuilderFactory.get("step2")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("execute step2。。。");
return RepeatStatus.FINISHED;
}).build();
} | private Step step3() {
return stepBuilderFactory.get("step3")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("execute step3。。。");
return RepeatStatus.FINISHED;
}).build();
}
// 创建一个flow对象,包含若干个step
private Flow flow() {
return new FlowBuilder<Flow>("flow")
.start(step1())
.next(step2())
.build();
}
} | repos\springboot-demo-master\SpringBatch\src\main\java\com\et\batch\job\FlowJobDemo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUOMSymbol() {
return uomSymbol;
}
/**
* Sets the value of the uomSymbol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUOMSymbol(String value) {
this.uomSymbol = value;
}
/**
* Gets the value of the x12DE355 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getX12DE355() { | return x12DE355;
}
/**
* Sets the value of the x12DE355 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setX12DE355(String value) {
this.x12DE355 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCUOMType.java | 2 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Color Schema.
@param PA_ColorSchema_ID
Performance Color Schema
*/
public void setPA_ColorSchema_ID (int PA_ColorSchema_ID) | {
if (PA_ColorSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, Integer.valueOf(PA_ColorSchema_ID));
}
/** Get Color Schema.
@return Performance Color Schema
*/
public int getPA_ColorSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ColorSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ColorSchema.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handleEvent(@NonNull final ReceiptScheduleDeletedEvent event)
{
final CandidatesQuery query = ReceiptsScheduleHandlerUtil.queryByReceiptScheduleId(event);
final Candidate candidateToDelete = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(query);
if (candidateToDelete == null)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No deletable candidate found; query={}", query);
return;
}
final BigDecimal actualQty = candidateToDelete.computeActualQty();
final boolean candidateHasTransactions = actualQty.signum() > 0;
if (candidateHasTransactions)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("candidateId={} for the deleted receiptScheduleId={} already has actual trasactions",
candidateToDelete.getId(), event.getReceiptScheduleId());
candidateChangeHandler.onCandidateNewOrChange(candidateToDelete.withQuantity(actualQty));
}
else
{
Loggables.withLogger(logger, Level.DEBUG).addLog("candidateId={} for the deleted receiptScheduleId={} can be deleted", | candidateToDelete.getId(), event.getReceiptScheduleId());
candidateChangeHandler.onCandidateDelete(candidateToDelete);
}
}
protected CandidatesQuery createCandidatesQuery(@NonNull final ReceiptScheduleDeletedEvent deletedEvent)
{
final PurchaseDetailsQuery purchaseDetailsQuery = PurchaseDetailsQuery.builder()
.receiptScheduleRepoId(deletedEvent.getReceiptScheduleId())
.build();
return CandidatesQuery.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE)
.purchaseDetailsQuery(purchaseDetailsQuery)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\receiptschedule\ReceiptsScheduleDeletedHandler.java | 2 |
请完成以下Java代码 | protected PageData<DashboardId> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return dashboardDao.findIdsByTenantId(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardId dashboardId) {
deleteDashboard(tenantId, dashboardId);
}
};
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDashboardById(tenantId, new DashboardId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findDashboardByIdAsync(tenantId, new DashboardId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return dashboardDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.DASHBOARD;
}
private class CustomerDashboardsRemover extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsRemover(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
unassignDashboardFromCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer.getId()); | }
}
private class CustomerDashboardsUpdater extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsUpdater(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
updateAssignedCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer);
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\dashboard\DashboardServiceImpl.java | 1 |
请完成以下Java代码 | private final class HttpSessionWrapper extends HttpSessionAdapter<S> {
HttpSessionWrapper(S session, ServletContext servletContext) {
super(session, servletContext);
}
@Override
public void invalidate() {
super.invalidate();
SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true;
setCurrentSession(null);
clearRequestedSessionCache();
SessionRepositoryFilter.this.sessionRepository.deleteById(getId());
}
}
/**
* Ensures session is committed before issuing an include.
*
* @since 1.3.4
*/
private final class SessionCommittingRequestDispatcher implements RequestDispatcher {
private final RequestDispatcher delegate;
SessionCommittingRequestDispatcher(RequestDispatcher delegate) {
this.delegate = delegate;
} | @Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.delegate.forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
if (!SessionRepositoryRequestWrapper.this.hasCommittedInInclude) {
SessionRepositoryRequestWrapper.this.commitSession();
SessionRepositoryRequestWrapper.this.hasCommittedInInclude = true;
}
this.delegate.include(request, response);
}
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionRepositoryFilter.java | 1 |
请完成以下Java代码 | private static void addLineNumber() {
printHeader("add line number by hasNextLine() ");
Scanner scanner = new Scanner(INPUT);
int i = 0;
while (scanner.hasNextLine()) {
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
}
log.info(END_LINE);
scanner.close();
}
private static void printHeader(String title) {
log.info(LINE);
log.info(title);
log.info(LINE);
}
public static void main(String[] args) throws IOException {
setLogger(); | hasNextBasic();
hasNextWithDelimiter();
hasNextWithDelimiterFixed();
addLineNumber();
}
//overwrite the logger config
private static void setLogger() throws IOException {
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
Properties props = new Properties();
props.load(is);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
} | repos\tutorials-master\core-java-modules\core-java-scanner\src\main\java\com\baeldung\scanner\HasNextVsHasNextLineDemo.java | 1 |
请完成以下Java代码 | public class CustomSpliterator implements Spliterator<Integer> {
private final List<Integer> elements;
private int currentIndex;
public CustomSpliterator(List<Integer> elements) {
this.elements = elements;
this.currentIndex = 0;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (currentIndex < elements.size()) {
action.accept(elements.get(currentIndex));
currentIndex++;
return true;
}
return false;
}
@Override
public Spliterator<Integer> trySplit() {
int currentSize = elements.size() - currentIndex; | if (currentSize < 2) {
return null;
}
int splitIndex = currentIndex + currentSize / 2;
CustomSpliterator newSpliterator = new CustomSpliterator(elements.subList(currentIndex, splitIndex));
currentIndex = splitIndex;
return newSpliterator;
}
@Override
public long estimateSize() {
return elements.size() - currentIndex;
}
@Override
public int characteristics() {
return ORDERED | SIZED | SUBSIZED | NONNULL;
}
} | repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\spliterator\CustomSpliterator.java | 1 |
请完成以下Java代码 | private List<JsonNode> getLastMsgs() {
if (lastMsgs.isEmpty()) {
return lastMsgs;
}
List<JsonNode> errors = lastMsgs.stream()
.map(msg -> msg.get("errorMsg"))
.filter(errorMsg -> errorMsg != null && !errorMsg.isNull() && StringUtils.isNotEmpty(errorMsg.asText()))
.toList();
if (!errors.isEmpty()) {
throw new RuntimeException("WS error from server: " + errors.stream()
.map(JsonNode::asText)
.collect(Collectors.joining(", ")));
}
return lastMsgs;
}
public Map<String, String> getLatest(UUID deviceId) { | Map<String, String> updates = new HashMap<>();
getLastMsgs().forEach(msg -> {
EntityDataUpdate update = JacksonUtil.treeToValue(msg, EntityDataUpdate.class);
Map<String, String> latest = update.getLatest(deviceId);
updates.putAll(latest);
});
return updates;
}
@Override
protected void onSetSSLParameters(SSLParameters sslParameters) {
sslParameters.setEndpointIdentificationAlgorithm(null);
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\client\WsClient.java | 1 |
请完成以下Java代码 | public void setAttributeName (final java.lang.String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
@Override
public java.lang.String getAttributeName()
{
return get_ValueAsString(COLUMNNAME_AttributeName);
}
@Override
public void setAttributeValue (final java.lang.String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
@Override
public java.lang.String getAttributeValue()
{
return get_ValueAsString(COLUMNNAME_AttributeValue);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
} | @Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_ActivityResult.java | 1 |
请完成以下Java代码 | public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
public int getOrderId() {
return orderId;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getPaymentMethod() { | return paymentMethod;
}
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-ordercontext\src\main\java\com\baeldung\dddcontexts\ordercontext\model\CustomerOrder.java | 1 |
请完成以下Java代码 | public static long parseDate(String value, DateFormat[] threadLocalformats) {
Long cachedDate = null;
try {
cachedDate = parseCache.get(value);
}
catch (Exception ex) {
}
if (cachedDate != null) {
return cachedDate;
}
Long date;
if (threadLocalformats != null) {
date = internalParseDate(value, threadLocalformats);
synchronized (parseCache) {
updateCache(parseCache, value, date);
}
}
else {
synchronized (parseCache) {
date = internalParseDate(value, formats);
updateCache(parseCache, value, date);
}
}
return (date != null) ? date : -1L;
}
/**
* Updates cache. | * @param cache Cache to be updated
* @param key Key to be updated
* @param value New value
*/
@SuppressWarnings("unchecked")
private static void updateCache(HashMap cache, Object key, @Nullable Object value) {
if (value == null) {
return;
}
if (cache.size() > 1000) {
cache.clear();
}
cache.put(key, value);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\FastHttpDateFormat.java | 1 |
请完成以下Java代码 | public String getName() {
return DEFAULT_NAME;
}
@Override
public String getContextualName(DataLoaderObservationContext context) {
List<?> result = context.getResult();
if (result.isEmpty()) {
return "graphql dataloader";
}
else {
return "graphql dataloader " + result.get(0).getClass().getSimpleName().toLowerCase(Locale.ROOT);
}
}
@Override
public KeyValues getLowCardinalityKeyValues(DataLoaderObservationContext context) {
return KeyValues.of(errorType(context), loaderType(context), outcome(context));
}
@Override
public KeyValues getHighCardinalityKeyValues(DataLoaderObservationContext context) {
return KeyValues.of(loaderSize(context));
}
protected KeyValue errorType(DataLoaderObservationContext context) {
if (context.getError() != null) {
return KeyValue.of(DataLoaderLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName());
}
return ERROR_TYPE_NONE;
}
protected KeyValue loaderType(DataLoaderObservationContext context) {
if (StringUtils.hasText(context.getDataLoader().getName())) { | return KeyValue.of(DataLoaderLowCardinalityKeyNames.LOADER_NAME, context.getDataLoader().getName());
}
return LOADER_TYPE_UNKNOWN;
}
protected KeyValue outcome(DataLoaderObservationContext context) {
if (context.getError() != null) {
return OUTCOME_ERROR;
}
return OUTCOME_SUCCESS;
}
protected KeyValue loaderSize(DataLoaderObservationContext context) {
return KeyValue.of(DataLoaderHighCardinalityKeyNames.LOADER_SIZE, String.valueOf(context.getResult().size()));
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataLoaderObservationConvention.java | 1 |
请完成以下Java代码 | protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (isLoginAttempt(request, response)) {
return executeLogin(request, response);
}
return true;
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态 | if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
/**
* 将非法请求 /401
*/
private void response401(ServletRequest req, ServletResponse resp) {
try {
HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
httpServletResponse.sendRedirect("/401");
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\JWTFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user")
.passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
.password("password")
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
.password("password")
.roles("ADMIN")
.build();
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(user);
userDetailsManager.createUser(admin);
return userDetailsManager;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login")
.permitAll()
.requestMatchers("/customError")
.permitAll()
.requestMatchers("/access-denied")
.permitAll()
.requestMatchers("/secured")
.hasRole("ADMIN")
.anyRequest()
.authenticated())
.formLogin(form -> form.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler()))
.exceptionHandling(ex -> ex.accessDeniedHandler(accessDeniedHandler())) | .logout(Customizer.withDefaults());
return http.build();
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\exceptionhandler\security\SecurityConfig.java | 2 |
请完成以下Spring Boot application配置 | server.port=8080
server.address=0.0.0.0
spring.jpa.hibernate.ddl-auto=create
logging.file=azure.log
logging.level.root=info
spring.datasource.url=jdbc:h2:mem:azure-test-db
spring.datasource.username=sa
spring.datasource.password=
#spring.datasource.url=jdbc:mysql | ://localhost:3306/localdb
#spring.datasource.username=your-db-username
#spring.datasource.password=your-db-password | repos\tutorials-master\spring-boot-modules\spring-boot-azure-deployment\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static char getDefaultAttributeQuoteChar()
{
return attribute_quote_char;
}
/*
Should we wrap quotes around an attribute?
*/
public static boolean getDefaultAttributeQuote()
{
return attribute_quote;
}
/**
Does this element need a closing tag?
*/
public static boolean getDefaultEndElement()
{
return end_element;
}
/**
What codeset are we going to use the default is 8859_1
*/
public static String getDefaultCodeset()
{
return codeset;
}
/**
position of tag relative to start and end.
*/
public static int getDefaultPosition()
{
return position; | }
/**
Default value to set case type
*/
public static int getDefaultCaseType()
{
return case_type;
}
public static char getDefaultStartTag()
{
return start_tag;
}
public static char getDefaultEndTag()
{
return end_tag;
}
/**
Should we print html in a more readable format?
*/
public static boolean getDefaultPrettyPrint()
{
return pretty_print;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ECSDefaults.java | 1 |
请完成以下Java代码 | private void autoReportActivities()
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
if (activity.isMilestone()
&& (activity.isSubcontracting() || orderRouting.isFirstActivity(activity)))
{
ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder()
.order(this)
.orderActivity(activity)
.qtyMoved(activity.getQtyToDeliver())
.durationSetup(Duration.ZERO)
.duration(Duration.ZERO)
.build());
}
}
}
private void createVariances()
{ | final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
//
for (final I_PP_Order_BOMLine bomLine : getLines())
{
ppCostCollectorBL.createMaterialUsageVariance(this, bomLine);
}
//
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
ppCostCollectorBL.createResourceUsageVariance(this, activity);
}
}
} // MPPOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PickingJob reservePickingSlotIfPossible(@NonNull final PickingJob pickingJob)
{
final PickingSlotId slotId = pickingJob.getPickingSlotId()
.orElse(null);
if (slotId == null)
{
return pickingJob;
}
return PickingJobAllocatePickingSlotCommand.builder()
.pickingJobRepository(pickingJobRepository)
.pickingSlotService(pickingSlotService)
.pickingJob(pickingJob.withPickingSlot(null))
.pickingSlotId(slotId)
.failIfNotAllocated(false)
.build()
.execute();
}
private void reactivateLine(@NonNull final PickingJobLine line)
{
line.getSteps().forEach(this::reactivateStepIfNeeded);
}
private void reactivateStepIfNeeded(@NonNull final PickingJobStep step)
{
final IMutableHUContext huContext = huService.createMutableHUContextForProcessing();
step.getPickFroms().getKeys()
.stream()
.map(key -> step.getPickFroms().getPickFrom(key))
.map(PickingJobStepPickFrom::getPickedTo) | .filter(Objects::nonNull)
.map(PickingJobStepPickedTo::getActualPickedHUs)
.flatMap(List::stream)
.filter(pickStepHu -> huIdsToPick.containsKey(pickStepHu.getActualPickedHU().getId()))
.forEach(pickStepHU -> {
final HuId huId = pickStepHU.getActualPickedHU().getId();
final I_M_HU hu = huService.getById(huId);
shipmentScheduleService.addQtyPickedAndUpdateHU(AddQtyPickedRequest.builder()
.scheduleId(step.getScheduleId())
.qtyPicked(CatchWeightHelper.extractQtys(
huContext,
step.getProductId(),
pickStepHU.getQtyPicked(),
hu))
.tuOrVHU(hu)
.huContext(huContext)
.anonymousHuPickedOnTheFly(huIdsToPick.get(huId).isAnonymousHuPickedOnTheFly())
.build());
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobReopenCommand.java | 2 |
请完成以下Java代码 | public final class PharmaVendorPermissions
{
public static PharmaVendorPermissions of(final I_C_BPartner bpartner)
{
if (!bpartner.isVendor())
{
return NONE;
}
final ImmutableSet.Builder<PharmaVendorPermission> permissionsBuilder = ImmutableSet.builder();
if (bpartner.isPharmaVendorAgentPermission())
{
permissionsBuilder.add(PharmaVendorPermission.PHARMA_AGENT);
}
if (bpartner.isPharmaVendorManufacturerPermission())
{
permissionsBuilder.add(PharmaVendorPermission.PHARMA_MANUFACTURER);
}
if (bpartner.isPharmaVendorWholesalePermission())
{
permissionsBuilder.add(PharmaVendorPermission.PHARMA_WHOLESALE);
}
if (bpartner.isPharmaVendorNarcoticsPermission())
{
permissionsBuilder.add(PharmaVendorPermission.PHARMA_NARCOTICS);
}
final ImmutableSet<PharmaVendorPermission> permissions = permissionsBuilder.build();
if (permissions.isEmpty())
{
return NONE;
}
return new PharmaVendorPermissions(permissions);
}
private static final PharmaVendorPermissions NONE = new PharmaVendorPermissions(ImmutableSet.of());
private final ImmutableSet<PharmaVendorPermission> permissions; | private PharmaVendorPermissions(final Set<PharmaVendorPermission> permissions)
{
this.permissions = ImmutableSet.copyOf(permissions);
}
public boolean hasNoPermissions()
{
return permissions.isEmpty();
}
public boolean hasAtLeastOnePermission()
{
return !permissions.isEmpty();
}
public boolean hasPermission(final PharmaVendorPermission permission)
{
return permissions.contains(permission);
}
public boolean hasOnlyPermission(final PharmaVendorPermission permission)
{
return permissions.size() == 1 && permissions.contains(permission);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\PharmaVendorPermissions.java | 1 |
请完成以下Java代码 | public List<IncidentDto> getIncidents(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
IncidentQuery query = queryDto.toQuery(getProcessEngine());
List<Incident> queryResult = QueryUtil.list(query, firstResult, maxResults);
List<IncidentDto> result = new ArrayList<>();
for (Incident incident : queryResult) {
IncidentDto dto = IncidentDto.fromIncident(incident);
result.add(dto);
}
return result;
}
@Override | public CountResultDto getIncidentsCount(UriInfo uriInfo) {
IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
IncidentQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public IncidentResource getIncident(String incidentId) {
return new IncidentResourceImpl(getProcessEngine(), incidentId, getObjectMapper());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\IncidentRestServiceImpl.java | 1 |
请完成以下Java代码 | protected boolean beforeSave (boolean newRecord)
{
if (isAchieved())
{
if (getManualActual().signum() == 0)
setManualActual(Env.ONE);
if (getDateDoc() == null)
setDateDoc(new Timestamp(System.currentTimeMillis()));
}
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (success)
updateAchievementGoals();
return success;
} // afterSave
/**
* After Delete
* @param success success
* @return success | */
@Override
protected boolean afterDelete (boolean success)
{
if (success)
updateAchievementGoals();
return success;
} // afterDelete
/**
* Update Goals with Achievement
*/
private void updateAchievementGoals()
{
MMeasure measure = MMeasure.get (getCtx(), getPA_Measure_ID());
measure.updateGoals();
} // updateAchievementGoals
} // MAchievement | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAchievement.java | 1 |
请完成以下Java代码 | public Long getCity() {
return city;
}
public void setCity(Long city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} | public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
@Override
public String toString() {
return getCity() + "," + getName() + "," + getAddress() + "," + getZip();
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-samples\pagehelper-spring-boot-sample-xml\src\main\java\tk\mybatis\pagehelper\domain\Hotel.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getParameterName());
}
/** Set Process Date.
@param P_Date
Process Parameter
*/
public void setP_Date (Timestamp P_Date)
{
set_Value (COLUMNNAME_P_Date, P_Date);
}
/** Get Process Date.
@return Process Parameter
*/
public Timestamp getP_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_P_Date);
}
/** Set Process Date To.
@param P_Date_To
Process Parameter
*/
public void setP_Date_To (Timestamp P_Date_To)
{
set_Value (COLUMNNAME_P_Date_To, P_Date_To);
}
/** Get Process Date To.
@return Process Parameter
*/
public Timestamp getP_Date_To ()
{
return (Timestamp)get_Value(COLUMNNAME_P_Date_To);
}
/** Set Process Number.
@param P_Number
Process Parameter
*/
public void setP_Number (BigDecimal P_Number)
{
set_Value (COLUMNNAME_P_Number, P_Number);
}
/** Get Process Number.
@return Process Parameter
*/
public BigDecimal getP_Number ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Process Number To.
@param P_Number_To
Process Parameter
*/
public void setP_Number_To (BigDecimal P_Number_To)
{
set_Value (COLUMNNAME_P_Number_To, P_Number_To);
}
/** Get Process Number To.
@return Process Parameter
*/
public BigDecimal getP_Number_To ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number_To);
if (bd == null) | return Env.ZERO;
return bd;
}
/** Set Process String.
@param P_String
Process Parameter
*/
public void setP_String (String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Process Parameter
*/
public String getP_String ()
{
return (String)get_Value(COLUMNNAME_P_String);
}
/** Set Process String To.
@param P_String_To
Process Parameter
*/
public void setP_String_To (String P_String_To)
{
set_Value (COLUMNNAME_P_String_To, P_String_To);
}
/** Get Process String To.
@return Process Parameter
*/
public String getP_String_To ()
{
return (String)get_Value(COLUMNNAME_P_String_To);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Para.java | 1 |
请完成以下Java代码 | public List<Object> provideLineGroupingValues(final OLCand cand)
{
return providers.stream()
.flatMap(provider -> provider.provideLineGroupingValues(cand).stream())
.collect(Collectors.toList());
}
}
private static final class NullOLCandValidator implements IOLCandValidator
{
public static final transient NullOLCandValidator instance = new NullOLCandValidator();
/** @return {@code 0} */
@Override
public int getSeqNo()
{
return 0;
}
@Override
public void validate(final I_C_OLCand olCand)
{
// nothing to do
}
}
private static final class CompositeOLCandValidator implements IOLCandValidator
{
private final ImmutableList<IOLCandValidator> validators;
private final IErrorManager errorManager;
private CompositeOLCandValidator(@NonNull final List<IOLCandValidator> validators, @NonNull final IErrorManager errorManager)
{
this.validators = ImmutableList.copyOf(validators);
this.errorManager = errorManager;
}
/** @return {@code 0}. Actually, it doesn't matte for this validator. */
@Override
public int getSeqNo()
{
return 0;
}
/**
* Change {@link I_C_OLCand#COLUMN_IsError IsError}, {@link I_C_OLCand#COLUMN_ErrorMsg ErrorMsg},
* {@link I_C_OLCand#COLUMNNAME_AD_Issue_ID ADIssueID} accordingly, but <b>do not</b> save. | */
@Override
public void validate(@NonNull final I_C_OLCand olCand)
{
for (final IOLCandValidator olCandValdiator : validators)
{
try
{
olCandValdiator.validate(olCand);
}
catch (final Exception e)
{
final AdempiereException me = AdempiereException
.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("OLCandValidator", olCandValdiator.getClass().getSimpleName());
olCand.setIsError(true);
olCand.setErrorMsg(me.getLocalizedMessage());
final AdIssueId issueId = errorManager.createIssue(e);
olCand.setAD_Issue_ID(issueId.getRepoId());
olCand.setErrorMsgJSON(JsonObjectMapperHolder.toJsonNonNull(JsonErrorItem.builder()
.message(me.getLocalizedMessage())
.errorCode(AdempiereException.extractErrorCodeOrNull(me))
.stackTrace(Trace.toOneLineStackTraceString(me.getStackTrace()))
.adIssueId(JsonMetasfreshId.of(issueId.getRepoId()))
.errorCode(AdempiereException.extractErrorCodeOrNull(me))
.throwable(me)
.build()));
break;
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandSPIRegistry.java | 1 |
请完成以下Java代码 | public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID)
{
if (M_Shipper_RoutingCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID);
}
@Override
public int getM_Shipper_RoutingCode_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_RoutingCode.java | 1 |
请完成以下Java代码 | public StringElement addElement(String hashcode,String element)
{
// We do it this way so that filtering will work.
// 1. create a new StringElement(element) - this is the only way that setTextTag will get called
// 2. copy the filter state of this string element to this child.
// 3. copy the filter for this string element to this child.
StringElement se = new StringElement(element);
se.setFilterState(getFilterState());
se.setFilter(getFilter());
addElementToRegistry(hashcode,se);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public StringElement addElement(String element)
{
addElement(Integer.toString(element.hashCode()),element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public StringElement addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element. | @param hashcode the name of the element to be removed.
*/
public StringElement removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
protected String createStartTag()
{
return("");
}
protected String createEndTag()
{
return("");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\StringElement.java | 1 |
请完成以下Java代码 | public class CdiBusinessProcessEvent implements BusinessProcessEvent {
protected final String activityId;
protected final ProcessDefinition processDefinition;
protected final String transitionName;
protected final String processInstanceId;
protected final String executionId;
protected final DelegateTask delegateTask;
protected final BusinessProcessEventType type;
protected final Date timeStamp;
public CdiBusinessProcessEvent(String activityId,
String transitionName,
ProcessDefinition processDefinition,
DelegateExecution execution,
BusinessProcessEventType type,
Date timeStamp) {
this.activityId = activityId;
this.transitionName = transitionName;
this.processInstanceId = execution.getProcessInstanceId();
this.executionId = execution.getId();
this.type = type;
this.timeStamp = timeStamp;
this.processDefinition = processDefinition;
this.delegateTask = null;
}
public CdiBusinessProcessEvent(DelegateTask task, ProcessDefinitionEntity processDefinition, BusinessProcessEventType type, Date timeStamp) {
this.activityId = null;
this.transitionName = null;
this.processInstanceId = task.getProcessInstanceId();
this.executionId = task.getExecutionId();
this.type = type;
this.timeStamp = timeStamp;
this.processDefinition = processDefinition;
this.delegateTask = task;
}
@Override
public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getTransitionName() { | return transitionName;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public BusinessProcessEventType getType() {
return type;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public DelegateTask getTask() {
return delegateTask;
}
@Override
public String getTaskId() {
if (delegateTask != null) {
return delegateTask.getId();
}
return null;
}
@Override
public String getTaskDefinitionKey() {
if (delegateTask != null) {
return delegateTask.getTaskDefinitionKey();
}
return null;
}
@Override
public String toString() {
return "Event '" + processDefinition.getKey() + "' ['" + type + "', " + (type == BusinessProcessEventType.TAKE ? transitionName : activityId) + "]";
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\event\CdiBusinessProcessEvent.java | 1 |
请完成以下Java代码 | protected final void setDeliveredDataFromFirstInOut(@NonNull final I_C_Invoice_Candidate ic, @Nullable final I_M_InOut firstInOut)
{
ic.setM_InOut(firstInOut);
if (firstInOut == null)
{
ic.setDeliveryDate(null);
ic.setFirst_Ship_BPLocation_ID(-1);
ic.setC_Shipping_Location_ID(-1);
}
else
{
ic.setDeliveryDate(firstInOut.getMovementDate());
ic.setFirst_Ship_BPLocation_ID(firstInOut.getC_BPartner_Location_ID()); // C_BPartner_Location
ic.setC_Shipping_Location_ID(firstInOut.getC_BPartner_Location_Value_ID()); // C_Location
}
}
/**
* Assumes that the given {@code icRecord}'s {@code AD_Client_ID}, {@code AD_Org_ID} and {@code IsSOTrx} are already set at this point | */
protected final void setDefaultInvoiceDocType(final @NonNull I_C_Invoice_Candidate icRecord)
{
final DocTypeQuery docTypeQuery = DocTypeQuery.builder()
.adClientId(icRecord.getAD_Client_ID())
.adOrgId(icRecord.getAD_Org_ID())
.isSOTrx(icRecord.isSOTrx())
.docBaseType(icRecord.isSOTrx()
? InvoiceDocBaseType.CustomerInvoice.getCode()
: InvoiceDocBaseType.VendorInvoice.getCode())
.build();
final DocTypeId docTypeIdOrNull = docTypeBL.getDocTypeIdOrNull(docTypeQuery);
if (docTypeIdOrNull != null)
{
icRecord.setC_DocTypeInvoice_ID(docTypeIdOrNull.getRepoId());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\AbstractInvoiceCandidateHandler.java | 1 |
请完成以下Java代码 | public int compare(final ISideAction action1, final ISideAction action2)
{
final String displayName1 = getDisplayName(action1);
final String displayName2 = getDisplayName(action2);
return displayName1.compareTo(displayName2);
}
private final String getDisplayName(final ISideAction action)
{
final String displayName = action == null ? "" : action.getDisplayName();
return displayName == null ? "" : displayName;
}
};
enum SideActionType
{
Toggle,
ExecutableAction,
Label,
}
String getId();
/** @return user friendly name */
String getDisplayName();
/** @return side action type */ | SideActionType getType();
/**
* In case this action is of type {@link SideActionType#Toggle},
* this method is called by API/UI to tell this action that it was toggled(activated) or untoggled(deactivated).
*
* @param toggled
*/
void setToggled(final boolean toggled);
/**
* @return true if this side action is of type {@link SideActionType#Toggle} and it's toggled.
* @see #setToggled(boolean).
*/
boolean isToggled();
/**
* Called by API when user clicks on UI component of this action.
*/
void execute();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\ISideAction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TestController {
@Autowired
private UserService userService;
@GetMapping("testRequestMerge")
public void testRequerstMerge() throws InterruptedException, ExecutionException {
Future<User> f1 = userService.findUser(1L);
Future<User> f2 = userService.findUser(2L);
Future<User> f3 = userService.findUser(3L);
f1.get();
f2.get();
f3.get();
Thread.sleep(200);
Future<User> f4 = userService.findUser(4L);
f4.get();
}
@GetMapping("testCache")
public void testCache() {
userService.getUser(1L);
userService.getUser(1L);
userService.getUser(1L);
}
@GetMapping("user/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping("user")
public List<User> getUsers() { | return userService.getUsers();
}
@GetMapping("user/add")
public String addUser() {
return userService.addUser();
}
@GetMapping("user/update")
public void updateUser() {
userService.updateUser(new User(1L, "mrbird", "123456"));
}
@GetMapping("user/delete/{id:\\d+}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
} | repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\controller\TestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public void setData(String data) {
this.data = data;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getIdPrefix() {
// id prefix is empty because sequence is used instead of id prefix
return "";
}
@Override
public void setLogNumber(long logNumber) {
this.logNumber = logNumber;
}
@Override
public long getLogNumber() {
return logNumber;
} | @Override
public String getType() {
return type;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")";
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Todo> retrieveTodos(String user) {
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if (todo.getUser().equalsIgnoreCase(user)) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
public Todo retrieveTodo(int id) {
for (Todo todo : todos) {
if (todo.getId()==id) {
return todo;
}
}
return null;
} | public void updateTodo(Todo todo){
todos.remove(todo);
todos.add(todo);
}
public void addTodo(String name, String desc, Date targetDate,
boolean isDone) {
todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));
}
public void deleteTodo(int id) {
Iterator<Todo> iterator = todos.iterator();
while (iterator.hasNext()) {
Todo todo = iterator.next();
if (todo.getId() == id) {
iterator.remove();
}
}
}
} | repos\SpringBootForBeginners-master\02.Spring-Boot-Web-Application\src\main\java\com\in28minutes\springboot\web\service\TodoService.java | 2 |
请完成以下Java代码 | public String getValidateFormFields() {
return validateFormFields;
}
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
@Override
public void addExitCriterion(Criterion exitCriterion) {
exitCriteria.add(exitCriterion);
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
}
@Override
public List<Criterion> getExitCriteria() {
return exitCriteria; | }
@Override
public void setExitCriteria(List<Criterion> exitCriteria) {
this.exitCriteria = exitCriteria;
}
public String getBusinessStatus() {
return businessStatus;
}
public void setBusinessStatus(String businessStatus) {
this.businessStatus = businessStatus;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java | 1 |
请完成以下Java代码 | private IWorkPackageBuilder initiateWorkPackageBuilder(
@NonNull final IWorkPackageQueue workPackageQueue,
@NonNull final ILock mainLock,
@Nullable final AsyncBatchId asyncBatchId,
final boolean propagateAsyncBatchIdToOrderRecord)
{
final IWorkPackageBuilder workpackageBuilder = workPackageQueue.newWorkPackage()
// we want the enqueuing user to be notified on problems
.setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null))
.parameter(PARAM_PROPAGATE_ASYNC_BATCH_ID_TO_ORDER_RECORD, propagateAsyncBatchIdToOrderRecord)
.parameter(PARAM_OLCandProcessor_ID, C_OlCandProcessor_ID_Default);
Optional.ofNullable(asyncBatchId)
.map(asyncBatchDAO::retrieveAsyncBatchRecordOutOfTrx)
.ifPresent(workpackageBuilder::setC_Async_Batch);
workpackageBuilder.setElementsLocker(splitLock(mainLock));
return workpackageBuilder;
}
@NonNull
private ILockCommand splitLock(@NonNull final ILock mainLock)
{
// Create a new locker which will grab the locked candidate from initial lock
// and it will move them to a new owner which is created per work package
final LockOwner workpackageElementsLockOwner = LockOwner.newOwner("ProcessOLCand_" + Instant.now().getMillis());
return mainLock
.split()
.setOwner(workpackageElementsLockOwner)
.setAutoCleanup(false);
}
@NonNull
private ILock lockSelection(@NonNull final PInstanceId selectionId)
{
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, I_AD_PInstance.COLUMN_AD_PInstance_ID + "=" + selectionId.getRepoId());
return lockManager.lock()
.setOwner(lockOwner)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_C_OLCand.class, selectionId)
.acquire();
}
private void setHeaderAggregationKey(@NonNull final C_OLCandToOrderEnqueuer.EnqueueWorkPackageRequest request)
{
final IOLCandBL olCandBL = Services.get(IOLCandBL.class);
final OLCandIterator olCandIterator = getOrderedOLCandIterator(request);
final OLCandProcessorDescriptor olCandProcessorDescriptor = request.getOlCandProcessorDescriptor();
while (olCandIterator.hasNext()) | {
final OLCand candidate = olCandIterator.next();
final String headerAggregationKey = olCandProcessorDescriptor.getAggregationInfo().computeHeaderAggregationKey(candidate);
candidate.setHeaderAggregationKey(headerAggregationKey);
olCandBL.saveCandidate(candidate);
}
}
@Builder
@Value
private static class EnqueueWorkPackageRequest
{
@NonNull
ILock mainLock;
@NonNull
PInstanceId orderLineCandSelectionId;
@NonNull
OLCandProcessorDescriptor olCandProcessorDescriptor;
@Nullable
AsyncBatchId asyncBatchId;
boolean propagateAsyncBatchIdToOrderRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\async\C_OLCandToOrderEnqueuer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
} | public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\EventResponse.java | 2 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Type AD_Reference_ID=53245 */
public static final int TYPE_AD_Reference_ID=53245;
/** Concept = C */
public static final String TYPE_Concept = "C";
/** Rule Engine = E */
public static final String TYPE_RuleEngine = "E";
/** Information = I */
public static final String TYPE_Information = "I";
/** Reference = R */
public static final String TYPE_Reference = "R";
/** Set Type.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day) | */
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** 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);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getValue());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept.java | 1 |
请完成以下Java代码 | class ClusterNodes implements Streamable<TransportAddress> {
public static ClusterNodes DEFAULT = ClusterNodes.of("127.0.0.1:9300");
private static final String COLON = ":";
private static final String COMMA = ",";
private final List<TransportAddress> clusterNodes;
/**
* Creates a new {@link ClusterNodes} by parsing the given source.
*
* @param source must not be {@literal null} or empty.
*/
private ClusterNodes(String source) {
Assert.hasText(source, "Cluster nodes source must not be null or empty!");
String[] nodes = StringUtils.delimitedListToStringArray(source, COMMA);
this.clusterNodes = Arrays.stream(nodes).map(node -> {
String[] segments = StringUtils.delimitedListToStringArray(node, COLON);
Assert.isTrue(segments.length == 2,
() -> String.format("Invalid cluster node %s in %s! Must be in the format host:port!", node, source));
String host = segments[0].trim();
String port = segments[1].trim();
Assert.hasText(host, () -> String.format("No host name given cluster node %s!", node));
Assert.hasText(port, () -> String.format("No port given in cluster node %s!", node));
return new TransportAddress(toInetAddress(host), Integer.valueOf(port));
}).collect(Collectors.toList());
} | /**
* Creates a new {@link ClusterNodes} by parsing the given source. The expected format is a comma separated list of
* host-port-combinations separated by a colon: {@code host:port,host:port,…}.
*
* @param source must not be {@literal null} or empty.
* @return
*/
public static ClusterNodes of(String source) {
return new ClusterNodes(source);
}
/*
* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<TransportAddress> iterator() {
return clusterNodes.iterator();
}
private static InetAddress toInetAddress(String host) {
try {
return InetAddress.getByName(host);
} catch (UnknownHostException o_O) {
throw new IllegalArgumentException(o_O);
}
}
} | repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\spring\ClusterNodes.java | 1 |
请完成以下Java代码 | public VariableInstanceQuery excludeTaskVariables() {
wrappedVariableInstanceQuery.excludeTaskVariables();
return this;
}
@Override
public VariableInstanceQuery excludeLocalVariables() {
wrappedVariableInstanceQuery.excludeLocalVariables();
return this;
}
@Override
public VariableInstanceQuery excludeVariableInitialization() {
wrappedVariableInstanceQuery.excludeVariableInitialization();
return this;
}
@Override
public VariableInstanceQuery variableValueEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueNotEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLike(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLike(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery orderByVariableName() {
wrappedVariableInstanceQuery.orderByVariableName();
return this;
} | @Override
public VariableInstanceQuery asc() {
wrappedVariableInstanceQuery.asc();
return this;
}
@Override
public VariableInstanceQuery desc() {
wrappedVariableInstanceQuery.desc();
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property) {
wrappedVariableInstanceQuery.orderBy(property);
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return wrappedVariableInstanceQuery.count();
}
@Override
public VariableInstance singleResult() {
return wrappedVariableInstanceQuery.singleResult();
}
@Override
public List<VariableInstance> list() {
return wrappedVariableInstanceQuery.list();
}
@Override
public List<VariableInstance> listPage(int firstResult, int maxResults) {
return wrappedVariableInstanceQuery.listPage(firstResult, maxResults);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java | 1 |
请完成以下Java代码 | protected CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return getCaseDefinitionManager().findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
@Override
protected CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return getCaseDefinitionManager().findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId);
}
@Override
protected void persistDefinition(CaseDefinitionEntity definition) {
getCaseDefinitionManager().insertCaseDefinition(definition);
}
@Override
protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, CaseDefinitionEntity definition) {
deploymentCache.addCaseDefinition(definition);
}
// context ///////////////////////////////////////////////////////////////////////////////////////////
protected CaseDefinitionManager getCaseDefinitionManager() {
return getCommandContext().getCaseDefinitionManager();
}
// getters/setters ///////////////////////////////////////////////////////////////////////////////////
public ExpressionManager getExpressionManager() {
return expressionManager; | }
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public CmmnTransformer getTransformer() {
return transformer;
}
public void setTransformer(CmmnTransformer transformer) {
this.transformer = transformer;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\deployer\CmmnDeployer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDeploymentUrl() {
return deploymentUrl;
}
public void setDeploymentUrl(String deploymentUrl) {
this.deploymentUrl = deploymentUrl;
}
@ApiModelProperty(example = "null")
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public String getSourceExtraUrl() {
return sourceExtraUrl;
}
public void setSourceExtraUrl(String sourceExtraUrl) {
this.sourceExtraUrl = sourceExtraUrl;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelResponse.java | 2 |
请完成以下Java代码 | private void notifyExecutions(List<EventSubscriptionEntity> catchSignalEventSubscription) {
for (EventSubscriptionEntity signalEventSubscriptionEntity : catchSignalEventSubscription) {
if (isActiveEventSubscription(signalEventSubscriptionEntity)) {
signalEventSubscriptionEntity.eventReceived(builder.getVariables(), false);
}
}
}
private boolean isActiveEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
ExecutionEntity execution = signalEventSubscriptionEntity.getExecution();
return !execution.isEnded() && !execution.isCanceled();
}
private void startProcessInstances(List<EventSubscriptionEntity> startSignalEventSubscriptions, Map<String, ProcessDefinitionEntity> processDefinitions) {
for (EventSubscriptionEntity signalStartEventSubscription : startSignalEventSubscriptions) {
ProcessDefinitionEntity processDefinition = processDefinitions.get(signalStartEventSubscription.getId());
if (processDefinition != null) {
ActivityImpl signalStartEvent = processDefinition.findActivity(signalStartEventSubscription.getActivityId());
PvmProcessInstance processInstance = processDefinition.createProcessInstanceForInitial(signalStartEvent);
processInstance.start(builder.getVariables());
}
}
}
protected List<EventSubscriptionEntity> filterIntermediateSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) { | if (subscription.getExecutionId() != null) {
result.add(subscription);
}
}
return result;
}
protected List<EventSubscriptionEntity> filterStartSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) {
if (subscription.getExecutionId() == null) {
result.add(subscription);
}
}
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SignalEventReceivedCmd.java | 1 |
请完成以下Java代码 | public NamePair getNullAttributeValue()
{
final IAttributeValuesProvider attributeValuesProvider = getAttributeValuesProvider();
return attributeValuesProvider.getNullValue();
}
@Override
public final boolean isNumericValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number.equals(valueType);
}
@Override
public final boolean isStringValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40.equals(valueType);
}
@Override
public final boolean isDateValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(valueType);
}
@Override
public final boolean isList()
{
return _attributeValuesProvider != null;
}
@Override
public final boolean isEmpty()
{
return Objects.equals(getValue(), getEmptyValue());
}
@Nullable
@Override
public final Object getEmptyValue()
{
final Object value = getValue();
if (value == null)
{
return null;
}
if (value instanceof BigDecimal)
{
return BigDecimal.ZERO;
}
else if (value instanceof String)
{
return null;
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return null;
}
else
{
throw new InvalidAttributeValueException("Value type '" + value.getClass() + "' not supported for " + attribute);
}
}
@Override
public final void addAttributeValueListener(final IAttributeValueListener listener)
{
listeners.addAttributeValueListener(listener);
}
@Override
public final void removeAttributeValueListener(final IAttributeValueListener listener)
{
listeners.removeAttributeValueListener(listener);
}
@Override
public I_C_UOM getC_UOM() | {
final int uomId = attribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
return null;
}
}
private IAttributeValueCallout _attributeValueCallout = null;
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
if (_attributeValueCallout == null)
{
final IAttributeValueGenerator attributeValueGenerator = getAttributeValueGeneratorOrNull();
if (attributeValueGenerator instanceof IAttributeValueCallout)
{
_attributeValueCallout = (IAttributeValueCallout)attributeValueGenerator;
}
else
{
_attributeValueCallout = NullAttributeValueCallout.instance;
}
}
return _attributeValueCallout;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
final I_M_Attribute attribute = getM_Attribute();
final IAttributeValueGenerator attributeValueGenerator = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute);
return attributeValueGenerator;
}
/**
* @return true if NOT disposed
* @see IAttributeStorage#assertNotDisposed()
*/
protected final boolean assertNotDisposed()
{
return getAttributeStorage().assertNotDisposed();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractAttributeValue.java | 1 |
请完成以下Java代码 | public int getAD_ReplicationStrategy_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationStrategy_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_DocType getC_DocType() throws RuntimeException
{
return (I_C_DocType)MTable.get(getCtx(), I_C_DocType.Table_Name)
.getPO(getC_DocType_ID(), get_TrxName()); }
/** Set Document Type.
@param C_DocType_ID
Document type or rules
*/
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Document Type.
@return Document type or rules
*/
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/ | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ReplicationType AD_Reference_ID=126 */
public static final int REPLICATIONTYPE_AD_Reference_ID=126;
/** Local = L */
public static final String REPLICATIONTYPE_Local = "L";
/** Merge = M */
public static final String REPLICATIONTYPE_Merge = "M";
/** Reference = R */
public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */
public static final String REPLICATIONTYPE_Broadcast = "B";
/** Set Replication Type.
@param ReplicationType
Type of Data Replication
*/
public void setReplicationType (String ReplicationType)
{
set_Value (COLUMNNAME_ReplicationType, ReplicationType);
}
/** Get Replication Type.
@return Type of Data Replication
*/
public String getReplicationType ()
{
return (String)get_Value(COLUMNNAME_ReplicationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationDocument.java | 1 |
请完成以下Java代码 | public @Nullable Integer getActive() {
try {
return getDataSource().getBorrowedConnectionsCount();
}
catch (SQLException ex) {
return null;
}
}
@Override
public @Nullable Integer getIdle() {
try {
return getDataSource().getAvailableConnectionsCount();
}
catch (SQLException ex) {
return null;
}
}
@Override
public @Nullable Integer getMax() { | return getDataSource().getMaxPoolSize();
}
@Override
public @Nullable Integer getMin() {
return getDataSource().getMinPoolSize();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getSQLForValidateConnection();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
String autoCommit = getDataSource().getConnectionProperty("autoCommit");
return StringUtils.hasText(autoCommit) ? Boolean.valueOf(autoCommit) : null;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\OracleUcpDataSourcePoolMetadata.java | 1 |
请完成以下Java代码 | public class CountdownLatchResetExample {
private int count;
private int threadCount;
private final AtomicInteger updateCount;
CountdownLatchResetExample(int count, int threadCount) {
updateCount = new AtomicInteger(0);
this.count = count;
this.threadCount = threadCount;
}
public int countWaits() {
CountDownLatch countDownLatch = new CountDownLatch(count);
ExecutorService es = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
es.execute(() -> {
long prevValue = countDownLatch.getCount();
countDownLatch.countDown(); | if (countDownLatch.getCount() != prevValue) {
updateCount.incrementAndGet();
}
});
}
es.shutdown();
return updateCount.get();
}
public static void main(String[] args) {
CountdownLatchResetExample ex = new CountdownLatchResetExample(5, 20);
System.out.println("Count : " + ex.countWaits());
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\countdownlatch\CountdownLatchResetExample.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.