instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public static @NonNull Consumer<Object> beanNameAwareObjectInitializer(@Nullable String beanName) {
return hasNoText(beanName) ? NO_OP : target -> {
if (target instanceof BeanNameAware) {
((BeanNameAware) target).setBeanName(beanName);
}
};
}
/**
* Returns a {@link Consumer} capable of initializing an {@link EnvironmentAware} {@link Object}
* with the given {@link Environment}.
*
* The {@link EnvironmentAware#setEnvironment(Environment)} method is only called on the {@link EnvironmentAware}
* {@link Object} if the {@link Environment} is not {@literal null}.
*
* @param environment {@link Environment} set on the {@link EnvironmentAware} {@link Object} by the {@link Consumer}.
* @return a {@link Consumer} capable of initializing an {@link EnvironmentAware} {@link Object}
* with the given {@link Environment}; never {@literal null}.
* @see org.springframework.context.EnvironmentAware
* @see org.springframework.core.env.Environment
* @see java.util.function.Consumer
*/
public static @NonNull Consumer<Object> environmentAwareObjectInitializer(@Nullable Environment environment) {
return environment == null ? NO_OP : target -> {
if (target instanceof EnvironmentAware) {
((EnvironmentAware) target).setEnvironment(environment);
}
};
} | /**
* Returns a {@link Consumer} capable of initializing an {@link ResourceLoaderAware} {@link Object}
* with the given {@link ResourceLoader}.
*
* The {@link ResourceLoaderAware#setResourceLoader(ResourceLoader)} method is only called on
* the {@link ResourceLoaderAware} {@link Object} if the {@link ResourceLoader} is not {@literal null}.
*
* @param resourceLoader {@link ResourceLoader} set on the {@link ResourceLoaderAware} {@link Object}
* by the {@link Consumer}.
* @return a {@link Consumer} capable of initializing an {@link ResourceLoaderAware} {@link Object}
* with the given {@link ResourceLoader}; never {@literal null}.
* @see org.springframework.context.ResourceLoaderAware
* @see org.springframework.core.io.ResourceLoader
* @see java.util.function.Consumer
*/
public static @NonNull Consumer<Object> resourceLoaderAwareObjectInitializer(@Nullable ResourceLoader resourceLoader) {
return resourceLoader == null ? NO_OP : target -> {
if (target instanceof ResourceLoaderAware) {
((ResourceLoaderAware) target).setResourceLoader(resourceLoader);
}
};
}
private static boolean hasNoText(@Nullable String value) {
return !StringUtils.hasText(value);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\util\ObjectAwareUtils.java | 1 |
请完成以下Java代码 | public de.metas.procurement.base.model.I_PMM_Week getPMM_Week() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PMM_Week_ID, de.metas.procurement.base.model.I_PMM_Week.class);
}
@Override
public void setPMM_Week(de.metas.procurement.base.model.I_PMM_Week PMM_Week)
{
set_ValueFromPO(COLUMNNAME_PMM_Week_ID, de.metas.procurement.base.model.I_PMM_Week.class, PMM_Week);
}
/** Set Procurement Week.
@param PMM_Week_ID Procurement Week */
@Override
public void setPMM_Week_ID (int PMM_Week_ID)
{
if (PMM_Week_ID < 1)
set_Value (COLUMNNAME_PMM_Week_ID, null);
else
set_Value (COLUMNNAME_PMM_Week_ID, Integer.valueOf(PMM_Week_ID));
}
/** Get Procurement Week.
@return Procurement Week */
@Override
public int getPMM_Week_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Week_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Week report event.
@param PMM_WeekReport_Event_ID Week report event */
@Override
public void setPMM_WeekReport_Event_ID (int PMM_WeekReport_Event_ID)
{
if (PMM_WeekReport_Event_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_WeekReport_Event_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_WeekReport_Event_ID, Integer.valueOf(PMM_WeekReport_Event_ID));
}
/** Get Week report event.
@return Week report event */
@Override
public int getPMM_WeekReport_Event_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_WeekReport_Event_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Wochenerster.
@param WeekDate Wochenerster */
@Override
public void setWeekDate (java.sql.Timestamp WeekDate)
{
set_Value (COLUMNNAME_WeekDate, WeekDate);
}
/** Get Wochenerster.
@return Wochenerster */
@Override
public java.sql.Timestamp getWeekDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_WeekDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_WeekReport_Event.java | 1 |
请完成以下Java代码 | public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/
public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */ | public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void confirmReceive(String orderId, String userId) {
// 构造受理上下文
OrderProcessContext<String> context = buildContext(orderId, userId,null, ProcessReqEnum.ConfirmReceive);
// 受理下单请求
processEngine.process(context);
}
/**
* 请求参数校验
* @param req 请求参数
* @param expCodeEnum 异常枚举
* @param <T> 请求参数类型
*/
private <T> void checkParam(T req, ExpCodeEnum expCodeEnum) {
if (req == null) {
throw new CommonBizException(expCodeEnum);
}
}
private <T> OrderProcessContext<String> buildContext(String orderId, String userId, T reqData, ProcessReqEnum processReqEnum) {
OrderProcessContext context = new OrderProcessContext();
// 受理请求
OrderProcessReq req = new OrderProcessReq(); | req.setProcessReqEnum(processReqEnum);
req.setUserId(userId);
if (StringUtils.isNotEmpty(orderId)) {
req.setOrderId(orderId);
}
if (reqData != null) {
req.setReqData(reqData);
}
context.setOrderProcessReq(req);
return context;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\service\OrderServiceImpl.java | 2 |
请完成以下Java代码 | public void execute(ActivityExecution execution) throws Exception {
EnsureUtil
.ensureNotNull("Could not find cancel boundary event for cancel end event " + execution.getActivity(), "cancelBoundaryEvent", cancelBoundaryEvent);
List<EventSubscriptionEntity> compensateEventSubscriptions =
CompensationUtil.collectCompensateEventSubscriptionsForScope(execution);
if(compensateEventSubscriptions.isEmpty()) {
leave(execution);
}
else {
CompensationUtil.throwCompensationEvent(compensateEventSubscriptions, execution, false);
}
}
public void doLeave(ActivityExecution execution) {
// continue via the appropriate cancel boundary event
ScopeImpl eventScope = (ScopeImpl) cancelBoundaryEvent.getEventScope();
ActivityExecution boundaryEventScopeExecution = execution.findExecutionForFlowScope(eventScope);
boundaryEventScopeExecution.executeActivity(cancelBoundaryEvent);
} | public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
// join compensating executions
if(!execution.hasChildren()) {
leave(execution);
} else {
((ExecutionEntity)execution).forceUpdate();
}
}
public void setCancelBoundaryEvent(PvmActivity cancelBoundaryEvent) {
this.cancelBoundaryEvent = cancelBoundaryEvent;
}
public PvmActivity getCancelBoundaryEvent() {
return cancelBoundaryEvent;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CancelEndEventActivityBehavior.java | 1 |
请完成以下Java代码 | public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIban() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIban(String value) {
this.iban = value;
}
/**
* Gets the value of the referenceNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the customerNote property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerNote() {
return customerNote;
}
/**
* Sets the value of the customerNote property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerNote(String value) {
this.customerNote = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\EsrQRType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() { | return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public TimePeriod getPeriod() {
return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
} | repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\domain\Item.java | 2 |
请完成以下Java代码 | public class Address implements Serializable {
private final String street;
private final String city;
private final String zipCode;
public Address(String street, String city, String zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
} | public String getZipCode() {
return zipCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Address)) return false;
Address address = (Address) o;
return street.equals(address.street) && city.equals(address.city) && zipCode.equals(address.zipCode);
}
@Override
public int hashCode() {
return street.hashCode() + city.hashCode() + zipCode.hashCode();
}
} | repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\apachefury\event\Address.java | 1 |
请完成以下Java代码 | protected void parseProcessEnginePlugins(Element element, List<ProcessEnginePluginXml> plugins) {
for (Element chidElement : element.elements()) {
if(PLUGIN.equals(chidElement.getTagName())) {
parseProcessEnginePlugin(chidElement, plugins);
}
}
}
/**
* Transform a <code><plugin ... /></code> structure.
*/
protected void parseProcessEnginePlugin(Element element, List<ProcessEnginePluginXml> plugins) {
ProcessEnginePluginXmlImpl plugin = new ProcessEnginePluginXmlImpl();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(PLUGIN_CLASS.equals(childElement.getTagName())) {
plugin.setPluginClass(childElement.getText());
} else if(PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties);
}
}
plugin.setProperties(properties);
plugins.add(plugin);
}
/**
* Transform a
* <pre> | * <properties>
* <property name="name">value</property>
* </properties>
* </pre>
* structure into a properties {@link Map}
*
* Supports resolution of Ant-style placeholders against system properties.
*
*/
protected void parseProperties(Element element, Map<String, String> properties) {
for (Element childElement : element.elements()) {
if(PROPERTY.equals(childElement.getTagName())) {
String resolved = PropertyHelper.resolveProperty(System.getProperties(), childElement.getText());
properties.put(childElement.attribute(NAME), resolved);
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\metadata\DeploymentMetadataParse.java | 1 |
请完成以下Java代码 | public java.math.BigDecimal getDK_ParcelLength ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelLength);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Sendungsnummer.
@param DK_ParcelNumber Sendungsnummer */
@Override
public void setDK_ParcelNumber (java.lang.String DK_ParcelNumber)
{
set_Value (COLUMNNAME_DK_ParcelNumber, DK_ParcelNumber);
}
/** Get Sendungsnummer.
@return Sendungsnummer */
@Override
public java.lang.String getDK_ParcelNumber ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_ParcelNumber);
}
/** Set Paketgewicht.
@param DK_ParcelWeight Paketgewicht */
@Override
public void setDK_ParcelWeight (java.math.BigDecimal DK_ParcelWeight)
{
set_Value (COLUMNNAME_DK_ParcelWeight, DK_ParcelWeight);
}
/** Get Paketgewicht.
@return Paketgewicht */
@Override
public java.math.BigDecimal getDK_ParcelWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWeight);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Paketbreite.
@param DK_ParcelWidth Paketbreite */
@Override
public void setDK_ParcelWidth (java.math.BigDecimal DK_ParcelWidth)
{
set_Value (COLUMNNAME_DK_ParcelWidth, DK_ParcelWidth);
}
/** Get Paketbreite.
@return Paketbreite */
@Override
public java.math.BigDecimal getDK_ParcelWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWidth);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Referenz.
@param DK_Reference Referenz */
@Override
public void setDK_Reference (java.lang.String DK_Reference)
{ | set_Value (COLUMNNAME_DK_Reference, DK_Reference);
}
/** Get Referenz.
@return Referenz */
@Override
public java.lang.String getDK_Reference ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Reference);
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Einzelne Zeile in dem Dokument
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine.java | 1 |
请完成以下Java代码 | public ADRefList getDisposalReasons()
{
return adReferenceService.getRefListById(QtyRejectedReasonCode.REFERENCE_ID);
}
public void createDisposeCandidates(
@NonNull final HuId huId,
@NonNull final QtyRejectedReasonCode reasonCode)
{
trxManager.runInThreadInheritedTrx(() -> createDisposeCandidatesInTrx(huId, reasonCode));
}
public void createDisposeCandidatesInTrx(
@NonNull final HuId huId,
@NonNull final QtyRejectedReasonCode reasonCode)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
if (!huStatusBL.isQtyOnHand(hu.getHUStatus()))
{
throw new AdempiereException("Invalid HU status: " + hu.getHUStatus());
}
final ImmutableMap<ProductId, I_M_Inventory_Candidate> existingRecords = Maps.uniqueIndex(
queryByHuIdAndNotProcessed(huId).create().list(),
record -> ProductId.ofRepoId(record.getM_Product_ID()));
handlingUnitsBL.getStorageFactory()
.getStorage(hu)
.getProductStorages()
.forEach(huProductStorage -> {
final I_M_Inventory_Candidate existingRecord = existingRecords.get(huProductStorage.getProductId());
createOrUpdateDisposeCandidate(huProductStorage, reasonCode, existingRecord);
});
}
private void createOrUpdateDisposeCandidate(
@NonNull final IHUProductStorage huProductStorage,
@NonNull final QtyRejectedReasonCode reasonCode,
@Nullable final I_M_Inventory_Candidate existingRecord) | {
final I_M_Inventory_Candidate record;
if (existingRecord == null)
{
record = InterfaceWrapperHelper.newInstance(I_M_Inventory_Candidate.class);
record.setM_HU_ID(huProductStorage.getHuId().getRepoId());
record.setM_Product_ID(huProductStorage.getProductId().getRepoId());
}
else
{
record = existingRecord;
}
final Quantity qty = huProductStorage.getQty();
record.setC_UOM_ID(qty.getUomId().getRepoId());
record.setQtyToDispose(qty.toBigDecimal());
record.setIsWholeHU(true);
record.setDisposeReason(reasonCode.getCode());
InterfaceWrapperHelper.save(record);
}
private IQueryBuilder<I_M_Inventory_Candidate> queryByHuIdAndNotProcessed(final @NonNull HuId huId)
{
return queryBL.createQueryBuilder(I_M_Inventory_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_M_HU_ID, huId)
.addEqualsFilter(I_M_Inventory_Candidate.COLUMNNAME_Processed, false);
}
public boolean isDisposalPending(final @NonNull HuId huId)
{
return queryByHuIdAndNotProcessed(huId)
.addNotNull(I_M_Inventory_Candidate.COLUMNNAME_DisposeReason)
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\InventoryCandidateService.java | 1 |
请完成以下Java代码 | public Object getRenderedStartForm(String processDefinitionId) {
return commandExecutor.execute(new GetRenderedStartFormCmd(processDefinitionId, null));
}
@Override
public Object getRenderedStartForm(String processDefinitionId, String engineName) {
return commandExecutor.execute(new GetRenderedStartFormCmd(processDefinitionId, engineName));
}
@Override
public Object getRenderedTaskForm(String taskId) {
return commandExecutor.execute(new GetRenderedTaskFormCmd(taskId, null));
}
@Override
public Object getRenderedTaskForm(String taskId, String engineName) {
return commandExecutor.execute(new GetRenderedTaskFormCmd(taskId, engineName));
}
@Override
public StartFormData getStartFormData(String processDefinitionId) {
return commandExecutor.execute(new GetStartFormCmd(processDefinitionId));
}
@Override
public TaskFormData getTaskFormData(String taskId) {
return commandExecutor.execute(new GetTaskFormCmd(taskId));
}
@Override
public ProcessInstance submitStartFormData(String processDefinitionId, Map<String, String> properties) {
return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, null, properties));
}
@Override
public ProcessInstance submitStartFormData(String processDefinitionId, String businessKey, Map<String, String> properties) {
return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, businessKey, properties));
} | @Override
public void submitTaskFormData(String taskId, Map<String, String> properties) {
commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, true));
}
@Override
public String getStartFormKey(String processDefinitionId) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId));
}
@Override
public String getTaskFormKey(String processDefinitionId, String taskDefinitionKey) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId, taskDefinitionKey));
}
@Override
public void saveFormData(String taskId, Map<String, String> properties) {
commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, false));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\FormServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
protected Integer age;
protected Long id;
protected String name;
/**
* 获取age属性的值。
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getAge() {
return age;
}
/**
* 设置age属性的值。
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setAge(Integer value) {
this.age = value;
}
/**
* 获取id属性的值。
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* 设置id属性的值。
* | * @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* 获取name属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* 设置name属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
} | repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\User.java | 2 |
请完成以下Java代码 | class Money {
int amount;
String currencyCode;
Money(int amount, String currencyCode) {
this.amount = amount;
this.currencyCode = currencyCode;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Money))
return false;
Money other = (Money)o; | boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
|| (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
return this.amount == other.amount
&& currencyCodeEquals;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + amount;
if (currencyCode != null) {
result = 31 * result + currencyCode.hashCode();
}
return result;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-methods\src\main\java\com\baeldung\equalshashcode\Money.java | 1 |
请完成以下Java代码 | protected void enrichMessage(ObjectNode msgData, TbMsgMetaData metaData, KvEntry kvEntry, String targetKey) {
if (TbMsgSource.DATA.equals(fetchTo)) {
JacksonUtil.addKvEntry(msgData, kvEntry, targetKey);
} else if (TbMsgSource.METADATA.equals(fetchTo)) {
metaData.putValue(targetKey, kvEntry.getValueAsString());
}
}
protected TbMsg transformMessage(TbMsg msg, ObjectNode msgDataNode, TbMsgMetaData msgMetaData) {
switch (fetchTo) {
case DATA:
return msg.transform()
.data(JacksonUtil.toString(msgDataNode))
.build();
case METADATA:
return msg.transform()
.metaData(msgMetaData)
.build();
default:
log.debug("Unexpected FetchTo value: {}. Allowed values: {}", fetchTo, TbMsgSource.values());
return msg;
}
}
protected TbPair<Boolean, JsonNode> upgradeRuleNodesWithOldPropertyToUseFetchTo(
JsonNode oldConfiguration,
String oldProperty,
String ifTrue,
String ifFalse
) throws TbNodeException {
var newConfig = (ObjectNode) oldConfiguration;
if (!newConfig.has(oldProperty)) { | throw new TbNodeException("property to update: '" + oldProperty + "' doesn't exists in configuration!");
}
return upgradeConfigurationToUseFetchTo(oldProperty, ifTrue, ifFalse, newConfig);
}
protected TbPair<Boolean, JsonNode> upgradeConfigurationToUseFetchTo(
String oldProperty, String ifTrue,
String ifFalse, ObjectNode newConfig
) throws TbNodeException {
var value = newConfig.get(oldProperty).asText();
if ("true".equals(value)) {
newConfig.remove(oldProperty);
newConfig.put(FETCH_TO_PROPERTY_NAME, ifTrue);
return new TbPair<>(true, newConfig);
} else if ("false".equals(value)) {
newConfig.remove(oldProperty);
newConfig.put(FETCH_TO_PROPERTY_NAME, ifFalse);
return new TbPair<>(true, newConfig);
} else {
throw new TbNodeException("property to update: '" + oldProperty + "' has unexpected value: "
+ value + ". Allowed values: true or false!");
}
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractNodeWithFetchTo.java | 1 |
请完成以下Java代码 | public Object getBase() {
return base;
}
/**
* Obtain the {@link MethodInfo} for the {@link MethodExpression} for which this {@link MethodReference} has been
* generated.
*
* @return The {@link MethodInfo} for the {@link MethodExpression} for which this {@link MethodReference} has been
* generated.
*/
public MethodInfo getMethodInfo() {
return this.methodInfo;
}
/**
* Obtain the annotations on the method to which the associated expression resolves.
*
* @return The annotations on the method to which the associated expression resolves. If the are no annotations,
* then an empty array is returned.
*/
public Annotation[] getAnnotations() {
return annotations;
}
/**
* Obtain the evaluated parameter values that will be passed to the method to which the associated expression
* resolves.
*
* @return The evaluated parameters.
*/
public Object[] getEvaluatedParameters() {
return evaluatedParameters;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(annotations);
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + Arrays.deepHashCode(evaluatedParameters);
result = prime * result + ((methodInfo == null) ? 0 : methodInfo.hashCode());
return result;
} | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MethodReference other = (MethodReference) obj;
if (!Arrays.equals(annotations, other.annotations)) {
return false;
}
if (base == null) {
if (other.base != null) {
return false;
}
} else if (!base.equals(other.base)) {
return false;
}
if (!Arrays.deepEquals(evaluatedParameters, other.evaluatedParameters)) {
return false;
}
if (methodInfo == null) {
return other.methodInfo == null;
} else {
return methodInfo.equals(other.methodInfo);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodReference.java | 1 |
请完成以下Java代码 | public class EventPublisherPlugin extends SpringBootProcessEnginePlugin {
private static final Logger logger = LoggerFactory.getLogger(EventPublisherPlugin.class);
private final EventingProperty property;
private final ApplicationEventPublisher publisher;
public EventPublisherPlugin(final CamundaBpmProperties properties, final ApplicationEventPublisher publisher) {
this(properties.getEventing(), publisher);
}
public EventPublisherPlugin(final EventingProperty property, final ApplicationEventPublisher publisher) {
this.property = property;
this.publisher = publisher;
}
@Override
public void preInit(SpringProcessEngineConfiguration processEngineConfiguration) {
if (!property.isTask() && !property.isExecution() && !property.isHistory()) {
logger.info("EVENTING-002: Camunda Spring Boot Eventing Plugin is found, but disabled via property.");
return;
}
if (property.isTask() || property.isExecution()) {
logger.info("EVENTING-001: Initialized Camunda Spring Boot Eventing Engine Plugin.");
if (property.isTask()) {
logger.info("EVENTING-003: Task events will be published as Spring Events.");
} else {
logger.info("EVENTING-004: Task eventing is disabled via property.");
}
if (property.isExecution()) {
logger.info("EVENTING-005: Execution events will be published as Spring Events.");
} else { | logger.info("EVENTING-006: Execution eventing is disabled via property.");
}
if (property.isSkippable()) {
logger.info("EVENTING-009: Listeners will not be invoked if a skipCustomListeners API parameter is set to true by user.");
} else {
logger.info("EVENTING-009: Listeners will always be invoked regardless of skipCustomListeners API parameters.");
}
// register parse listener
processEngineConfiguration.getCustomPostBPMNParseListeners().add(new PublishDelegateParseListener(this.publisher, property));
}
if (property.isHistory()) {
logger.info("EVENTING-007: History events will be published as Spring events.");
// register composite DB event handler.
processEngineConfiguration.getCustomHistoryEventHandlers()
.add(new PublishHistoryEventHandler(this.publisher));
} else {
logger.info("EVENTING-008: History eventing is disabled via property.");
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\EventPublisherPlugin.java | 1 |
请完成以下Java代码 | protected void setValueBasedOnAnnotation(String key, String value) {
List<Method> matchingMethods = findMatchingAnnotatedMethods(key);
for (Method method : matchingMethods) {
Class<? extends StringToTypeConverter<?>> converterClass = findAnnotatedTypeConverter(method);
if (converterClass == null) {
continue;
}
StringToTypeConverter<?> converter = null;
try {
converter = converterClass.newInstance();
Object convertedValue = converter.convertQueryParameterToType(value);
method.invoke(this, convertedValue);
} catch (InstantiationException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Server error.");
} catch (IllegalAccessException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Server error.");
} catch (InvocationTargetException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e, "Cannot set query parameter '" + key + "' to value '" + value + "'");
} catch (RestException e) {
throw new InvalidRequestException(e.getStatus(), e,
"Cannot set query parameter '" + key + "' to value '" + value + "': " + e.getMessage());
}
}
}
private List<Method> findMatchingAnnotatedMethods(String parameterName) {
List<Method> result = new ArrayList<Method>();
Method[] methods = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Annotation[] methodAnnotations = method.getAnnotations();
for (int j = 0; j < methodAnnotations.length; j++) { | Annotation annotation = methodAnnotations[j];
if (annotation instanceof CamundaQueryParam) {
CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
if (parameterAnnotation.value().equals(parameterName)) {
result.add(method);
}
}
}
}
return result;
}
private Class<? extends StringToTypeConverter<?>> findAnnotatedTypeConverter(Method method) {
Annotation[] methodAnnotations = method.getAnnotations();
for (int j = 0; j < methodAnnotations.length; j++) {
Annotation annotation = methodAnnotations[j];
if (annotation instanceof CamundaQueryParam) {
CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
return parameterAnnotation.converter();
}
}
return null;
}
@JsonIgnore
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\rest\dto\AbstractRestQueryParametersDto.java | 1 |
请完成以下Java代码 | public void setFeeAmt (BigDecimal FeeAmt)
{
set_Value (COLUMNNAME_FeeAmt, FeeAmt);
}
/** Get Fee Amount.
@return Fee amount in invoice currency
*/
public BigDecimal getFeeAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_FeeAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Interest Amount.
@param InterestAmt
Interest Amount
*/
public void setInterestAmt (BigDecimal InterestAmt)
{
set_Value (COLUMNNAME_InterestAmt, InterestAmt);
}
/** Get Interest Amount.
@return Interest Amount
*/
public BigDecimal getInterestAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InterestAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd; | }
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Times Dunned.
@param TimesDunned
Number of times dunned previously
*/
public void setTimesDunned (int TimesDunned)
{
set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned));
}
/** Get Times Dunned.
@return Number of times dunned previously
*/
public int getTimesDunned ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Total Amount.
@param TotalAmt
Total Amount
*/
public void setTotalAmt (BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Total Amount.
@return Total Amount
*/
public BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java | 1 |
请完成以下Java代码 | public String toString()
{
return "MatchAll";
};
@Override
public boolean test(final LookupValue lookupValue)
{
return true;
}
@Override
public boolean isMatchAll()
{
return true;
};
};
private static final class ContainsLookupValueFilterPredicate implements LookupValueFilterPredicate
{
private final String filterNormalized;
private final String adLanguage;
private ContainsLookupValueFilterPredicate(final String filter, final String adLanguage)
{
super();
filterNormalized = normalizeString(filter);
this.adLanguage = Check.isEmpty(adLanguage, true) ? null : adLanguage;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper("ContainsIgnoreCase")
.omitNullValues()
.addValue(filterNormalized)
.add("adLanguage", adLanguage)
.toString(); | }
private static final String normalizeString(final String str)
{
return str.toLowerCase();
}
@Override
public boolean test(final LookupValue lookupValue)
{
if (lookupValue == null)
{
return false;
}
final String displayName = adLanguage != null ? lookupValue.getDisplayName(adLanguage) : lookupValue.getDisplayName();
if (displayName == null)
{
return false;
}
final String displayNameNormalized = normalizeString(displayName);
return displayNameNormalized.indexOf(filterNormalized) >= 0;
}
@Override
public boolean isMatchAll()
{
return false;
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupValueFilterPredicates.java | 1 |
请完成以下Java代码 | public void setRequestDate(XMLGregorianCalendar value) {
this.requestDate = value;
}
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
/**
* Gets the value of the reminderLevel property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReminderLevel() {
if (reminderLevel == null) {
return "1";
} else {
return reminderLevel;
}
}
/**
* Sets the value of the reminderLevel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReminderLevel(String value) { | this.reminderLevel = value;
}
/**
* Gets the value of the reminderText property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReminderText() {
return reminderText;
}
/**
* Sets the value of the reminderText property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReminderText(String value) {
this.reminderText = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ReminderType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setState(String state) {
this.state = state;
}
public Boolean getIncludeProcessVariables() {
return includeProcessVariables;
}
public void setIncludeProcessVariables(Boolean includeProcessVariables) {
this.includeProcessVariables = includeProcessVariables;
}
public Collection<String> getIncludeProcessVariablesNames() {
return includeProcessVariablesNames;
}
public void setIncludeProcessVariablesNames(Collection<String> includeProcessVariablesNames) {
this.includeProcessVariablesNames = includeProcessVariablesNames;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getVariables() {
return variables;
}
public void setVariables(List<QueryVariable> variables) {
this.variables = variables;
}
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
public String getParentCaseInstanceId() {
return parentCaseInstanceId;
}
public void setParentCaseInstanceId(String parentCaseInstanceId) {
this.parentCaseInstanceId = parentCaseInstanceId;
}
public Boolean getWithoutCallbackId() {
return withoutCallbackId;
}
public void setWithoutCallbackId(Boolean withoutCallbackId) {
this.withoutCallbackId = withoutCallbackId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
} | public String getTenantIdLikeIgnoreCase() {
return tenantIdLikeIgnoreCase;
}
public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) {
this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getCallbackIds() {
return callbackIds;
}
public void setCallbackIds(Set<String> callbackIds) {
this.callbackIds = callbackIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public void setValueMin (String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
/** Get Min. Value.
@return Minimum Value for a field
*/
public String getValueMin ()
{
return (String)get_Value(COLUMNNAME_ValueMin);
}
/** Set Value Format.
@param VFormat | Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
public void setVFormat (String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
public String getVFormat ()
{
return (String)get_Value(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class DefaultAiRequestsExecutor implements AiRequestsExecutor {
private final AiRequestsExecutorProperties properties;
@Data
@Validated
@Configuration
@ConfigurationProperties(prefix = "actors.rule.ai-requests-thread-pool")
private static class AiRequestsExecutorProperties {
@NotBlank(message = "Pool name must be not blank")
private String poolName = "ai-requests";
@Min(value = 1, message = "Pool size must be at least 1")
private int poolSize = 50;
@Min(value = 1, message = "Termination timeout must be at least 1 second")
private int terminationTimeoutSeconds = 60;
}
private ListeningExecutorService executorService; | @PostConstruct
private void init() {
executorService = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(properties.getPoolSize(), ThingsBoardThreadFactory.forName(properties.getPoolName()))
);
}
@Override
public FluentFuture<ChatResponse> sendChatRequestAsync(ChatModel chatModel, ChatRequest chatRequest) {
return FluentFuture.from(executorService.submit(() -> chatModel.chat(chatRequest)));
}
@PreDestroy
private void destroy() {
if (executorService != null) {
MoreExecutors.shutdownAndAwaitTermination(executorService, Duration.ofSeconds(properties.getTerminationTimeoutSeconds()));
executorService = null;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ai\DefaultAiRequestsExecutor.java | 2 |
请完成以下Java代码 | public int getPhase() {
return Integer.MAX_VALUE;
}
@Override
public boolean isAutoStartup() {
return true;
}
/**
* Creates and starts the grpc server.
*
* @throws IOException If the server is unable to bind the port.
*/
protected void createAndStartGrpcServer() throws IOException {
if (this.server == null) {
final Server localServer = this.factory.createServer();
this.server = localServer;
localServer.start();
final String address = this.factory.getAddress();
final int port = this.factory.getPort();
log.info("gRPC Server started, listening on address: {}, port: {}", address, port);
this.eventPublisher.publishEvent(new GrpcServerStartedEvent(this, localServer, address, port));
// Prevent the JVM from shutting down while the server is running
final Thread awaitThread = new Thread(() -> {
try {
localServer.awaitTermination();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
});
awaitThread.setName("grpc-server-container-" + (serverCounter.incrementAndGet()));
awaitThread.setDaemon(false);
awaitThread.start();
}
}
/**
* Initiates an orderly shutdown of the grpc server and releases the references to the server. This call waits for
* the server to be completely shut down.
*/ | protected void stopAndReleaseGrpcServer() {
final Server localServer = this.server;
if (localServer != null) {
final long millis = this.shutdownGracePeriod.toMillis();
log.debug("Initiating gRPC server shutdown");
this.eventPublisher.publishEvent(new GrpcServerShutdownEvent(this, localServer));
localServer.shutdown();
// Wait for the server to shutdown completely before continuing with destroying the spring context
try {
if (millis > 0) {
localServer.awaitTermination(millis, MILLISECONDS);
} else if (millis == 0) {
// Do not wait
} else {
// Wait infinitely
localServer.awaitTermination();
}
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
localServer.shutdownNow();
this.server = null;
}
log.info("Completed gRPC server shutdown");
this.eventPublisher.publishEvent(new GrpcServerTerminatedEvent(this, localServer));
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\GrpcServerLifecycle.java | 1 |
请完成以下Java代码 | public static void findOneAndUpdateOperations() {
FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions();
upsertOptions.returnDocument(ReturnDocument.AFTER);
upsertOptions.upsert(true);
Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda"), upsertOptions);
System.out.println("resultDocument:- " + resultDocument);
}
public static void replaceOneOperations() {
UpdateOptions options = new UpdateOptions().upsert(true);
Document replaceDocument = new Document();
replaceDocument.append("modelName", "GTPP")
.append("companyName", "Hero Honda")
.append("launchYear", 2022)
.append("type", "Bike")
.append("registeredNo", "EPS 5562");
UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options);
System.out.println("updateReplaceResult:- " + updateReplaceResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
// | // Update with upsert operation
//
updateOperations();
//
// Update with upsert operation using setOnInsert
//
updateSetOnInsertOperations();
//
// Update with upsert operation using findOneAndUpdate
//
findOneAndUpdateOperations();
//
// Update with upsert operation using replaceOneOperations
//
replaceOneOperations();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class KpiConsumer {
private final Logger logger = LoggerFactory.getLogger(KpiConsumer.class);
private CountDownLatch latch = new CountDownLatch(1);
private ConsumerRecord<String, String> message;
@Autowired
private DataLakeService dataLakeService;
@KafkaListener(id = "kpi-listener", topics = "kpi_topic", containerFactory = "kafkaKpiListenerContainerFactory")
public void listen(ConsumerRecord<String, String> record) throws InterruptedException {
logger.info("messages received: {}", record.value());
this.message = record;
//pause the current thread and resume it when the count-down latch is reset to 0
latch.await(); | List<String> messages = new ArrayList<>();
messages.add(record.value());
dataLakeService.save(messages);
//reset the latch
latch = new CountDownLatch(1);
}
public ConsumerRecord<String, String> getMessage() {
return message;
}
public CountDownLatch getLatch() {
return latch;
}
} | repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\kafka\batch\KpiConsumer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class LicenseFeeConfig implements CommissionConfig
{
@NonNull
LicenseFeeContract licenseFeeContract;
@NonNull
ProductId commissionProductId;
@NonNull
Percent commissionPercent;
@NonNull
Integer pointsPrecision;
@NonNull
LicenseFeeSettingsLineId licenseFeeSettingsLineId;
@Builder
public LicenseFeeConfig(
@NonNull final LicenseFeeContract licenseFeeContract,
@NonNull final ProductId commissionProductId,
@NonNull final Percent commissionPercent,
@NonNull final Integer pointsPrecision,
@NonNull final LicenseFeeSettingsLineId licenseFeeSettingsLineId)
{
this.licenseFeeContract = licenseFeeContract;
this.commissionProductId = commissionProductId;
this.commissionPercent = commissionPercent;
this.pointsPrecision = pointsPrecision;
this.licenseFeeSettingsLineId = licenseFeeSettingsLineId;
}
public static boolean isInstance(@NonNull final CommissionConfig config)
{
return config instanceof LicenseFeeConfig;
}
@NonNull
public static LicenseFeeConfig cast(@NonNull final CommissionConfig config)
{
return castOrEmpty(config) | .orElseThrow(() -> new AdempiereException("Cannot cast the given commission config to LicenseFeeConfig")
.appendParametersToMessage()
.setParameter("config", config));
}
@NonNull
public static Optional<LicenseFeeConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig)
{
if (isInstance(commissionConfig))
{
return Optional.of((LicenseFeeConfig)commissionConfig);
}
return Optional.empty();
}
@Override
public CommissionType getCommissionType()
{
return CommissionType.LICENSE_FEE_COMMISSION;
}
@Override
@Nullable
public CommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId)
{
if (licenseFeeContract.getContractOwnerBPartnerId().equals(contractualBPartnerId))
{
return licenseFeeContract;
}
return null;
}
@NonNull
public LicenseFeeSettingsId getId()
{
return licenseFeeSettingsLineId.getLicenseFeeSettingsId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\algorithm\LicenseFeeConfig.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Role other = (Role) obj;
if (id == null) {
if (other.id != null) {
return false; | }
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Role [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\model\Role.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void sendVerificationCode(SecurityUser user, String verificationCode, SmsTwoFaProviderConfig providerConfig, SmsTwoFaAccountConfig accountConfig) throws ThingsboardException {
Map<String, String> messageData = Map.of(
"code", verificationCode,
"userEmail", user.getEmail()
);
String message = TbNodeUtils.processTemplate(providerConfig.getSmsVerificationMessageTemplate(), messageData);
String phoneNumber = accountConfig.getPhoneNumber();
try {
smsService.sendSms(user.getTenantId(), user.getCustomerId(), new String[]{phoneNumber}, message);
auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, null, phoneNumber);
} catch (ThingsboardException e) {
auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, e, phoneNumber);
throw e;
}
} | @Override
public void check(TenantId tenantId) throws ThingsboardException {
if (!smsService.isConfigured(tenantId)) {
throw new ThingsboardException("SMS service is not configured", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.SMS;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\SmsTwoFaProvider.java | 2 |
请完成以下Java代码 | public boolean shouldSelectCell(final EventObject e)
{
return isValueDisplayed();
}
private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex);
return model.getRow(modelRowIndex);
}
/**
* Destroy existing editor.
*
* Very important to be called because this will also unregister the listeners from editor to underlying lookup (if any).
*/
private final void destroyEditor()
{
if (editor == null)
{
return;
}
editor.dispose();
editor = null;
}
@Override | public boolean stopCellEditing()
{
if (!super.stopCellEditing())
{
return false;
}
destroyEditor();
return true;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
destroyEditor();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindValueEditor.java | 1 |
请完成以下Java代码 | public class BooleanFormType extends AbstractFormType {
private static final long serialVersionUID = 1L;
@Override
public String getName() {
return "boolean";
}
public String getMimeType() {
return "plain/text";
}
@Override
public Object convertFormValueToModelValue(String propertyValue) {
if (propertyValue == null || "".equals(propertyValue)) {
return null; | }
return Boolean.valueOf(propertyValue);
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue == null) {
return null;
}
if (Boolean.class.isAssignableFrom(modelValue.getClass()) || boolean.class.isAssignableFrom(modelValue.getClass())) {
return modelValue.toString();
}
throw new FlowableIllegalArgumentException("Model value is not of type boolean, but of type " + modelValue.getClass().getName());
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\BooleanFormType.java | 1 |
请完成以下Java代码 | public class SignCSRBouncyCastle {
static {
Security.addProvider(new BouncyCastleProvider());
}
public X509Certificate signCSR(PKCS10CertificationRequest inputCSR, PrivateKey caPrivate, KeyPair pair) throws OperatorCreationException, CertificateException, NoSuchProviderException, IOException {
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
.find("SHA1withRSA");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
.find(sigAlgId);
AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(caPrivate
.getEncoded());
SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pair
.getPublic().getEncoded());
X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
new X500Name("CN=issuer"), new BigInteger("1"), new Date(
System.currentTimeMillis()), new Date(
System.currentTimeMillis() + 30L * 365 * 24 * 60 * 60
* 1000), inputCSR.getSubject(), keyInfo);
ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
.build(foo);
X509CertificateHolder holder = myCertificateGenerator.build(sigGen);
Certificate eeX509CertificateStructure = holder.toASN1Structure();
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); | InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded());
X509Certificate theCert = (X509Certificate) cf.generateCertificate(is1);
is1.close();
return theCert;
}
public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static PKCS10CertificationRequest generateCSR(KeyPair pair) throws OperatorCreationException {
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
new X500Principal("CN=Requested Test Certificate"), pair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = csBuilder.build(pair.getPrivate());
return p10Builder.build(signer);
}
} | repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\bouncycastle\SignCSRBouncyCastle.java | 1 |
请完成以下Java代码 | private TbEmail getEmail(TbMsg msg) {
TbEmail email = JacksonUtil.fromString(msg.getData(), TbEmail.class);
if (StringUtils.isBlank(email.getTo())) {
throw new IllegalStateException("Email destination can not be blank [" + email.getTo() + "]");
}
return email;
}
private void validateType(TbMsg msg) {
if (!msg.isTypeOf(TbMsgType.SEND_EMAIL)) {
String type = msg.getType();
log.warn("Not expected msg type [{}] for SendEmail Node", type);
throw new IllegalStateException("Not expected msg type " + type + " for SendEmail Node");
}
}
private JavaMailSenderImpl createMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(this.config.getSmtpHost());
mailSender.setPort(this.config.getSmtpPort());
mailSender.setUsername(this.config.getUsername());
mailSender.setPassword(this.config.getPassword());
mailSender.setJavaMailProperties(createJavaMailProperties());
return mailSender;
}
private Properties createJavaMailProperties() {
Properties javaMailProperties = new Properties();
String protocol = this.config.getSmtpProtocol(); | javaMailProperties.put("mail.transport.protocol", protocol);
javaMailProperties.put(MAIL_PROP + protocol + ".host", this.config.getSmtpHost());
javaMailProperties.put(MAIL_PROP + protocol + ".port", this.config.getSmtpPort() + "");
javaMailProperties.put(MAIL_PROP + protocol + ".timeout", this.config.getTimeout() + "");
javaMailProperties.put(MAIL_PROP + protocol + ".auth", String.valueOf(StringUtils.isNotEmpty(this.config.getUsername())));
javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", Boolean.valueOf(this.config.isEnableTls()).toString());
if (this.config.isEnableTls() && StringUtils.isNoneEmpty(this.config.getTlsVersion())) {
javaMailProperties.put(MAIL_PROP + protocol + ".ssl.protocols", this.config.getTlsVersion());
}
if (this.config.isEnableProxy()) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.host", config.getProxyHost());
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.port", config.getProxyPort());
if (StringUtils.isNoneEmpty(config.getProxyUser())) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.user", config.getProxyUser());
}
if (StringUtils.isNoneEmpty(config.getProxyPassword())) {
javaMailProperties.put(MAIL_PROP + protocol + ".proxy.password", config.getProxyPassword());
}
}
return javaMailProperties;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mail\TbSendEmailNode.java | 1 |
请完成以下Java代码 | protected void prepare()
{
final IParams para = getParameterAsIParams();
p_flatrateconditionsID = para.getParameterAsInt(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Conditions_ID, -1);
final int materialTrackingID = getRecord_ID();
final I_M_Material_Tracking materialTracking = InterfaceWrapperHelper.create(getCtx(), materialTrackingID, I_M_Material_Tracking.class, getTrxName());
final I_C_Flatrate_Conditions conditions = InterfaceWrapperHelper.create(getCtx(), p_flatrateconditionsID, I_C_Flatrate_Conditions.class, getTrxName());
setConditions(conditions);
addProduct(productsRepo.getById(materialTracking.getM_Product_ID()));
setStartDate(materialTracking.getValidFrom());
setEndDate(materialTracking.getValidTo());
final UserId salesRepId = UserId.ofRepoIdOrNull(materialTracking.getSalesRep_ID());
final I_AD_User salesRep = salesRepId != null
? Services.get(IUserDAO.class).getById(salesRepId)
: null;
setUserInCharge(salesRep); | setIsCompleteDocument(true);
}
@Override
public Iterable<I_C_BPartner> getBPartners()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final I_M_Material_Tracking materialTracking = getProcessInfo().getRecord(I_M_Material_Tracking.class);
// made this iterator to fit he superclass method
final BPartnerId bpartnerId = BPartnerId.ofRepoId(materialTracking.getC_BPartner_ID());
final Iterator<I_C_BPartner> it = queryBL.createQueryBuilder(I_C_BPartner.class, materialTracking)
.addEqualsFilter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, bpartnerId)
.create()
.iterate(I_C_BPartner.class);
return () -> it;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\C_Flatrate_Term_Create_For_MaterialTracking.java | 1 |
请完成以下Java代码 | public void setTp(InterestType1Choice value) {
this.tp = value;
}
/**
* Gets the value of the rate property.
*
* @return
* possible object is
* {@link Rate3 }
*
*/
public Rate3 getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link Rate3 }
*
*/
public void setRate(Rate3 value) {
this.rate = value;
}
/**
* Gets the value of the frToDt property.
*
* @return
* possible object is
* {@link DateTimePeriodDetails }
*
*/
public DateTimePeriodDetails getFrToDt() {
return frToDt;
}
/**
* Sets the value of the frToDt property.
*
* @param value
* allowed object is
* {@link DateTimePeriodDetails }
*
*/
public void setFrToDt(DateTimePeriodDetails value) {
this.frToDt = value;
}
/** | * Gets the value of the rsn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRsn() {
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRsn(String value) {
this.rsn = value;
}
/**
* Gets the value of the tax property.
*
* @return
* possible object is
* {@link TaxCharges2 }
*
*/
public TaxCharges2 getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxCharges2 }
*
*/
public void setTax(TaxCharges2 value) {
this.tax = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java | 1 |
请完成以下Java代码 | public CurrentPickingTarget withPickingSlot(@Nullable final PickingSlotIdAndCaption pickingSlot)
{
return PickingSlotIdAndCaption.equals(this.pickingSlot, pickingSlot)
? this
: toBuilder().pickingSlot(pickingSlot).build();
}
@NonNull
public Optional<LUPickingTarget> getLuPickingTarget() {return Optional.ofNullable(luPickingTarget);}
@NonNull
public CurrentPickingTarget withLuPickingTarget(@NonNull final UnaryOperator<LUPickingTarget> luPickingTargetMapper)
{
return withLuPickingTarget(luPickingTargetMapper.apply(luPickingTarget));
}
@NonNull
public CurrentPickingTarget withLuPickingTarget(final @Nullable LUPickingTarget luPickingTarget)
{
if (LUPickingTarget.equals(this.luPickingTarget, luPickingTarget))
{
return this;
}
return toBuilder()
.luPickingTarget(luPickingTarget)
.tuPickingTarget(luPickingTarget == null ? null : this.tuPickingTarget)
.build();
}
public CurrentPickingTarget withClosedLUAndTUPickingTarget(@Nullable final LUIdsAndTopLevelTUIdsCollector closedHuIdCollector)
{
// already closed
if (this.luPickingTarget == null && this.tuPickingTarget == null)
{
return this;
}
if (closedHuIdCollector != null)
{
if (luPickingTarget == null || luPickingTarget.isNewLU())
{
// collect only top level TUs i.e. no LUs
if (tuPickingTarget != null && tuPickingTarget.isExistingTU())
{
closedHuIdCollector.addTopLevelTUId(tuPickingTarget.getTuIdNotNull());
}
}
else if (luPickingTarget.isExistingLU())
{
closedHuIdCollector.addLUId(luPickingTarget.getLuIdNotNull());
}
} | return toBuilder()
.luPickingTarget(null)
.tuPickingTarget(null)
.build();
}
@NonNull
public Optional<TUPickingTarget> getTuPickingTarget() {return Optional.ofNullable(tuPickingTarget);}
@NonNull
public CurrentPickingTarget withTuPickingTarget(@Nullable final TUPickingTarget tuPickingTarget)
{
return TUPickingTarget.equals(this.tuPickingTarget, tuPickingTarget)
? this
: toBuilder().tuPickingTarget(tuPickingTarget).build();
}
public boolean matches(@NonNull final HuId huId)
{
return luPickingTarget != null && HuId.equals(luPickingTarget.getLuId(), huId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\CurrentPickingTarget.java | 1 |
请完成以下Java代码 | private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
}
private static Instant convertClientSecretExpiresAt(Object clientSecretExpiresAt) {
if (clientSecretExpiresAt != null && String.valueOf(clientSecretExpiresAt).equals("0")) {
// 0 indicates that client_secret_expires_at does not expire
return null;
}
return (Instant) INSTANT_CONVERTER.convert(clientSecretExpiresAt);
}
private static List<String> convertScope(Object scope) {
if (scope == null) {
return Collections.emptyList();
}
return Arrays.asList(StringUtils.delimitedListToStringArray(scope.toString(), " "));
}
}
private static final class OAuth2ClientRegistrationMapConverter
implements Converter<OAuth2ClientRegistration, Map<String, Object>> { | @Override
public Map<String, Object> convert(OAuth2ClientRegistration source) {
Map<String, Object> responseClaims = new LinkedHashMap<>(source.getClaims());
if (source.getClientIdIssuedAt() != null) {
responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_ID_ISSUED_AT,
source.getClientIdIssuedAt().getEpochSecond());
}
if (source.getClientSecret() != null) {
long clientSecretExpiresAt = 0;
if (source.getClientSecretExpiresAt() != null) {
clientSecretExpiresAt = source.getClientSecretExpiresAt().getEpochSecond();
}
responseClaims.put(OAuth2ClientMetadataClaimNames.CLIENT_SECRET_EXPIRES_AT, clientSecretExpiresAt);
}
if (!CollectionUtils.isEmpty(source.getScopes())) {
responseClaims.put(OAuth2ClientMetadataClaimNames.SCOPE,
StringUtils.collectionToDelimitedString(source.getScopes(), " "));
}
return responseClaims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\http\converter\OAuth2ClientRegistrationHttpMessageConverter.java | 1 |
请完成以下Java代码 | 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 int getAge() {
return age;
} | public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-1 课: Spring Boot 使用 JDBC 操作数据库\spring-boot-jdbc\src\main\java\com\neo\model\User.java | 1 |
请完成以下Java代码 | public boolean isEmpty(@Nullable final String str)
{
return isEmpty(str, false);
}
/**
* @return return true if the string is null, has length 0, or contains only whitespace.
*/
@Contract("null -> true")
public boolean isBlank(@Nullable final String str)
{
return isEmpty(str, true);
}
/**
* @return return true if the string is not null, has length > 0, and does not contain only whitespace.
*/
@Contract("null -> false")
public boolean isNotBlank(@Nullable final String str)
{
return !isEmpty(str, true);
}
/**
* Is String Empty
*
* @param str string
* @param trimWhitespaces trim whitespaces
* @return true if >= 1 char
*/
@Contract("null, _ -> true")
public boolean isEmpty(@Nullable final String str, final boolean trimWhitespaces)
{
if (str == null)
{
return true;
} | if (trimWhitespaces)
{
return str.trim().isEmpty();
}
else
{
return str.isEmpty();
}
} // isEmpty
/**
* @return true if the array is null or it's length is zero.
*/
@Contract("null -> true")
public <T> boolean isEmpty(@Nullable final T[] arr)
{
return arr == null || arr.length == 0;
}
/**
* @return true if given collection is <code>null</code> or it has no elements
*/
@Contract("null -> true")
public boolean isEmpty(@Nullable final Collection<?> collection)
{
return collection == null || collection.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\EmptyUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicJobService {
private final JobRepository jobRepository;
private final JobLauncher jobLauncher;
private final PlatformTransactionManager transactionManager;
public DynamicJobService(JobRepository jobRepository, JobLauncher jobLauncher, PlatformTransactionManager transactionManager) {
this.jobRepository = jobRepository;
this.jobLauncher = jobLauncher;
this.transactionManager = transactionManager;
}
public void createAndRunJob(Map<String, List<String>> jobsData) throws Exception {
List<Job> jobs = new ArrayList<>();
// Create chunk-oriented jobs
for (Map.Entry<String, List<String>> entry : jobsData.entrySet()) {
if (entry.getValue() instanceof List) {
jobs.add(createJob(entry.getKey(), entry.getValue()));
}
}
// Run all jobs
for (Job job : jobs) {
JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(job, jobParameters);
} | }
private Job createJob(String jobName, List<String> data) {
return new JobBuilder(jobName, jobRepository).start(createStep(data))
.build();
}
private Step createStep(List<String> data) {
return new StepBuilder("step", jobRepository).<String, String> chunk(10, transactionManager)
.reader(new ListItemReader<>(data))
.processor(item -> item.toUpperCase())
.writer(items -> items.forEach(System.out::println))
.build();
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\DynamicJobService.java | 2 |
请完成以下Java代码 | public class C_BPartner_SyncTo_RabbitMQ_HTTP extends C_BPartner_SyncTo_ExternalSystem
{
private final ExportBPartnerToRabbitMQService exportBPartnerToRabbitMQService = SpringContextHolder.instance.getBean(ExportBPartnerToRabbitMQService.class);
private final DataExportAuditRepository dataExportAuditRepository = SpringContextHolder.instance.getBean(DataExportAuditRepository.class);
private static final AdMessageKey MSG_RABBIT_MQ_SENT = AdMessageKey.of("RabbitMQ_Sent");
private static final String PARAM_EXTERNAL_SYSTEM_CONFIG_RABBITMQ_HTTP_ID = I_ExternalSystem_Config_RabbitMQ_HTTP.COLUMNNAME_ExternalSystem_Config_RabbitMQ_HTTP_ID;
@Param(parameterName = PARAM_EXTERNAL_SYSTEM_CONFIG_RABBITMQ_HTTP_ID)
private int externalSystemConfigRabbitMQId;
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.RabbitMQ;
}
@Override
protected IExternalSystemChildConfigId getExternalSystemChildConfigId()
{
return ExternalSystemRabbitMQConfigId.ofRepoId(externalSystemConfigRabbitMQId);
}
@Override | protected String getExternalSystemParam()
{
return PARAM_EXTERNAL_SYSTEM_CONFIG_RABBITMQ_HTTP_ID;
}
@Override
protected ExportToExternalSystemService getExportToBPartnerExternalSystem()
{
return exportBPartnerToRabbitMQService;
}
protected Optional<ProcessPreconditionsResolution> applyCustomPreconditionsIfAny(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return Optional.empty();
}
final BPartnerId bPartnerId = BPartnerId.ofRepoId(context.getSingleSelectedRecordId());
return dataExportAuditRepository.getByTableRecordReference(TableRecordReference.of(I_C_BPartner.Table_Name, bPartnerId))
.map(bPartnerAudit -> ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_RABBIT_MQ_SENT)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\export\bpartner\C_BPartner_SyncTo_RabbitMQ_HTTP.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set User Save Custom Info.
@param AD_User_SaveCustomInfo_ID User Save Custom Info */
@Override
public void setAD_User_SaveCustomInfo_ID (int AD_User_SaveCustomInfo_ID)
{
if (AD_User_SaveCustomInfo_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_SaveCustomInfo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_SaveCustomInfo_ID, Integer.valueOf(AD_User_SaveCustomInfo_ID));
}
/** Get User Save Custom Info.
@return User Save Custom Info */
@Override
public int getAD_User_SaveCustomInfo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SaveCustomInfo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_Country getC_Country() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setC_Country(org.compiere.model.I_C_Country C_Country)
{
set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country);
}
/** Set Land.
@param C_Country_ID
Land
*/
@Override
public void setC_Country_ID (int C_Country_ID)
{
if (C_Country_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Country_ID, null); | else
set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID));
}
/** Get Land.
@return Land
*/
@Override
public int getC_Country_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Capture Sequence.
@param CaptureSequence Capture Sequence */
@Override
public void setCaptureSequence (java.lang.String CaptureSequence)
{
set_Value (COLUMNNAME_CaptureSequence, CaptureSequence);
}
/** Get Capture Sequence.
@return Capture Sequence */
@Override
public java.lang.String getCaptureSequence ()
{
return (java.lang.String)get_Value(COLUMNNAME_CaptureSequence);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SaveCustomInfo.java | 1 |
请完成以下Java代码 | public void apply(final DocumentPath documentPath, final JSONIncludedTabInfo jsonIncludedTabInfo)
{
// TODO: implement... but it's not so critical atm
}
private boolean isReadonly(@NonNull final Document document)
{
return readonlyDocuments.computeIfAbsent(document.getDocumentPath(), documentPath -> !DocumentPermissionsHelper.canEdit(document, permissions));
}
public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator()
{
DocumentFieldLogicExpressionResultRevaluator logicExpressionRevaluator = this.logicExpressionRevaluator;
if (logicExpressionRevaluator == null)
{
logicExpressionRevaluator = this.logicExpressionRevaluator = DocumentFieldLogicExpressionResultRevaluator.using(permissions);
}
return logicExpressionRevaluator;
}
public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document)
{
final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions());
Boolean allowWindowEdit = null;
Boolean allowDocumentEdit = null;
for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); )
{
final DocumentStandardAction action = it.next();
if (action.isDocumentWriteAccessRequired())
{
if (allowDocumentEdit == null)
{
allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions);
}
if (!allowDocumentEdit)
{ | it.remove();
continue;
}
}
if (action.isWindowWriteAccessRequired())
{
if (allowWindowEdit == null)
{
final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();
final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow()
? entityDescriptor.getWindowId().toAdWindowId()
: null;
allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess();
}
if (!allowWindowEdit)
{
it.remove();
//noinspection UnnecessaryContinue
continue;
}
}
}
return ImmutableSet.copyOf(standardActions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Converter<List<ParamFlowRuleCorrectEntity>, String> paramFlowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<ParamFlowRuleCorrectEntity>> paramFlowRuleEntityDecoder() {
return s -> JSON.parseArray(s, ParamFlowRuleCorrectEntity.class);
}
/**
* 系统规则
* @return
*/
@Bean
public Converter<List<SystemRuleEntity>, String> systemRuleRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<SystemRuleEntity>> systemRuleRuleEntityDecoder() {
return s -> JSON.parseArray(s, SystemRuleEntity.class);
}
/**
* 授权规则
* @return
*/
@Bean
public Converter<List<AuthorityRuleCorrectEntity>, String> authorityRuleRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<AuthorityRuleCorrectEntity>> authorityRuleRuleEntityDecoder() {
return s -> JSON.parseArray(s, AuthorityRuleCorrectEntity.class);
}
/**
* 网关API
*
* @return
* @throws Exception
*/
@Bean | public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() {
return s -> JSON.parseArray(s, ApiDefinitionEntity.class);
}
/**
* 网关flowRule
*
* @return
* @throws Exception
*/
@Bean
public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {
return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);
}
@Bean
public ConfigService nacosConfigService() throws Exception {
Properties properties=new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr());
if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){
properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){
properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){
properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace());
}
return ConfigFactory.createConfigService(properties);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\SentinelConfig.java | 2 |
请完成以下Java代码 | public void setPrev_CurrentCostPriceLL (java.math.BigDecimal Prev_CurrentCostPriceLL)
{
set_Value (COLUMNNAME_Prev_CurrentCostPriceLL, Prev_CurrentCostPriceLL);
}
/** Get Previous Current Cost Price LL.
@return Previous Current Cost Price LL */
@Override
public java.math.BigDecimal getPrev_CurrentCostPriceLL ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPriceLL);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Previous Current Qty.
@param Prev_CurrentQty Previous Current Qty */
@Override
public void setPrev_CurrentQty (java.math.BigDecimal Prev_CurrentQty)
{
set_Value (COLUMNNAME_Prev_CurrentQty, Prev_CurrentQty);
}
/** Get Previous Current Qty.
@return Previous Current Qty */
@Override
public java.math.BigDecimal getPrev_CurrentQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
throw new IllegalArgumentException ("Price is virtual column"); }
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
} | /** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public void setSourceAmt (final @Nullable BigDecimal SourceAmt)
{
set_Value (COLUMNNAME_SourceAmt, SourceAmt);
}
@Override
public BigDecimal getSourceAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SourceAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSource_Currency_ID (final int Source_Currency_ID)
{
if (Source_Currency_ID < 1)
set_Value (COLUMNNAME_Source_Currency_ID, null);
else
set_Value (COLUMNNAME_Source_Currency_ID, Source_Currency_ID);
}
@Override
public int getSource_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Currency_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostDetail.java | 1 |
请完成以下Java代码 | public boolean equals(Object o)
{
if (!(o instanceof Pair))
return false;
Pair pair = (Pair) o;
if (pair.second == null)
if (second == null)
return pair.first.equals(first);
else
return false;
if (second == null)
return false;
return pair.first.equals(first) && pair.second.equals(second);
}
@Override
public int hashCode()
{
int firstHash = 0; | int secondHash = 0;
if (first != null)
firstHash = first.hashCode();
if (second != null)
secondHash = second.hashCode();
return firstHash + secondHash;
}
@Override
public int compareTo(Object o)
{
if (equals(o))
return 0;
return hashCode() - o.hashCode();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\accessories\Pair.java | 1 |
请完成以下Java代码 | public void setField(org.compiere.model.GridField mField)
{
if (mField != null)
{
m_WindowNo = mField.getWindowNo();
}
m_mField = mField;
if (mField != null && mField.isAutocomplete())
{
enableLookupAutocomplete();
}
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
private VAccountAutoCompleter lookupAutoCompleter = null;
/**
*
* @return <code>true</code>
*/
private boolean enableLookupAutocomplete()
{
if (lookupAutoCompleter != null)
{
return true; // auto-complete already initialized
}
// FIXME: check what happens when lookup changes
lookupAutoCompleter = new VAccountAutoCompleter(m_text, this, m_mAccount, getAcctSchemaId());
return true;
}
@Override
public GridField getField()
{
return m_mField;
}
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("VAccount[")
.append(m_title)
.append(", value=").append(m_value)
.append("]");
return sb.toString();
} // toString
@Override
public void focusGained(FocusEvent e)
{
}
/**
* Mostly copied from {@link VLookup}, can't claim I really understand it.
*/
@Override
public void focusLost(FocusEvent e)
{
if (e.isTemporary())
{
return;
}
if (m_button == null // guarding against NPE (i.e. component was disposed in meantime)
|| !m_button.isEnabled()) // set by actionButton
{
return;
}
if (m_mAccount == null)
{
return;
}
// metas: begin: 02029: nerviges verhalten wenn man eine Maskeneingabe abbrechen will (2011082210000084)
// Check if toolbar Ignore button was pressed
if (e.getOppositeComponent() instanceof AbstractButton)
{
final AbstractButton b = (AbstractButton)e.getOppositeComponent(); | if (APanel.CMD_Ignore.equals(b.getActionCommand()))
{
return;
}
}
// metas: end
if (m_text == null)
return; // arhipac: teo_sarca: already disposed
// Test Case: Open a window, click on account field that is mandatory but not filled, close the window and you will get an NPE
// TODO: integrate to trunk
// New text
String newText = m_text.getText();
if (newText == null)
newText = "";
// Actual text
String actualText = m_mAccount.getDisplay(m_value);
if (actualText == null)
actualText = "";
// If text was modified, try to resolve the valid combination
if (!newText.equals(actualText))
{
cmd_text();
}
}
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VAccount | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAccount.java | 1 |
请完成以下Java代码 | private ImmutableSet<FactAcctId> getClearingFactAcctIds()
{
ImmutableSet<FactAcctId> clearingFactAcctIds = this._clearingFactAcctIds;
if (clearingFactAcctIds == null)
{
clearingFactAcctIds = this._clearingFactAcctIds = computeClearingFactAcctIds();
}
return clearingFactAcctIds;
}
private ImmutableSet<FactAcctId> computeClearingFactAcctIds()
{
final ImmutableSet<FAOpenItemKey> openItemKeys = factAcctDAO.stream(FactAcctQuery.builder()
.tableName(fromRecordRef.getTableName())
.recordId(fromRecordRef.getRecord_ID())
.isOpenItem(true)
.openItemTrxType(FAOpenItemTrxType.OPEN_ITEM)
.build())
.map(ClearingFactAcctsQuerySupplier::extractOpenItemKeyOrNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (openItemKeys.isEmpty())
{
return ImmutableSet.of();
}
return factAcctDAO.listIds(FactAcctQuery.builder() | .tableName(I_SAP_GLJournal.Table_Name)
.excludeRecordRef(fromRecordRef)
.isOpenItem(true)
.openItemTrxType(FAOpenItemTrxType.CLEARING)
.openItemsKeys(openItemKeys)
.build());
}
private static FAOpenItemKey extractOpenItemKeyOrNull(final I_Fact_Acct record)
{
try
{
return FAOpenItemKey.parseNullable(record.getOpenItemKey()).orElse(null);
}
catch (Exception ex)
{
logger.warn("Failed extracting open item key from {}. Returning null.", record, ex);
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\open_items\related_documents\ClearingFactAcctsQuerySupplier.java | 1 |
请完成以下Java代码 | public abstract class AbstractInterfaceWrapperHelper implements IInterfaceWrapperHelper
{
private static final String COLUMNNAME_SUFFIX_Override = "_Override";
/**
* Gets columnName's override value or null
*/
@Nullable
protected static <T> T getValueOverrideOrNull(final IModelInternalAccessor modelAccessor, final String columnName)
{
//
// Try ColumnName_Override
// e.g. for "C_Tax_ID", the C_Tax_ID_Override" will be checked
{
final String overrideColumnName = (columnName + COLUMNNAME_SUFFIX_Override);
if (modelAccessor.hasColumnName(overrideColumnName))
{
@SuppressWarnings("unchecked")
final T value = (T)modelAccessor.getValue(overrideColumnName, Object.class);
if (value != null)
{
return value;
}
}
}
//
// Try ColumnName_Override_ID
// e.g. for "C_Tax_ID", the C_Tax_Override_ID" will be checked
if (columnName.endsWith("_ID")) | {
final String overrideColumnName;
if (columnName.endsWith("_Value_ID"))
{
overrideColumnName = (columnName.substring(0, columnName.length() - 9) + COLUMNNAME_SUFFIX_Override + "_Value_ID");
}
else
{
overrideColumnName = (columnName.substring(0, columnName.length() - 3) + COLUMNNAME_SUFFIX_Override + "_ID");
}
if (modelAccessor.hasColumnName(overrideColumnName))
{
@SuppressWarnings("unchecked")
final T value = (T)modelAccessor.getValue(overrideColumnName, Object.class);
return value; // might be null as well
}
}
// No override values found => return null
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\AbstractInterfaceWrapperHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) {
return dataManager.findJobsByWorkerIdAndTenantId(workerId, tenantId);
}
@Override
public List<ExternalWorkerJob> findJobsByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) {
return dataManager.findJobsByQueryCriteria(jobQuery);
}
@Override
public long findJobCountByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) {
return dataManager.findJobCountByQueryCriteria(jobQuery);
}
@Override
public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) {
return dataManager.findExternalJobsToExecute(builder, numberOfJobs); | }
@Override
public void delete(ExternalWorkerJobEntity entity, boolean fireDeleteEvent) {
deleteByteArrayRef(entity.getExceptionByteArrayRef());
deleteByteArrayRef(entity.getCustomValuesByteArrayRef());
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(entity);
}
super.delete(entity, fireDeleteEvent);
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\ExternalWorkerJobEntityManagerImpl.java | 2 |
请完成以下Java代码 | public int getM_Securpharm_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Pharma REST API URL.
@param PharmaRestApiBaseURL Pharma REST API URL */
@Override
public void setPharmaRestApiBaseURL (java.lang.String PharmaRestApiBaseURL)
{
set_Value (COLUMNNAME_PharmaRestApiBaseURL, PharmaRestApiBaseURL);
}
/** Get Pharma REST API URL.
@return Pharma REST API URL */
@Override
public java.lang.String getPharmaRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_PharmaRestApiBaseURL);
}
/** Set Support Benutzer.
@param Support_User_ID
Benutzer für Benachrichtigungen
*/
@Override
public void setSupport_User_ID (int Support_User_ID)
{
if (Support_User_ID < 1)
set_Value (COLUMNNAME_Support_User_ID, null);
else
set_Value (COLUMNNAME_Support_User_ID, Integer.valueOf(Support_User_ID));
}
/** Get Support Benutzer.
@return Benutzer für Benachrichtigungen
*/
@Override
public int getSupport_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Support_User_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set TAN Passwort.
@param TanPassword
TAN Passwort benutzt für Authentifizierung
*/
@Override
public void setTanPassword (java.lang.String TanPassword)
{
set_Value (COLUMNNAME_TanPassword, TanPassword);
}
/** Get TAN Passwort.
@return TAN Passwort benutzt für Authentifizierung
*/
@Override
public java.lang.String getTanPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_TanPassword);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Config.java | 1 |
请完成以下Java代码 | public void reload() {
}
void doFind() {
FindDialog dlg = new FindDialog();
//dlg.setLocation(linkActionB.getLocationOnScreen());
Dimension dlgSize = dlg.getSize();
//dlg.setSize(400, 300);
Dimension frmSize = this.getSize();
Point loc = this.getLocationOnScreen();
dlg.setLocation(
(frmSize.width - dlgSize.width) / 2 + loc.x,
(frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true);
if (editor.getSelectedText() != null)
dlg.txtSearch.setText(editor.getSelectedText());
else if (Context.get("LAST_SEARCHED_WORD") != null)
dlg.txtSearch.setText(Context.get("LAST_SEARCHED_WORD").toString());
dlg.setVisible(true);
if (dlg.CANCELLED)
return;
Context.put("LAST_SEARCHED_WORD", dlg.txtSearch.getText());
String repl = null;
if (dlg.chkReplace.isSelected())
repl = dlg.txtReplace.getText();
Finder finder =
new Finder(
this,
dlg.txtSearch.getText(),
dlg.chkWholeWord.isSelected(),
dlg.chkCaseSens.isSelected(),
dlg.chkRegExp.isSelected(),
repl);
finder.start();
}
// metas: begin
public String getHtmlText()
{
try
{
StringWriter sw = new StringWriter();
new AltHTMLWriter(sw, this.document).write();
// new HTMLWriter(sw, editor.document).write();
String html = sw.toString();
return html;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public HTMLDocument getDocument()
{
return this.document;
}
@Override
public void requestFocus()
{
this.editor.requestFocus(); | }
@Override
public boolean requestFocus(boolean temporary)
{
return this.editor.requestFocus(temporary);
}
@Override
public boolean requestFocusInWindow()
{
return this.editor.requestFocusInWindow();
}
public void setText(String html)
{
this.editor.setText(html);
}
public void setCaretPosition(int position)
{
this.editor.setCaretPosition(position);
}
public ActionMap getEditorActionMap()
{
return this.editor.getActionMap();
}
public InputMap getEditorInputMap(int condition)
{
return this.editor.getInputMap(condition);
}
public Keymap getEditorKeymap()
{
return this.editor.getKeymap();
}
public JTextComponent getTextComponent()
{
return this.editor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java | 1 |
请完成以下Spring Boot application配置 | server.port=${port:8080}
spring.application.name = Bootstrap Spring Cloud
spring.thymeleaf.cache = false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
server.error.path=/error
server.error.whitelabel.enabled=false
spring.jpa.generate-ddl=true
spring.jpa.hib | ernate.ddl-auto=update
spring.mail.host=localhost
spring.mail.port=8025
spring.jpa.properties.hibernate.globally_quoted_identifiers=true | repos\tutorials-master\spring-boot-modules\spring-boot-simple\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class PersonNameConverter implements AttributeConverter<PersonName, String> {
private static final String SEPARATOR = ", ";
@Override
public String convertToDatabaseColumn(PersonName personName) {
if (personName == null) {
return null;
}
StringBuilder sb = new StringBuilder();
if (personName.getSurname() != null && !personName.getSurname()
.isEmpty()) {
sb.append(personName.getSurname());
sb.append(SEPARATOR);
}
if (personName.getName() != null && !personName.getName()
.isEmpty()) {
sb.append(personName.getName());
}
return sb.toString();
}
@Override
public PersonName convertToEntityAttribute(String dbPersonName) {
if (dbPersonName == null || dbPersonName.isEmpty()) {
return null;
}
String[] pieces = dbPersonName.split(SEPARATOR);
if (pieces == null || pieces.length == 0) {
return null;
} | PersonName personName = new PersonName();
String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
if (dbPersonName.contains(SEPARATOR)) {
personName.setSurname(firstPiece);
if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) {
personName.setName(pieces[1]);
}
} else {
personName.setName(firstPiece);
}
return personName;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\converters\PersonNameConverter.java | 1 |
请完成以下Java代码 | public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
/**
* 名称
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 地址
*/
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis-redis\src\main\java\com\xiaolyuh\domain\model\Person.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) {
if (!deployment.isNew()) {
return;
}
LOGGER.debug("BpmnDeployer: processing deployment {}", deployment.getName());
DeploymentBuilder bpmnDeploymentBuilder = null;
Map<String, EngineResource> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
if (isBpmnResource(resourceName)) {
LOGGER.info("BpmnDeployer: processing resource {}", resourceName);
if (bpmnDeploymentBuilder == null) {
RepositoryService repositoryService = CommandContextUtil.getProcessEngineConfiguration().getRepositoryService();
bpmnDeploymentBuilder = repositoryService.createDeployment().name(deployment.getName());
}
bpmnDeploymentBuilder.addBytes(resourceName, resources.get(resourceName).getBytes());
}
}
if (bpmnDeploymentBuilder != null) {
bpmnDeploymentBuilder.parentDeploymentId(deployment.getId());
bpmnDeploymentBuilder.key(deployment.getKey());
if (deployment.getTenantId() != null && deployment.getTenantId().length() > 0) {
bpmnDeploymentBuilder.tenantId(deployment.getTenantId());
}
bpmnDeploymentBuilder.deploy();
}
}
protected boolean isBpmnResource(String resourceName) { | for (String suffix : ResourceNameUtil.BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
@Override
public void undeploy(EngineDeployment parentDeployment, boolean cascade) {
RepositoryService repositoryService = CommandContextUtil.getProcessEngineConfiguration().getRepositoryService();
List<Deployment> deployments = repositoryService
.createDeploymentQuery()
.parentDeploymentId(parentDeployment.getId())
.list();
for (Deployment deployment : deployments) {
repositoryService.deleteDeployment(deployment.getId(), cascade);
}
}
@Override
public int getUndeployOrder() {
return BPMN_DEFAULT_UNDEPLOY_ORDER;
}
} | repos\flowable-engine-main\modules\flowable-engine-configurator\src\main\java\org\flowable\engine\configurator\impl\deployer\BpmnDeployer.java | 2 |
请完成以下Java代码 | public Builder notBefore(Instant notBefore) {
this.claim(JwtClaimNames.NBF, notBefore);
return this;
}
/**
* Use this subject in the resulting {@link Jwt}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
this.claim(JwtClaimNames.SUB, subject);
return this;
}
/**
* Build the {@link Jwt}
* @return The constructed {@link Jwt}
*/
public Jwt build() { | Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT));
Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP));
return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\Jwt.java | 1 |
请完成以下Java代码 | public class C_Dunning_Candidate_SetDunningGrace extends JavaProcess
{
private static final String PARAM_DunningGrace = I_C_Dunning_Candidate.COLUMNNAME_DunningGrace;
private Timestamp p_DunningGrace = null;
@Override
protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
if (para.getParameter() == null)
{
// skip if no parameter value
continue;
}
final String name = para.getParameterName();
if (name.equals(PARAM_DunningGrace))
{
p_DunningGrace = para.getParameterAsTimestamp();
}
}
}
@Override
protected String doIt()
{
final Iterator<I_C_Dunning_Candidate> it = retrieveSelectionIterator();
setDunningGrace(it, p_DunningGrace);
return "@Updated@";
}
private void setDunningGrace(final Iterator<I_C_Dunning_Candidate> it, final Timestamp dunningGrace)
{
while (it.hasNext())
{
final I_C_Dunning_Candidate candidate = it.next();
setDunningGrace(candidate, dunningGrace);
}
} | private void setDunningGrace(final I_C_Dunning_Candidate candidate, final Timestamp dunningGrace)
{
candidate.setDunningGrace(dunningGrace);
// We want to make sure that model validators are triggered EVEN if the old DunningGrace value equals with new DunningGrace value
markColumnChanged(candidate, I_C_Dunning_Candidate.COLUMNNAME_DunningGrace);
save(candidate);
}
private Iterator<I_C_Dunning_Candidate> retrieveSelectionIterator()
{
final StringBuilder sqlWhere = new StringBuilder();
final List<Object> params = new ArrayList<>();
if (!Check.isEmpty(getProcessInfo().getWhereClause(), true))
{
sqlWhere.append(getProcessInfo().getWhereClause())
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'"); // 03663 : Must make sure to take only unprocessed candidates.
}
else
{
// We have no where clause. Assume all unprocessed candidates.
sqlWhere.append(I_C_Dunning_Candidate.COLUMNNAME_IsActive + " = 'Y'")
.append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'");
}
return new Query(getCtx(), I_C_Dunning_Candidate.Table_Name, sqlWhere.toString(), get_TrxName())
.setParameters(params)
.setClient_ID()
.setOnlyActiveRecords(true)
.setRequiredAccess(Access.WRITE)
.iterate(I_C_Dunning_Candidate.class, false); // guaranteed=false
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_SetDunningGrace.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
queryBL
.createQueryBuilder(I_M_ShipperTransportation.class)
.setOnlySelection(getPinstanceId())
.create()
.iterateAndStream()
.filter(this::isCompleted)
.filter(this::hasDerKurierMailAddress)
.map(I_M_ShipperTransportation::getM_ShipperTransportation_ID)
.map(ShipperTransportationId::ofRepoId)
.forEach(derKurierDeliveryOrderEmailer::sendShipperTransportationAsEmail);
return MSG_OK;
}
private boolean isCompleted(@NonNull final I_M_ShipperTransportation shipperTransportationRecord)
{
return documentBL.isDocumentCompleted(shipperTransportationRecord); | }
private boolean hasDerKurierMailAddress(@NonNull final I_M_ShipperTransportation shipperTransportationRecord)
{
final DerKurierShipperConfigRepository derKurierShipperConfigRepository = Adempiere.getBean(DerKurierShipperConfigRepository.class);
final int shipperId = shipperTransportationRecord.getM_Shipper_ID();
final DerKurierShipperConfig config = derKurierShipperConfigRepository.retrieveConfigForShipperIdOrNull(shipperId);
if (config == null)
{
return false;
}
final EMailAddress mailTo = config.getDeliveryOrderRecipientEmailOrNull();
return mailTo != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\process\M_ShipperTransportation_SendDerKurierEMail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MarginConfig implements CommissionConfig
{
@NonNull
ProductId commissionProductId;
@NonNull
Percent tradedPercent;
@NonNull
Integer pointsPrecision;
@NonNull
MarginContract marginContract;
@NonNull
CustomerTradeMarginLineId customerTradeMarginLineId;
public static boolean isInstance(@NonNull final CommissionConfig config)
{
return config instanceof MarginConfig;
}
@NonNull
public static MarginConfig cast(@NonNull final CommissionConfig config)
{
return castOrEmpty(config)
.orElseThrow(() -> new AdempiereException("Cannot cast the given config to MarginConfig")
.appendParametersToMessage()
.setParameter("config", config));
}
@NonNull
public static Optional<MarginConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig)
{
if (commissionConfig instanceof MarginConfig)
{
return Optional.of((MarginConfig)commissionConfig);
}
return Optional.empty();
}
@Builder | MarginConfig(
@JsonProperty("commissionProductId") @NonNull final ProductId commissionProductId,
@JsonProperty("tradedPercent") @NonNull final Percent tradedPercent,
@JsonProperty("pointsPrecision") @NonNull final Integer pointsPrecision,
@JsonProperty("marginContract") @NonNull final MarginContract marginContract,
@JsonProperty("customerTradeMarginLineId") @NonNull final CustomerTradeMarginLineId customerTradeMarginLineId)
{
this.commissionProductId = commissionProductId;
this.tradedPercent = tradedPercent;
this.pointsPrecision = pointsPrecision;
this.marginContract = marginContract;
this.customerTradeMarginLineId = customerTradeMarginLineId;
}
@Override
public CommissionType getCommissionType()
{
return CommissionType.MARGIN_COMMISSION;
}
@Override
public CommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId)
{
if (marginContract.getContractOwnerBPartnerId().equals(contractualBPartnerId))
{
return marginContract;
}
return null;
}
@NonNull
public CustomerTradeMarginId getId()
{
return customerTradeMarginLineId.getCustomerTradeMarginId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\margin\MarginConfig.java | 2 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public String getLockTime() {
return lockTime;
}
public void setLockTime(String lockTime) { | this.lockTime = lockTime;
}
public int getProcessed() {
return isProcessed;
}
public void setProcessed(int isProcessed) {
this.isProcessed = isProcessed;
}
@Override
public String toString() {
return timeStamp.toString() + " : " + type;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User implements Persistable<Long> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "varchar")
private UUID uuid;
private String name;
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public UUID getUuid() {
return uuid;
} | public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean isNew() {
return true;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\uuidexception\User.java | 2 |
请完成以下Java代码 | public void run(String[] args) {
String parsedCmdStr;
try {
jCommander.parse(args);
parsedCmdStr = jCommander.getParsedCommand();
switch (parsedCmdStr) {
case SUBMIT_CMD:
if (submitUsageCmd.isHelp()) {
getSubCommandHandle(SUBMIT_CMD).usage();
}
System.out.println("Parsing usage request...");
submitUsageCmd.submit();
break;
case FETCH_CMD:
if (fetchChargesCmd.isHelp()) {
getSubCommandHandle(SUBMIT_CMD).usage();
}
System.out.println("Preparing fetch query...");
fetchChargesCmd.fetch();
break;
default:
System.err.println("Invalid command: " + parsedCmdStr);
}
} catch (ParameterException e) {
System.err.println(e.getLocalizedMessage());
parsedCmdStr = jCommander.getParsedCommand(); | if (parsedCmdStr != null) {
getSubCommandHandle(parsedCmdStr).usage();
} else {
jCommander.usage();
}
}
}
private JCommander getSubCommandHandle(String command) {
JCommander cmd = jCommander.getCommands().get(command);
if (cmd == null) {
System.err.println("Invalid command: " + command);
}
return cmd;
}
private void setUsageFormatter(String subCommand) {
JCommander cmd = getSubCommandHandle(subCommand);
cmd.setUsageFormatter(new UnixStyleUsageFormatter(cmd));
}
} | repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\cli\UsageBasedBilling.java | 1 |
请完成以下Java代码 | private static void buildEnabled(StringBuilder sb, Object[] elements) {
boolean writingAnsi = false;
boolean containsEncoding = false;
for (Object element : elements) {
if (element instanceof AnsiElement) {
containsEncoding = true;
if (!writingAnsi) {
sb.append(ENCODE_START);
writingAnsi = true;
}
else {
sb.append(ENCODE_JOIN);
}
}
else {
if (writingAnsi) {
sb.append(ENCODE_END);
writingAnsi = false;
}
}
sb.append(element);
}
if (containsEncoding) {
sb.append(writingAnsi ? ENCODE_JOIN : ENCODE_START);
sb.append(RESET);
sb.append(ENCODE_END);
}
}
private static void buildDisabled(StringBuilder sb, @Nullable Object[] elements) {
for (Object element : elements) {
if (!(element instanceof AnsiElement) && element != null) {
sb.append(element);
}
}
}
private static boolean isEnabled() {
if (enabled == Enabled.DETECT) {
if (ansiCapable == null) {
ansiCapable = detectIfAnsiCapable();
}
return ansiCapable;
}
return enabled == Enabled.ALWAYS;
}
private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
} | Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Console.class, "isTerminal");
if (isTerminalMethod != null) {
Boolean isTerminal = (Boolean) isTerminalMethod.invoke(console);
if (Boolean.FALSE.equals(isTerminal)) {
return false;
}
}
}
return !(OPERATING_SYSTEM_NAME.contains("win"));
}
catch (Throwable ex) {
return false;
}
}
/**
* Possible values to pass to {@link AnsiOutput#setEnabled}. Determines when to output
* ANSI escape sequences for coloring application output.
*/
public enum Enabled {
/**
* Try to detect whether ANSI coloring capabilities are available. The default
* value for {@link AnsiOutput}.
*/
DETECT,
/**
* Enable ANSI-colored output.
*/
ALWAYS,
/**
* Disable ANSI-colored output.
*/
NEVER
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiOutput.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReadOnlyInfo
{
public static final ReadOnlyInfo TRUE = ReadOnlyInfo.builder()
.isReadOnly(BooleanWithReason.TRUE)
.forceReadOnlySubDocuments(false)
.build();
public static final ReadOnlyInfo FALSE = ReadOnlyInfo.builder()
.isReadOnly(BooleanWithReason.FALSE)
.forceReadOnlySubDocuments(false)
.build();
@NonNull
public static ReadOnlyInfo of(@NonNull final BooleanWithReason isReadOnly)
{
if (BooleanWithReason.TRUE.equals(isReadOnly))
{
return TRUE;
}
else if (BooleanWithReason.FALSE.equals(isReadOnly))
{
return FALSE;
}
else
{
return ReadOnlyInfo.builder()
.isReadOnly(isReadOnly)
.forceReadOnlySubDocuments(false)
.build();
} | }
@Getter(AccessLevel.NONE) @NonNull BooleanWithReason isReadOnly;
boolean forceReadOnlySubDocuments;
public boolean isReadOnly()
{
return isReadOnly.isTrue();
}
@NonNull
public BooleanWithReason getIsReadOnlyWithReason()
{
return isReadOnly;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\decorator\ReadOnlyInfo.java | 2 |
请完成以下Java代码 | public void serverSideStreamingGetListStockQuotes(Stock request, StreamObserver<StockQuote> responseObserver) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request))
.setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
responseObserver.onCompleted();
}
@Override
public StreamObserver<Stock> clientSideStreamingGetStatisticsOfStocks(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
int count;
double price = 0.0;
StringBuffer sb = new StringBuffer();
@Override
public void onNext(Stock stock) {
count++;
price = +fetchStockPriceBid(stock);
sb.append(":")
.append(stock.getTickerSymbol());
}
@Override
public void onCompleted() {
responseObserver.onNext(StockQuote.newBuilder()
.setPrice(price / count)
.setDescription("Statistics-" + sb.toString())
.build());
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
} | @Override
public StreamObserver<Stock> bidirectionalStreamingGetListsStockQuotes(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
@Override
public void onNext(Stock request) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request))
.setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
}
}
private static double fetchStockPriceBid(Stock stock) {
return stock.getTickerSymbol()
.length()
+ ThreadLocalRandom.current()
.nextDouble(-0.1d, 0.1d);
}
} | repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\streaming\StockServer.java | 1 |
请完成以下Java代码 | public boolean isOverrideId() {
return overrideId;
}
public void setOverrideId(boolean overrideId) {
this.overrideId = overrideId;
}
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public LayoutDefinition getLayout() {
return layout;
}
public void setLayout(LayoutDefinition layout) { | this.layout = layout;
}
@JsonInclude(Include.NON_EMPTY)
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
@JsonIgnore
public Object getParam(String name) {
if (params != null) {
return params.get(name);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-form-model\src\main\java\org\flowable\form\model\FormField.java | 1 |
请完成以下Java代码 | public String retrieveDocumentNoByYearAndMonth(final int AD_Sequence_ID, java.util.Date date)
{
if (date == null)
{
date = new Date();
}
final SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
final String calendarYear = yearFormat.format(date);
final SimpleDateFormat monthFormat = new SimpleDateFormat("M");
final String calendarMonth = monthFormat.format(date);
return DB.getSQLValueStringEx(ITrx.TRXNAME_None, SQL_AD_SEQUENCE_NO_BY_YEAR_MONTH, AD_Sequence_ID, calendarYear, calendarMonth);
}
@Override
public String retrieveDocumentNoByYearMonthAndDay(final int AD_Sequence_ID, java.util.Date date)
{
if (date == null)
{
date = new Date();
}
final SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
final String calendarYear = yearFormat.format(date);
final SimpleDateFormat monthFormat = new SimpleDateFormat("M");
final String calendarMonth = monthFormat.format(date);
final SimpleDateFormat dayFormat = new SimpleDateFormat("d");
final String calendarDay = dayFormat.format(date);
return DB.getSQLValueStringEx(ITrx.TRXNAME_None, SQL_AD_SEQUENCE_NO_BY_YEAR_MONTH_DAY, AD_Sequence_ID, calendarYear, calendarMonth, calendarDay);
}
@Override | public DocTypeSequenceMap retrieveDocTypeSequenceMap(final I_C_DocType docType)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(docType);
final int docTypeId = docType.getC_DocType_ID();
return retrieveDocTypeSequenceMap(ctx, docTypeId);
}
@Cached(cacheName = I_C_DocType_Sequence.Table_Name + "#by#" + I_C_DocType_Sequence.COLUMNNAME_C_DocType_ID)
public DocTypeSequenceMap retrieveDocTypeSequenceMap(@CacheCtx final Properties ctx, final int docTypeId)
{
final DocTypeSequenceMap.Builder docTypeSequenceMapBuilder = DocTypeSequenceMap.builder();
final I_C_DocType docType = InterfaceWrapperHelper.create(ctx, docTypeId, I_C_DocType.class, ITrx.TRXNAME_None);
final DocSequenceId docNoSequenceId = DocSequenceId.ofRepoIdOrNull(docType.getDocNoSequence_ID());
docTypeSequenceMapBuilder.defaultDocNoSequenceId(docNoSequenceId);
final List<I_C_DocType_Sequence> docTypeSequenceDefs = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_DocType_Sequence.class, ctx, ITrx.TRXNAME_None)
.addEqualsFilter(I_C_DocType_Sequence.COLUMNNAME_C_DocType_ID, docTypeId)
.addOnlyActiveRecordsFilter()
.create()
.list(I_C_DocType_Sequence.class);
for (final I_C_DocType_Sequence docTypeSequenceDef : docTypeSequenceDefs)
{
final ClientId adClientId = ClientId.ofRepoId(docTypeSequenceDef.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(docTypeSequenceDef.getAD_Org_ID());
final DocSequenceId docSequenceId = DocSequenceId.ofRepoId(docTypeSequenceDef.getDocNoSequence_ID());
docTypeSequenceMapBuilder.addDocSequenceId(adClientId, adOrgId, docSequenceId);
}
return docTypeSequenceMapBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocumentSequenceDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StudentService {
private static final List<Student> students = new ArrayList<>();
static {
// Initialize Data
var courseOne = new Course("Course1", "Spring", "10 Steps",
List.of("Learn Maven", "Import Project", "First Example", "Second Example"));
var courseTwo = new Course("Course2", "Spring MVC", "10 Examples",
List.of("Learn Maven", "Import Project", "First Example", "Second Example"));
var ranga = new Student("Student1", "Ranga Karanam",
"Hiker, Programmer and Architect", new ArrayList<>(List.of(courseOne, courseTwo)));
students.add(ranga);
} | public Student retrieveStudent(String studentId) {
return students.stream()
.filter(student -> student.id().equals(studentId))
.findAny()
.orElse(null);
}
public List<Course> retrieveCourses(String studentId) {
var student = retrieveStudent(studentId);
return student == null ? null : student.courses();
}
} | repos\spring-boot-examples-master\spring-boot-web-application\src\main\java\com\in28minutes\springboot\service\StudentService.java | 2 |
请完成以下Java代码 | public String getTaxTp() {
return taxTp;
}
/**
* Sets the value of the taxTp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxTp(String value) {
this.taxTp = value;
}
/**
* Gets the value of the addtlPdctInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlPdctInf() { | return addtlPdctInf;
}
/**
* Sets the value of the addtlPdctInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlPdctInf(String value) {
this.addtlPdctInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Product2.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Incoterms_ID (final int C_Incoterms_ID)
{
if (C_Incoterms_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Incoterms_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Incoterms_ID, C_Incoterms_ID);
}
@Override
public int getC_Incoterms_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Incoterms_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
} | @Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setDefaultLocation (final @Nullable java.lang.String DefaultLocation)
{
set_Value (COLUMNNAME_DefaultLocation, DefaultLocation);
}
@Override
public java.lang.String getDefaultLocation()
{
return get_ValueAsString(COLUMNNAME_DefaultLocation);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Incoterms.java | 1 |
请完成以下Java代码 | private UserNotificationsGroup toNotificationGroup(final I_AD_Role_NotificationGroup record)
{
final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class);
final NotificationGroupName groupInternalName = notificationGroupRepo.getNameById(NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID())).orElse(null);
if (groupInternalName == null)
{
// group does not exist or it was deactivated
return null;
}
return UserNotificationsGroup.builder()
.groupInternalName(groupInternalName)
.notificationTypes(UserNotificationsConfigRepository.toNotificationTypes(record.getNotificationType()))
.build();
}
@Override
public ImmutableSet<RoleId> getRoleIdsContainingNotificationGroupName(@NonNull final NotificationGroupName notificationGroupName)
{
final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class);
final NotificationGroupId notificationGroupId = notificationGroupRepo.getNotificationGroupId(notificationGroupName).orElse(null);
if(notificationGroupId == null) | {
return ImmutableSet.of();
}
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_Role_NotificationGroup.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Role_NotificationGroup.COLUMN_AD_NotificationGroup_ID, notificationGroupId)
.create()
.listDistinct(I_AD_Role_NotificationGroup.COLUMNNAME_AD_Role_ID, Integer.class)
.stream()
.map(RoleId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\RoleNotificationsConfigRepository.java | 1 |
请完成以下Java代码 | public String getExecutorShardingParam() {
return executorShardingParam;
}
public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
}
public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public Date getHandleTime() {
return handleTime;
} | public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java | 1 |
请完成以下Java代码 | public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
} | return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Forecast.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setExternalId (final @Nullable java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternalUrl (final @Nullable java.lang.String ExternalUrl)
{
set_Value (COLUMNNAME_ExternalUrl, ExternalUrl);
}
@Override
public java.lang.String getExternalUrl()
{
return get_ValueAsString(COLUMNNAME_ExternalUrl);
}
@Override
public void setMilestone_DueDate (final @Nullable java.sql.Timestamp Milestone_DueDate)
{
set_Value (COLUMNNAME_Milestone_DueDate, Milestone_DueDate);
}
@Override
public java.sql.Timestamp getMilestone_DueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_Milestone_DueDate);
}
@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 setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
} | @Override
public void setS_Milestone_ID (final int S_Milestone_ID)
{
if (S_Milestone_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Milestone_ID, S_Milestone_ID);
}
@Override
public int getS_Milestone_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Milestone_ID);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Milestone.java | 2 |
请完成以下Java代码 | public class Person {
private final String firstName;
private final String middleName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this(firstName, null, lastName, age);
}
public Person(String firstName, String middleName, String lastName, int age) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age; | }
public String getMiddleName() {
return middleName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(middleName, person.middleName) && Objects.equals(lastName, person.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, middleName, lastName, age);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\constructorchaining\Person.java | 1 |
请完成以下Java代码 | public void storeExternalPinstanceLog(@NonNull final CreatePInstanceLogRequest request, @NonNull final PInstanceId pInstanceId)
{
try
{
final List<ProcessInfoLog> processInfoLogList = request.getLogs()
.stream()
.map(JsonPInstanceLog::getMessage)
.map(ProcessInfoLog::ofMessage)
.collect(Collectors.toList());
instanceDAO.saveProcessInfoLogs(pInstanceId, processInfoLogList);
}
catch (final Exception e)
{
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e);
logger.error("Could not save the given model; message={}; AD_Issue_ID={}", e.getLocalizedMessage(), issueId);
throw e;
}
}
@NonNull
public Optional<ExternalSystemParentConfig> getByTypeAndValue(@NonNull final ExternalSystemType type, @NonNull final String childConfigValue)
{
return externalSystemConfigRepo.getByTypeAndValue(type, childConfigValue);
}
@NonNull
public Optional<ExternalSystemExportAudit> getMostRecentByTableReferenceAndSystem(
@NonNull final TableRecordReference tableRecordReference,
@NonNull final ExternalSystemType externalSystemType)
{
return externalSystemExportAuditRepo.getMostRecentByTableReferenceAndSystem(tableRecordReference, externalSystemType);
}
@NonNull
public ExternalSystemExportAudit createESExportAudit(@NonNull final CreateExportAuditRequest request)
{
return externalSystemExportAuditRepo.createESExportAudit(request);
}
@NonNull
private InsertRemoteIssueRequest createInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem, final PInstanceId pInstanceId)
{
return InsertRemoteIssueRequest.builder()
.issueCategory(jsonErrorItem.getIssueCategory()) | .issueSummary(StringUtils.isEmpty(jsonErrorItem.getMessage()) ? DEFAULT_ISSUE_SUMMARY : jsonErrorItem.getMessage())
.sourceClassName(jsonErrorItem.getSourceClassName())
.sourceMethodName(jsonErrorItem.getSourceMethodName())
.stacktrace(jsonErrorItem.getStackTrace())
.errorCode(jsonErrorItem.getErrorCode())
.pInstance_ID(pInstanceId)
.orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode()))
.build();
}
@Nullable
public ExternalSystemType getExternalSystemTypeByCodeOrNameOrNull(@Nullable final String value)
{
final ExternalSystem externalSystem = value != null
? externalSystemRepository.getByLegacyCodeOrValueOrNull(value)
: null;
return externalSystem != null
? externalSystem.getType()
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\externlasystem\dto\ExternalSystemService.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Sequence_Audit[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Sequence getAD_Sequence() throws RuntimeException
{
return (I_AD_Sequence)MTable.get(getCtx(), I_AD_Sequence.Table_Name)
.getPO(getAD_Sequence_ID(), get_TrxName()); }
/** Set Sequence.
@param AD_Sequence_ID
Document Sequence
*/
public void setAD_Sequence_ID (int AD_Sequence_ID)
{
if (AD_Sequence_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, Integer.valueOf(AD_Sequence_ID));
}
/** Get Sequence.
@return Document Sequence
*/
public int getAD_Sequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Sequence_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_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (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();
}
/** Set Document No. | @param DocumentNo
Document sequence number of the document
*/
public void setDocumentNo (String DocumentNo)
{
set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo);
}
/** Get Document No.
@return Document sequence number of the document
*/
public String getDocumentNo ()
{
return (String)get_Value(COLUMNNAME_DocumentNo);
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
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 Record ID.
@return Direct internal record ID
*/
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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TableResponse {
protected String name;
protected String url;
protected Long count;
@ApiModelProperty(example = "ACT_RU_VARIABLE")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "http://localhost:8080/flowable-rest/service/management/tables/ACT_RU_VARIABLE")
public String getUrl() {
return url; | }
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "4528")
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\TableResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DataSize getFileSizeThreshold() {
return this.fileSizeThreshold;
}
public void setFileSizeThreshold(DataSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
}
public boolean isResolveLazily() {
return this.resolveLazily;
}
public void setResolveLazily(boolean resolveLazily) {
this.resolveLazily = resolveLazily;
}
public boolean isStrictServletCompliance() {
return this.strictServletCompliance;
}
public void setStrictServletCompliance(boolean strictServletCompliance) {
this.strictServletCompliance = strictServletCompliance;
} | /**
* Create a new {@link MultipartConfigElement} using the properties.
* @return a new {@link MultipartConfigElement} configured using there properties
*/
public MultipartConfigElement createMultipartConfig() {
MultipartConfigFactory factory = new MultipartConfigFactory();
PropertyMapper map = PropertyMapper.get();
map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);
map.from(this.location).whenHasText().to(factory::setLocation);
map.from(this.maxRequestSize).to(factory::setMaxRequestSize);
map.from(this.maxFileSize).to(factory::setMaxFileSize);
return factory.createMultipartConfig();
}
} | repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\MultipartProperties.java | 2 |
请完成以下Java代码 | private static DocumentEntityDescriptor.Builder createDescriptorBuilder(
final DocumentId documentTypeId,
final DetailId detailId,
@NonNull final Optional<SOTrx> soTrx)
{
return DocumentEntityDescriptor.builder()
.setDocumentType(DocumentType.QuickInput, documentTypeId)
.setIsSOTrx(soTrx)
.disableDefaultTableCallouts()
// Defaults:
.setDetailId(detailId)
.setTableName(I_C_OrderLine.Table_Name); // TODO: figure out if it's needed
}
private DocumentFieldDescriptor.Builder createProductFieldBuilder(final String fieldName)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final ITranslatableString caption = msgBL.translatable(fieldName);
return DocumentFieldDescriptor.builder(fieldName)
.setLookupDescriptorProvider(productLookupDescriptor)
.setCaption(caption)
.setWidgetType(DocumentFieldWidgetType.Lookup)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true) | .setMandatoryLogic(ConstantLogicExpression.TRUE)
.setDisplayLogic(ConstantLogicExpression.TRUE)
.addCallout(CableSalesOrderLineQuickInputDescriptorFactory::onProductChangedCallout)
.addCharacteristic(Characteristic.PublicField);
}
private static DocumentFieldDescriptor.Builder createQuantityFieldBuilder(final String fieldName)
{
return DocumentFieldDescriptor.builder(fieldName)
.setCaption(Services.get(IMsgBL.class).translatable(fieldName))
.setWidgetType(DocumentFieldWidgetType.Quantity)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.TRUE)
.setDisplayLogic(ConstantLogicExpression.TRUE)
.addCharacteristic(Characteristic.PublicField);
}
private static void onProductChangedCallout(final ICalloutField calloutField)
{
// TODO
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\vertical\cables\webui\quickinput\CableSalesOrderLineQuickInputDescriptorFactory.java | 1 |
请完成以下Java代码 | public class PathFilterRule implements SecurityFilterRule {
protected List<RequestMatcher> allowedPaths = new ArrayList<>();
protected List<RequestMatcher> deniedPaths = new ArrayList<>();
@Override
public Authorization authorize(String requestMethod, String requestUri) {
boolean secured = false;
for (RequestMatcher pattern : deniedPaths) {
Match match = pattern.match(requestMethod, requestUri);
if (match != null) {
secured = true;
break;
}
}
if (!secured) {
return Authorization.granted(Authentication.ANONYMOUS); | }
for (RequestMatcher pattern : allowedPaths) {
Match match = pattern.match(requestMethod, requestUri);
if (match != null) {
return match.authorize();
}
}
return null;
}
public List<RequestMatcher> getAllowedPaths() {
return allowedPaths;
}
public List<RequestMatcher> getDeniedPaths() {
return deniedPaths;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\PathFilterRule.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
System.setProperty("systemValue", "Some system parameter value");
System.setProperty("priority", "System property");
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesApp.class);
}
@Bean
public SomeBean someBean() {
return new SomeBean(10);
}
@PostConstruct
public void afterInitialize() {
System.out.println(stringValue);
System.out.println(valueFromFile);
System.out.println(systemValue); | System.out.println(someDefault);
System.out.println(prioritySystemProperty);
System.out.println(Arrays.toString(valuesArray));
System.out.println(spelValue);
System.out.println(spelSomeDefault);
System.out.println(someBeanValue);
System.out.println(valuesList);
System.out.println(valuesMap);
System.out.println(valuesMapKey1);
System.out.println(unknownMapKey);
System.out.println(unknownMap);
System.out.println(unknownMapKeyWithDefaultValue);
System.out.println(valuesMapFiltered);
System.out.println(systemPropertiesMap);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\value\ValuesApp.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public Integer getVersion() {
return version;
} | public void setVersion(Integer version) {
this.version = version;
}
public String getProjectReleaseVersion() {
return projectReleaseVersion;
}
public void setProjectReleaseVersion(String projectReleaseVersion) {
this.projectReleaseVersion = projectReleaseVersion;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RabbitConfig {
/**
* 同步RPC队列
*/
public static final String QUEUE_SYNC_RPC = "rpc.sync";
/**
* 异步RPC队列,使用临时回复队列,或者使用“Direct reply-to”特性
*/
public static final String QUEUE_ASYNC_RPC = "rpc.async";
/**
* 异步RPC队列,每个客户端使用不同的固定回复队列,需要额外提供correlationId以关联请求和响应
*/
public static final String QUEUE_ASYNC_RPC_WITH_FIXED_REPLY = "rpc.with.fixed.reply";
@Bean
public Queue syncRPCQueue() {
return new Queue(QUEUE_SYNC_RPC);
}
@Bean
public Queue asyncRPCQueue() {
return new Queue(QUEUE_ASYNC_RPC);
}
@Bean
public Queue fixedReplyRPCQueue() {
return new Queue(QUEUE_ASYNC_RPC_WITH_FIXED_REPLY);
}
@Bean | public Queue repliesQueue() {
return new AnonymousQueue();
}
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
@Bean
@Primary
public SimpleMessageListenerContainer replyContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
container.setQueueNames(repliesQueue().getName());
return container;
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jsonMessageConverter());
return rabbitTemplate;
}
@Bean
public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate template, SimpleMessageListenerContainer container) {
return new AsyncRabbitTemplate(template, container);
}
} | repos\SpringBootBucket-master\springboot-rabbitmq-rpc\springboot-rabbitmq-rpc-client\src\main\java\com\xncoding\pos\config\RabbitConfig.java | 2 |
请完成以下Java代码 | public boolean supports(Class<?> authentication) {
return OAuth2DeviceAuthorizationConsentAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Sets the {@code Consumer} providing access to the
* {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
* {@link OAuth2AuthorizationConsent.Builder} and additional context information.
*
* <p>
* The following context attributes are available:
* <ul>
* <li>The {@link OAuth2AuthorizationConsent.Builder} used to build the authorization
* consent prior to
* {@link OAuth2AuthorizationConsentService#save(OAuth2AuthorizationConsent)}.</li>
* <li>The {@link Authentication} of type
* {@link OAuth2DeviceAuthorizationConsentAuthenticationToken}.</li>
* <li>The {@link RegisteredClient} associated with the device authorization
* request.</li>
* <li>The {@link OAuth2Authorization} associated with the state token presented in
* the device authorization consent request.</li>
* </ul> | * @param authorizationConsentCustomizer the {@code Consumer} providing access to the
* {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
* {@link OAuth2AuthorizationConsent.Builder}
*/
public void setAuthorizationConsentCustomizer(
Consumer<OAuth2AuthorizationConsentAuthenticationContext> authorizationConsentCustomizer) {
Assert.notNull(authorizationConsentCustomizer, "authorizationConsentCustomizer cannot be null");
this.authorizationConsentCustomizer = authorizationConsentCustomizer;
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass())
&& principal.isAuthenticated();
}
private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationConsentAuthenticationProvider.java | 1 |
请完成以下Java代码 | public static PORelationException throwMissingWindowId(final String referenceName, final String tableName, final boolean isSOTrx)
{
final Object[] msgParams = { referenceName, tableName, DisplayType.toBooleanString(isSOTrx) };
throw new PORelationException(MSG_ERR_WINDOW_3P, msgParams);
}
/**
* Message indicates that a po has more or less than one key columns.
* <ul>
* <li>Param 1: the po (toString)</li>
* <li>Param 2: the number of key columns</li>
* </ul>
*/
private static final AdMessageKey MSG_ERR_KEY_COLUMNS_2P = AdMessageKey.of("MRelationType_Err_KeyColumns_2P"); | /**
* Message indicates that neither the reference nor the table have an
* AD_Window_ID set.
* <ul>
* <li>Param 1: The AD_Reference's name</li>
* <li>Param 2: The Table name</li>
* <li>Param 3: Whether we are in the ctx of a SO (Y or N)</li>
* </ul>
*/
private static final AdMessageKey MSG_ERR_WINDOW_3P = AdMessageKey.of("MRelationType_Err_Window_3P");
private PORelationException(final AdMessageKey adMsg, final Object... msgParams)
{
super(adMsg, msgParams);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\PORelationException.java | 1 |
请完成以下Java代码 | public LookupValuesList retrieveLookupValueByIdsInOrder(final @NonNull LookupDataSourceContext evalCtx)
{
cache_retrieveLookupValueById.getAllOrLoad(
evalCtx.streamSingleIdContexts().collect(ImmutableSet.toImmutableSet()),
singleIdCtxs -> {
final LookupDataSourceContext multipleIdsCtx = LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs);
return delegate.retrieveLookupValueByIdsInOrder(LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs))
.getValues()
.stream()
.collect(ImmutableMap.toImmutableMap(
lookupValue -> multipleIdsCtx.withIdToFilter(IdsToFilter.ofSingleValue(lookupValue.getId())),
lookupValue -> lookupValue));
}
);
return LookupDataSourceFetcher.super.retrieveLookupValueByIdsInOrder(evalCtx);
}
@Override
public Builder newContextForFetchingList() | {
return delegate.newContextForFetchingList();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
return cache_retrieveEntities.getOrLoad(evalCtx, delegate::retrieveEntities);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return delegate.getZoomIntoWindowId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\CachedLookupDataSourceFetcherAdapter.java | 1 |
请完成以下Java代码 | public Date resolveDuedate(String duedate) {
Date resolvedDuedate = Context.getCommandContext().getClock().getCurrentTime();
String[] tokens = duedate.split(" and ");
for (String token : tokens) {
resolvedDuedate = addSingleUnitQuantity(resolvedDuedate, token);
}
return resolvedDuedate;
}
@Override
public Boolean validateDuedate(String duedateDescription, int maxIterations, Date endDate, Date newTimer) {
return true;
}
@Override
public Date resolveEndDate(String endDate) {
return null;
}
protected Date addSingleUnitQuantity(Date startDate, String singleUnitQuantity) { | int spaceIndex = singleUnitQuantity.indexOf(' ');
if (spaceIndex == -1 || singleUnitQuantity.length() < spaceIndex + 1) {
throw new FlowableIllegalArgumentException("invalid duedate format: " + singleUnitQuantity);
}
String quantityText = singleUnitQuantity.substring(0, spaceIndex);
int quantity = Integer.parseInt(quantityText);
String unitText = singleUnitQuantity.substring(spaceIndex + 1).trim().toLowerCase();
int unit = units.get(unitText);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
calendar.add(unit, quantity);
return calendar.getTime();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\calendar\DefaultBusinessCalendar.java | 1 |
请完成以下Java代码 | public FlowableScriptEvaluationRequest storeScriptVariables() {
this.storeScriptVariables = true;
return this;
}
@Override
public ScriptEvaluation evaluate() throws FlowableScriptException {
if (StringUtils.isEmpty(language)) {
throw new FlowableIllegalArgumentException("language is required");
}
if (StringUtils.isEmpty(script)) {
throw new FlowableIllegalArgumentException("script is required");
} | ScriptEngine scriptEngine = getEngineByName(language);
Bindings bindings = createBindings();
try {
Object result = scriptEngine.eval(script, bindings);
return new ScriptEvaluationImpl(resolver, result);
} catch (ScriptException e) {
throw new FlowableScriptException(e.getMessage(), e);
}
}
protected Bindings createBindings() {
return new ScriptBindings(Collections.singletonList(resolver), scopeContainer, inputVariableContainer, storeScriptVariables);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\JSR223FlowableScriptEngine.java | 1 |
请完成以下Java代码 | public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID));
}
/** Get Attribute Set Instance.
@return Product Attribute Set Instance
*/
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_CostElement getM_CostElement() throws RuntimeException
{
return (I_M_CostElement)MTable.get(getCtx(), I_M_CostElement.Table_Name)
.getPO(getM_CostElement_ID(), get_TrxName()); }
/** Set Cost Element.
@param M_CostElement_ID
Product Cost Element
*/
public void setM_CostElement_ID (int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID));
}
/** Get Cost Element.
@return Product Cost Element
*/
public int getM_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{ | if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCostAllocation.java | 1 |
请完成以下Java代码 | public String getName() {
return null;
}
@Override
public String getOriginalFilename() {
return null;
}
@Override
public String getContentType() {
return null;
}
@Override
public boolean isEmpty() {
return input == null || input.length == 0;
}
@Override
public long getSize() {
return input.length;
}
@Override
public byte[] getBytes() { | return input;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(input);
}
@Override
public void transferTo(File destination) throws IOException, IllegalStateException {
try(FileOutputStream fos = new FileOutputStream(destination)) {
fos.write(input);
}
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-file\src\main\java\com\baeldung\file\CustomMultipartFile.java | 1 |
请完成以下Java代码 | public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
assertInTransit();
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId);
updateStatus();
}
private void updateStatus()
{
this.status = computeStatus();
}
private DDOrderMoveScheduleStatus computeStatus()
{
if (isDropTo())
{
return DDOrderMoveScheduleStatus.COMPLETED;
}
else if (isPickedFrom())
{
return DDOrderMoveScheduleStatus.IN_PROGRESS;
}
else
{
return DDOrderMoveScheduleStatus.NOT_STARTED;
}
}
@NonNull
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
if (pickedHUs == null) | {
return ExplainedOptional.emptyBecause("Schedule is not picked yet");
}
return pickedHUs.getInTransitLocatorId();
}
@NonNull
public ImmutableSet<HuId> getPickedHUIds()
{
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
return pickedHUs.getActualHUIdsPicked();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java | 1 |
请完成以下Java代码 | public ProcessEngineConfigurationImpl setAsyncExecutorResetExpiredJobsPageSize(
int asyncExecutorResetExpiredJobsPageSize
) {
this.asyncExecutorResetExpiredJobsPageSize = asyncExecutorResetExpiredJobsPageSize;
return this;
}
public boolean isAsyncExecutorIsMessageQueueMode() {
return asyncExecutorMessageQueueMode;
}
public ProcessEngineConfigurationImpl setAsyncExecutorMessageQueueMode(boolean asyncExecutorMessageQueueMode) {
this.asyncExecutorMessageQueueMode = asyncExecutorMessageQueueMode;
return this;
}
public boolean isRollbackDeployment() {
return isRollbackDeployment;
}
public void setRollbackDeployment(boolean rollbackDeployment) {
isRollbackDeployment = rollbackDeployment;
}
public EventSubscriptionPayloadMappingProvider getEventSubscriptionPayloadMappingProvider() {
return eventSubscriptionPayloadMappingProvider;
} | public void setEventSubscriptionPayloadMappingProvider(
EventSubscriptionPayloadMappingProvider eventSubscriptionPayloadMappingProvider
) {
this.eventSubscriptionPayloadMappingProvider = eventSubscriptionPayloadMappingProvider;
}
public ProcessDefinitionHelper getProcessDefinitionHelper() {
return processDefinitionHelper;
}
public ProcessEngineConfigurationImpl setProcessDefinitionHelper(ProcessDefinitionHelper processDefinitionHelper) {
this.processDefinitionHelper = processDefinitionHelper;
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java | 1 |
请完成以下Java代码 | public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setLevelHierarchy (final int LevelHierarchy)
{
set_ValueNoCheck (COLUMNNAME_LevelHierarchy, LevelHierarchy);
}
@Override
public int getLevelHierarchy()
{
return get_ValueAsInt(COLUMNNAME_LevelHierarchy);
}
@Override
public void setPointsSum_Forecasted (final BigDecimal PointsSum_Forecasted)
{
set_Value (COLUMNNAME_PointsSum_Forecasted, PointsSum_Forecasted);
}
@Override
public BigDecimal getPointsSum_Forecasted()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Forecasted);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_Invoiceable (final BigDecimal PointsSum_Invoiceable)
{
set_ValueNoCheck (COLUMNNAME_PointsSum_Invoiceable, PointsSum_Invoiceable);
}
@Override
public BigDecimal getPointsSum_Invoiceable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiceable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override | public void setPointsSum_Invoiced (final BigDecimal PointsSum_Invoiced)
{
set_Value (COLUMNNAME_PointsSum_Invoiced, PointsSum_Invoiced);
}
@Override
public BigDecimal getPointsSum_Invoiced()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_Settled (final BigDecimal PointsSum_Settled)
{
set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled);
}
@Override
public BigDecimal getPointsSum_Settled()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle)
{
set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle);
}
@Override
public BigDecimal getPointsSum_ToSettle()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java | 1 |
请完成以下Java代码 | public boolean isRootRow()
{
return getParentRowId() == null;
}
private IViewRowType getType()
{
return type;
}
public Builder setType(final IViewRowType type)
{
this.type = type;
return this;
}
public Builder setProcessed(final boolean processed)
{
this.processed = processed;
return this;
}
private boolean isProcessed()
{
if (processed == null)
{
// NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example.
// return DisplayType.toBoolean(values.getOrDefault("Processed", false));
return false;
}
else
{
return processed.booleanValue();
}
}
public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue)
{
if (jsonValue == null || JSONNullValue.isNull(jsonValue))
{
values.remove(fieldName); | }
else
{
values.put(fieldName, jsonValue);
}
return this;
}
private Map<String, Object> getValues()
{
return values;
}
public LookupValue getFieldValueAsLookupValue(final String fieldName)
{
return LookupValue.cast(values.get(fieldName));
}
public Builder addIncludedRow(final IViewRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<IViewRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java | 1 |
请完成以下Java代码 | private String getAmountColumnName()
{
return _amountColumn.getColumnName();
}
@Override
public ICompositeQueryFilter<SourceModelType> filter()
{
return this.filters;
}
@Override
public String getSql(final Properties ctx, final List<Object> sqlParamsOut)
{
final List<IQueryFilter<SourceModelType>> nonSqlFilters = filters.getNonSqlFilters();
Check.assume(nonSqlFilters == null || nonSqlFilters.isEmpty(), "Non-SQL filters are not supported: {}", nonSqlFilters);
final String sqlWhereClause = filters.getSqlFiltersWhereClause();
final String sql = "COALESCE(SUM(CASE WHEN (" + sqlWhereClause + ") THEN " + getAmountColumnName() + " ELSE 0 END), 0)";
final List<Object> sqlWhereClauseParams = filters.getSqlFiltersParams(ctx);
sqlParamsOut.addAll(sqlWhereClauseParams);
return sql;
}
@Override
public SumQueryAggregateColumnBuilder<SourceModelType, TargetModelType> setDynAttribute(final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute)
{
this.dynAttribute = dynAttribute;
return this;
}
@Override
public ModelDynAttributeAccessor<TargetModelType, BigDecimal> getDynAttribute()
{
Check.assumeNotNull(dynAttribute, "dynAttribute not null");
return dynAttribute;
}
@Override
public IAggregator<BigDecimal, SourceModelType> createAggregator(final TargetModelType targetModel)
{
Check.assumeNotNull(targetModel, "targetModel not null");
return new IAggregator<BigDecimal, SourceModelType>()
{
private final ICompositeQueryFilter<SourceModelType> filters = SumQueryAggregateColumnBuilder.this.filters.copy();
private final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute = SumQueryAggregateColumnBuilder.this.dynAttribute;
private BigDecimal sum = BigDecimal.ZERO;
@Override | public void add(final SourceModelType model)
{
if (filters.accept(model))
{
final Optional<BigDecimal> value = InterfaceWrapperHelper.getValue(model, getAmountColumnName());
if (value.isPresent())
{
sum = sum.add(value.get());
}
}
// Update target model's dynamic attribute
dynAttribute.setValue(targetModel, sum);
}
@Override
public BigDecimal getValue()
{
return sum;
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\SumQueryAggregateColumnBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RetrieveOrdersProcessor implements Processor
{
@Override
public void process(final Exchange exchange) throws Exception
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
exchange.getIn().setHeader(GetPatientsRouteConstants.HEADER_ORG_CODE, request.getOrgCode());
if (request.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue());
}
final String apiKey = request.getParameters().get(ExternalSystemConstants.PARAM_API_KEY);
final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final String tenant = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT);
final String updatedAfter = CoalesceUtil.coalesceNotNull(
request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE),
request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER),
Instant.ofEpochMilli(0).toString());
final AlbertaConnectionDetails albertaConnectionDetails = AlbertaConnectionDetails.builder()
.apiKey(apiKey)
.basePath(basePath)
.tenant(tenant)
.build();
final ApiClient apiClient = new ApiClient();
apiClient.setBasePath(basePath);
final OrderApi orderApi = new OrderApi(apiClient);
final ArrayOfOrders createdOrders = orderApi.getCreatedOrders(apiKey, GetOrdersRouteConstants.OrderStatus.CREATED.getValue(), updatedAfter);
final @NonNull List<Order> ordersToImport = createdOrders == null || createdOrders.isEmpty()
? new ArrayList<>()
: createdOrders;
final Set<String> createOrderIds = ordersToImport.stream() | .map(Order::getId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
final List<Order> updatedOrders = orderApi.getCreatedOrders(apiKey, GetOrdersRouteConstants.OrderStatus.UPDATED.getValue(), updatedAfter);
if (updatedOrders != null && !updatedOrders.isEmpty())
{
updatedOrders.stream()
.filter(order -> order.getId() != null && !createOrderIds.contains(order.getId()))
.forEach(ordersToImport::add);
}
exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_ORG_CODE, request.getOrgCode());
exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_ALBERTA_CONN_DETAILS, albertaConnectionDetails);
exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_ALBERTA_PHARMACY_API, new PharmacyApi(apiClient));
exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_DOCTOR_API, new DoctorApi(apiClient));
exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, new NextImportSinceTimestamp(Instant.parse(updatedAfter)));
exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_COMMAND, request.getCommand());
exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_EXTERNAL_SYSTEM_CONFIG_ID, request.getExternalSystemConfigId());
exchange.getIn().setBody(ordersToImport.isEmpty() ? null : ordersToImport);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\RetrieveOrdersProcessor.java | 2 |
请完成以下Java代码 | public String getIsDirectPrint ()
{
return (String)get_Value(COLUMNNAME_IsDirectPrint);
}
/** Set Drucker.
@param PrinterName
Name of the Printer
*/
public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Drucker.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), getPrinterName());
}
/** PrinterType AD_Reference_ID=540227 */
public static final int PRINTERTYPE_AD_Reference_ID=540227;
/** General = G */
public static final String PRINTERTYPE_General = "G";
/** Fax = F */
public static final String PRINTERTYPE_Fax = "F";
/** Label = L */
public static final String PRINTERTYPE_Label = "L";
/** Set Printer Type.
@param PrinterType Printer Type */
public void setPrinterType (String PrinterType)
{
set_Value (COLUMNNAME_PrinterType, PrinterType);
}
/** Get Printer Type.
@return Printer Type */
public String getPrinterType ()
{
return (String)get_Value(COLUMNNAME_PrinterType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Printer.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.