instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class ShipmentScheduleAndJobSchedules
{
@NonNull I_M_ShipmentSchedule shipmentSchedule;
@NonNull PickingJobScheduleCollection jobSchedules;
@NonNull ShipmentScheduleId shipmentScheduleId;
private ShipmentScheduleAndJobSchedules(@NonNull final I_M_ShipmentSchedule shipmentSchedule, @Nullable Collection<PickingJobSchedule> jobSchedules)
{
this.shipmentSchedule = shipmentSchedule;
this.shipmentScheduleId = ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
if (jobSchedules == null || jobSchedules.isEmpty())
{
this.jobSchedules = PickingJobScheduleCollection.EMPTY;
}
else
{
this.jobSchedules = PickingJobScheduleCollection.ofCollection(jobSchedules);
this.jobSchedules.assertSingleShipmentScheduleId(this.shipmentScheduleId);
}
}
public static ShipmentScheduleAndJobSchedules of(@NonNull final I_M_ShipmentSchedule shipmentSchedule, @Nullable Collection<PickingJobSchedule> jobSchedules)
{
return new ShipmentScheduleAndJobSchedules(shipmentSchedule, jobSchedules);
}
public static ShipmentScheduleAndJobSchedules ofShipmentSchedule(@NonNull final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentSchedule)
{
return new ShipmentScheduleAndJobSchedules(InterfaceWrapperHelper.create(shipmentSchedule, I_M_ShipmentSchedule.class), null);
}
|
public ShipmentScheduleAndJobScheduleIdSet toScheduleIds()
{
return jobSchedules.isEmpty()
? ShipmentScheduleAndJobScheduleIdSet.of(getShipmentScheduleId())
: jobSchedules.toShipmentScheduleAndJobScheduleIdSet();
}
public boolean isProcessed()
{
return shipmentSchedule.isProcessed();
}
public boolean hasJobSchedules()
{
return !jobSchedules.isEmpty();
}
public Set<PickingJobScheduleId> getJobScheduleIds() {return jobSchedules.getJobScheduleIds();}
public String getHeaderAggregationKey() {return StringUtils.trimBlankToNull(shipmentSchedule.getHeaderAggregationKey());}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleAndJobSchedules.java
| 2
|
请完成以下Java代码
|
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
}
if (this.mode == 'o' || this.mode == 'a') {
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
/**
* Pop an array or object scope.
*
* @param c
* The scope to close.
* @throws JSONException
* If nesting is wrong.
*/
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
}
/**
* Push an array or object scope.
*
* @throws JSONException
* If nesting is too deep.
*/
private void push(JSONObject jo) throws JSONException {
if (this.top >= maxdepth) {
throw new JSONException("Nesting too deep.");
}
this.stack[this.top] = jo;
this.mode = jo == null ? 'a' : 'k';
this.top += 1;
}
/**
|
* Append either the value <code>true</code> or the value <code>false</code> .
*
* @param b
* A boolean.
* @return this
* @throws JSONException
*/
public JSONWriter value(boolean b) throws JSONException {
return this.append(b ? "true" : "false");
}
/**
* Append a double value.
*
* @param d
* A double.
* @return this
* @throws JSONException
* If the number is not finite.
*/
public JSONWriter value(double d) throws JSONException {
return this.value(Double.valueOf(d));
}
/**
* Append a long value.
*
* @param l
* A long.
* @return this
* @throws JSONException
*/
public JSONWriter value(long l) throws JSONException {
return this.append(Long.toString(l));
}
/**
* Append an object value.
*
* @param o
* The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an object with a toJSONString() method.
* @return this
* @throws JSONException
* If the value is out of sequence.
*/
public JSONWriter value(Object o) throws JSONException {
return this.append(JSONObject.valueToString(o));
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class C_Order
{
private final TransactionResultService transactionResultService;
private final CreditPassConfigRepository creditPassConfigRepository;
public C_Order(@NonNull final TransactionResultService transactionResultService,
@NonNull final CreditPassConfigRepository creditPassConfigRepository)
{
this.transactionResultService = transactionResultService;
this.creditPassConfigRepository = creditPassConfigRepository;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = { I_C_Order.COLUMNNAME_PaymentRule,
})
public void setCreditPassInfo(final I_C_Order order)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final CreditPassConfig config = creditPassConfigRepository.getConfigByBPartnerId(bPartnerId);
final Optional<TransactionResult> transactionResult = transactionResultService.findLastTransactionResult(order.getPaymentRule(), BPartnerId.ofRepoId(order.getC_BPartner_ID()));
final Optional<CreditPassConfig> configuration = Optional.ofNullable(config);
final IMsgBL msgBL = Services.get(IMsgBL.class);
if (configuration.isPresent() && configuration.get().getCreditPassConfigPaymentRuleList().stream()
.map(CreditPassConfigPaymentRule::getPaymentRule)
.anyMatch(pr -> StringUtils.equals(pr, order.getPaymentRule())))
{
if (transactionResult.filter(tr -> tr.getRequestDate().until(LocalDateTime.now(), ChronoUnit.DAYS) < config.getRetryDays()).isPresent())
{
if (transactionResult.filter(tr -> tr.getResultCodeEffective() == ResultCode.P).isPresent())
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_SUCCESS_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
else
{
|
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
else
{
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
else
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NOT_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void validateCreditpassForOrder(final I_C_Order order)
{
if (order.getCreditpassFlag() && order.isSOTrx())
{
throw new AdempiereException(CreditPassConstants.ORDER_COMPLETED_CREDITPASS_ERROR);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\interceptor\C_Order.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void setResponseComposite(@NonNull final Exchange exchange)
{
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
exchange.getIn().setBody(routeContext.getJsonResponseComposite());
}
@Nullable
private static JsonExportDirectorySettings getJsonExportDirSettings(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
final String exportDirSettings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_JSON_EXPORT_DIRECTORY_SETTINGS);
if (Check.isBlank(exportDirSettings))
{
return null;
|
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper()
.readValue(exportDirSettings, JsonExportDirectorySettings.class);
}
catch (final JsonProcessingException e)
{
throw new RuntimeException("Could not read value of type JsonExportDirectorySettings!"
+ "ExternalSystemConfigId=" + externalSystemRequest.getExternalSystemConfigId() + ";"
+ " PInstance=" + externalSystemRequest.getAdPInstanceId());
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\GRSSignumExportBPartnerRouteBuilder.java
| 2
|
请完成以下Java代码
|
public class BpmnActivityBehavior implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Performs the default outgoing BPMN 2.0 behavior, which is having parallel paths of executions for the outgoing sequence flow.
*
* More precisely: every sequence flow that has a condition which evaluates to true (or which doesn't have a condition), is selected for continuation of the process instance. If multiple sequencer
* flow are selected, multiple, parallel paths of executions are created.
*/
public void performDefaultOutgoingBehavior(ExecutionEntity activityExecution) {
performOutgoingBehavior(activityExecution, true, false);
}
/**
* Performs the default outgoing BPMN 2.0 behavior (@see {@link #performDefaultOutgoingBehavior(ExecutionEntity)}), but without checking the conditions on the outgoing sequence flow.
*
* This means that every outgoing sequence flow is selected for continuing the process instance, regardless of having a condition or not. In case of multiple outgoing sequence flow, multiple
* parallel paths of executions will be created.
*/
public void performIgnoreConditionsOutgoingBehavior(ExecutionEntity activityExecution) {
performOutgoingBehavior(activityExecution, false, false);
}
|
/**
* Actual implementation of leaving an activity.
*
* @param execution
* The current execution context
* @param checkConditions
* Whether or not to check conditions before determining whether or not to take a transition.
* @param throwExceptionIfExecutionStuck
* If true, an {@link FlowableException} will be thrown in case no transition could be found to leave the activity.
*/
protected void performOutgoingBehavior(ExecutionEntity execution, boolean checkConditions, boolean throwExceptionIfExecutionStuck) {
CommandContextUtil.getAgenda().planTakeOutgoingSequenceFlowsOperation(execution, true);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\BpmnActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ForecastListLineItemExtensionType {
@XmlElement(name = "ForecastListLineItemExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
protected at.erpel.schemas._1p0.documents.extensions.edifact.ForecastListLineItemExtensionType forecastListLineItemExtension;
@XmlElement(name = "ErpelForecastLineItemExtension")
protected CustomType erpelForecastLineItemExtension;
/**
* Gets the value of the forecastListLineItemExtension property.
*
* @return
* possible object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.ForecastListLineItemExtensionType }
*
*/
public at.erpel.schemas._1p0.documents.extensions.edifact.ForecastListLineItemExtensionType getForecastListLineItemExtension() {
return forecastListLineItemExtension;
}
/**
* Sets the value of the forecastListLineItemExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.ForecastListLineItemExtensionType }
*
*/
public void setForecastListLineItemExtension(at.erpel.schemas._1p0.documents.extensions.edifact.ForecastListLineItemExtensionType value) {
this.forecastListLineItemExtension = value;
}
/**
|
* Gets the value of the erpelForecastLineItemExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelForecastLineItemExtension() {
return erpelForecastLineItemExtension;
}
/**
* Sets the value of the erpelForecastLineItemExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelForecastLineItemExtension(CustomType value) {
this.erpelForecastLineItemExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\ForecastListLineItemExtensionType.java
| 2
|
请完成以下Java代码
|
public void setCtrySubDvsn(String value) {
this.ctrySubDvsn = value;
}
/**
* Gets the value of the ctry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtry() {
return ctry;
}
/**
* Sets the value of the ctry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtry(String value) {
this.ctry = value;
}
/**
* Gets the value of the adrLine property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
|
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adrLine property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdrLine().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdrLine() {
if (adrLine == null) {
adrLine = new ArrayList<String>();
}
return this.adrLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PostalAddress6.java
| 1
|
请完成以下Java代码
|
public class parser_dll
{
private NeuralNetworkParser parser;
public parser_dll()
{
this(ConfigOption.PATH);
}
public parser_dll(String modelPath)
{
parser = GlobalObjectPool.get(modelPath);
if (parser != null) return;
parser = new NeuralNetworkParser();
long start = System.currentTimeMillis();
logger.info("开始加载神经网络依存句法模型:" + modelPath);
if (!parser.load(modelPath))
{
throw new IllegalArgumentException("加载神经网络依存句法模型[" + modelPath + "]失败!");
}
logger.info("加载神经网络依存句法模型[" + modelPath + "]成功,耗时 " + (System.currentTimeMillis() - start) + " ms");
parser.setup_system();
parser.build_feature_space();
GlobalObjectPool.put(modelPath, parser);
}
/**
* 分析句法
|
*
* @param words 词语列表
* @param postags 词性列表
* @param heads 输出依存指向列表
* @param deprels 输出依存名称列表
* @return 节点的个数
*/
public int parse(List<String> words, List<String> postags, List<Integer> heads, List<String> deprels)
{
Instance inst = new Instance();
inst.forms.add(SpecialOption.ROOT);
inst.postags.add(SpecialOption.ROOT);
for (int i = 0; i < words.size(); i++)
{
inst.forms.add(words.get(i));
inst.postags.add(postags.get(i));
}
parser.predict(inst, heads, deprels);
heads.remove(0);
deprels.remove(0);
return heads.size();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\parser_dll.java
| 1
|
请完成以下Java代码
|
public void setOpenAmt (final BigDecimal OpenAmt)
{
set_ValueNoCheck (COLUMNNAME_OpenAmt, OpenAmt);
}
@Override
public BigDecimal getOpenAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPayAmt (final BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
@Override
public BigDecimal getPayAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PayAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* PaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int PAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String PAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String PAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String PAYMENTRULE_OnCredit = "P";
|
/** DirectDebit = D */
public static final String PAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String PAYMENTRULE_Mixed = "M";
/** PayPal = L */
public static final String PAYMENTRULE_PayPal = "L";
/** PayPal Extern = V */
public static final String PAYMENTRULE_PayPalExtern = "V";
/** Kreditkarte Extern = U */
public static final String PAYMENTRULE_KreditkarteExtern = "U";
/** Sofortüberweisung = R */
public static final String PAYMENTRULE_Sofortueberweisung = "R";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Rueckerstattung = "E";
/** Verrechnung = F */
public static final String PAYMENTRULE_Verrechnung = "F";
@Override
public void setPaymentRule (final java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
@Override
public java.lang.String getPaymentRule()
{
return get_ValueAsString(COLUMNNAME_PaymentRule);
}
@Override
public void setReference (final @Nullable java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
@Override
public java.lang.String getReference()
{
return get_ValueAsString(COLUMNNAME_Reference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelectionLine.java
| 1
|
请完成以下Java代码
|
public I_CM_Media getCM_Media() throws RuntimeException
{
return (I_CM_Media)MTable.get(getCtx(), I_CM_Media.Table_Name)
.getPO(getCM_Media_ID(), get_TrxName()); }
/** Set Media Item.
@param CM_Media_ID
Contains media content like images, flash movies etc.
*/
public void setCM_Media_ID (int CM_Media_ID)
{
if (CM_Media_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Media_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Media_ID, Integer.valueOf(CM_Media_ID));
}
/** Get Media Item.
@return Contains media content like images, flash movies etc.
*/
public int getCM_Media_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_Media_Server getCM_Media_Server() throws RuntimeException
{
return (I_CM_Media_Server)MTable.get(getCtx(), I_CM_Media_Server.Table_Name)
.getPO(getCM_Media_Server_ID(), get_TrxName()); }
/** Set Media Server.
@param CM_Media_Server_ID
Media Server list to which content should get transfered
*/
public void setCM_Media_Server_ID (int CM_Media_Server_ID)
{
if (CM_Media_Server_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Media_Server_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Media_Server_ID, Integer.valueOf(CM_Media_Server_ID));
}
/** Get Media Server.
@return Media Server list to which content should get transfered
*/
public int getCM_Media_Server_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_Server_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
|
}
/** Set Deployed.
@param IsDeployed
Entity is deployed
*/
public void setIsDeployed (boolean IsDeployed)
{
set_Value (COLUMNNAME_IsDeployed, Boolean.valueOf(IsDeployed));
}
/** Get Deployed.
@return Entity is deployed
*/
public boolean isDeployed ()
{
Object oo = get_Value(COLUMNNAME_IsDeployed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Synchronized.
@param LastSynchronized
Date when last synchronized
*/
public void setLastSynchronized (Timestamp LastSynchronized)
{
set_Value (COLUMNNAME_LastSynchronized, LastSynchronized);
}
/** Get Last Synchronized.
@return Date when last synchronized
*/
public Timestamp getLastSynchronized ()
{
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_MediaDeploy.java
| 1
|
请完成以下Java代码
|
public MGoal getMGoal() {
return m_goal;
}
/**
*
* @param mgoal
*/
public void setMGoal(MGoal mgoal) {
m_goal = mgoal;
}
/**
*
* @return X axis label
*/
public String getXAxisLabel() {
return m_X_AxisLabel;
}
/**
*
* @param axisLabel
*/
public void setXAxisLabel(String axisLabel) {
m_X_AxisLabel = axisLabel;
}
/**
*
* @return Y axis label
*/
public String getYAxisLabel() {
return m_Y_AxisLabel;
}
/**
*
* @param axisLabel
*/
public void setYAxisLabel(String axisLabel) {
m_Y_AxisLabel = axisLabel;
}
/**
*
* @return graph column list
*/
public ArrayList<GraphColumn> loadData() {
// Calculated
MMeasure measure = getMGoal().getMeasure();
if (measure == null)
{
|
log.warn("No Measure for " + getMGoal());
return null;
}
ArrayList<GraphColumn>list = measure.getGraphColumnList(getMGoal());
pieDataset = new DefaultPieDataset();
dataset = new DefaultCategoryDataset();
for (int i = 0; i < list.size(); i++){
String series = m_X_AxisLabel;
if (list.get(i).getDate() != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(list.get(i).getDate());
series = Integer.toString(cal.get(Calendar.YEAR));
}
dataset.addValue(list.get(i).getValue(), series,
list.get(i).getLabel());
linearDataset.addValue(list.get(i).getValue(), m_X_AxisLabel,
list.get(i).getLabel());
pieDataset.setValue(list.get(i).getLabel(), list.get(i).getValue());
}
return list;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\apps\graph\GraphBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTown() {
return town;
}
/**
* Sets the value of the town property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTown(String value) {
this.town = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCountry(String value) {
|
this.country = value;
}
/**
* Details about the contact person at the delivery point.
*
* @return
* possible object is
* {@link ContactType }
*
*/
public ContactType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link ContactType }
*
*/
public void setContact(ContactType value) {
this.contact = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryPointDetails.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public I_C_UOM getCommonUOM()
{
//validate that all qtys have the same UOM
mapReduce(part -> part.getQty().getUomId())
.orElseThrow(()-> new AdempiereException("Missing I_C_UOM!")
.appendParametersToMessage()
.setParameter("Parts", this));
return toList().get(0).getQty().getUOM();
}
@Override
public Iterator<PackingItemPart> iterator()
{
return toList().iterator();
}
public void clear()
{
partsMap.clear();
}
public void addQtys(final PackingItemParts partsToAdd)
{
partsToAdd.toList()
.forEach(this::addQty);
|
}
private void addQty(final PackingItemPart part)
{
partsMap.compute(part.getId(),
(id, existingPart) -> existingPart != null ? existingPart.addQty(part.getQty()) : part);
}
public void removePart(final PackingItemPart part)
{
partsMap.remove(part.getId(), part);
}
public void updatePart(@NonNull final PackingItemPart part)
{
partsMap.put(part.getId(), part);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemParts.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MobileUIManufacturingConfig
{
@NonNull OptionalBoolean isScanResourceRequired;
@NonNull OptionalBoolean isAllowIssuingAnyHU;
public MobileUIManufacturingConfig fallbackTo(@NonNull final MobileUIManufacturingConfig other)
{
final MobileUIManufacturingConfig result = MobileUIManufacturingConfig.builder()
.isScanResourceRequired(this.isScanResourceRequired.ifUnknown(other.isScanResourceRequired))
.isAllowIssuingAnyHU(this.isAllowIssuingAnyHU.ifUnknown(other.isAllowIssuingAnyHU))
.build();
if (result.equals(this))
{
return this;
}
else if (result.equals(other))
{
return other;
}
else
{
return result;
}
}
public static Optional<MobileUIManufacturingConfig> merge(@Nullable final MobileUIManufacturingConfig... configs)
|
{
if (configs == null || configs.length <= 0)
{
return Optional.empty();
}
MobileUIManufacturingConfig result = null;
for (final MobileUIManufacturingConfig config : configs)
{
if (config == null)
{
continue;
}
result = result != null ? result.fallbackTo(config) : config;
}
return Optional.ofNullable(result);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\config\MobileUIManufacturingConfig.java
| 2
|
请完成以下Java代码
|
public PInstanceId createSelection(final @NonNull Collection<PPOrderCandidateId> candidateIds)
{
if (candidateIds.isEmpty())
{
throw new AdempiereException("At least one candidateId must be specified");
}
final PInstanceId selectionId = queryBL.createQueryBuilder(I_PP_Order_Candidate.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID, candidateIds)
.create()
.createSelection();
if (candidateIds.isEmpty())
{
throw new AdempiereException("No candidates found");
}
return selectionId;
}
@NonNull
public Result enqueueSelection(@NonNull final EnqueuePPOrderCandidateRequest request)
{
final PInstanceId adPInstanceId = request.getAdPInstanceId();
final LockOwner lockOwner = LockOwner.newOwner(PPOrderCandidateEnqueuer.class.getSimpleName(), adPInstanceId.getRepoId());
final ILockCommand elementsLocker = lockManager
.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_PP_Order_Candidate.class, adPInstanceId);
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(request.getCtx(), GeneratePPOrderFromPPOrderCandidate.class);
final I_C_Queue_WorkPackage workPackage = queue
.newWorkPackage()
.parameter(WP_PINSTANCE_ID_PARAM, adPInstanceId)
.parameter(WP_COMPLETE_DOC_PARAM, request.getIsCompleteDocOverride())
|
.parameter(WP_AUTO_PROCESS_CANDIDATES_AFTER_PRODUCTION, request.isAutoProcessCandidatesAfterProduction())
.parameter(WP_AUTO_CLOSE_CANDIDATES_AFTER_PRODUCTION, request.isAutoCloseCandidatesAfterProduction())
.setElementsLocker(elementsLocker)
.buildAndEnqueue();
final Result result = new Result();
result.addEnqueuedWorkPackageId(QueueWorkPackageId.ofRepoId(workPackage.getC_Queue_WorkPackage_ID()));
return result;
}
public static class Result
{
private final List<QueueWorkPackageId> enqueuedWorkpackageIds = new ArrayList<>();
public int getEnqueuedPackagesCount()
{
return enqueuedWorkpackageIds.size();
}
public ImmutableList<QueueWorkPackageId> getEnqueuedPackageIds()
{
return ImmutableList.copyOf(enqueuedWorkpackageIds);
}
private void addEnqueuedWorkPackageId(@NonNull final QueueWorkPackageId workPackageId)
{
enqueuedWorkpackageIds.add(workPackageId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\async\PPOrderCandidateEnqueuer.java
| 1
|
请完成以下Java代码
|
private final void loadItems()
{
final PT parentModel = getParentModel();
final IContextAware ctx = createPlainContextAware(parentModel);
//
// Retrieve fresh items
final List<T> items = retrieveItems(ctx, parentModel);
//
// Update status
this.ctx = ctx;
this.items = items == null ? null : new ArrayList<T>(items); // NOTE: we need to do a copy just in case we get an unmodifiable list
this.parentModelLoadCount = InterfaceWrapperHelper.getLoadCount(parentModel);
this.debugEmptyNotStaledSet = false;
}
/**
* Sets an empty inner list and flag this list as not staled anymore.
*
* To be used after parent model is created, to start maintaining this list from the very beginning.
*/
public final void setEmptyNotStaled()
{
final PT parentModel = getParentModel();
this.ctx = createPlainContextAware(parentModel);
this.items = new ArrayList<T>();
this.debugEmptyNotStaledSet = true;
debugCheckItemsValid();
}
private final void debugCheckItemsValid()
{
if (!DEBUG)
{
return;
}
final PT parentModel = getParentModel();
final IContextAware ctx = createPlainContextAware(parentModel);
final boolean instancesTrackerEnabled = POJOLookupMapInstancesTracker.ENABLED;
POJOLookupMapInstancesTracker.ENABLED = false;
try
{
|
//
// Retrieve fresh items
final List<T> itemsRetrievedNow = retrieveItems(ctx, parentModel);
if (itemsComparator != null)
{
Collections.sort(itemsRetrievedNow, itemsComparator);
}
if (!Objects.equals(this.items, itemsRetrievedNow))
{
final int itemsCount = this.items == null ? 0 : this.items.size();
final int itemsRetrievedNowCount = itemsRetrievedNow.size();
throw new AdempiereException("Loaded items and cached items does not match."
+ "\n Parent: " + parentModelRef.get()
+ "\n Cached items(" + itemsCount + "): " + this.items
+ "\n Fresh items(" + itemsRetrievedNowCount + "): " + itemsRetrievedNow
+ "\n debugEmptyNotStaledSet=" + debugEmptyNotStaledSet //
);
}
}
finally
{
POJOLookupMapInstancesTracker.ENABLED = instancesTrackerEnabled;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\cache\AbstractModelListCacheLocal.java
| 1
|
请完成以下Java代码
|
public class UserCacheObject {
/**
* 用户编号
*/
private Integer id;
/**
* 昵称
*/
private String name;
/**
* 性别
*/
private Integer gender;
public Integer getId() {
return id;
}
public UserCacheObject setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return name;
|
}
public UserCacheObject setName(String name) {
this.name = name;
return this;
}
public Integer getGender() {
return gender;
}
public UserCacheObject setGender(Integer gender) {
this.gender = gender;
return this;
}
@Override
public String toString() {
return "UserCacheObject{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\java\cn\iocoder\springboot\labs\lab10\springdatarediswithjedis\cacheobject\UserCacheObject.java
| 1
|
请完成以下Java代码
|
public de.metas.ui.web.base.model.I_WEBUI_Dashboard getWEBUI_Dashboard()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_Dashboard_ID, de.metas.ui.web.base.model.I_WEBUI_Dashboard.class);
}
@Override
public void setWEBUI_Dashboard(final de.metas.ui.web.base.model.I_WEBUI_Dashboard WEBUI_Dashboard)
{
set_ValueFromPO(COLUMNNAME_WEBUI_Dashboard_ID, de.metas.ui.web.base.model.I_WEBUI_Dashboard.class, WEBUI_Dashboard);
}
@Override
public void setWEBUI_Dashboard_ID (final int WEBUI_Dashboard_ID)
{
if (WEBUI_Dashboard_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, WEBUI_Dashboard_ID);
}
@Override
public int getWEBUI_Dashboard_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Dashboard_ID);
}
@Override
public void setWEBUI_DashboardItem_ID (final int WEBUI_DashboardItem_ID)
{
if (WEBUI_DashboardItem_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_DashboardItem_ID, WEBUI_DashboardItem_ID);
}
@Override
public int getWEBUI_DashboardItem_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_DashboardItem_ID);
}
/**
* WEBUI_DashboardWidgetType AD_Reference_ID=540697
* Reference name: WEBUI_DashboardWidgetType
*/
public static final int WEBUI_DASHBOARDWIDGETTYPE_AD_Reference_ID=540697;
/** Target = T */
public static final String WEBUI_DASHBOARDWIDGETTYPE_Target = "T";
/** KPI = K */
public static final String WEBUI_DASHBOARDWIDGETTYPE_KPI = "K";
@Override
|
public void setWEBUI_DashboardWidgetType (final java.lang.String WEBUI_DashboardWidgetType)
{
set_Value (COLUMNNAME_WEBUI_DashboardWidgetType, WEBUI_DashboardWidgetType);
}
@Override
public java.lang.String getWEBUI_DashboardWidgetType()
{
return get_ValueAsString(COLUMNNAME_WEBUI_DashboardWidgetType);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class);
}
@Override
public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI)
{
set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_Value (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_Value (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_DashboardItem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ResourceController {
/**
* 需要用户角色权限
* @return
*/
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value="user", method= RequestMethod.GET)
public String helloUser() {
return "hello user";
}
/**
* 需要管理角色权限
*
* @return
*/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value="admin", method=RequestMethod.GET)
public String helloAdmin() {
return "hello admin";
}
/**
* 需要客户端权限
*
* @return
*/
@PreAuthorize("hasRole('ROLE_CLIENT')")
|
@RequestMapping(value="client", method=RequestMethod.GET)
public String helloClient() {
return "hello user authenticated by normal client";
}
/**
* 需要受信任的客户端权限
*
* @return
*/
@PreAuthorize("hasRole('ROLE_TRUSTED_CLIENT')")
@RequestMapping(value="trusted_client", method=RequestMethod.GET)
public String helloTrustedClient() {
return "hello user authenticated by trusted client";
}
@RequestMapping(value="principal", method=RequestMethod.GET)
public Object getPrincipal() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return principal;
}
@RequestMapping(value="roles", method=RequestMethod.GET)
public Object getRoles() {
return SecurityContextHolder.getContext().getAuthentication().getAuthorities();
}
}
|
repos\spring-boot-quick-master\quick-oauth2\quick-oauth2-server\src\main\java\com\quick\auth\server\controller\ResourceController.java
| 2
|
请完成以下Java代码
|
public class OrderItem {
private UUID productId;
private BigDecimal price;
public OrderItem(final Product product) {
this.productId = product.getId();
this.price = product.getPrice();
}
public UUID getProductId() {
return productId;
}
public BigDecimal getPrice() {
return price;
}
|
private OrderItem() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderItem orderItem = (OrderItem) o;
return Objects.equals(productId, orderItem.productId) && Objects.equals(price, orderItem.price);
}
@Override
public int hashCode() {
return Objects.hash(productId, price);
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\OrderItem.java
| 1
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_Container_URL[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Last Checked.
@param Checked
Info when we did the last check
*/
public void setChecked (Timestamp Checked)
{
set_Value (COLUMNNAME_Checked, Checked);
}
/** Get Last Checked.
@return Info when we did the last check
*/
public Timestamp getChecked ()
{
return (Timestamp)get_Value(COLUMNNAME_Checked);
}
public I_CM_Container getCM_Container() throws RuntimeException
{
return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name)
.getPO(getCM_Container_ID(), get_TrxName()); }
/** Set Web Container.
@param CM_Container_ID
Web Container contains content like images, text etc.
*/
public void setCM_Container_ID (int CM_Container_ID)
{
if (CM_Container_ID < 1)
set_Value (COLUMNNAME_CM_Container_ID, null);
else
set_Value (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID));
}
/** Get Web Container.
@return Web Container contains content like images, text etc.
*/
public int getCM_Container_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Container URL.
@param CM_Container_URL_ID
Contains info on used URLs
*/
public void setCM_Container_URL_ID (int CM_Container_URL_ID)
{
if (CM_Container_URL_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, Integer.valueOf(CM_Container_URL_ID));
}
|
/** Get Container URL.
@return Contains info on used URLs
*/
public int getCM_Container_URL_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Last Result.
@param Last_Result
Contains data on the last check result
*/
public void setLast_Result (String Last_Result)
{
set_Value (COLUMNNAME_Last_Result, Last_Result);
}
/** Get Last Result.
@return Contains data on the last check result
*/
public String getLast_Result ()
{
return (String)get_Value(COLUMNNAME_Last_Result);
}
/** Set Status.
@param Status
Status of the currently running check
*/
public void setStatus (String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MSV3PeerAuthToken
{
public static final String NAME = "AuthToken";
public static final MSV3PeerAuthToken TOKEN_NOT_SET = MSV3PeerAuthToken.of("missing-msv3server.peer.authToken-in-msv3server");
@JsonCreator
public static MSV3PeerAuthToken of(final String value)
{
return new MSV3PeerAuthToken(value);
}
private final String valueAsString;
private MSV3PeerAuthToken(@NonNull final String valueAsString)
{
if (valueAsString.isEmpty())
{
throw new IllegalArgumentException("Empty string is not a valid " + MSV3PeerAuthToken.class);
|
}
this.valueAsString = valueAsString;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue("********")
.toString();
}
@JsonValue
public String toJson()
{
return valueAsString;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3PeerAuthToken.java
| 2
|
请完成以下Java代码
|
public Date getTimeStamp() {
return timeStamp;
}
@Override
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public byte[] getData() {
return data;
}
@Override
public void setData(byte[] data) {
this.data = data;
}
@Override
public String getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(String lockOwner) {
|
this.lockOwner = lockOwner;
}
@Override
public String getLockTime() {
return lockTime;
}
@Override
public void setLockTime(String lockTime) {
this.lockTime = lockTime;
}
@Override
public int getProcessed() {
return isProcessed;
}
@Override
public void setProcessed(int isProcessed) {
this.isProcessed = isProcessed;
}
@Override
public String toString() {
return timeStamp.toString() + " : " + type;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ContextSourceBuilder port(int port) {
this.port = port;
return this;
}
/**
* Optional root suffix for the embedded LDAP server. Default is
* "dc=springframework,dc=org"
* @param root root suffix for the embedded LDAP server
* @return the {@link ContextSourceBuilder} for further customization
*/
public ContextSourceBuilder root(String root) {
this.root = root;
return this;
}
/**
* Specifies the ldap server URL when not using the embedded LDAP server. For
* example, "ldaps://ldap.example.com:33389/dc=myco,dc=org".
* @param url the ldap server URL
* @return the {@link ContextSourceBuilder} for further customization
*/
public ContextSourceBuilder url(String url) {
this.url = url;
return this;
}
/**
* Gets the {@link LdapAuthenticationProviderConfigurer} for further
* customizations
* @return the {@link LdapAuthenticationProviderConfigurer} for further
* customizations
*/
public LdapAuthenticationProviderConfigurer<B> and() {
return LdapAuthenticationProviderConfigurer.this;
}
private DefaultSpringSecurityContextSource build() {
if (this.url == null) {
startEmbeddedLdapServer();
}
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(getProviderUrl());
if (this.managerDn != null) {
contextSource.setUserDn(this.managerDn);
if (this.managerPassword == null) {
throw new IllegalStateException("managerPassword is required if managerDn is supplied");
}
contextSource.setPassword(this.managerPassword);
}
contextSource = postProcess(contextSource);
return contextSource;
}
private void startEmbeddedLdapServer() {
if (unboundIdPresent) {
UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif);
unboundIdContainer.setPort(getPort());
postProcess(unboundIdContainer);
this.port = unboundIdContainer.getPort();
}
|
else {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
}
private int getPort() {
if (this.port == null) {
this.port = getDefaultPort();
}
return this.port;
}
private int getDefaultPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return serverSocket.getLocalPort();
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
private String getProviderUrl() {
if (this.url == null) {
return "ldap://127.0.0.1:" + getPort() + "/" + this.root;
}
return this.url;
}
private ContextSourceBuilder() {
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\ldap\LdapAuthenticationProviderConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;
private String username;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
|
this.email = email;
}
public Person(int id, @NotBlank String username, @Email String email) {
super();
this.id = id;
this.username = username;
this.email = email;
}
public Person() {
super();
}
public String toString() {
return this.id + ":" +this.username;
}
}
|
repos\tutorials-master\microservices-modules\open-liberty\src\main\java\com\baeldung\openliberty\person\model\Person.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static final class Options {
/**
* No options.
*/
public static final Options NONE = new Options(Collections.emptySet());
private final Set<Option> options;
private Options(Set<Option> options) {
this.options = Collections.unmodifiableSet(options);
}
Set<Option> asSet() {
return this.options;
}
/**
* Returns if the given option is contained in this set.
* @param option the option to check
* @return {@code true} of the option is present
*/
public boolean contains(Option option) {
return this.options.contains(option);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Options other = (Options) obj;
return this.options.equals(other.options);
}
@Override
public int hashCode() {
return this.options.hashCode();
}
@Override
public String toString() {
return this.options.toString();
}
/**
* Create a new {@link Options} instance that contains the options in this set
* excluding the given option.
* @param option the option to exclude
* @return a new {@link Options} instance
*/
public Options without(Option option) {
return copy((options) -> options.remove(option));
}
/**
* Create a new {@link Options} instance that contains the options in this set
* including the given option.
* @param option the option to include
* @return a new {@link Options} instance
*/
public Options with(Option option) {
return copy((options) -> options.add(option));
}
private Options copy(Consumer<EnumSet<Option>> processor) {
EnumSet<Option> options = (!this.options.isEmpty()) ? EnumSet.copyOf(this.options)
: EnumSet.noneOf(Option.class);
processor.accept(options);
return new Options(options);
}
/**
* Create a new instance with the given {@link Option} values.
* @param options the options to include
|
* @return a new {@link Options} instance
*/
public static Options of(Option... options) {
Assert.notNull(options, "'options' must not be null");
if (options.length == 0) {
return NONE;
}
return new Options(EnumSet.copyOf(Arrays.asList(options)));
}
}
/**
* Option flags that can be applied.
*/
public enum Option {
/**
* Ignore all imports properties from the source.
*/
IGNORE_IMPORTS,
/**
* Ignore all profile activation and include properties.
* @since 2.4.3
*/
IGNORE_PROFILES,
/**
* Indicates that the source is "profile specific" and should be included after
* profile specific sibling imports.
* @since 2.4.5
*/
PROFILE_SPECIFIC
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigData.java
| 2
|
请完成以下Java代码
|
public ShipperGatewayId getShipperGatewayId()
{
return DerKurierConstants.SHIPPER_GATEWAY_ID;
}
@Override
public ShipperGatewayClient newClientForShipperId(@NonNull final ShipperId shipperId)
{
final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository.retrieveConfigForShipperId(shipperId.getRepoId());
return createClient(shipperConfig);
}
@VisibleForTesting
DerKurierClient createClient(@NonNull final DerKurierShipperConfig shipperConfig)
{
final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri(shipperConfig.getRestApiBaseUrl());
final RestTemplate restTemplate = restTemplateBuilder.build();
extractAndConfigureObjectMapperOfRestTemplate(restTemplate);
return new DerKurierClient(
restTemplate,
converters,
derKurierDeliveryOrderService,
derKurierDeliveryOrderRepository);
}
|
/**
* Put JavaTimeModule into the rest template's jackson object mapper.
* <b>
* Note 1: there have to be better ways to achieve this, but i don't know them.
* thx to https://stackoverflow.com/a/47176770/1012103
* <b>
* Note 2: visible because this is the object mapper we run with; we want our unit tests to use it as well.
*/
@VisibleForTesting
public static ObjectMapper extractAndConfigureObjectMapperOfRestTemplate(@NonNull final RestTemplate restTemplate)
{
final MappingJackson2HttpMessageConverter messageConverter = restTemplate
.getMessageConverters()
.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow(() -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
final ObjectMapper objectMapper = messageConverter.getObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierClientFactory.java
| 1
|
请完成以下Java代码
|
public void run(final String localTrxName)
{
// WORKAROUND: add subsequent methods called from here depends on source's trxName, so we are loading the candidate in this transaction
InterfaceWrapperHelper.refresh(source, localTrxName);
final I_C_Dunning_Candidate candidate = source.getC_Dunning_Candidate();
writeOffDunningCandidate(candidate, writeOffDescription);
source.setIsWriteOffApplied(true);
InterfaceWrapperHelper.save(source);
countWriteOff.setValue(countWriteOff.getValue() + 1);
}
@Override
public boolean doCatch(Throwable e) throws Throwable
{
final String errmsg = "Error processing: " + source;
logger.error(errmsg, e);
// notify monitor too about this issue
Loggables.addLog(errmsg);
return true; // rollback
}
@Override
public void doFinally()
{
// nothing
}
});
}
return countWriteOff.getValue();
}
|
/**
*
* @param candidate
* @param writeOffDescription
* @return true if candidate's invoice was written-off
*/
protected boolean writeOffDunningCandidate(final I_C_Dunning_Candidate candidate, final String writeOffDescription)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(candidate);
final String trxName = InterfaceWrapperHelper.getTrxName(candidate);
// services
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
final IDunningEventDispatcher dunningEventDispatcher = Services.get(IDunningEventDispatcher.class);
if (candidate.getAD_Table_ID() == adTableDAO.retrieveTableId(I_C_Invoice.Table_Name))
{
final I_C_Invoice invoice = InterfaceWrapperHelper.create(ctx, candidate.getRecord_ID(), I_C_Invoice.class, trxName);
Check.assumeNotNull(invoice, "No invoice found for candidate {}", candidate);
invoiceBL.writeOffInvoice(invoice, candidate.getOpenAmt(), writeOffDescription);
dunningEventDispatcher.fireDunningCandidateEvent(IInvoiceSourceBL.EVENT_AfterInvoiceWriteOff, candidate);
return true;
}
// other document types are ignored for now
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\api\impl\InvoiceSourceBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HttpHandler httpHandler(ApplicationContext applicationContext, WebFluxProperties properties) {
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(applicationContext).build();
return new CloudFoundryHttpHandler(properties.getBasePath(), httpHandler);
}
private static final class CloudFoundryHttpHandler implements HttpHandler {
private final HttpHandler delegate;
private final ContextPathCompositeHandler contextPathDelegate;
private CloudFoundryHttpHandler(String basePath, HttpHandler delegate) {
this.delegate = delegate;
this.contextPathDelegate = new ContextPathCompositeHandler(Map.of(basePath, delegate));
}
|
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
// Remove underlying context path first (e.g. Servlet container)
String path = request.getPath().pathWithinApplication().value();
if (path.startsWith("/cloudfoundryapplication")) {
return this.delegate.handle(request, response);
}
else {
return this.contextPathDelegate.handle(request, response);
}
}
}
}
|
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\actuator\cloudfoundry\customcontextpath\MyReactiveCloudFoundryConfiguration.java
| 2
|
请完成以下Java代码
|
public Mono<AuthorizationResult> authorize(Mono<Authentication> authentication, T object) {
return authentication.filter(this::isNotAnonymous)
.map(this::getAuthorizationDecision)
.defaultIfEmpty(new AuthorizationDecision(false));
}
private AuthorizationResult getAuthorizationDecision(Authentication authentication) {
return new AuthorizationDecision(authentication.isAuthenticated());
}
/**
* Verify (via {@link AuthenticationTrustResolver}) that the given authentication is
* not anonymous.
* @param authentication to be checked
* @return <code>true</code> if not anonymous, otherwise <code>false</code>.
|
*/
private boolean isNotAnonymous(Authentication authentication) {
return !this.authTrustResolver.isAnonymous(authentication);
}
/**
* Gets an instance of {@link AuthenticatedReactiveAuthorizationManager}
* @param <T>
* @return
*/
public static <T> AuthenticatedReactiveAuthorizationManager<T> authenticated() {
return new AuthenticatedReactiveAuthorizationManager<>();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthenticatedReactiveAuthorizationManager.java
| 1
|
请完成以下Java代码
|
public static PlasticTheme getCurrentTheme()
{
return THEME_CURRENT;
}
/**
* Error Feedback.
* <p>
* Invoked when the user attempts an invalid operation,
* such as pasting into an uneditable <code>JTextField</code>
* that has focus.
* </p>
* <p>
* If the user has enabled visual error indication on
* the desktop, this method will flash the caption bar
|
* of the active window. The user can also set the
* property awt.visualbell=true to achieve the same
* results.
* </p>
* @param component Component the error occurred in, may be
* null indicating the error condition is
* not directly associated with a
* <code>Component</code>.
*/
@Override
public void provideErrorFeedback (Component component)
{
super.provideErrorFeedback (component);
}
} // AdempiereLookAndFeel
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereLookAndFeel.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty()
{
return sections.isEmpty();
}
public static final class Builder
{
public WindowId windowId;
private ITranslatableString caption;
private ITranslatableString description;
private NotFoundMessages notFoundMessages;
private final ArrayList<DocumentLayoutSectionDescriptor.Builder> sectionBuilders = new ArrayList<>();
private Builder()
{
super();
}
public DocumentLayoutSingleRow build()
{
return new DocumentLayoutSingleRow(this);
}
private List<DocumentLayoutSectionDescriptor> buildSections()
{
return sectionBuilders
.stream()
.filter(DocumentLayoutSectionDescriptor.Builder::isValid)
.map(DocumentLayoutSectionDescriptor.Builder::build)
.filter(DocumentLayoutSectionDescriptor::hasColumns)
.collect(ImmutableList.toImmutableList());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("caption", caption)
.add("sections-count", sectionBuilders.size())
.toString();
}
public Builder setWindowId(final WindowId windowId)
{
this.windowId = windowId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
|
this.description = description;
return this;
}
public Builder notFoundMessages(@Nullable NotFoundMessages notFoundMessages)
{
this.notFoundMessages = notFoundMessages;
return this;
}
public Builder addSection(@NonNull final DocumentLayoutSectionDescriptor.Builder sectionBuilderToAdd)
{
sectionBuilders.add(sectionBuilderToAdd);
return this;
}
public Builder addSections(@NonNull final Collection<DocumentLayoutSectionDescriptor.Builder> sectionBuildersToAdd)
{
sectionBuilders.addAll(sectionBuildersToAdd);
return this;
}
public boolean isEmpty()
{
return sectionBuilders.isEmpty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSingleRow.java
| 1
|
请完成以下Java代码
|
private void initialize() {
button.setText("Click me");
handleClickEvent();
handleHoverEffect();
reuseRightClickEventHandler();
}
private void handleClickEvent() {
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
logger.info("OnAction {}", event);
}
});
button.setOnAction(event -> logger.info("OnAction {}", event));
button.setOnAction(event -> logger.info("OnAction2 {}", event));
}
|
private void handleHoverEffect() {
Effect shadow = new DropShadow();
button.setOnMouseEntered(e -> button.setEffect(shadow));
button.setOnMouseExited(e -> button.setEffect(null));
}
private void reuseRightClickEventHandler() {
EventHandler<MouseEvent> rightClickHandler = event -> {
if (MouseButton.SECONDARY.equals(event.getButton())) {
button.setFont(new Font(button.getFont()
.getSize() + 1));
}
};
button.setOnMousePressed(rightClickHandler);
label.setOnMousePressed(rightClickHandler);
}
}
|
repos\tutorials-master\javafx\src\main\java\com\baeldung\button\eventhandler\ButtonEventHandlerController.java
| 1
|
请完成以下Java代码
|
private boolean isEmployee(Authentication authentication) {
return (authentication
.getPrincipal()
.toString()
.startsWith("employee"));
}
private AuthenticationFilter authenticationFilter() {
AuthenticationFilter filter = new AuthenticationFilter(
resolver(), authenticationConverter());
filter.setSuccessHandler((request, response, auth) -> {});
return filter;
}
private AuthenticationManager employeesAuthenticationManager() {
return authentication -> {
if (isEmployee(authentication)) {
return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
|
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
throw new UsernameNotFoundException(authentication
.getPrincipal()
.toString());
};
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class);
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\authresolver\CustomWebSecurityConfigurer.java
| 1
|
请完成以下Java代码
|
public void repackage(Libraries libraries) throws IOException {
repackage(getSource(), libraries);
}
/**
* Repackage to the given destination so that it can be launched using '
* {@literal java -jar}'.
* @param destination the destination file (may be the same as the source)
* @param libraries the libraries required to run the archive
* @throws IOException if the file cannot be repackaged
*/
public void repackage(File destination, Libraries libraries) throws IOException {
repackage(destination, libraries, null);
}
/**
* Repackage to the given destination so that it can be launched using '
* {@literal java -jar}'.
* @param destination the destination file (may be the same as the source)
* @param libraries the libraries required to run the archive
* @param lastModifiedTime an optional last modified time to apply to the archive and
* its contents
* @throws IOException if the file cannot be repackaged
* @since 4.0.0
*/
public void repackage(File destination, Libraries libraries, @Nullable FileTime lastModifiedTime)
throws IOException {
Assert.isTrue(destination != null && !destination.isDirectory(), "Invalid destination");
getLayout(); // get layout early
destination = destination.getAbsoluteFile();
File source = getSource();
if (isAlreadyPackaged() && source.equals(destination)) {
return;
}
File workingSource = source;
if (source.equals(destination)) {
workingSource = getBackupFile();
workingSource.delete();
renameFile(source, workingSource);
}
destination.delete();
try {
try (JarFile sourceJar = new JarFile(workingSource)) {
repackage(sourceJar, destination, libraries, lastModifiedTime);
}
}
finally {
if (!this.backupSource && !source.equals(workingSource)) {
|
deleteFile(workingSource);
}
}
}
private void repackage(JarFile sourceJar, File destination, Libraries libraries,
@Nullable FileTime lastModifiedTime) throws IOException {
try (JarWriter writer = new JarWriter(destination, lastModifiedTime)) {
write(sourceJar, libraries, writer, lastModifiedTime != null);
}
if (lastModifiedTime != null) {
destination.setLastModified(lastModifiedTime.toMillis());
}
}
private void renameFile(File file, File dest) {
if (!file.renameTo(dest)) {
throw new IllegalStateException("Unable to rename '" + file + "' to '" + dest + "'");
}
}
private void deleteFile(File file) {
if (!file.delete()) {
throw new IllegalStateException("Unable to delete '" + file + "'");
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Repackager.java
| 1
|
请完成以下Java代码
|
public void setListener(T listener) {
Assert.notNull(listener, "'listener' must not be null");
Assert.isTrue(isSupportedType(listener), "'listener' is not of a supported type");
this.listener = listener;
}
/**
* Return the listener to be registered.
* @return the listener to be registered
*/
public @Nullable T getListener() {
return this.listener;
}
@Override
protected String getDescription() {
Assert.notNull(this.listener, "'listener' must not be null");
return "listener " + this.listener;
}
@Override
protected void register(String description, ServletContext servletContext) {
try {
servletContext.addListener(this.listener);
}
catch (RuntimeException ex) {
throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex);
}
}
|
/**
* Returns {@code true} if the specified listener is one of the supported types.
* @param listener the listener to test
* @return if the listener is of a supported type
*/
public static boolean isSupportedType(EventListener listener) {
for (Class<?> type : SUPPORTED_TYPES) {
if (ClassUtils.isAssignableValue(type, listener)) {
return true;
}
}
return false;
}
/**
* Return the supported types for this registration.
* @return the supported types
*/
public static Set<Class<?>> getSupportedTypes() {
return SUPPORTED_TYPES;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletListenerRegistrationBean.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class IsAdapter implements Adapter {
private static final Logger LOG = LoggerFactory.getLogger(IsAdapter.class);
private final String classPath;
public IsAdapter(String classPath) {
this.classPath = classPath;
}
@Override
public void loadPolicy(Model model) {
if (classPath.equals("")) {
// throw new Error("invalid file path, file path cannot be empty");
return;
}
loadPolicyClassPath(model, Helper::loadPolicyLine);
}
@Override
public void savePolicy(Model model) {
LOG.warn("savePolicy is not implemented !");
}
@Override
public void addPolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removePolicy(String sec, String ptype, List<String> rule) {
throw new Error("not implemented");
}
@Override
public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) {
throw new Error("not implemented");
}
private void loadPolicyClassPath(Model model, Helper.loadPolicyLineHandler<String, Model> handler) {
|
InputStream is = IsAdapter.class.getResourceAsStream(classPath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while((line = br.readLine()) != null) {
handler.accept(line, model);
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("IO error occurred");
}
}
}
|
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\IsAdapter.java
| 2
|
请完成以下Java代码
|
private BigDecimal retrieveWriteoffAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice))
{
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineWriteOff = amountAccessor.getValue(line);
if (null != ah && ah.getC_Currency_ID() != invoice.getC_Currency_ID())
{
final BigDecimal lineWriteOffConv = Services.get(ICurrencyBL.class).convert(
lineWriteOff, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
ah.getDateTrx().toInstant(), // ConvDate
|
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineWriteOffConv);
}
else
{
sum = sum.add(lineWriteOff);
}
}
return sum;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\impl\PlainAllocationDAO.java
| 1
|
请完成以下Java代码
|
public Builder setListNullItemCaption(@NonNull final ITranslatableString listNullItemCaption)
{
this.listNullItemCaption = listNullItemCaption;
return this;
}
public Builder setEmptyFieldText(final ITranslatableString emptyFieldText)
{
this.emptyFieldText = emptyFieldText;
return this;
}
public Builder trackField(final DocumentFieldDescriptor.Builder field)
{
documentFieldBuilder = field;
return this;
}
public boolean isSpecialFieldToExcludeFromLayout()
{
return documentFieldBuilder != null && documentFieldBuilder.isSpecialFieldToExcludeFromLayout();
}
public Builder setDevices(@NonNull final DeviceDescriptorsList devices)
{
this._devices = devices;
return this;
}
private DeviceDescriptorsList getDevices()
{
return _devices;
}
public Builder setSupportZoomInto(final boolean supportZoomInto)
{
this.supportZoomInto = supportZoomInto;
return this;
}
|
private boolean isSupportZoomInto()
{
return supportZoomInto;
}
public Builder setForbidNewRecordCreation(final boolean forbidNewRecordCreation)
{
this.forbidNewRecordCreation = forbidNewRecordCreation;
return this;
}
private boolean isForbidNewRecordCreation()
{
return forbidNewRecordCreation;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementFieldDescriptor.java
| 1
|
请完成以下Java代码
|
public TUMergeBuilder setTargetTU(final I_M_HU targetHU)
{
this.targetHU = targetHU;
return this;
}
@Override
public TUMergeBuilder setCUProductId(final ProductId cuProductId)
{
this.cuProductId = cuProductId;
return this;
}
@Override
public TUMergeBuilder setCUQty(final BigDecimal qty)
{
cuQty = qty;
return this;
}
@Override
public TUMergeBuilder setCUUOM(final I_C_UOM uom)
{
cuUOM = uom;
return this;
}
@Override
public TUMergeBuilder setCUTrxReferencedModel(final Object trxReferencedModel)
{
cuTrxReferencedModel = trxReferencedModel;
return this;
}
@Override
public void mergeTUs()
{
huTrxBL.createHUContextProcessorExecutor(huContextInitial).run((IHUContextProcessor)huContext0 -> {
// Make a copy of the processing context, we will need to modify it
final IMutableHUContext huContext = huContext0.copyAsMutable();
// Register our split HUTrxListener because this "merge" operation is similar with a split
// More, this will allow our listeners to execute on-split operations (e.g. linking the newly created VHU to same document as the source VHU).
huContext.getTrxListeners().addListener(HUSplitBuilderTrxListener.instance);
mergeTUs0(huContext);
return IHUContextProcessor.NULL_RESULT; // we don't care about the result
});
}
private void mergeTUs0(final IHUContext huContext)
{
final IAllocationRequest allocationRequest = createMergeAllocationRequest(huContext);
//
// Source: Selected handling units
final IAllocationSource source = HUListAllocationSourceDestination.of(sourceHUs);
//
// Destination: Handling unit we want to merge on
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU);
//
|
// Perform allocation
HULoader.of(source, destination)
.setAllowPartialUnloads(true) // force allow partial unloads when merging
.setAllowPartialLoads(true) // force allow partial loads when merging
.load(allocationRequest); // execute it; we don't care about the result
//
// Destroy HUs which had their storage emptied
for (final I_M_HU sourceHU : sourceHUs)
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, sourceHU);
}
}
/**
* Create an allocation request for the cuQty of the builder
*
* @param huContext
* @param referencedModel referenced model to be used in created request
* @return created request
*/
private IAllocationRequest createMergeAllocationRequest(final IHUContext huContext)
{
final ZonedDateTime date = SystemTime.asZonedDateTime();
return AllocationUtils.createQtyRequest(
huContext,
cuProductId, // Product
Quantity.of(cuQty, cuUOM), // quantity
date, // Date
cuTrxReferencedModel, // Referenced model
false // force allocation
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\TUMergeBuilder.java
| 1
|
请完成以下Java代码
|
public DiagramLayout getProcessDiagramLayout(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessDiagramLayoutCmd(processDefinitionId));
}
@Override
public Model newModel() {
return commandExecutor.execute(new CreateModelCmd());
}
@Override
public void saveModel(Model model) {
commandExecutor.execute(new SaveModelCmd((ModelEntity) model));
}
@Override
public void deleteModel(String modelId) {
commandExecutor.execute(new DeleteModelCmd(modelId));
}
@Override
public void addModelEditorSource(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes));
}
@Override
public void addModelEditorSourceExtra(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes));
}
@Override
public ModelQuery createModelQuery() {
return new ModelQueryImpl(commandExecutor);
}
@Override
public NativeModelQuery createNativeModelQuery() {
return new NativeModelQueryImpl(commandExecutor);
}
@Override
public Model getModel(String modelId) {
return commandExecutor.execute(new GetModelCmd(modelId));
}
@Override
public byte[] getModelEditorSource(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceCmd(modelId));
}
@Override
public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
@Override
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
|
}
@Override
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\RepositoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public static OrgIdAccessList ofSet(final Set<OrgId> orgIds)
{
return new OrgIdAccessList(false, orgIds);
}
private void assertNotAny()
{
if (any)
{
throw new AdempiereException("Assumed not an ANY org access list: " + this);
}
}
public Iterator<OrgId> iterator()
{
|
assertNotAny();
return orgIds.iterator();
}
public boolean contains(@NonNull final OrgId orgId)
{
return any || orgIds.contains(orgId);
}
public ImmutableSet<OrgId> toSet()
{
assertNotAny();
return orgIds;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\OrgIdAccessList.java
| 1
|
请完成以下Java代码
|
public class StoreRecord extends UpdatableRecordImpl<StoreRecord> {
private static final long serialVersionUID = 1L;
/**
* Setter for <code>public.Store.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>public.Store.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>public.Store.name</code>.
*/
public void setName(String value) {
set(1, value);
}
/**
* Getter for <code>public.Store.name</code>.
*/
public String getName() {
return (String) get(1);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
|
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached StoreRecord
*/
public StoreRecord() {
super(Store.STORE);
}
/**
* Create a detached, initialised StoreRecord
*/
public StoreRecord(Integer id, String name) {
super(Store.STORE);
setId(id);
setName(name);
resetChangedOnNotNull();
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\StoreRecord.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 Deployment selectLatestDeployment() {
return deploymentConverter.from(
repositoryService
.createDeploymentQuery()
.deploymentName("SpringAutoDeployment")
.latestVersion()
.singleResult()
);
}
public org.activiti.engine.runtime.ProcessInstance internalProcessInstance(String processInstanceId) {
org.activiti.engine.runtime.ProcessInstance internalProcessInstance = runtimeService
.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();
if (internalProcessInstance == null) {
throw new NotFoundException("Unable to find process instance for the given id:'" + processInstanceId + "'");
}
return internalProcessInstance;
}
private boolean canReadProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) {
return (
securityPoliciesManager.canRead(processInstance.getProcessDefinitionKey()) &&
(securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId()) ||
isATaskAssigneeOrACandidate(processInstance.getProcessInstanceId()))
);
}
private boolean canWriteProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) {
return (
securityPoliciesManager.canWrite(processInstance.getProcessDefinitionKey()) &&
securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId())
|
);
}
private boolean isATaskAssigneeOrACandidate(String processInstanceId) {
String authenticatedUserId = securityManager.getAuthenticatedUserId();
TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processInstanceId);
taskQuery
.or()
.taskCandidateOrAssigned(
securityManager.getAuthenticatedUserId(),
securityManager.getAuthenticatedUserGroups()
)
.taskOwner(authenticatedUserId)
.endOr();
return taskQuery.count() > 0;
}
private List<String> getCurrentUserGroupsIncludingEveryOneGroup() {
List<String> groups = new ArrayList<>(securityManager.getAuthenticatedUserGroups());
groups.add(EVERYONE_GROUP);
return groups;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ProcessRuntimeImpl.java
| 1
|
请完成以下Java代码
|
public class MaterialDispoGroupId
{
@JsonCreator
public static MaterialDispoGroupId ofInt(final int value)
{
return new MaterialDispoGroupId(value);
}
public static MaterialDispoGroupId ofIntOrNull(@Nullable final Integer value)
{
return value != null && value > 0 ? ofInt(value) : null;
}
public static MaterialDispoGroupId ofIdOrNull(final RepoIdAware id)
{
return id != null ? ofIntOrNull(id.getRepoId()) : null;
}
private final int value;
|
private MaterialDispoGroupId(final int value)
{
Check.assumeGreaterThanZero(value, "value");
this.value = value;
}
@Override
public String toString()
{
return String.valueOf(value);
}
@JsonValue
public int toInt()
{
return value;
}
public static int toInt(@Nullable final MaterialDispoGroupId groupId) {return groupId != null ? groupId.toInt() : -1;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\MaterialDispoGroupId.java
| 1
|
请完成以下Java代码
|
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
|
}
public List<ContactDetails> getContactDetailsList() {
return contactDetailsList;
}
public void setContactDetailsList(List<ContactDetails> contactDetailsList) {
this.contactDetailsList = contactDetailsList;
}
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]";
}
}
|
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\pojo\Customer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BPSupplierApprovalId implements RepoIdAware
{
int repoId;
@JsonCreator
public static BPSupplierApprovalId ofRepoId(final int repoId)
{
return new BPSupplierApprovalId(repoId);
}
@Nullable
public static BPSupplierApprovalId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new BPSupplierApprovalId(repoId) : null;
}
@Nullable
public static BPSupplierApprovalId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new BPSupplierApprovalId(repoId) : null;
}
public static Optional<BPSupplierApprovalId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final BPSupplierApprovalId bpSupplierApprovalId)
{
return toRepoIdOr(bpSupplierApprovalId, -1);
}
public static int toRepoIdOr(@Nullable final BPSupplierApprovalId bpSupplierApprovalId, final int defaultValue)
|
{
return bpSupplierApprovalId != null ? bpSupplierApprovalId.getRepoId() : defaultValue;
}
private BPSupplierApprovalId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BP_SupplierApproval_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPSupplierApprovalId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String serviceRendered;
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 String getServiceRendered() {
return serviceRendered;
}
public void setServiceRendered(String serviceRendered) {
this.serviceRendered = serviceRendered;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\Customer.java
| 2
|
请完成以下Java代码
|
public String getMessage()
{
m_message = fMessage.getText();
return m_message;
} // getMessage
public void setAttributes(final BoilerPlateContext attributes)
{
this.attributes = attributes;
fMessage.setAttributes(attributes);
}
public BoilerPlateContext getAttributes()
{
return attributes;
}
/**
* Action Listener - Send email
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
try
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
confirmPanel.getOKButton().setEnabled(false);
//
if (m_isPrintOnOK)
{
m_isPrinted = fMessage.print();
}
}
finally
{
confirmPanel.getOKButton().setEnabled(true);
setCursor(Cursor.getDefaultCursor());
}
// m_isPrinted = true;
m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
|
dispose();
}
} // actionPerformed
public void setPrintOnOK(final boolean value)
{
m_isPrintOnOK = value;
}
public boolean isPressedOK()
{
return m_isPressedOK;
}
public boolean isPrinted()
{
return m_isPrinted;
}
public File getPDF()
{
return fMessage.getPDF(getTitle());
}
public RichTextEditor getRichTextEditor()
{
return fMessage;
}
} // Letter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\LetterDialog.java
| 1
|
请完成以下Java代码
|
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
@Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU);
}
@Override
public java.lang.String getUPC_CU()
{
return get_ValueAsString(COLUMNNAME_UPC_CU);
}
@Override
public void setUPC_TU (final @Nullable java.lang.String UPC_TU)
{
set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
|
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
@Override
public void setValue (final @Nullable 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.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java
| 1
|
请完成以下Java代码
|
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=540002
* Reference name: C_SubscriptionProgress Status
*/
public static final int STATUS_AD_Reference_ID=540002;
/** Planned = P */
public static final String STATUS_Planned = "P";
/** Open = O */
|
public static final String STATUS_Open = "O";
/** Delivered = D */
public static final String STATUS_Delivered = "D";
/** InPicking = C */
public static final String STATUS_InPicking = "C";
/** Done = E */
public static final String STATUS_Done = "E";
/** Delayed = H */
public static final String STATUS_Delayed = "H";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscriptionProgress.java
| 1
|
请完成以下Java代码
|
public class EndpointMapping {
private final String path;
/**
* Creates a new {@code EndpointMapping} using the given {@code path}.
* @param path the path
*/
public EndpointMapping(String path) {
this.path = normalizePath(path);
}
/**
* Returns the path to which endpoints should be mapped.
* @return the path
*/
public String getPath() {
return this.path;
}
|
public String createSubPath(String path) {
return this.path + normalizePath(path);
}
private static String normalizePath(String path) {
if (!StringUtils.hasText(path)) {
return path;
}
String normalizedPath = path;
if (!normalizedPath.startsWith("/")) {
normalizedPath = "/" + normalizedPath;
}
if (normalizedPath.endsWith("/")) {
normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1);
}
return normalizedPath;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\EndpointMapping.java
| 1
|
请完成以下Java代码
|
public class SpringProcessApplicationElResolver implements ProcessApplicationElResolver {
private final static Logger LOGGER = Logger.getLogger(SpringProcessApplicationElResolver.class.getName());
@Override
public Integer getPrecedence() {
return ProcessApplicationElResolver.SPRING_RESOLVER;
}
@Override
public ELResolver getElResolver(AbstractProcessApplication processApplication) {
if (processApplication instanceof SpringProcessApplication) {
SpringProcessApplication springProcessApplication = (SpringProcessApplication) processApplication;
return new ApplicationContextElResolver(springProcessApplication.getApplicationContext());
} else if (processApplication instanceof org.camunda.bpm.application.impl.ServletProcessApplication) {
// Using fully-qualified class name instead of import statement to allow for automatic transformation
org.camunda.bpm.application.impl.ServletProcessApplication servletProcessApplication = (org.camunda.bpm.application.impl.ServletProcessApplication) processApplication;
if(!ClassUtils.isPresent("org.springframework.web.context.support.WebApplicationContextUtils", processApplication.getProcessApplicationClassloader())) {
|
LOGGER.log(Level.FINE, "WebApplicationContextUtils must be present for SpringProcessApplicationElResolver to work");
return null;
}
ServletContext servletContext = servletProcessApplication.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
if(applicationContext != null) {
return new ApplicationContextElResolver(applicationContext);
}
}
LOGGER.log(Level.FINE, "Process application class {0} unsupported by SpringProcessApplicationElResolver", processApplication);
return null;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\application\SpringProcessApplicationElResolver.java
| 1
|
请完成以下Java代码
|
public String get_ValueAsString(final String variableName)
{
if (VAR_Label.equals(variableName))
{
return getAttributeLabel();
}
else if (VAR_Value.equals(variableName))
{
final ITranslatableString valueTrl = getAttributeValueAsDisplayString();
return valueTrl != null ? valueTrl.translate(adLanguage) : null;
}
else if (VAR_UOM.equals(variableName))
{
return getAttributeUOM();
}
else
{
return null;
}
}
@Override
public boolean has_Variable(final String variableName)
{
return VARS.contains(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
return get_ValueAsString(variableName);
}
private String getAttributeLabel()
{
return attribute.getDisplayName().getDefaultValue();
}
private String getAttributeUOM()
{
final UomId uomId = attribute.getUomId();
if (uomId == null)
{
return null;
}
final I_C_UOM uom = uomsRepo.getById(uomId);
if (uom == null)
{
return null;
}
return uom.getUOMSymbol();
}
private ITranslatableString getAttributeValueAsDisplayString()
{
final AttributeValueType valueType = attribute.getValueType();
if (AttributeValueType.STRING.equals(valueType))
{
final String valueStr = attributeValue != null ? attributeValue.toString() : null;
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
else if (AttributeValueType.NUMBER.equals(valueType))
{
final BigDecimal valueBD = attributeValue != null ? NumberUtils.asBigDecimal(attributeValue, null) : null;
if (valueBD == null && !verboseDescription)
{
return null;
}
else
{
return ASIDescriptionBuilderCommand.formatNumber(valueBD, attribute.getNumberDisplayType());
|
}
}
else if (AttributeValueType.DATE.equals(valueType))
{
final Date valueDate = attributeValue != null ? TimeUtil.asDate(attributeValue) : null;
if (valueDate == null && !verboseDescription)
{
return null;
}
else
{
return ASIDescriptionBuilderCommand.formatDateValue(valueDate);
}
}
else if (AttributeValueType.LIST.equals(valueType))
{
final AttributeListValue attributeValue = attributeValueId != null ? attributesRepo.retrieveAttributeValueOrNull(attribute, attributeValueId) : null;
if (attributeValue != null)
{
return ASIDescriptionBuilderCommand.formatStringValue(attributeValue.getName());
}
else
{
return ASIDescriptionBuilderCommand.formatStringValue(null);
}
}
else
{
// Unknown attributeValueType
final String valueStr = attributeValue != null ? attributeValue.toString() : null;
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDescriptionPatternEvalCtx.java
| 1
|
请完成以下Java代码
|
protected Ingress desired(DeptrackResource primary, Context<DeptrackResource> context) {
ObjectMeta meta = fromPrimary(primary,COMPONENT)
.build();
return new IngressBuilder(template)
.withMetadata(meta)
.editSpec()
.editDefaultBackend()
.editOrNewService()
.withName(primary.getFrontendServiceName())
.endService()
.endDefaultBackend()
.editFirstRule()
.withHost(primary.getSpec().getIngressHostname())
.withHttp(buildHttpRule(primary))
.endRule()
.endSpec()
.build();
}
private HTTPIngressRuleValue buildHttpRule(DeptrackResource primary) {
return new HTTPIngressRuleValueBuilder()
// Backend route
.addNewPath()
.withPath("/api")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getApiServerServiceName())
.withNewPort()
.withName("http")
.endPort()
.endService()
.endBackend()
|
.endPath()
// Frontend route
.addNewPath()
.withPath("/")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getFrontendServiceName())
.withNewPort()
.withName("http")
.endPort()
.endService()
.endBackend()
.endPath()
.build();
}
}
|
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackIngressResource.java
| 1
|
请完成以下Java代码
|
public Boolean getLocked() {
return locked;
}
public Boolean getNotLocked() {
return notLocked;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
return activityId;
}
|
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getRetriesLeft() {
return retriesLeft;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java
| 1
|
请完成以下Java代码
|
private DocumentPrintOptions getDocumentPrintOptions(@NonNull final I_C_Order order)
{
final OptionalBoolean printTotals = getPrintTotalsOption(order);
if (printTotals.isPresent())
{
return DocumentPrintOptions.builder()
.sourceName("Order document: C_Order_ID=" + order.getC_Order_ID())
.option(DocumentPrintOptions.OPTION_IsPrintTotals, printTotals.isTrue())
.build();
}
else
{
return DocumentPrintOptions.NONE;
}
}
|
private OptionalBoolean getPrintTotalsOption(@NonNull final I_C_Order order)
{
final String docSubType = order.getOrderType();
if (X_C_DocType.DOCSUBTYPE_Proposal.equals(docSubType)
|| X_C_DocType.DOCSUBTYPE_Quotation.equals(docSubType))
{
return StringUtils.toOptionalBoolean(order.getPRINTER_OPTS_IsPrintTotals());
}
else
{
return OptionalBoolean.UNKNOWN;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderDocumentReportAdvisor.java
| 1
|
请完成以下Java代码
|
public class AuthorizationCreateDto {
protected Integer type;
protected String[] permissions;
protected String userId;
protected String groupId;
protected Integer resourceType;
protected String resourceId;
// transformers ///////////////////////////////////////
public static void update(AuthorizationCreateDto dto, Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) {
dbAuthorization.setGroupId(dto.getGroupId());
dbAuthorization.setUserId(dto.getUserId());
dbAuthorization.setResourceType(dto.getResourceType());
dbAuthorization.setResourceId(dto.getResourceId());
dbAuthorization.setPermissions(PermissionConverter.getPermissionsForNames(dto.getPermissions(), dto.getResourceType(), engineConfiguration));
}
//////////////////////////////////////////////////////
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String[] getPermissions() {
return permissions;
}
|
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getResourceType() {
return resourceType;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationCreateDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DashboardSyncService {
private final GitSyncService gitSyncService;
private final ResourceService resourceService;
private final ImageService imageService;
private final WidgetsBundleService widgetsBundleService;
private final PartitionService partitionService;
private final ProjectInfo projectInfo;
@Value("${transport.gateway.dashboard.sync.repository_url:}")
private String repoUrl;
@Value("${transport.gateway.dashboard.sync.branch:}")
private String branch;
@Value("${transport.gateway.dashboard.sync.fetch_frequency:24}")
private int fetchFrequencyHours;
private static final String REPO_KEY = "gateways-dashboard";
private static final String GATEWAYS_DASHBOARD_KEY = "gateways_dashboard.json";
@AfterStartUp(order = AfterStartUp.REGULAR_SERVICE)
public void init() throws Exception {
if (StringUtils.isBlank(branch)) {
branch = "release/" + projectInfo.getProjectVersion();
}
gitSyncService.registerSync(REPO_KEY, repoUrl, branch, TimeUnit.HOURS.toMillis(fetchFrequencyHours), this::update);
}
private void update() {
if (!partitionService.isMyPartition(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)) {
return;
}
List<RepoFile> resources = listFiles("resources");
for (RepoFile resourceFile : resources) {
byte[] data = getFileContent(resourceFile.path());
resourceService.createOrUpdateSystemResource(ResourceType.JS_MODULE, ResourceSubType.EXTENSION, resourceFile.name(), data);
}
List<RepoFile> images = listFiles("images");
for (RepoFile imageFile : images) {
byte[] data = getFileContent(imageFile.path());
imageService.createOrUpdateSystemImage(imageFile.name(), data);
}
|
Stream<String> widgetsBundles = listFiles("widget_bundles").stream()
.map(widgetsBundleFile -> new String(getFileContent(widgetsBundleFile.path()), StandardCharsets.UTF_8));
Stream<String> widgetTypes = listFiles("widget_types").stream()
.map(widgetTypeFile -> new String(getFileContent(widgetTypeFile.path()), StandardCharsets.UTF_8));
widgetsBundleService.updateSystemWidgets(widgetsBundles, widgetTypes);
RepoFile dashboardFile = listFiles("dashboards").get(0);
resourceService.createOrUpdateSystemResource(ResourceType.DASHBOARD, null, GATEWAYS_DASHBOARD_KEY, getFileContent(dashboardFile.path()));
log.info("Gateways dashboard sync completed");
}
private List<RepoFile> listFiles(String path) {
return gitSyncService.listFiles(REPO_KEY, path, 1, FileType.FILE);
}
private byte[] getFileContent(String path) {
return gitSyncService.getFileContent(REPO_KEY, path);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\dashboard\DashboardSyncService.java
| 2
|
请完成以下Java代码
|
public void handleEvent(@NonNull final PPOrderRequestedEvent event)
{
createProductionOrder(event);
}
/**
* Creates a production order. Note that it does not fire an event, because production orders can be created and changed for many reasons,<br>
* and therefore we leave the event-firing to a model interceptor.
*/
@VisibleForTesting
I_PP_Order createProductionOrder(@NonNull final PPOrderRequestedEvent ppOrderRequestedEvent)
{
final PPOrder ppOrder = ppOrderRequestedEvent.getPpOrder();
final PPOrderData ppOrderData = ppOrder.getPpOrderData();
final Instant dateOrdered = ppOrderRequestedEvent.getDateOrdered();
final ProductId productId = ProductId.ofRepoId(ppOrderData.getProductDescriptor().getProductId());
final I_C_UOM uom = productBL.getStockUOM(productId);
final Quantity qtyRequired = Quantity.of(ppOrderData.getQtyRequired(), uom);
return ppOrderService.createOrder(PPOrderCreateRequest.builder()
.clientAndOrgId(ppOrderData.getClientAndOrgId())
|
.productPlanningId(ProductPlanningId.ofRepoIdOrNull(ppOrderData.getProductPlanningId()))
.materialDispoGroupId(ppOrderData.getMaterialDispoGroupId())
.plantId(ppOrderData.getPlantId())
.workstationId(ppOrderData.getWorkstationId())
.warehouseId(ppOrderData.getWarehouseId())
//
.productId(productId)
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNone(ppOrderData.getProductDescriptor().getAttributeSetInstanceId()))
.qtyRequired(qtyRequired)
//
.dateOrdered(dateOrdered)
.datePromised(ppOrderData.getDatePromised())
.dateStartSchedule(ppOrderData.getDateStartSchedule())
//
.shipmentScheduleId(ShipmentScheduleId.ofRepoIdOrNull(ppOrderData.getShipmentScheduleIdAsRepoId()))
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(ppOrderData.getOrderLineIdAsRepoId()))
//
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\event\PPOrderRequestedEventHandler.java
| 1
|
请完成以下Java代码
|
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getExecutionId() {
return executionId;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean iswithException() {
return withJobException;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<ProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
/**
* Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property.
*/
public String getParentId() {
return null;
}
public boolean isOnlyChildExecutions() {
return onlyChildExecutions;
}
public boolean isOnlyProcessInstanceExecutions() {
return onlyProcessInstanceExecutions;
}
|
public boolean isOnlySubProcessExecutions() {
return onlySubProcessExecutions;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public int getC_Printing_Queue_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Printing_Queue_ID);
}
@Override
public void setDeliveryDate (final @Nullable java.sql.Timestamp DeliveryDate)
{
set_Value (COLUMNNAME_DeliveryDate, DeliveryDate);
}
@Override
public java.sql.Timestamp getDeliveryDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DeliveryDate);
}
@Override
public void setIsDifferentInvoicingPartner (final boolean IsDifferentInvoicingPartner)
{
throw new IllegalArgumentException ("IsDifferentInvoicingPartner is virtual column"); }
@Override
public boolean isDifferentInvoicingPartner()
{
return get_ValueAsBoolean(COLUMNNAME_IsDifferentInvoicingPartner);
}
@Override
public void setIsForeignCustomer (final boolean IsForeignCustomer)
{
throw new IllegalArgumentException ("IsForeignCustomer is virtual column"); }
@Override
public boolean isForeignCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_IsForeignCustomer);
}
@Override
public void setIsPrintoutForOtherUser (final boolean IsPrintoutForOtherUser)
{
set_Value (COLUMNNAME_IsPrintoutForOtherUser, IsPrintoutForOtherUser);
}
@Override
public boolean isPrintoutForOtherUser()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrintoutForOtherUser);
}
/**
* ItemName AD_Reference_ID=540735
* Reference name: ItemName
*/
public static final int ITEMNAME_AD_Reference_ID=540735;
/** Rechnung = Rechnung */
public static final String ITEMNAME_Rechnung = "Rechnung";
/** Mahnung = Mahnung */
public static final String ITEMNAME_Mahnung = "Mahnung";
/** Mitgliedsausweis = Mitgliedsausweis */
public static final String ITEMNAME_Mitgliedsausweis = "Mitgliedsausweis";
/** Brief = Brief */
public static final String ITEMNAME_Brief = "Brief";
/** Sofort-Druck PDF = Sofort-Druck PDF */
public static final String ITEMNAME_Sofort_DruckPDF = "Sofort-Druck PDF";
/** PDF = PDF */
public static final String ITEMNAME_PDF = "PDF";
/** Versand/Wareneingang = Versand/Wareneingang */
public static final String ITEMNAME_VersandWareneingang = "Versand/Wareneingang";
@Override
public void setItemName (final @Nullable java.lang.String ItemName)
{
|
set_Value (COLUMNNAME_ItemName, ItemName);
}
@Override
public java.lang.String getItemName()
{
return get_ValueAsString(COLUMNNAME_ItemName);
}
@Override
public void setPrintingQueueAggregationKey (final @Nullable java.lang.String PrintingQueueAggregationKey)
{
set_Value (COLUMNNAME_PrintingQueueAggregationKey, PrintingQueueAggregationKey);
}
@Override
public java.lang.String getPrintingQueueAggregationKey()
{
return get_ValueAsString(COLUMNNAME_PrintingQueueAggregationKey);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue.java
| 1
|
请完成以下Java代码
|
public void closing(CommandContext commandContext) {}
@Override
public void afterSessionsFlush(CommandContext commandContext) {}
@Override
public void closed(CommandContext context) {
if (context.getEventDispatcher().isEnabled()) {
context
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_EXECUTION_SUCCESS, job));
}
}
@Override
public void closeFailure(CommandContext commandContext) {
if (commandContext.getEventDispatcher().isEnabled()) {
commandContext
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createEntityExceptionEvent(
ActivitiEventType.JOB_EXECUTION_FAILURE,
job,
|
commandContext.getException()
)
);
}
CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), commandContext.getException());
log.trace(
"Using FailedJobCommandFactory '" +
failedJobCommandFactory.getClass() +
"' and command of type '" +
cmd.getClass() +
"'"
);
commandExecutor.execute(commandConfig, cmd);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\jobexecutor\FailedJobListener.java
| 1
|
请完成以下Java代码
|
public String getTaskHadCandidateUser() {
return taskHadCandidateUser;
}
public String[] getTaskDefinitionKeys() {
return taskDefinitionKeys;
}
public List<TaskQueryVariableValue> getVariables() {
return variables;
}
public Boolean getVariableNamesIgnoreCase() {
return variableNamesIgnoreCase;
}
public Boolean getVariableValuesIgnoreCase() {
return variableValuesIgnoreCase;
}
public String getTaskOwnerLike() {
return taskOwnerLike;
}
public String getTaskOwner() {
return taskOwner;
}
public Integer getTaskPriority() {
return taskPriority;
}
public String getTaskParentTaskId() {
return taskParentTaskId;
}
public String[] getTenantIds() {
return tenantIds;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public Date getFinishedAfter() {
return finishedAfter;
}
public Date getFinishedBefore() {
return finishedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
|
public List<HistoricTaskInstanceQueryImpl> getQueries() {
return queries;
}
public boolean isOrQueryActive() {
return isOrQueryActive;
}
public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) {
orQuery.isOrQueryActive = true;
this.queries.add(orQuery);
}
public void setOrQueryActive() {
isOrQueryActive = true;
}
@Override
public HistoricTaskInstanceQuery or() {
if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public HistoricTaskInstanceQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public class X_M_HU_QRCode extends org.compiere.model.PO implements I_M_HU_QRCode, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -2052191480L;
/** Standard Constructor */
public X_M_HU_QRCode (final Properties ctx, final int M_HU_QRCode_ID, @Nullable final String trxName)
{
super (ctx, M_HU_QRCode_ID, trxName);
}
/** Load Constructor */
public X_M_HU_QRCode (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setattributes (final String attributes)
{
set_ValueNoCheck (COLUMNNAME_attributes, attributes);
}
@Override
public String getattributes()
{
return get_ValueAsString(COLUMNNAME_attributes);
}
@Override
public void setDisplayableQRCode (final String DisplayableQRCode)
{
set_Value (COLUMNNAME_DisplayableQRCode, DisplayableQRCode);
}
@Override
public String getDisplayableQRCode()
{
return get_ValueAsString(COLUMNNAME_DisplayableQRCode);
}
@Override
public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID)
{
if (M_HU_QRCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID);
|
}
@Override
public int getM_HU_QRCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID);
}
@Override
public void setRenderedQRCode (final String RenderedQRCode)
{
set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode);
}
@Override
public String getRenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_RenderedQRCode);
}
@Override
public void setUniqueId (final String UniqueId)
{
set_ValueNoCheck (COLUMNNAME_UniqueId, UniqueId);
}
@Override
public String getUniqueId()
{
return get_ValueAsString(COLUMNNAME_UniqueId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode.java
| 1
|
请完成以下Java代码
|
public static void listCollectionNamesSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
boolean collectionExists = database.listCollectionNames()
.into(new ArrayList<String>())
.contains(testCollectionName);
System.out.println("collectionExists:- " + collectionExists);
}
public static void countSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
System.out.println(collection.countDocuments());
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
|
//
// Check the db existence using DB class's method
//
collectionExistsSolution();
//
// Check the db existence using the createCollection method of MongoDatabase class
//
createCollectionSolution();
//
// Check the db existence using the listCollectionNames method of MongoDatabase class
//
listCollectionNamesSolution();
//
// Check the db existence using the count method of MongoDatabase class
//
countSolution();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\collectionexistence\CollectionExistence.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public byte[] getModelBytes(@ApiParam(name = "modelId") @PathVariable String modelId, HttpServletResponse response) {
Model model = getModelFromRequest(modelId);
byte[] editorSource = repositoryService.getModelEditorSource(model.getId());
if (editorSource == null) {
throw new FlowableObjectNotFoundException("Model with id '" + modelId + "' does not have source available.", String.class);
}
response.setContentType("application/octet-stream");
return editorSource;
}
@ApiOperation(value = "Set the editor source for a model", tags = { "Models" }, consumes = "multipart/form-data",
notes = "Response body contains the model’s raw editor source. The response’s content-type is set to application/octet-stream, regardless of the content of the source.",
code = 204)
@ApiImplicitParams({
@ApiImplicitParam(name = "file", dataType = "file", paramType = "form", required = true)
})
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the model was found and the source has been updated."),
@ApiResponse(code = 404, message = "Indicates the requested model was not found.")
})
@PutMapping(value = "/repository/models/{modelId}/source", consumes = "multipart/form-data")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void setModelSource(@ApiParam(name = "modelId") @PathVariable String modelId, HttpServletRequest request) {
Model model = getModelFromRequest(modelId);
if (!(request instanceof MultipartHttpServletRequest)) {
throw new FlowableIllegalArgumentException("Multipart request is required");
}
|
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
if (multipartRequest.getFileMap().size() == 0) {
throw new FlowableIllegalArgumentException("Multipart request with file content is required");
}
MultipartFile file = multipartRequest.getFileMap().values().iterator().next();
try {
repositoryService.addModelEditorSource(model.getId(), file.getBytes());
} catch (Exception e) {
throw new FlowableException("Error adding model editor source extra", e);
}
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelSourceResource.java
| 2
|
请完成以下Java代码
|
public String getTableName()
{
return recordRef.getTableName();
}
public DocumentId getDocumentId()
{
return DocumentId.of(recordRef.getRecord_ID());
}
public Collection<IncludedDocumentToInvalidate> getIncludedDocuments()
{
return includedDocumentsByTableName.values();
}
|
DocumentToInvalidate combine(@NonNull final DocumentToInvalidate other)
{
Check.assumeEquals(this.recordRef, other.recordRef, "recordRef");
this.invalidateDocument = this.invalidateDocument || other.invalidateDocument;
for (final Map.Entry<String, IncludedDocumentToInvalidate> e : other.includedDocumentsByTableName.entrySet())
{
this.includedDocumentsByTableName.merge(
e.getKey(),
e.getValue(),
(item1, item2) -> item1.combine(item2));
}
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentToInvalidate.java
| 1
|
请完成以下Java代码
|
public JsonGetTransactionResponse getTransactionById(@NonNull final SumUpClientTransactionId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "transactions")
.queryParam("client_transaction_id", id.getAsString())
.toUriString();
final String json = httpCall(uri, HttpMethod.GET, null, String.class);
try
{
return jsonObjectMapper.readValue(json, JsonGetTransactionResponse.class)
.withJson(json);
}
catch (JsonProcessingException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
/**
* @implSpec <a href="https://developer.sumup.com/api/transactions/get">spec</a>
*/
public JsonGetTransactionResponse getTransactionById(@NonNull final SumUpTransactionExternalId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "transactions")
.queryParam("id", id.getAsString())
.toUriString();
|
final String json = httpCall(uri, HttpMethod.GET, null, String.class);
try
{
return jsonObjectMapper.readValue(json, JsonGetTransactionResponse.class)
.withJson(json);
}
catch (JsonProcessingException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
public void refundTransaction(@NonNull final SumUpTransactionExternalId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "refund", id.getAsString())
.toUriString();
httpCall(uri, HttpMethod.POST, null, null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\SumUpClient.java
| 1
|
请完成以下Java代码
|
public void setType(String type) {
this.type = type;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
/**
* @deprecated since 7.4 A new instance of a sentry
* does not reference the source case execution id anymore.
*/
public abstract String getSourceCaseExecutionId();
/**
* @deprecated since 7.4 A new instance of a sentry
* does not reference the source case execution id anymore.
*/
public abstract CmmnExecution getSourceCaseExecution();
/**
* @deprecated since 7.4 A new instance of a sentry
* does not reference the source case execution id anymore.
*/
public abstract void setSourceCaseExecution(CmmnExecution sourceCaseExecution);
public String getStandardEvent() {
return standardEvent;
}
public void setStandardEvent(String standardEvent) {
this.standardEvent = standardEvent;
}
public boolean isSatisfied() {
|
return satisfied;
}
public void setSatisfied(boolean satisfied) {
this.satisfied = satisfied;
}
public String getVariableEvent() {
return variableEvent;
}
public void setVariableEvent(String variableEvent) {
this.variableEvent = variableEvent;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CmmnSentryPart.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isReverseCharge(final TaxId taxId)
{
final Tax tax = taxBL.getTaxById(taxId);
return tax.isReverseCharge();
}
@NonNull
public Account getTaxAccount(
@NonNull final TaxId taxId,
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final PostingSign postingSign)
{
final TaxAcctType taxAcctType = postingSign.isDebit()
? TaxAcctType.TaxCredit
: TaxAcctType.TaxDue;
return taxAccountsRepository.getAccounts(taxId, acctSchemaId)
.getAccount(taxAcctType)
.orElseThrow(() -> new AdempiereException("No account found for " + taxId + ", " + acctSchemaId + ", " + taxAcctType));
|
}
public Money calculateTaxAmt(
@NonNull final Money lineAmt,
@NonNull final TaxId taxId,
final boolean isTaxIncluded)
{
//
final CurrencyId currencyId = lineAmt.getCurrencyId();
final CurrencyPrecision precision = moneyService.getStdPrecision(currencyId);
final Tax tax = taxBL.getTaxById(taxId);
final CalculateTaxResult taxResult = tax.calculateTax(lineAmt.toBigDecimal(), isTaxIncluded, precision.toInt());
return tax.isReverseCharge()
? Money.of(taxResult.getReverseChargeAmt(), currencyId)
: Money.of(taxResult.getTaxAmount(), currencyId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalTaxProvider.java
| 2
|
请完成以下Java代码
|
public class ManagerRole {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
private Integer id;
/**
* 管理用户ID
*/
private Integer managerId;
/**
* 角色ID
*/
private Integer roleId;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新时间
*/
private Date updatedTime;
/**
* 获取 主键ID.
*
* @return 主键ID.
*/
public Integer getId() {
return id;
}
/**
* 设置 主键ID.
*
* @param id 主键ID.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取 管理用户ID.
*
* @return 管理用户ID.
*/
public Integer getManagerId() {
return managerId;
}
/**
* 设置 管理用户ID.
*
* @param managerId 管理用户ID.
*/
public void setManagerId(Integer managerId) {
this.managerId = managerId;
}
/**
* 获取 角色ID.
*
* @return 角色ID.
*/
public Integer getRoleId() {
return roleId;
}
/**
* 设置 角色ID.
*
* @param roleId 角色ID.
*/
public void setRoleId(Integer roleId) {
|
this.roleId = roleId;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
}
|
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\ManagerRole.java
| 1
|
请完成以下Java代码
|
public static DistributionFacetId ofWarehouseFromId(@NonNull WarehouseId warehouseId)
{
return ofRepoId(DistributionFacetGroupType.WAREHOUSE_FROM, warehouseId);
}
public static DistributionFacetId ofWarehouseToId(@NonNull WarehouseId warehouseId)
{
return ofRepoId(DistributionFacetGroupType.WAREHOUSE_TO, warehouseId);
}
public static DistributionFacetId ofSalesOrderId(@NonNull OrderId salesOrderId)
{
return ofRepoId(DistributionFacetGroupType.SALES_ORDER, salesOrderId);
}
public static DistributionFacetId ofManufacturingOrderId(@NonNull PPOrderId manufacturingOrderId)
{
return ofRepoId(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, manufacturingOrderId);
}
public static DistributionFacetId ofDatePromised(@NonNull LocalDate datePromised)
{
return ofLocalDate(DistributionFacetGroupType.DATE_PROMISED, datePromised);
}
public static DistributionFacetId ofProductId(@NonNull ProductId productId)
{
return ofRepoId(DistributionFacetGroupType.PRODUCT, productId);
}
private static DistributionFacetId ofRepoId(@NonNull DistributionFacetGroupType groupType, @NonNull RepoIdAware id)
{
final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofId(groupType.toWorkflowLaunchersFacetGroupId(), id);
return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId);
}
|
@SuppressWarnings("SameParameterValue")
private static DistributionFacetId ofLocalDate(@NonNull DistributionFacetGroupType groupType, @NonNull LocalDate localDate)
{
final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofLocalDate(groupType.toWorkflowLaunchersFacetGroupId(), localDate);
return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId);
}
public static DistributionFacetId ofQuantity(@NonNull Quantity qty)
{
return ofWorkflowLaunchersFacetId(
WorkflowLaunchersFacetId.ofQuantity(
DistributionFacetGroupType.QUANTITY.toWorkflowLaunchersFacetGroupId(),
qty.toBigDecimal(),
qty.getUomId()
)
);
}
public static DistributionFacetId ofPlantId(@NonNull final ResourceId plantId)
{
return ofRepoId(DistributionFacetGroupType.PLANT_RESOURCE_ID, plantId);
}
private static Quantity getAsQuantity(final @NonNull WorkflowLaunchersFacetId workflowLaunchersFacetId)
{
final ImmutablePair<BigDecimal, Integer> parts = workflowLaunchersFacetId.getAsQuantity();
return Quantitys.of(parts.getLeft(), UomId.ofRepoId(parts.getRight()));
}
public WorkflowLaunchersFacetId toWorkflowLaunchersFacetId() {return workflowLaunchersFacetId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetId.java
| 1
|
请完成以下Java代码
|
public Esr5Type getEsr5() {
return esr5;
}
/**
* Sets the value of the esr5 property.
*
* @param value
* allowed object is
* {@link Esr5Type }
*
*/
public void setEsr5(Esr5Type value) {
this.esr5 = value;
}
/**
* Gets the value of the esr9 property.
*
* @return
* possible object is
* {@link Esr9Type }
*
*/
public Esr9Type getEsr9() {
return esr9;
}
/**
* Sets the value of the esr9 property.
*
* @param value
* allowed object is
* {@link Esr9Type }
*
*/
public void setEsr9(Esr9Type value) {
this.esr9 = value;
}
|
/**
* Gets the value of the esrRed property.
*
* @return
* possible object is
* {@link EsrRedType }
*
*/
public EsrRedType getEsrRed() {
return esrRed;
}
/**
* Sets the value of the esrRed property.
*
* @param value
* allowed object is
* {@link EsrRedType }
*
*/
public void setEsrRed(EsrRedType value) {
this.esrRed = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ReimbursementType.java
| 1
|
请完成以下Java代码
|
public final String getName()
{
return m_name;
}
@JsonProperty("description")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public final String getDescription()
{
return m_description;
}
/**
* Returns Key or Value as String
*
* @return String or null
*/
public abstract String getID();
/**
* Comparator Interface (based on toString value)
*
* @param o1 Object 1
* @param o2 Object 2
* @return compareTo value
*/
@Override
public final int compare(Object o1, Object o2)
{
String s1 = o1 == null ? "" : o1.toString();
String s2 = o2 == null ? "" : o2.toString();
return s1.compareTo(s2); // sort order ??
} // compare
/**
* Comparator Interface (based on toString value)
*
* @param o1 Object 1
* @param o2 Object 2
* @return compareTo value
*/
public final int compare(NamePair o1, NamePair o2)
{
String s1 = o1 == null ? "" : o1.toString();
String s2 = o2 == null ? "" : o2.toString();
return s1.compareTo(s2); // sort order ??
} // compare
/**
* Comparable Interface (based on toString value)
*
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
|
@Override
public final int compareTo(Object o)
{
return compare(this, o);
} // compareTo
/**
* Comparable Interface (based on toString value)
*
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
public final int compareTo(NamePair o)
{
return compare(this, o);
} // compareTo
/**
* To String - returns name
*/
@Override
public String toString()
{
return m_name;
}
/**
* To String - detail
*
* @return String in format ID=Name
*/
public final String toStringX()
{
StringBuilder sb = new StringBuilder(getID());
sb.append("=").append(m_name);
return sb.toString();
} // toStringX
} // NamePair
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\NamePair.java
| 1
|
请完成以下Java代码
|
protected VirtualFile getVirtualFileForUrl(final URL url) {
try {
return VFS.getChild(url.toURI());
}
catch (URISyntaxException e) {
throw LOG.exceptionWhileGettingVirtualFolder(url, e);
}
}
protected void scanRoot(VirtualFile processArchiveRoot, final String[] additionalResourceSuffixes, Map<String, byte[]> resources) {
try {
List<VirtualFile> processes = processArchiveRoot.getChildrenRecursively(new VirtualFileFilter() {
public boolean accepts(VirtualFile file) {
return file.isFile() && ProcessApplicationScanningUtil.isDeployable(file.getName(), additionalResourceSuffixes);
}
});
for (final VirtualFile process : processes) {
addResource(process, processArchiveRoot, resources);
// find diagram(s) for process
List<VirtualFile> diagrams = process.getParent().getChildren(new VirtualFileFilter() {
public boolean accepts(VirtualFile file) {
return ProcessApplicationScanningUtil.isDiagram(file.getName(), process.getName());
}
});
for (VirtualFile diagram : diagrams) {
addResource(diagram, processArchiveRoot, resources);
}
}
|
}
catch (IOException e) {
LOG.cannotScanVfsRoot(processArchiveRoot, e);
}
}
private void addResource(VirtualFile virtualFile, VirtualFile processArchiveRoot, Map<String, byte[]> resources) {
String resourceName = virtualFile.getPathNameRelativeTo(processArchiveRoot);
try {
InputStream inputStream = virtualFile.openStream();
byte[] bytes = IoUtil.readInputStream(inputStream, resourceName);
IoUtil.closeSilently(inputStream);
resources.put(resourceName, bytes);
}
catch (IOException e) {
LOG.cannotReadInputStreamForFile(resourceName, processArchiveRoot, e);
}
}
protected Enumeration<URL> loadClasspathResourceRoots(final ClassLoader classLoader, String strippedPaResourceRootPath) {
try {
return classLoader.getResources(strippedPaResourceRootPath);
}
catch (IOException e) {
throw LOG.exceptionWhileLoadingCpRoots(strippedPaResourceRootPath, classLoader, e);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\VfsProcessApplicationScanner.java
| 1
|
请完成以下Java代码
|
protected void moveExternalWorkerJobToExecutableJob(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) {
jobServiceConfiguration.getJobManager().moveExternalWorkerJobToExecutableJob(externalWorkerJob);
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
processEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.deleteIdentityLinksByScopeIdAndType(externalWorkerJob.getCorrelationId(), ScopeTypes.EXTERNAL_WORKER);
}
protected ExternalWorkerJobEntity resolveJob(CommandContext commandContext) {
if (StringUtils.isEmpty(externalJobId)) {
throw new FlowableIllegalArgumentException("externalJobId must not be empty");
}
if (StringUtils.isEmpty(workerId)) {
throw new FlowableIllegalArgumentException("workerId must not be empty");
}
|
ExternalWorkerJobEntityManager externalWorkerJobEntityManager = jobServiceConfiguration.getExternalWorkerJobEntityManager();
ExternalWorkerJobEntity job = externalWorkerJobEntityManager.findById(externalJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No External Worker job found for id: " + externalJobId, ExternalWorkerJobEntity.class);
}
if (!Objects.equals(workerId, job.getLockOwner())) {
throw new FlowableIllegalArgumentException(workerId + " does not hold a lock on the requested job");
}
return job;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\AbstractExternalWorkerJobCmd.java
| 1
|
请完成以下Java代码
|
public String getColumnSQL()
{
final boolean withAS = false;
return gridField.getColumnSQL(withAS);
}
public int getDisplayType()
{
return gridField.getDisplayType();
}
public ReferenceId getAD_Reference_Value_ID()
{
return gridField.getAD_Reference_Value_ID();
}
public boolean isLookup()
{
return gridField.isLookup();
}
public Lookup getLookup()
{
return gridField.getLookup();
}
public boolean isVirtualColumn()
{
return gridField.isVirtualColumn();
}
/**
* Creates the editor component
*
* @param tableEditor true if table editor
* @return editor or null if editor could not be created
*/
public VEditor createEditor(final boolean tableEditor)
{
// Reset lookup state
// background: the lookup implements MutableComboBoxModel which stores the selected item.
// If this lookup was previously used somewhere, the selected item is retained from there and we will get unexpected results.
final Lookup lookup = gridField.getLookup();
if (lookup != null)
{
lookup.setSelectedItem(null);
}
//
// Create a new editor
VEditor editor = swingEditorFactory.getEditor(gridField, tableEditor);
if (editor == null && tableEditor)
{
editor = new VString();
}
//
// Configure the new editor
if (editor != null)
{
editor.setMandatory(false);
editor.setReadWrite(true);
}
return editor;
}
public CLabel createEditorLabel()
{
return swingEditorFactory.getLabel(gridField);
}
|
@Override
public Object convertValueToFieldType(final Object valueObj)
{
return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName());
}
@Override
public String getValueDisplay(final Object value)
{
String infoDisplay = value == null ? "" : value.toString();
if (isLookup())
{
final Lookup lookup = getLookup();
if (lookup != null)
{
infoDisplay = lookup.getDisplay(value);
}
}
else if (getDisplayType() == DisplayType.YesNo)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay);
}
return infoDisplay;
}
@Override
public boolean matchesColumnName(final String columnName)
{
if (columnName == null || columnName.isEmpty())
{
return false;
}
if (columnName.equals(getColumnName()))
{
return true;
}
if (gridField.isVirtualColumn())
{
if (columnName.equals(gridField.getColumnSQL(false)))
{
return true;
}
if (columnName.equals(gridField.getColumnSQL(true)))
{
return true;
}
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
| 1
|
请完成以下Java代码
|
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams) {
|
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location.equals("query")) {
queryParams.add(paramName, value);
} else if (location.equals("header")) {
headerParams.add(paramName, value);
}
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\invoker\auth\ApiKeyAuth.java
| 1
|
请完成以下Java代码
|
S getSession() {
return this.session;
}
@Override
public long getCreationTime() {
checkState();
return this.session.getCreationTime().toEpochMilli();
}
@Override
public String getId() {
return this.session.getId();
}
@Override
public long getLastAccessedTime() {
checkState();
return this.session.getLastAccessedTime().toEpochMilli();
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public void setMaxInactiveInterval(int interval) {
this.session.setMaxInactiveInterval(Duration.ofSeconds(interval));
}
@Override
public int getMaxInactiveInterval() {
return (int) this.session.getMaxInactiveInterval().getSeconds();
}
@Override
public Object getAttribute(String name) {
checkState();
return this.session.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
checkState();
return Collections.enumeration(this.session.getAttributeNames());
}
@Override
public void setAttribute(String name, Object value) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.setAttribute(name, value);
if (value != oldValue) {
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
if (value instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
|
}
}
}
@Override
public void removeAttribute(String name) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.removeAttribute(name);
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
@Override
public void invalidate() {
checkState();
this.invalidated = true;
}
@Override
public boolean isNew() {
checkState();
return !this.old;
}
void markNotNew() {
this.old = true;
}
private void checkState() {
if (this.invalidated) {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java
| 1
|
请完成以下Java代码
|
public class NGramDictionaryMaker
{
BinTrie<Integer> trie;
/**
* 转移矩阵
*/
TMDictionaryMaker tmDictionaryMaker;
public NGramDictionaryMaker()
{
trie = new BinTrie<Integer>();
tmDictionaryMaker = new TMDictionaryMaker();
}
public void addPair(IWord first, IWord second)
{
String combine = first.getValue() + "@" + second.getValue();
Integer frequency = trie.get(combine);
if (frequency == null) frequency = 0;
trie.put(combine, frequency + 1);
// 同时还要统计标签的转移情况
tmDictionaryMaker.addPair(first.getLabel(), second.getLabel());
}
/**
* 保存NGram词典和转移矩阵
*
* @param path
* @return
*/
public boolean saveTxtTo(String path)
{
saveNGramToTxt(path + ".ngram.txt");
saveTransformMatrixToTxt(path + ".tr.txt");
return true;
}
/**
* 保存NGram词典
*
* @param path
* @return
*/
public boolean saveNGramToTxt(String path)
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
for (Map.Entry<String, Integer> entry : trie.entrySet())
|
{
bw.write(entry.getKey() + " " + entry.getValue());
bw.newLine();
}
bw.close();
}
catch (Exception e)
{
Predefine.logger.warning("在保存NGram词典到" + path + "时发生异常" + e);
return false;
}
return true;
}
/**
* 保存转移矩阵
*
* @param path
* @return
*/
public boolean saveTransformMatrixToTxt(String path)
{
return tmDictionaryMaker.saveTxtTo(path);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\NGramDictionaryMaker.java
| 1
|
请完成以下Java代码
|
public void setPrice (BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Price.
@return Price
*/
public BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Product.
@param Product Product */
public void setProduct (String Product)
{
set_Value (COLUMNNAME_Product, Product);
}
/** Get Product.
@return Product */
public String getProduct ()
{
return (String)get_Value(COLUMNNAME_Product);
}
/** 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;
}
public I_W_Basket getW_Basket() throws RuntimeException
{
return (I_W_Basket)MTable.get(getCtx(), I_W_Basket.Table_Name)
.getPO(getW_Basket_ID(), get_TrxName()); }
/** Set W_Basket_ID.
@param W_Basket_ID
Web Basket
*/
public void setW_Basket_ID (int W_Basket_ID)
{
if (W_Basket_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID));
}
/** Get W_Basket_ID.
@return Web Basket
*/
public int getW_Basket_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Basket Line.
@param W_BasketLine_ID
Web Basket Line
*/
public void setW_BasketLine_ID (int W_BasketLine_ID)
{
if (W_BasketLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, Integer.valueOf(W_BasketLine_ID));
}
/** Get Basket Line.
@return Web Basket Line
*/
public int getW_BasketLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_BasketLine_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_W_BasketLine.java
| 1
|
请完成以下Java代码
|
public class LogGrpcInterceptor implements ClientInterceptor {
private static final Logger log = LoggerFactory.getLogger(LogGrpcInterceptor.class);
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method,
final CallOptions callOptions,
final Channel next) {
log.info("Received call to {}", method.getFullMethodName());
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void sendMessage(ReqT message) {
log.debug("Request message: {}", message);
super.sendMessage(message);
}
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
super.start(
new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onMessage(RespT message) {
log.debug("Response message: {}", message);
|
super.onMessage(message);
}
@Override
public void onHeaders(Metadata headers) {
log.debug("gRPC headers: {}", headers);
super.onHeaders(headers);
}
@Override
public void onClose(Status status, Metadata trailers) {
log.info("Interaction ends with status: {}", status);
log.info("Trailers: {}", trailers);
super.onClose(status, trailers);
}
}, headers);
}
};
}
}
|
repos\grpc-spring-master\examples\cloud-grpc-client\src\main\java\net\devh\boot\grpc\examples\cloud\client\LogGrpcInterceptor.java
| 1
|
请完成以下Java代码
|
public ImportedValues getImportValues() {
return importedValuesChild.getChild(this);
}
public void setImportValues(ImportedValues importedValues) {
importedValuesChild.setChild(this, importedValues);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(LiteralExpression.class, DMN_ELEMENT_LITERAL_EXPRESSION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<LiteralExpression>() {
public LiteralExpression newInstance(ModelTypeInstanceContext instanceContext) {
return new LiteralExpressionImpl(instanceContext);
}
|
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
importedValuesChild = sequenceBuilder.element(ImportedValues.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\LiteralExpressionImpl.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: demo-producer-application
cloud:
# Spring Cloud Stream 配置项,对应 BindingServiceProperties 类
stream:
# Binder 配置项,对应 BinderProperties Map
# binders:
# Binding 配置项,对应 BindingProperties Map
bindings:
demo01-output:
destination: DEMO-TOPIC-01 # 目的地。这里使用 Kafka Topic
content-type: application/json # 内容格式。这里使用 JSON
# Spring Cloud Stream Kafka 配置项
kafka:
# Kafka Binder 配置项,对应 KafkaBinderConfigurationProperties 类
binder:
brokers: 127.0.0.1:9092 # 指定 Kafka Broker 地址,可以设置多个,以逗号分隔
transaction:
transaction-id-prefix: demo. # 事务编号前缀
producer:
configuration:
retries: 1 # 发送失败时,重试发送的次数
|
acks: all # 0-不应答。1-leader 应答。all-所有 leader 和 follower 应答。
# Kafka 自定义 Binding 配置项,对应 KafkaBindingProperties Map
bindings:
demo01-output:
# Kafka Producer 配置项,对应 KafkaProducerProperties 类
producer:
sync: true # 是否同步发送消息,默认为 false 异步。
server:
port: 18080
|
repos\SpringBoot-Labs-master\labx-11-spring-cloud-stream-kafka\labx-11-sc-stream-kafka-producer-transaction\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setField(GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField()
{
return m_mField;
}
/**
* Set Enabled
*
* @param enabled enabled
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
m_text.setEnabled(enabled);
m_button.setReadWrite(enabled && m_readWrite);
} // setEnabled
@Override
public void addActionListener(ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
@Override
public void setBackground(final Color bg)
{
m_text.setBackground(bg);
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
|
}
@Override
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
}
public int getCaretPosition()
{
return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
DbSqlSession dbSqlSession = getDbSqlSession();
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeId", scopeId);
parameters.put("scopeType", scopeType);
if (ScopeTypes.CMMN.equals(scopeType) && isEntityInserted(dbSqlSession, "caseInstance", scopeId)) {
deleteCachedEntities(dbSqlSession, identityLinksByScopeIdAndTypeMatcher, parameters);
} else {
bulkDelete("deleteIdentityLinksByScopeIdAndScopeType", identityLinksByScopeIdAndTypeMatcher, parameters);
}
}
@Override
public void deleteIdentityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeDefinitionId", scopeDefinitionId);
|
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("deleteIdentityLinksByScopeDefinitionIdAndScopeType", parameters, IdentityLinkEntityImpl.class);
}
@Override
public void bulkDeleteIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("scopeIds", createSafeInValuesList(scopeIds));
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("bulkDeleteIdentityLinksForScopeIdsAndScopeType", parameters, IdentityLinkEntityImpl.class);
}
@Override
protected IdGenerator getIdGenerator() {
return identityLinkServiceConfiguration.getIdGenerator();
}
}
|
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\data\impl\MybatisIdentityLinkDataManager.java
| 2
|
请完成以下Java代码
|
public <T> T getParameterValueAs(@NonNull final String parameterName)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
@SuppressWarnings("unchecked") final T value = (T)param.getValue();
return value;
}
//
//
//
//
//
public static final class DocumentFilterBuilder
{
public DocumentFilterBuilder setFilterId(final String filterId)
{
return filterId(filterId);
}
public DocumentFilterBuilder setCaption(@NonNull final ITranslatableString caption)
{
return caption(caption);
}
public DocumentFilterBuilder setCaption(@NonNull final String caption)
{
return caption(TranslatableStrings.constant(caption));
|
}
public DocumentFilterBuilder setFacetFilter(final boolean facetFilter)
{
return facetFilter(facetFilter);
}
public boolean hasParameters()
{
return !Check.isEmpty(parameters)
|| !Check.isEmpty(internalParameterNames);
}
public DocumentFilterBuilder setParameters(@NonNull final List<DocumentFilterParam> parameters)
{
return parameters(parameters);
}
public DocumentFilterBuilder addParameter(@NonNull final DocumentFilterParam parameter)
{
return parameter(parameter);
}
public DocumentFilterBuilder addInternalParameter(@NonNull final DocumentFilterParam parameter)
{
parameter(parameter);
internalParameterName(parameter.getFieldName());
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilter.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final String captionOverride)
{
return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride));
}
public ProcessPreconditionsResolution deriveWithCaptionOverride(@NonNull final ITranslatableString captionOverride)
{
return withCaptionMapper(new ProcessCaptionOverrideMapper(captionOverride));
}
@Value
private static class ProcessCaptionOverrideMapper implements ProcessCaptionMapper
{
@NonNull ITranslatableString captionOverride;
public ProcessCaptionOverrideMapper(@NonNull final ITranslatableString captionOverride)
{
this.captionOverride = captionOverride;
}
public ProcessCaptionOverrideMapper(@NonNull final String captionOverride)
{
this.captionOverride = TranslatableStrings.anyLanguage(captionOverride);
}
@Override
public ITranslatableString computeCaption(final ITranslatableString originalProcessCaption)
{
return captionOverride;
}
}
public ProcessPreconditionsResolution withCaptionMapper(@Nullable final ProcessCaptionMapper captionMapper)
{
return toBuilder().captionMapper(captionMapper).build();
}
/**
|
* Override default SortNo used with ordering related processes
*/
public ProcessPreconditionsResolution withSortNo(final int sortNo)
{
return !this.sortNo.isPresent() || this.sortNo.getAsInt() != sortNo
? toBuilder().sortNo(OptionalInt.of(sortNo)).build()
: this;
}
public @NonNull OptionalInt getSortNo() {return this.sortNo;}
public ProcessPreconditionsResolution and(final Supplier<ProcessPreconditionsResolution> resolutionSupplier)
{
if (isRejected())
{
return this;
}
return resolutionSupplier.get();
}
public void throwExceptionIfRejected()
{
if (isRejected())
{
throw new AdempiereException(getRejectReason());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessPreconditionsResolution.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: listener-demo
cloud:
# Consul
consul:
host: 127.0.0.1
port: 8500
server:
port: 18080 # 随机端口,方便启动多个消费者
management:
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配
|
置类
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
|
repos\SpringBoot-Labs-master\labx-29-spring-cloud-consul-bus\labx-29-sc-bus-consul-demo-listener-actuator\src\main\resources\application.yml
| 2
|
请完成以下Spring Boot application配置
|
spring.datasource.driver-class-name=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.datasource.url=jdbc-secretsmanager:mysql://database-1.cwhqvgjbpgfw.eu-central-1.rds.amazonaws.com:3306/test
spring.datasource.username=rds/credentials
#Overwriting application.properties
|
configuration back to default.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=true
spring.config.import=aws-secretsmanager:test/secret/
|
repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\resources\application-aws.properties
| 2
|
请完成以下Java代码
|
public class SetTaskVariablesCmd extends AbstractSetVariableCmd implements VariableInstanceLifecycleListener<VariableInstanceEntity> {
private static final long serialVersionUID = 1L;
protected boolean taskLocalVariablesUpdated = false;
public SetTaskVariablesCmd(String taskId, Map<String, ? extends Object> variables, boolean isLocal) {
super(taskId, variables, isLocal);
}
protected TaskEntity getEntity() {
ensureNotNull("taskId", entityId);
TaskEntity task = commandContext
.getTaskManager()
.findTaskById(entityId);
ensureNotNull("task " + entityId + " doesn't exist", "task", task);
checkSetTaskVariables(task);
task.addCustomLifecycleListener(this);
return task;
}
@Override
protected void onSuccess(AbstractVariableScope scope) {
TaskEntity task = (TaskEntity) scope;
if (taskLocalVariablesUpdated) {
task.triggerUpdateEvent();
}
task.removeCustomLifecycleListener(this);
super.onSuccess(scope);
}
@Override
protected ExecutionEntity getContextExecution() {
|
return getEntity().getExecution();
}
protected void logVariableOperation(AbstractVariableScope scope) {
TaskEntity task = (TaskEntity) scope;
commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), null, task.getId(),
PropertyChange.EMPTY_CHANGE);
}
protected void checkSetTaskVariables(TaskEntity task) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateTaskVariable(task);
}
}
protected void onLocalVariableChanged() {
taskLocalVariablesUpdated = true;
}
@Override
public void onCreate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
@Override
public void onDelete(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
@Override
public void onUpdate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetTaskVariablesCmd.java
| 1
|
请完成以下Java代码
|
public class PrintingClient
{
private final transient Logger log = Logger.getLogger(getClass().getName());
private Thread clientDaemonThread;
private PrintingClientDaemon clientDaemon;
private final ReentrantLock threadCtrlLock = new ReentrantLock();
/**
* NOTE: automatically start client thread.
*/
public PrintingClient()
{
this(true);
}
/**
*
* @param start start client thread
*/
public PrintingClient(final boolean start)
{
if (start)
{
start();
}
}
public void start()
{
threadCtrlLock.lock();
try
{
if (isStarted())
{
// already started, nothing to do
return;
}
clientDaemon = new PrintingClientDaemon();
final Thread thread = getCreateDaemonThread(clientDaemon);
thread.start();
log.config("Printing client daemon started: " + thread.getName());
}
finally
{
threadCtrlLock.unlock();
}
}
public void stop()
{
threadCtrlLock.lock();
try
{
if (clientDaemon != null)
{
clientDaemon.stop(); // make sure the demon will leave its endless while loop the next time it passes by
}
if (clientDaemonThread != null && clientDaemonThread.isAlive())
{
clientDaemonThread.interrupt(); // interrupt the thread in case it is sleeping or waiting
}
if (clientDaemonThread != null)
{
log.config("Printing client daemon '" + clientDaemonThread.getName() + "' already stopped: " + clientDaemonThread.isAlive());
|
}
clientDaemon = null;
clientDaemonThread = null;
}
finally
{
threadCtrlLock.unlock();
}
}
public void destroy()
{
stop();
}
public boolean isStarted()
{
return clientDaemonThread != null && clientDaemonThread.isAlive();
}
private Thread getCreateDaemonThread(final PrintingClientDaemon clientDaemon)
{
if (clientDaemonThread != null)
{
return clientDaemonThread;
}
clientDaemonThread = new Thread(clientDaemon, clientDaemon.getName());
clientDaemonThread.setDaemon(true);
return clientDaemonThread;
}
public Thread getDaemonThread()
{
return clientDaemonThread;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\PrintingClient.java
| 1
|
请完成以下Java代码
|
public class HibernateAnnotationUtil {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
/**
* Utility class
*/
private HibernateAnnotationUtil() {
}
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
private static SessionFactory buildSessionFactory() {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(dbSettings())
.build();
|
Metadata metadata = new MetadataSources(serviceRegistry)
.addAnnotatedClass(RuntimeConfiguration.class)
.buildMetadata();
return metadata.buildSessionFactory();
}
private static Map<String, Object> dbSettings() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");
dbSettings.put(Environment.DRIVER, "org.h2.Driver");
dbSettings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
dbSettings.put(Environment.SHOW_SQL, "true");
dbSettings.put(Environment.HBM2DDL_AUTO, "create");
return dbSettings;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\HibernateAnnotationUtil.java
| 1
|
请完成以下Java代码
|
public String[] getWhereClauses(final List<Object> params)
{
if (!checkbox.isEnabled() || !checkbox.isSelected())
{
return null;
}
if (record2productId.isEmpty())
{
return new String[] { "1=2" };
}
final String productColumnName = org.compiere.model.I_M_Product.Table_Name + "." + org.compiere.model.I_M_Product.COLUMNNAME_M_Product_ID;
final StringBuilder whereClause = new StringBuilder(productColumnName + " IN " + DB.buildSqlList(record2productId.values(), params));
if (gridConvertAfterLoadDelegate != null)
{
final String productComb = gridConvertAfterLoadDelegate.getProductCombinations();
if (productComb != null)
{
whereClause.append(productComb);
}
}
//
// 05135: We need just to display rows that have Qtys, but DON'T discard other filtering criterias
|
// return new String[] { WHERECLAUSE_CLEAR_PREVIOUS, whereClause, WHERECLAUSE_STOP};
return new String[] { whereClause.toString() };
}
@Override
public String getText()
{
return null;
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyController.java
| 1
|
请完成以下Java代码
|
public ActivityImpl getParentActivity() {
if (parent instanceof ActivityImpl) {
return (ActivityImpl) parent;
}
return null;
}
// restricted setters ///////////////////////////////////////////////////////
protected void setOutgoingTransitions(List<TransitionImpl> outgoingTransitions) {
this.outgoingTransitions = outgoingTransitions;
}
protected void setParent(ScopeImpl parent) {
this.parent = parent;
}
protected void setIncomingTransitions(List<TransitionImpl> incomingTransitions) {
this.incomingTransitions = incomingTransitions;
}
// getters and setters //////////////////////////////////////////////////////
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getOutgoingTransitions() {
return (List) outgoingTransitions;
}
public ActivityBehavior getActivityBehavior() {
return activityBehavior;
}
public void setActivityBehavior(ActivityBehavior activityBehavior) {
this.activityBehavior = activityBehavior;
}
@Override
public ScopeImpl getParent() {
return parent;
}
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getIncomingTransitions() {
return (List) incomingTransitions;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
@Override
public int getX() {
return x;
}
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
|
}
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean isAsync() {
return isAsync;
}
public void setAsync(boolean isAsync) {
this.isAsync = isAsync;
}
@Override
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public MessagesStats createMessagesStats(String key) {
StatsCounter totalCounter = createStatsCounter(key, TOTAL_MSGS);
StatsCounter successfulCounter = createStatsCounter(key, SUCCESSFUL_MSGS);
StatsCounter failedCounter = createStatsCounter(key, FAILED_MSGS);
return new DefaultMessagesStats(totalCounter, successfulCounter, failedCounter);
}
@Override
public Timer createTimer(String key, String... tags) {
Timer.Builder timerBuilder = Timer.builder(key)
.tags(tags)
.publishPercentiles();
if (timerPercentiles != null && timerPercentiles.length > 0) {
timerBuilder.publishPercentiles(timerPercentiles);
}
return timerBuilder.register(meterRegistry);
}
@Override
public StatsTimer createStatsTimer(String type, String name, String... tags) {
return new StatsTimer(name, Timer.builder(type)
.tags(getTags(name, tags))
.register(meterRegistry));
}
private static String[] getTags(String statsName, String[] otherTags) {
String[] tags = new String[]{STATS_NAME_TAG, statsName};
if (otherTags.length > 0) {
if (otherTags.length % 2 != 0) {
throw new IllegalArgumentException("Invalid tags array size");
}
tags = ArrayUtils.addAll(tags, otherTags);
|
}
return tags;
}
private static class StubCounter implements Counter {
@Override
public void increment(double amount) {
}
@Override
public double count() {
return 0;
}
@Override
public Id getId() {
return null;
}
}
}
|
repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\DefaultStatsFactory.java
| 1
|
请完成以下Java代码
|
public HttpServletRequestWrapper wrapRequest(HttpServletRequest req, boolean isBodyEmpty, PushbackInputStream requestBody) {
return new HttpServletRequestWrapper(req) {
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
final InputStream inputStream = getRequestBody(isBodyEmpty, requestBody);
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public synchronized void mark(int readlimit) {
inputStream.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
inputStream.reset();
|
}
@Override
public boolean markSupported() {
return inputStream.markSupported();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return EmptyBodyFilter.this.getReader(this.getInputStream());
}
};
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java
| 1
|
请完成以下Java代码
|
default Supplier<SecurityContext> getDeferredContext() {
return this::getContext;
}
/**
* Sets the current context.
* @param context to the new argument (should never be <code>null</code>, although
* implementations must check if <code>null</code> has been passed and throw an
* <code>IllegalArgumentException</code> in such cases)
*/
void setContext(SecurityContext context);
/**
* Sets a {@link Supplier} that will return the current context. Implementations can
* override the default to avoid invoking {@link Supplier#get()}.
* @param deferredContext a {@link Supplier} that returns the {@link SecurityContext}
|
* @since 5.8
*/
default void setDeferredContext(Supplier<SecurityContext> deferredContext) {
setContext(deferredContext.get());
}
/**
* Creates a new, empty context implementation, for use by
* <tt>SecurityContextRepository</tt> implementations, when creating a new context for
* the first time.
* @return the empty context.
*/
SecurityContext createEmptyContext();
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\SecurityContextHolderStrategy.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.