instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getIncludeExpression() {
return includeExpression;
}
public void setIncludeExpression(String includeExpression) {
this.includeExpression = includeExpression;
}
public String getUrlExpression() {
return urlExpression;
}
public void setUrlExpression(String urlExpression) {
this.urlExpression = urlExpression;
}
public boolean isLowerCaseServiceId() {
return lowerCaseServiceId;
}
public void setLowerCaseServiceId(boolean lowerCaseServiceId) {
this.lowerCaseServiceId = lowerCaseServiceId;
}
public List<PredicateDefinition> getPredicates() {
return predicates;
}
public void setPredicates(List<PredicateDefinition> predicates) {
this.predicates = predicates;
} | public List<FilterDefinition> getFilters() {
return filters;
}
public void setFilters(List<FilterDefinition> filters) {
this.filters = filters;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", enabled)
.append("routeIdPrefix", routeIdPrefix)
.append("includeExpression", includeExpression)
.append("urlExpression", urlExpression)
.append("lowerCaseServiceId", lowerCaseServiceId)
.append("predicates", predicates)
.append("filters", filters)
.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryLocatorProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
return companyMap.get(Id);
}
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", company.getName());
model.addAttribute("id", company.getId());
companyMap.put(company.getId(), company);
return "companyView";
} | @RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
final Map<String, String> result = new HashMap<>();
result.put("name", name);
return new ResponseEntity<>(result, HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\matrix\controller\CompanyController.java | 2 |
请完成以下Java代码 | public final class C_Order_MFGWarehouse_Report_RecordTextProvider implements IRecordTextProvider
{
public static final transient C_Order_MFGWarehouse_Report_RecordTextProvider instance = new C_Order_MFGWarehouse_Report_RecordTextProvider();
private static final String MSG_PrintingInfo_MFGWarehouse_Report = "de.metas.printing.C_Print_Job_Instructions.C_Order_MFGWarehouse_Report_Error";
private C_Order_MFGWarehouse_Report_RecordTextProvider()
{
super();
}
@Override
public Optional<String> getTextMessageIfApplies(ITableRecordReference referencedRecord)
{
if (referencedRecord.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Print_Job_Instructions.class))
{
return Optional.absent();
}
final IContextAware context = PlainContextAware.newOutOfTrxAllowThreadInherited(Env.getCtx());
// the reference record must be a I_C_PrintJobInstructions entry
final I_C_Print_Job_Instructions printJobInstructions = referencedRecord.getModel(context, I_C_Print_Job_Instructions.class);
final I_C_Print_Job_Instructions_v printingInfo = InterfaceWrapperHelper.create(
Services.get(IPrintJobDAO.class).retrieveC_Print_Job_Instructions_Info(printJobInstructions),
I_C_Print_Job_Instructions_v.class);
if (printingInfo == null)
{
return Optional.absent();
}
// an archive must exist in the C_Print_Job_Instructions_v view linked with this C_Print_Job_Instructions entry
final I_AD_Archive archive = printingInfo.getAD_Archive();
if (archive == null)
{
return Optional.absent();
} | // the archive must point to the C_Order_MFGWarehouse_Report table
if (archive.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Order_MFGWarehouse_Report.class))
{
return Optional.absent();
}
final I_C_Order_MFGWarehouse_Report mfgWarehouseReport = printingInfo.getC_Order_MFGWarehouse_Report();
// in case there is no I_C_Order_MFGWarehouse_Report with the ID given by AD_Archive's Record_ID ( shall never happen),
// just display the original error message from the print job instructions
if (mfgWarehouseReport == null)
{
return DefaultPrintingRecordTextProvider.instance.getTextMessage(printJobInstructions);
}
final Properties ctx = InterfaceWrapperHelper.getCtx(printJobInstructions);
final I_C_Order order = printingInfo.getC_Order();
final String orderDocNo = order == null ? "" : order.getDocumentNo();
final StringBuilder mfgWarehouseReportID = new StringBuilder();
mfgWarehouseReportID.append(mfgWarehouseReport.getC_Order_MFGWarehouse_Report_ID());
final String textMessge = Services.get(IMsgBL.class).getMsg(ctx, MSG_PrintingInfo_MFGWarehouse_Report, new Object[] { orderDocNo, mfgWarehouseReportID.toString() });
return Optional.of(CoalesceUtil.coalesce(textMessge, ""));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\printing\spi\impl\C_Order_MFGWarehouse_Report_RecordTextProvider.java | 1 |
请完成以下Java代码 | public String getExpressionString()
{
return expressionBaseLang.getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return expressionBaseLang.getFormatedExpressionString();
}
@Override
public Set<CtxName> getParameters()
{
return parameters;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
{
//
// Evaluate the adLanguage parameter
final OnVariableNotFound adLanguageOnVariableNoFound = getOnVariableNotFoundForInternalParameter(onVariableNotFound);
final String adLanguage = StringExpressionsHelper.evaluateParam(adLanguageParam, ctx, adLanguageOnVariableNoFound);
if (adLanguage == null || adLanguage == IStringExpression.EMPTY_RESULT)
{
return IStringExpression.EMPTY_RESULT;
}
else if (adLanguage.isEmpty() && onVariableNotFound == OnVariableNotFound.Empty)
{
return "";
}
final IStringExpression expressionEffective;
if (Language.isBaseLanguage(adLanguage))
{
expressionEffective = expressionBaseLang;
}
else
{
expressionEffective = expressionTrl;
}
return expressionEffective.evaluate(ctx, onVariableNotFound);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
} | }
private static final OnVariableNotFound getOnVariableNotFoundForInternalParameter(final OnVariableNotFound onVariableNotFound)
{
switch (onVariableNotFound)
{
case Preserve:
// Preserve is not supported because we don't know which expression to pick if the deciding parameter is not determined
return OnVariableNotFound.Fail;
default:
return onVariableNotFound;
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx)
{
try
{
boolean changed = false;
final IStringExpression expressionBaseLangNew = expressionBaseLang.resolvePartial(ctx);
if (!expressionBaseLang.equals(expressionBaseLangNew))
{
changed = true;
}
final IStringExpression expressionTrlNew = expressionTrl.resolvePartial(Evaluatees.excludingVariables(ctx, adLanguageParam.getName()));
if (!changed && !expressionTrl.equals(expressionTrlNew))
{
changed = true;
}
if (!changed)
{
return this;
}
return new TranslatableParameterizedStringExpression(adLanguageParam, expressionBaseLangNew, expressionTrlNew);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\TranslatableParameterizedStringExpression.java | 1 |
请完成以下Java代码 | public void setNoInventoryCount (int NoInventoryCount)
{
set_Value (COLUMNNAME_NoInventoryCount, Integer.valueOf(NoInventoryCount));
}
/** Get Number of Inventory counts.
@return Frequency of inventory counts per year
*/
public int getNoInventoryCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoInventoryCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of Product counts.
@param NoProductCount
Frequency of product counts per year
*/
public void setNoProductCount (int NoProductCount)
{
set_Value (COLUMNNAME_NoProductCount, Integer.valueOf(NoProductCount));
}
/** Get Number of Product counts.
@return Frequency of product counts per year
*/
public int getNoProductCount ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Number of runs.
@param NumberOfRuns
Frequency of processing Perpetual Inventory
*/
public void setNumberOfRuns (int NumberOfRuns)
{
set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns));
}
/** Get Number of runs.
@return Frequency of processing Perpetual Inventory
*/
public int getNumberOfRuns ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PerpetualInv.java | 1 |
请完成以下Java代码 | public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {
this.handler.onDeviceUpdate(sessionInfo, device, deviceProfileOpt);
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) {
log.trace("[{}] Received RPC command to device", sessionId);
this.rpcHandler.onToDeviceRpcRequest(toDeviceRequest, this.sessionInfo);
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
this.rpcHandler.onToServerRpcResponse(toServerResponse);
}
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
log.info("[{}] operationComplete", future);
}
@Override | public void onResourceUpdate(TransportProtos.ResourceUpdateMsg resourceUpdateMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceUpdateMsgOpt.getResourceType())) {
this.handler.onResourceUpdate(resourceUpdateMsgOpt);
}
}
@Override
public void onResourceDelete(TransportProtos.ResourceDeleteMsg resourceDeleteMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceDeleteMsgOpt.getResourceType())) {
this.handler.onResourceDelete(resourceDeleteMsgOpt);
}
}
@Override
public void onDeviceDeleted(DeviceId deviceId) {
log.trace("[{}] Device on delete", deviceId);
this.handler.onDeviceDelete(deviceId);
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mSessionMsgListener.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set XY Separator.
@param XYSeparator | The separator between the X and Y function.
*/
public void setXYSeparator (String XYSeparator)
{
set_Value (COLUMNNAME_XYSeparator, XYSeparator);
}
/** Get XY Separator.
@return The separator between the X and Y function.
*/
public String getXYSeparator ()
{
return (String)get_Value(COLUMNNAME_XYSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java | 1 |
请完成以下Java代码 | public ModelElementType build() {
model.registerType(modelType, instanceType);
return modelType;
}
public ModelElementTypeBuilder abstractType() {
modelType.setAbstract(true);
return this;
}
public SequenceBuilder sequence() {
SequenceBuilderImpl builder = new SequenceBuilderImpl(modelType);
modelBuildOperations.add(builder);
return builder;
}
public void buildTypeHierarchy(Model model) {
// build type hierarchy
if(extendedType != null) {
ModelElementTypeImpl extendedModelElementType = (ModelElementTypeImpl) model.getType(extendedType);
if(extendedModelElementType == null) { | throw new ModelException("Type "+modelType+" is defined to extend "+extendedType+" but no such type is defined.");
} else {
modelType.setBaseType(extendedModelElementType);
extendedModelElementType.registerExtendingType(modelType);
}
}
}
public void performModelBuild(Model model) {
for (ModelBuildOperation operation : modelBuildOperations) {
operation.performModelBuild(model);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeBuilderImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
int l = -1;
for (String c : catalog)
{
l = Math.max(l, c.length());
}
final int w = 6;
final StringBuilder sb = new StringBuilder(10000);
printf(sb, "%*s\t%*s\t%*s\t%*s\t%*s%n".replace('*', Character.forDigit(w, 10)), "P", "R", "F1", "A", "");
for (int i = 0; i < catalog.length; i++)
{
printf(sb, ("%*.2f\t%*.2f\t%*.2f\t%*.2f\t%"+l+"s%n").replace('*', Character.forDigit(w, 10)),
precision[i] * 100.,
recall[i] * 100.,
f1[i] * 100.,
accuracy[i] * 100.,
catalog[i]);
} | printf(sb, ("%*.2f\t%*.2f\t%*.2f\t%*.2f\t%"+l+"s%n").replace('*', Character.forDigit(w, 10)),
average_precision * 100.,
average_recall * 100.,
average_f1 * 100.,
average_accuracy * 100.,
"avg.");
printf(sb, "data size = %d, speed = %.2f doc/s\n", size, speed);
return sb.toString();
}
private static void printf(StringBuilder sb, String format, Object... args)
{
sb.append(String.format(format, args));
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\evaluations\FMeasure.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getCvn2() {
return cvn2;
} | public void setCvn2(String cvn2) {
this.cvn2 = cvn2;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
public String getIsAuth() {
return isAuth;
}
public void setIsAuth(String isAuth) {
this.isAuth = isAuth;
}
public String getStatusDesc() {
if (StringUtil.isEmpty(this.getStatus())) {
return "";
} else {
return PublicStatusEnum.getEnum(this.getStatus()).getDesc();
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserQuickPayBankAccount.java | 2 |
请完成以下Java代码 | public String taskProcess() {
return readJson("classpath:org/jeecg/modules/demo/mock/json/task_process.json");
}
//-------------------------------------------------------------------------------------------
//author:lvdandan-----date:20190315---for:添加数据日志json----
/**
* 数据日志
*/
public String sysDataLogJson() {
return readJson("classpath:org/jeecg/modules/demo/mock/json/sysdatalog.json");
}
//author:lvdandan-----date:20190315---for:添加数据日志json----
//--update-begin--author:wangshuai-----date:20201023---for:返回用户信息json数据----
/**
* 用户信息
*/
@GetMapping(value = "/getUserInfo")
public String getUserInfo(){
return readJson("classpath:org/jeecg/modules/demo/mock/json/userinfo.json"); | }
//--update-end--author:wangshuai-----date:20201023---for:返回用户信息json数据----
/**
* 读取json格式文件
* @param jsonSrc
* @return
*/
private String readJson(String jsonSrc) {
String json = "";
try {
//File jsonFile = ResourceUtils.getFile(jsonSrc);
//json = FileUtils.re.readFileToString(jsonFile);
//换个写法,解决springboot读取jar包中文件的问题
InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonSrc.replace("classpath:", ""));
json = IOUtils.toString(stream,"UTF-8");
} catch (IOException e) {
log.error(e.getMessage(),e);
}
return json;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\MockController.java | 1 |
请完成以下Java代码 | public class ErrorThrowingEventListener extends BaseDelegateEventListener {
protected String errorCode;
@Override
public void onEvent(ActivitiEvent event) {
if (isValidEvent(event)) {
onEventInternal(event);
}
}
protected void onEventInternal(ActivitiEvent event) {
ExecutionEntity execution = null;
if (event.getExecutionId() != null) {
// Get the execution based on the event's execution ID instead
execution = Context.getCommandContext().getExecutionEntityManager().findById(event.getExecutionId());
}
if (execution == null) {
throw new ActivitiException( | "No execution context active and event is not related to an execution. No compensation event can be thrown."
);
}
try {
ErrorPropagation.propagateError(errorCode, execution);
} catch (Exception e) {
throw new ActivitiException("Error while propagating error-event", e);
}
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
@Override
public boolean isFailOnException() {
return true;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ErrorThrowingEventListener.java | 1 |
请完成以下Java代码 | public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_BPartner_RelatedRecord1_ID (final int C_BPartner_RelatedRecord1_ID)
{
if (C_BPartner_RelatedRecord1_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_RelatedRecord1_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_RelatedRecord1_ID, C_BPartner_RelatedRecord1_ID);
}
@Override
public int getC_BPartner_RelatedRecord1_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_RelatedRecord1_ID); | }
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_RelatedRecord1.java | 1 |
请完成以下Java代码 | public void setChrgBr(ChargeBearerType1Code value) {
this.chrgBr = value;
}
/**
* Gets the value of the chrgsAcct property.
*
* @return
* possible object is
* {@link CashAccount16CHIdAndCurrency }
*
*/
public CashAccount16CHIdAndCurrency getChrgsAcct() {
return chrgsAcct;
}
/**
* Sets the value of the chrgsAcct property.
*
* @param value
* allowed object is
* {@link CashAccount16CHIdAndCurrency }
*
*/
public void setChrgsAcct(CashAccount16CHIdAndCurrency value) {
this.chrgsAcct = value;
}
/**
* Gets the value of the cdtTrfTxInf 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 cdtTrfTxInf property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getCdtTrfTxInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CreditTransferTransactionInformation10CH }
*
*
*/
public List<CreditTransferTransactionInformation10CH> getCdtTrfTxInf() {
if (cdtTrfTxInf == null) {
cdtTrfTxInf = new ArrayList<CreditTransferTransactionInformation10CH>();
}
return this.cdtTrfTxInf;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentInstructionInformation3CH.java | 1 |
请完成以下Java代码 | protected POInfo initPO(Properties ctx)
{
POInfo poi = POInfo.getPOInfo(ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer("X_M_PackagingTreeItemSched[")
.append(get_ID()).append("]");
return sb.toString();
}
/**
* Set Packaging Tree Item Schedule.
*
* @param M_PackagingTreeItemSched_ID
* Packaging Tree Item Schedule
*/
public void setM_PackagingTreeItemSched_ID(int M_PackagingTreeItemSched_ID)
{
if (M_PackagingTreeItemSched_ID < 1)
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, null);
else
set_ValueNoCheck(COLUMNNAME_M_PackagingTreeItemSched_ID, Integer.valueOf(M_PackagingTreeItemSched_ID));
}
/**
* Get Packaging Tree Item Schedule.
*
* @return Packaging Tree Item Schedule
*/
public int getM_PackagingTreeItemSched_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItemSched_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_PackagingTreeItem getM_PackagingTreeItem() throws RuntimeException
{
return (I_M_PackagingTreeItem)MTable.get(getCtx(), I_M_PackagingTreeItem.Table_Name)
.getPO(getM_PackagingTreeItem_ID(), get_TrxName());
}
/**
* Set Packaging Tree Item.
*
* @param M_PackagingTreeItem_ID
* Packaging Tree Item
*/
public void setM_PackagingTreeItem_ID(int M_PackagingTreeItem_ID)
{
if (M_PackagingTreeItem_ID < 1)
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, null);
else
set_Value(COLUMNNAME_M_PackagingTreeItem_ID, Integer.valueOf(M_PackagingTreeItem_ID));
}
/**
* Get Packaging Tree Item.
*
* @return Packaging Tree Item
*/
public int getM_PackagingTreeItem_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTreeItem_ID); | if (ii == null)
return 0;
return ii.intValue();
}
@Override
public I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException
{
return (I_M_ShipmentSchedule)MTable.get(getCtx(), I_M_ShipmentSchedule.Table_Name)
.getPO(getM_ShipmentSchedule_ID(), get_TrxName());
}
@Override
public int getM_ShipmentSchedule_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public void setM_ShipmentSchedule_ID(int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value(COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
/**
* Set Menge.
*
* @param Qty
* Menge
*/
public void setQty(BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
/**
* Get Menge.
*
* @return Menge
*/
public BigDecimal getQty()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItemSched.java | 1 |
请完成以下Java代码 | public boolean hasIgnoreCondition() {
return hasIgnoreRule() && (ignoreCondition.contains("#") || ignoreCondition.contains("$"));
}
public boolean hasDefaultCondition() {
return hasDefaultRule() && (defaultCondition.contains("#") || defaultCondition.contains("$"));
}
public String getDefaultCondition() {
return defaultCondition;
}
public void setDefaultCondition(String defaultCondition) {
this.defaultCondition = defaultCondition;
}
public String getActivateCondition() {
return activateCondition;
}
public void setActivateCondition(String activateCondition) {
this.activateCondition = activateCondition;
}
public String getIgnoreCondition() {
return ignoreCondition;
}
public void setIgnoreCondition(String ignoreCondition) {
this.ignoreCondition = ignoreCondition;
}
@Override
public String toString() {
return "ReactivationRule{} " + super.toString();
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReactivationRule that = (ReactivationRule) o;
return Objects.equals(activateCondition, that.activateCondition) && Objects.equals(ignoreCondition, that.ignoreCondition)
&& Objects.equals(defaultCondition, that.defaultCondition);
}
@Override
public int hashCode() {
return Objects.hash(activateCondition, ignoreCondition, defaultCondition);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ReactivationRule.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_BoilerPlate_Ref[")
.append(get_ID()).append("]");
return sb.toString();
}
@Override
public de.metas.letters.model.I_AD_BoilerPlate getAD_BoilerPlate() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class);
}
@Override
public void setAD_BoilerPlate(de.metas.letters.model.I_AD_BoilerPlate AD_BoilerPlate)
{
set_ValueFromPO(COLUMNNAME_AD_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class, AD_BoilerPlate);
}
/** Set Textbaustein.
@param AD_BoilerPlate_ID Textbaustein */
@Override
public void setAD_BoilerPlate_ID (int AD_BoilerPlate_ID)
{
if (AD_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, Integer.valueOf(AD_BoilerPlate_ID));
}
/** Get Textbaustein.
@return Textbaustein */
@Override
public int getAD_BoilerPlate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.letters.model.I_AD_BoilerPlate getRef_BoilerPlate() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class);
}
@Override
public void setRef_BoilerPlate(de.metas.letters.model.I_AD_BoilerPlate Ref_BoilerPlate)
{ | set_ValueFromPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class, Ref_BoilerPlate);
}
/** Set Referenced template.
@param Ref_BoilerPlate_ID Referenced template */
@Override
public void setRef_BoilerPlate_ID (int Ref_BoilerPlate_ID)
{
if (Ref_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, Integer.valueOf(Ref_BoilerPlate_ID));
}
/** Get Referenced template.
@return Referenced template */
@Override
public int getRef_BoilerPlate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_BoilerPlate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Ref.java | 1 |
请完成以下Java代码 | public static String encode(AnsiElement element) {
if (isEnabled()) {
return ENCODE_START + element + ENCODE_END;
}
return "";
}
/**
* Create a new ANSI string from the specified elements. Any {@link AnsiElement}s will
* be encoded as required.
* @param elements the elements to encode
* @return a string of the encoded elements
*/
public static String toString(Object... elements) {
StringBuilder sb = new StringBuilder();
if (isEnabled()) {
buildEnabled(sb, elements);
}
else {
buildDisabled(sb, elements);
}
return sb.toString();
}
private static void buildEnabled(StringBuilder sb, Object[] elements) {
boolean writingAnsi = false;
boolean containsEncoding = false;
for (Object element : elements) {
if (element instanceof AnsiElement) {
containsEncoding = true;
if (!writingAnsi) {
sb.append(ENCODE_START);
writingAnsi = true;
}
else {
sb.append(ENCODE_JOIN);
}
}
else {
if (writingAnsi) {
sb.append(ENCODE_END);
writingAnsi = false;
}
}
sb.append(element);
}
if (containsEncoding) {
sb.append(writingAnsi ? ENCODE_JOIN : ENCODE_START);
sb.append(RESET);
sb.append(ENCODE_END);
}
}
private static void buildDisabled(StringBuilder sb, @Nullable Object[] elements) {
for (Object element : elements) {
if (!(element instanceof AnsiElement) && element != null) {
sb.append(element);
}
}
}
private static boolean isEnabled() {
if (enabled == Enabled.DETECT) {
if (ansiCapable == null) {
ansiCapable = detectIfAnsiCapable();
} | return ansiCapable;
}
return enabled == Enabled.ALWAYS;
}
private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
}
Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Console.class, "isTerminal");
if (isTerminalMethod != null) {
Boolean isTerminal = (Boolean) isTerminalMethod.invoke(console);
if (Boolean.FALSE.equals(isTerminal)) {
return false;
}
}
}
return !(OPERATING_SYSTEM_NAME.contains("win"));
}
catch (Throwable ex) {
return false;
}
}
/**
* Possible values to pass to {@link AnsiOutput#setEnabled}. Determines when to output
* ANSI escape sequences for coloring application output.
*/
public enum Enabled {
/**
* Try to detect whether ANSI coloring capabilities are available. The default
* value for {@link AnsiOutput}.
*/
DETECT,
/**
* Enable ANSI-colored output.
*/
ALWAYS,
/**
* Disable ANSI-colored output.
*/
NEVER
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiOutput.java | 1 |
请完成以下Java代码 | public List<PermissionCheck> getProcessInstancePermissionChecks() {
return processInstancePermissionChecks;
}
public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) {
this.processInstancePermissionChecks = processInstancePermissionChecks;
}
public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) {
processInstancePermissionChecks.addAll(permissionChecks);
}
public List<PermissionCheck> getJobPermissionChecks() {
return jobPermissionChecks;
}
public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) {
this.jobPermissionChecks = jobPermissionChecks; | }
public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) {
jobPermissionChecks.addAll(permissionChecks);
}
public List<PermissionCheck> getIncidentPermissionChecks() {
return incidentPermissionChecks;
}
public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) {
this.incidentPermissionChecks = incidentPermissionChecks;
}
public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) {
incidentPermissionChecks.addAll(permissionChecks);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityStatisticsQueryImpl.java | 1 |
请完成以下Java代码 | public boolean equals(final Object other)
{
if (other instanceof AttachmentEntryDataResource)
{
return Arrays.equals(source, ((AttachmentEntryDataResource)other).source);
}
else
{
return false;
}
}
@Override
@NonNull
public String getFilename()
{
return filename;
} | @Override
public String getDescription()
{
return description;
}
@Override
public long contentLength()
{
return source.length;
}
@Override
public InputStream getInputStream()
{
return new ByteArrayInputStream(source);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryDataResource.java | 1 |
请完成以下Java代码 | public ApplicationContent read(InputStream inputStream) {
ApplicationContent application = new ApplicationContent();
try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
ZipEntry currentEntry = zipEntry;
applicationEntryDiscoveries
.stream()
.filter(applicationEntryDiscovery ->
applicationEntryDiscovery.filter(currentEntry).test(currentEntry)
)
.findFirst()
.ifPresent(applicationEntryDiscovery ->
application.add(
new ApplicationEntry(
applicationEntryDiscovery.getEntryType(),
new FileContent(currentEntry.getName(), readBytes(zipInputStream))
) | )
);
}
} catch (IOException e) {
throw new ApplicationLoadException("Unable to read zip file", e);
}
return application;
}
private byte[] readBytes(ZipInputStream zipInputStream) {
try {
return StreamUtils.copyToByteArray(zipInputStream);
} catch (IOException e) {
throw new ApplicationLoadException("Unable to read zip file", e);
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-application\src\main\java\org\activiti\application\ApplicationReader.java | 1 |
请完成以下Java代码 | public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type
+ ", userId=" + userId
+ ", time=" + time
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", revision= "+ revision
+ ", removalTime=" + removalTime
+ ", action=" + action
+ ", message=" + message
+ ", fullMessage=" + fullMessage
+ ", tenantId=" + tenantId
+ "]"; | }
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntryListValueId implements RepoIdAware
{
public static DataEntryListValueId ofRepoId(final int repoId)
{
return new DataEntryListValueId(repoId);
}
public static DataEntryListValueId ofRepoIdOrNull(final int repoId)
{
if (repoId <= 0)
{
return null;
}
return new DataEntryListValueId(repoId);
}
public static int getRepoId(@Nullable final DataEntryListValueId dataEntryListValueId)
{
if (dataEntryListValueId == null)
{
return 0;
}
return dataEntryListValueId.getRepoId();
} | int repoId;
@JsonCreator
public DataEntryListValueId(final int repoId)
{
this.repoId = assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue // note: annotating just the repoId member worked "often" which was very annoying
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\DataEntryListValueId.java | 2 |
请完成以下Java代码 | public int getPP_Order_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setPP_OrderCandidate_PP_Order_ID (final int PP_OrderCandidate_PP_Order_ID)
{
if (PP_OrderCandidate_PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_OrderCandidate_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_OrderCandidate_PP_Order_ID, PP_OrderCandidate_PP_Order_ID);
} | @Override
public int getPP_OrderCandidate_PP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_OrderCandidate_PP_Order_ID);
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderCandidate_PP_Order.java | 1 |
请完成以下Java代码 | public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{
if (M_PickingSlot_ID < 1)
set_Value (COLUMNNAME_M_PickingSlot_ID, null);
else
set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID);
}
@Override
public int getM_PickingSlot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID);
}
@Override
public void setM_PickingSlot_Trx_ID (final int M_PickingSlot_Trx_ID)
{
if (M_PickingSlot_Trx_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PickingSlot_Trx_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PickingSlot_Trx_ID, M_PickingSlot_Trx_ID);
}
@Override
public int getM_PickingSlot_Trx_ID() | {
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_Trx_ID);
}
@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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_PickingSlot_Trx.java | 1 |
请完成以下Java代码 | public static SOTrx ofBooleanNotNull(@NonNull final Boolean isSOTrx)
{
return isSOTrx ? SALES : PURCHASE;
}
public static Optional<SOTrx> optionalOfBoolean(@Nullable final Boolean isSOTrx)
{
return isSOTrx != null
? Optional.of(ofBooleanNotNull(isSOTrx))
: Optional.empty();
}
public boolean toBoolean()
{
return isSales();
}
public static boolean toBoolean(final SOTrx soTrx)
{
if (soTrx == null)
{
return false;
}
return soTrx.toBoolean();
}
public boolean isSales() | {
return this == SALES;
}
public boolean isPurchase()
{
return this == PURCHASE;
}
/**
* @return true if AP (Account Payable), aka Purchase
*/
public boolean isAP() {return isPurchase();}
public SOTrx invert()
{
return isSales() ? PURCHASE : SALES;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\lang\SOTrx.java | 1 |
请完成以下Java代码 | public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public List<String> getExternal() {
return external;
}
public void setExternal(List<String> external) {
this.external = external;
}
public class Component {
private Idm idm = new Idm();
private Service service = new Service();
public Idm getIdm() {
return idm;
}
public void setIdm(Idm idm) {
this.idm = idm;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
public class Idm {
private String url;
private String user;
private String password;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} | public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Service {
private String url;
private String token;
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yaml\YAMLConfig.java | 1 |
请完成以下Java代码 | public class AuditLog extends BaseData<AuditLogId> {
@Schema(description = "JSON object with Tenant Id", accessMode = Schema.AccessMode.READ_ONLY)
private TenantId tenantId;
@Schema(description = "JSON object with Customer Id", accessMode = Schema.AccessMode.READ_ONLY)
private CustomerId customerId;
@Schema(description = "JSON object with Entity id", accessMode = Schema.AccessMode.READ_ONLY)
private EntityId entityId;
@NoXss
@Schema(description = "Name of the logged entity", example = "Thermometer", accessMode = Schema.AccessMode.READ_ONLY)
private String entityName;
@Schema(description = "JSON object with User id.", accessMode = Schema.AccessMode.READ_ONLY)
private UserId userId;
@Schema(description = "Unique user name(email) of the user that performed some action on logged entity", example = "tenant@thingsboard.org", accessMode = Schema.AccessMode.READ_ONLY)
private String userName;
@Schema(description = "String represented Action type", example = "ADDED", accessMode = Schema.AccessMode.READ_ONLY)
private ActionType actionType;
@Schema(description = "JsonNode represented action data", accessMode = Schema.AccessMode.READ_ONLY)
private JsonNode actionData;
@Schema(description = "String represented Action status", example = "SUCCESS", allowableValues = {"SUCCESS", "FAILURE"}, accessMode = Schema.AccessMode.READ_ONLY)
private ActionStatus actionStatus;
@Schema(description = "Failure action details info. An empty string in case of action status type 'SUCCESS', otherwise includes stack trace of the caused exception.", accessMode = Schema.AccessMode.READ_ONLY)
private String actionFailureDetails;
public AuditLog() {
super();
}
public AuditLog(AuditLogId id) {
super(id);
}
public AuditLog(AuditLog auditLog) {
super(auditLog);
this.tenantId = auditLog.getTenantId();
this.customerId = auditLog.getCustomerId();
this.entityId = auditLog.getEntityId(); | this.entityName = auditLog.getEntityName();
this.userId = auditLog.getUserId();
this.userName = auditLog.getUserName();
this.actionType = auditLog.getActionType();
this.actionData = auditLog.getActionData();
this.actionStatus = auditLog.getActionStatus();
this.actionFailureDetails = auditLog.getActionFailureDetails();
}
@Schema(description = "Timestamp of the auditLog creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Schema(description = "JSON object with the auditLog Id")
@Override
public AuditLogId getId() {
return super.getId();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\audit\AuditLog.java | 1 |
请完成以下Java代码 | public class Customer {
String id;
String name;
String gender;
int transaction_amount;
public Customer() {
}
public Customer(String id, String name, String gender, int transaction_amount) {
this.id = id;
this.name = name;
this.gender = gender;
this.transaction_amount = transaction_amount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getTransaction_amount() {
return transaction_amount;
}
public void setTransaction_amount(int transaction_amount) {
this.transaction_amount = transaction_amount;
}
} | repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\Customer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<String> extractConstraintName(SQLException ex) {
final String sqlState = JdbcExceptionHelper.extractSqlState( ex );
if (sqlState != null) {
String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode( sqlState );
if ( sqlStateClassCode != null ) {
if (Arrays.asList(
"23", // "integrity constraint violation"
"27", // "triggered data change violation"
"44" // "with check option violation"
).contains(sqlStateClassCode)) {
if (ex instanceof PSQLException) {
return Optional.of(((PSQLException)ex).getServerErrorMessage().getConstraint());
}
}
}
}
return Optional.empty();
}
protected Statement createCassandraSelectStatement() {
StringBuilder selectStatementBuilder = new StringBuilder();
selectStatementBuilder.append("SELECT ");
for (CassandraToSqlColumn column : columns) {
selectStatementBuilder.append(column.getCassandraColumnName()).append(",");
}
selectStatementBuilder.deleteCharAt(selectStatementBuilder.length() - 1);
selectStatementBuilder.append(" FROM ").append(cassandraCf);
return SimpleStatement.newInstance(selectStatementBuilder.toString());
}
private PreparedStatement createSqlInsertStatement(Connection conn) throws SQLException {
StringBuilder insertStatementBuilder = new StringBuilder();
insertStatementBuilder.append("INSERT INTO ").append(this.sqlTableName).append(" ("); | for (CassandraToSqlColumn column : columns) {
insertStatementBuilder.append(column.getSqlColumnName()).append(",");
}
insertStatementBuilder.deleteCharAt(insertStatementBuilder.length() - 1);
insertStatementBuilder.append(") VALUES (");
for (CassandraToSqlColumn column : columns) {
if (column.getType() == CassandraToSqlColumnType.JSON) {
insertStatementBuilder.append("cast(? AS json)");
} else {
insertStatementBuilder.append("?");
}
insertStatementBuilder.append(",");
}
insertStatementBuilder.deleteCharAt(insertStatementBuilder.length() - 1);
insertStatementBuilder.append(")");
return conn.prepareStatement(insertStatementBuilder.toString());
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraToSqlTable.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AtomikosDataSourceBean inventoryDataSource() {
AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean();
dataSource.setLocalTransactionMode(true);
dataSource.setUniqueResourceName("db1");
dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource");
Properties xaProperties = new Properties();
xaProperties.put("databaseName", "db1");
xaProperties.put("createDatabase", "create");
dataSource.setXaProperties(xaProperties);
dataSource.setPoolSize(10);
return dataSource;
}
@Bean
public EntityManagerFactory inventoryEntityManager() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter); | factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.inventory");
factory.setDataSource(inventoryDataSource());
Properties jpaProperties = new Properties();
//jpaProperties.put("hibernate.show_sql", "true");
//jpaProperties.put("hibernate.format_sql", "true");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
jpaProperties.put("hibernate.current_session_context_class", "jta");
jpaProperties.put("javax.persistence.transactionType", "jta");
jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup");
jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
factory.setJpaProperties(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
} | repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\spring\jpa\inventory\InventoryConfig.java | 2 |
请完成以下Java代码 | public K getKey() { return key; }
/**
* Value of this this <code>Pair</code>.
*/
private V value;
/**
* Gets the value for this pair.
* @return value for this pair
*/
public V getValue() { return value; }
/**
* Creates a new pair
* @param key The key for this pair
* @param value The value to use for this pair
*/
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* <p><code>String</code> representation of this
* <code>Pair</code>.</p>
*
* <p>The default name/value delimiter '=' is always used.</p>
*
* @return <code>String</code> representation of this <code>Pair</code>
*/
@Override
public String toString() {
return key + "=" + value;
}
/**
* <p>Generate a hash code for this <code>Pair</code>.</p>
*
* <p>The hash code is calculated using both the name and
* the value of the <code>Pair</code>.</p>
*
* @return hash code for this <code>Pair</code>
*/
@Override
public int hashCode() {
// name's hashCode is multiplied by an arbitrary prime number (13) | // in order to make sure there is a difference in the hashCode between
// these two parameters:
// name: a value: aa
// name: aa value: a
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
/**
* <p>Test this <code>Pair</code> for equality with another
* <code>Object</code>.</p>
*
* <p>If the <code>Object</code> to be tested is not a
* <code>Pair</code> or is <code>null</code>, then this method
* returns <code>false</code>.</p>
*
* <p>Two <code>Pair</code>s are considered equal if and only if
* both the names and values are equal.</p>
*
* @param o the <code>Object</code> to test for
* equality with this <code>Pair</code>
* @return <code>true</code> if the given <code>Object</code> is
* equal to this <code>Pair</code> else <code>false</code>
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
return true;
}
return false;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Pair.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public de.metas.pos.repository.model.I_C_POS_Payment getC_POS_Payment()
{
return get_ValueAsPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class);
}
@Override
public void setC_POS_Payment(final de.metas.pos.repository.model.I_C_POS_Payment C_POS_Payment)
{
set_ValueFromPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class, C_POS_Payment);
}
@Override
public void setC_POS_Payment_ID (final int C_POS_Payment_ID)
{
if (C_POS_Payment_ID < 1)
set_Value (COLUMNNAME_C_POS_Payment_ID, null);
else
set_Value (COLUMNNAME_C_POS_Payment_ID, C_POS_Payment_ID);
}
@Override
public int getC_POS_Payment_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* Type AD_Reference_ID=541892
* Reference name: C_POS_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=541892;
/** CashPayment = CASH_PAY */ | public static final String TYPE_CashPayment = "CASH_PAY";
/** CardPayment = CARD_PAY */
public static final String TYPE_CardPayment = "CARD_PAY";
/** CashInOut = CASH_INOUT */
public static final String TYPE_CashInOut = "CASH_INOUT";
/** CashClosingDifference = CASH_DIFF */
public static final String TYPE_CashClosingDifference = "CASH_DIFF";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java | 2 |
请完成以下Java代码 | public void setSurchargeAmt (final @Nullable BigDecimal SurchargeAmt)
{
set_Value (COLUMNNAME_SurchargeAmt, SurchargeAmt);
}
@Override
public BigDecimal getSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalLines (final @Nullable BigDecimal TotalLines)
{
set_Value (COLUMNNAME_TotalLines, TotalLines);
}
@Override
public BigDecimal getTotalLines()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalLinesWithSurchargeAmt (final @Nullable BigDecimal TotalLinesWithSurchargeAmt)
{
set_Value (COLUMNNAME_TotalLinesWithSurchargeAmt, TotalLinesWithSurchargeAmt);
}
@Override
public BigDecimal getTotalLinesWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLinesWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalTaxBaseAmt (final @Nullable BigDecimal TotalTaxBaseAmt)
{
set_Value (COLUMNNAME_TotalTaxBaseAmt, TotalTaxBaseAmt);
}
@Override
public BigDecimal getTotalTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalTaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVat (final @Nullable BigDecimal TotalVat)
{
set_Value (COLUMNNAME_TotalVat, TotalVat);
}
@Override | public BigDecimal getTotalVat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVatWithSurchargeAmt (final BigDecimal TotalVatWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalVatWithSurchargeAmt, TotalVatWithSurchargeAmt);
}
@Override
public BigDecimal getTotalVatWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVatWithSurchargeAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_v.java | 1 |
请完成以下Java代码 | public static Date dateFrom(long timestamp) {
return new Date(timestamp);
}
public static Calendar calendarFrom(long timestamp) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
return calendar;
}
public static Instant fromNanos(long timestamp) {
long seconds = timestamp / 1_000_000_000;
long nanos = timestamp % 1_000_000_000;
return Instant.ofEpochSecond(seconds, nanos);
}
public static Instant fromTimestamp(long timestamp) {
return Instant.ofEpochMilli(millis(timestamp));
}
public static String format(Instant instant) {
LocalDateTime time = localTimeUtc(instant);
return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
public static LocalDateTime localTimeUtc(Instant instant) { | return LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
}
private static long millis(long timestamp) {
if (timestamp >= 1E16 || timestamp <= -1E16) {
return timestamp / 1_000_000;
}
if (timestamp >= 1E14 || timestamp <= -1E14) {
return timestamp / 1_000;
}
if (timestamp >= 1E11 || timestamp <= -3E10) {
return timestamp;
}
return timestamp * 1_000;
}
} | repos\tutorials-master\core-java-modules\core-java-date-operations-3\src\main\java\com\baeldung\unixtime\UnixTimeUtils.java | 1 |
请完成以下Java代码 | public String getDescription(final String adLanguage)
{
return description.translate(adLanguage);
}
public List<DocumentLayoutSectionDescriptor> getSections()
{
return sections;
}
public List<DocumentLayoutElementDescriptor> getElements()
{
List<DocumentLayoutElementDescriptor> elements = _elements;
if (elements == null)
{
elements = sections.stream()
.flatMap(section -> section.getColumns().stream())
.flatMap(column -> column.getElementGroups().stream())
.flatMap(elementGroup -> elementGroup.getElementLines().stream())
.flatMap(elementLine -> elementLine.getElements().stream())
.collect(ImmutableList.toImmutableList());
}
_elements = elements;
return elements;
}
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代码 | public class AuthenticationPayloadInterceptor implements PayloadInterceptor, Ordered {
private final ReactiveAuthenticationManager authenticationManager;
private int order;
private PayloadExchangeAuthenticationConverter authenticationConverter = new BasicAuthenticationPayloadExchangeConverter();
/**
* Creates a new instance
* @param authenticationManager the manager to use. Cannot be null
*/
public AuthenticationPayloadInterceptor(ReactiveAuthenticationManager authenticationManager) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.authenticationManager = authenticationManager;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* Sets the convert to be used
* @param authenticationConverter
*/
public void setAuthenticationConverter(PayloadExchangeAuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter; | }
@Override
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return this.authenticationConverter.convert(exchange)
.switchIfEmpty(chain.next(exchange).then(Mono.empty()))
.flatMap((a) -> this.authenticationManager.authenticate(a))
.flatMap((a) -> onAuthenticationSuccess(chain.next(exchange), a));
}
private Mono<Void> onAuthenticationSuccess(Mono<Void> payload, Authentication authentication) {
return payload.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authentication\AuthenticationPayloadInterceptor.java | 1 |
请完成以下Java代码 | public boolean isOneQRCodeForAggregatedHUs()
{
return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForAggregatedHUs);
}
@Override
public void setIsOneQRCodeForMatchingAttributes (final boolean IsOneQRCodeForMatchingAttributes)
{
set_Value (COLUMNNAME_IsOneQRCodeForMatchingAttributes, IsOneQRCodeForMatchingAttributes);
}
@Override
public boolean isOneQRCodeForMatchingAttributes()
{
return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForMatchingAttributes);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public String getName()
{ | return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID)
{
if (QRCode_Configuration_ID < 1)
set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID);
}
@Override
public int getQRCode_Configuration_ID()
{
return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Configuration.java | 1 |
请完成以下Java代码 | protected ProcessDefinitionEntity resolveSourceProcessDefinition(CommandContext commandContext) {
String sourceProcessDefinitionId = executionBuilder.getMigrationPlan()
.getSourceProcessDefinitionId();
ProcessDefinitionEntity sourceProcessDefinition =
getProcessDefinition(commandContext, sourceProcessDefinitionId);
EnsureUtil.ensureNotNull("sourceProcessDefinition", sourceProcessDefinition);
return sourceProcessDefinition;
}
protected ProcessDefinitionEntity resolveTargetProcessDefinition(CommandContext commandContext) {
String targetProcessDefinitionId = executionBuilder.getMigrationPlan()
.getTargetProcessDefinitionId();
ProcessDefinitionEntity sourceProcessDefinition = | getProcessDefinition(commandContext, targetProcessDefinitionId);
EnsureUtil.ensureNotNull("sourceProcessDefinition", sourceProcessDefinition);
return sourceProcessDefinition;
}
protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext,
String processDefinitionId) {
return commandContext
.getProcessEngineConfiguration()
.getDeploymentCache()
.findDeployedProcessDefinitionById(processDefinitionId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\AbstractMigrationCmd.java | 1 |
请完成以下Java代码 | private static UserNotificationRequest toUserNotification(@NonNull final I_M_Inventory inventory)
{
final TableRecordReference inventoryRef = TableRecordReference.of(inventory);
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC)
.recipientUserId(getNotificationRecipientUserId(inventory))
.contentADMessage(MSG_Event_InventoryGenerated)
.contentADMessageParam(inventoryRef)
.targetAction(TargetRecordAction.ofRecordAndWindow(inventoryRef, WINDOW_INTERNAL_INVENTORY))
.build();
}
private static UserId getNotificationRecipientUserId(final I_M_Inventory inventory)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inventory.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final UserId loggedUserId = Env.getLoggedUserIdIfExists().orElse(null); | if (loggedUserId != null)
{
return loggedUserId;
}
return UserId.ofRepoId(inventory.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(inventory.getCreatedBy());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\event\InventoryUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("pageId") String pageId) {
try {
this.userId = userId;
this.pageId = pageId;
this.socketId = userId + pageId;
this.session = session;
socketPool.put(this.socketId, this);
getUserPool(userId).put(this.pageId, this);
log.info("【vxeSocket】有新的连接,总数为:" + socketPool.size());
} catch (Exception ignored) {
}
}
/**
* websocket 断开连接
*/
@OnClose
public void onClose() {
try {
socketPool.remove(this.socketId);
getUserPool(this.userId).remove(this.pageId);
log.info("【vxeSocket】连接断开,总数为:" + socketPool.size());
} catch (Exception ignored) {
}
}
/**
* websocket 收到消息
*/
@OnMessage
public void onMessage(String message) {
// log.info("【vxeSocket】onMessage:" + message);
JSONObject json;
try {
json = JSON.parseObject(message); | } catch (Exception e) {
log.warn("【vxeSocket】收到不合法的消息:" + message);
return;
}
String type = json.getString(VxeSocketConst.TYPE);
switch (type) {
// 心跳检测
case VxeSocketConst.TYPE_HB:
this.sendMessage(VxeSocket.packageMessage(type, true));
break;
// 更新form数据
case VxeSocketConst.TYPE_UVT:
this.handleUpdateForm(json);
break;
default:
log.warn("【vxeSocket】收到不识别的消息类型:" + type);
break;
}
}
/**
* 处理 UpdateForm 事件
*/
private void handleUpdateForm(JSONObject json) {
// 将事件转发给所有人
JSONObject data = json.getJSONObject(VxeSocketConst.DATA);
VxeSocket.sendMessageToAll(VxeSocket.packageMessage(VxeSocketConst.TYPE_UVT, data));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\vxe\websocket\VxeSocket.java | 1 |
请完成以下Java代码 | public int getHR_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Posted.
@param Posted
Posting status
*/
public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
/** Get Posted.
@return Posting status
*/
public boolean isPosted ()
{
Object oo = get_Value(COLUMNNAME_Posted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed () | {
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException
{
return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name)
.getPO(getReversal_ID(), get_TrxName()); }
/** Set Reversal ID.
@param Reversal_ID
ID of document reversal
*/
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_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\eevolution\model\X_HR_Process.java | 1 |
请完成以下Java代码 | public class AuthorizationPayloadInterceptor implements PayloadInterceptor, Ordered {
private final ReactiveAuthorizationManager<PayloadExchange> authorizationManager;
private int order;
public AuthorizationPayloadInterceptor(ReactiveAuthorizationManager<PayloadExchange> authorizationManager) {
Assert.notNull(authorizationManager, "authorizationManager cannot be null");
this.authorizationManager = authorizationManager;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) { | this.order = order;
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return ReactiveSecurityContextHolder.getContext()
.mapNotNull(SecurityContext::getAuthentication)
.switchIfEmpty(Mono.error(() -> new AuthenticationCredentialsNotFoundException(
"An Authentication (possibly AnonymousAuthenticationToken) is required.")))
.as((authentication) -> this.authorizationManager.verify(authentication, exchange))
.then(chain.next(exchange));
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authorization\AuthorizationPayloadInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comments == null) ? 0 : comments.hashCode());
result = prime * result + (completed ? 1231 : 1237);
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TaskDTO other = (TaskDTO) obj;
if (comments == null) {
if (other.comments != null)
return false;
} else if (!comments.equals(other.comments))
return false;
if (completed != other.completed)
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (taskId == null) {
if (other.taskId != null) | return false;
} else if (!taskId.equals(other.taskId))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TaskDTO [taskId=" + taskId + ", description=" + description + ", completed=" + completed + ", userName="
+ userName + ", comments=" + comments + "]";
}
} | repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\dtos\TaskDTO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
JwtPair tokenPair;
if (authentication instanceof MfaAuthenticationToken) {
tokenPair = createMfaTokenPair(securityUser, Authority.PRE_VERIFICATION_TOKEN);
} else if (authentication instanceof MfaConfigurationToken) {
tokenPair = createMfaTokenPair(securityUser, Authority.MFA_CONFIGURATION_TOKEN);
} else {
tokenPair = tokenFactory.createTokenPair(securityUser);
}
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
JacksonUtil.writeValue(response.getWriter(), tokenPair);
clearAuthenticationAttributes(request);
}
public JwtPair createMfaTokenPair(SecurityUser securityUser, Authority scope) {
log.debug("[{}][{}] Creating {} token", securityUser.getTenantId(), securityUser.getId(), scope);
JwtPair tokenPair = new JwtPair();
int preVerificationTokenLifetime = twoFaConfigManager.getPlatformTwoFaSettings(securityUser.getTenantId(), true)
.flatMap(settings -> Optional.ofNullable(settings.getTotalAllowedTimeForVerification())
.filter(time -> time > 0))
.orElse((int) TimeUnit.MINUTES.toSeconds(30));
tokenPair.setToken(tokenFactory.createMfaToken(securityUser, scope, preVerificationTokenLifetime).token());
tokenPair.setRefreshToken(null);
tokenPair.setScope(scope);
return tokenPair;
}
/** | * Removes temporary authentication-related data which may have been stored
* in the session during the authentication process..
*
*/
protected final void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\rest\RestAwareAuthenticationSuccessHandler.java | 2 |
请完成以下Java代码 | public List<HistoricActivityInstanceEntity> findUnfinishedHistoricActivityInstancesByProcessInstanceId(
final String processInstanceId
) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("processInstanceId", processInstanceId);
return getList(
"selectUnfinishedHistoricActivityInstanceExecutionIdAndActivityId",
params,
unfinishedHistoricActivityInstanceMatcher,
true
);
}
@Override
public void deleteHistoricActivityInstancesByProcessInstanceId(String historicProcessInstanceId) {
getDbSqlSession().delete(
"deleteHistoricActivityInstancesByProcessInstanceId",
historicProcessInstanceId,
HistoricActivityInstanceEntityImpl.class
);
}
@Override
public long findHistoricActivityInstanceCountByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery
) {
return (Long) getDbSqlSession().selectOne(
"selectHistoricActivityInstanceCountByQueryCriteria",
historicActivityInstanceQuery
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricActivityInstance> findHistoricActivityInstancesByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery,
Page page
) {
return getDbSqlSession().selectList(
"selectHistoricActivityInstancesByQueryCriteria",
historicActivityInstanceQuery,
page
);
} | @Override
@SuppressWarnings("unchecked")
public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectHistoricActivityInstanceByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricActivityInstanceCountByNativeQuery", parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricActivityInstanceDataManager.java | 1 |
请完成以下Java代码 | public BigDecimal getQM_QtyDeliveredPercOfRaw()
{
return qtyDeliveredPercOfRaw;
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
Check.assumeNotNull(qtyDeliveredAvg, "qtyDeliveredAvg not null");
this.qtyDeliveredAvg = qtyDeliveredAvg;
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return qtyDeliveredAvg;
}
@Override
public String getVariantGroup()
{
return null; | }
@Override
public BOMComponentType getComponentType()
{
return null;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainProductionMaterial.java | 1 |
请完成以下Java代码 | public void setAD_BusinessRule_ID (final int AD_BusinessRule_ID)
{
if (AD_BusinessRule_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_ID, AD_BusinessRule_ID);
}
@Override
public int getAD_BusinessRule_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID);
}
@Override
public void setAD_BusinessRule_Trigger_ID (final int AD_BusinessRule_Trigger_ID)
{
if (AD_BusinessRule_Trigger_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, AD_BusinessRule_Trigger_ID);
}
@Override
public int getAD_BusinessRule_Trigger_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID);
}
@Override
public void setConditionSQL (final @Nullable java.lang.String ConditionSQL)
{
set_Value (COLUMNNAME_ConditionSQL, ConditionSQL);
}
@Override
public java.lang.String getConditionSQL()
{
return get_ValueAsString(COLUMNNAME_ConditionSQL);
}
@Override
public void setOnDelete (final boolean OnDelete)
{
set_Value (COLUMNNAME_OnDelete, OnDelete);
}
@Override
public boolean isOnDelete()
{
return get_ValueAsBoolean(COLUMNNAME_OnDelete);
}
@Override
public void setOnNew (final boolean OnNew)
{
set_Value (COLUMNNAME_OnNew, OnNew);
}
@Override
public boolean isOnNew()
{
return get_ValueAsBoolean(COLUMNNAME_OnNew);
}
@Override
public void setOnUpdate (final boolean OnUpdate)
{ | set_Value (COLUMNNAME_OnUpdate, OnUpdate);
}
@Override
public boolean isOnUpdate()
{
return get_ValueAsBoolean(COLUMNNAME_OnUpdate);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTargetRecordMappingSQL (final java.lang.String TargetRecordMappingSQL)
{
set_Value (COLUMNNAME_TargetRecordMappingSQL, TargetRecordMappingSQL);
}
@Override
public java.lang.String getTargetRecordMappingSQL()
{
return get_ValueAsString(COLUMNNAME_TargetRecordMappingSQL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Trigger.java | 1 |
请完成以下Java代码 | public class IterableSize {
/**
* Get the size of {@code Iterable} using Java 7.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingJava7(final Iterable data) {
if (data instanceof Collection) {
return ((Collection<?>) data).size();
}
int counter = 0;
for (final Object i : data) {
counter++;
}
return counter;
}
/**
* Get the size of {@code Iterable} using Java 8.
*
* @param data the iterable
* @return the size of the iterable
*/
public static long sizeUsingJava8(final Iterable data) {
return StreamSupport.stream(data.spliterator(), false).count();
} | /**
* Get the size of {@code Iterable} using Apache Collections.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingApacheCollections(final Iterable data) {
return IterableUtils.size(data);
}
/**
* Get the size of {@code Iterable} using Google Guava.
*
* @param data the iterable
* @return the size of the iterable
*/
public static int sizeUsingGoogleGuava(final Iterable data) {
return Iterables.size(data);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-2\src\main\java\com\baeldung\collections\iterablesize\IterableSize.java | 1 |
请完成以下Java代码 | default Instant getExpiresAt() {
return getClaimAsInstant(OAuth2TokenClaimNames.EXP);
}
/**
* Returns the Not Before {@code (nbf)} claim which identifies the time before which
* the OAuth 2.0 Token MUST NOT be accepted for processing.
* @return the Not Before time before which the OAuth 2.0 Token MUST NOT be accepted
* for processing
*/
default Instant getNotBefore() {
return getClaimAsInstant(OAuth2TokenClaimNames.NBF);
}
/**
* Returns the Issued at {@code (iat)} claim which identifies the time at which the
* OAuth 2.0 Token was issued. | * @return the Issued at claim which identifies the time at which the OAuth 2.0 Token
* was issued
*/
default Instant getIssuedAt() {
return getClaimAsInstant(OAuth2TokenClaimNames.IAT);
}
/**
* Returns the ID {@code (jti)} claim which provides a unique identifier for the OAuth
* 2.0 Token.
* @return the ID claim which provides a unique identifier for the OAuth 2.0 Token
*/
default String getId() {
return getClaimAsString(OAuth2TokenClaimNames.JTI);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimAccessor.java | 1 |
请完成以下Spring Boot application配置 | # # H2 database configuration steps
#debug=true
#
##H2 embedded static database
#datasource.security.driver-class-name=org.h2.Driver
#
## H2 configuration using hibernate.
#datasource.security.url=jdbc:h2:mem:management;DB_CLOSE_DELAY=-1
#datasource.security.username=sa
#datasource.security.password=
#
## Security configuration on system
#datasource.security.initialize=true
#
## H2 database configuration, using embedded DB
#datasource.orders.driver-class-name=org.h2.Driver
#datasource.orders.url=jdbc:h2:mem:ordersdb;DB_CLOSE_DELAY=-1
#datasource.orders.username=sa
#datasource.orders.password=
#
## Initialize db (any DB types are will be true)
#datasource.orders.initialize=true
#
## Hibernate configuration (auto-update, create.)
#spring.jpa.hibernate.ddl-auto=update
#
## DB represents debuging results.
#spring.jpa.show-sql=true
# MySQL database configuration
debug=true
Database
datasource.security.driver-class-name=com.mysql.jdbc.Driver
datasource.security.url=jdbc:mysql://localhost:3306/management
datasource | .security.username=root
datasource.security.password=posilka2020
# Secutiry datasource configuration
datasource.security.initialize=false
# Configuration MySQL
datasource.orders.driver-class-name=com.mysql.jdbc.Driver
datasource.orders.url=jdbc:mysql://localhost:3306/ordersdb
datasource.orders.username=root
datasource.orders.password=posilka2020
datasource.orders.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true | repos\Spring-Boot-Advanced-Projects-main\Springboot-Multiple-DataStructure\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setIsBPartnerFlatDiscount (final boolean IsBPartnerFlatDiscount)
{
set_Value (COLUMNNAME_IsBPartnerFlatDiscount, IsBPartnerFlatDiscount);
}
@Override
public boolean isBPartnerFlatDiscount()
{
return get_ValueAsBoolean(COLUMNNAME_IsBPartnerFlatDiscount);
}
@Override
public org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge getM_DiscountSchema_Calculated_Surcharge()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge(final org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge M_DiscountSchema_Calculated_Surcharge)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, org.compiere.model.I_M_DiscountSchema_Calculated_Surcharge.class, M_DiscountSchema_Calculated_Surcharge);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_ID < 1)
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null);
else
set_Value (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override | public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setScript (final @Nullable java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
@Override
public java.lang.String getScript()
{
return get_ValueAsString(COLUMNNAME_Script);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema.java | 1 |
请完成以下Java代码 | public boolean isHasRegion ()
{
Object oo = get_Value(COLUMNNAME_HasRegion);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reverse Local Address Lines.
@param IsAddressLinesLocalReverse
Print Local Address in reverse Order
*/
@Override
public void setIsAddressLinesLocalReverse (boolean IsAddressLinesLocalReverse)
{
set_Value (COLUMNNAME_IsAddressLinesLocalReverse, Boolean.valueOf(IsAddressLinesLocalReverse));
}
/** Get Reverse Local Address Lines.
@return Print Local Address in reverse Order
*/
@Override
public boolean isAddressLinesLocalReverse ()
{
Object oo = get_Value(COLUMNNAME_IsAddressLinesLocalReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reverse Address Lines.
@param IsAddressLinesReverse
Print Address in reverse Order
*/
@Override
public void setIsAddressLinesReverse (boolean IsAddressLinesReverse)
{
set_Value (COLUMNNAME_IsAddressLinesReverse, Boolean.valueOf(IsAddressLinesReverse));
}
/** Get Reverse Address Lines.
@return Print Address in reverse Order
*/
@Override
public boolean isAddressLinesReverse ()
{
Object oo = get_Value(COLUMNNAME_IsAddressLinesReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Media Size.
@param MediaSize
Java Media Size
*/
@Override
public void setMediaSize (java.lang.String MediaSize)
{
set_Value (COLUMNNAME_MediaSize, MediaSize);
}
/** Get Media Size.
@return Java Media Size
*/
@Override
public java.lang.String getMediaSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_MediaSize);
} | /** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Region.
@param RegionName
Name of the Region
*/
@Override
public void setRegionName (java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name of the Region
*/
@Override
public java.lang.String getRegionName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RegionName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MvcConfig implements WebMvcConfigurer {
public MvcConfig() {
super();
}
//
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true)
.dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true)
.build()));
messageConverters.add(createXmlHttpMessageConverter());
// messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new ProtobufHttpMessageConverter());
messageConverters.add(new KryoHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
}
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); | xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
} | repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\config\MvcConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProductUpsertRequestProducer
{
@NonNull
String orgCode;
@NonNull
List<LineItem> articles;
@NonNull
ProductRequestProducerResult.ProductRequestProducerResultBuilder resultBuilder;
@Builder
public ProductUpsertRequestProducer(
@NonNull final String orgCode,
@NonNull final List<LineItem> articles)
{
this.orgCode = orgCode;
this.articles = articles;
this.resultBuilder = ProductRequestProducerResult.builder();
}
@NonNull
public Optional<ProductRequestProducerResult> run()
{
if(articles.isEmpty())
{
return Optional.empty();
}
final JsonRequestProductUpsert jsonRequestProductUpsert = JsonRequestProductUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(getProductItems())
.build(); | resultBuilder.jsonRequestProductUpsert(jsonRequestProductUpsert);
return Optional.of(resultBuilder.build());
}
@NonNull
private List<JsonRequestProductUpsertItem> getProductItems()
{
return articles.stream()
.map(this::mapArticleToProductRequestItem)
.collect(Collectors.toList());
}
@NonNull
private JsonRequestProductUpsertItem mapArticleToProductRequestItem(@NonNull final LineItem article)
{
final String externalIdentifier = EbayUtils.formatExternalId(article.getSku());
final JsonRequestProduct jsonRequestProduct = new JsonRequestProduct();
jsonRequestProduct.setCode(article.getSku());
jsonRequestProduct.setName(article.getTitle());
jsonRequestProduct.setType(JsonRequestProduct.Type.ITEM);
jsonRequestProduct.setUomCode(EbayConstants.DEFAULT_PRODUCT_UOM);
return JsonRequestProductUpsertItem.builder()
.productIdentifier(externalIdentifier)
.requestProduct(jsonRequestProduct)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\product\ProductUpsertRequestProducer.java | 2 |
请完成以下Java代码 | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTypeName() {
if(value != null) {
return value.getType().getName();
}
else {
return null;
}
}
public String getName() {
return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
} | public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
} | public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java | 2 |
请完成以下Java代码 | public final BigDecimal getQualityAdjustmentForDateOrNull(final Date date)
{
if(date.after(getValidToDate()))
{
return maximumQualityAdjustment;
}
final int month = TimeUtil.asCalendar(date).get(Calendar.MONTH);
return getQualityAdjustmentForMonthOrNull(month);
}
/**
* @return zero if the given percentage is below 10, <code>0.06</code> otherwise
*/
@Override
public BigDecimal getScrapProcessingFeeForPercentage(final BigDecimal percentage)
{
if (percentage.compareTo(getScrapPercentageTreshold()) < 0)
{
return BigDecimal.ZERO;
}
else
{
return scrapFee;
}
}
@Override
public BigDecimal getScrapPercentageTreshold()
{
return scrapPercentageTreshold;
}
@Override
public boolean isFeeForProducedMaterial(final I_M_Product m_Product)
{
return productWithProcessingFee.getM_Product_ID() == m_Product.getM_Product_ID()
&& !feeProductPercentage2fee.isEmpty();
}
@Override
public BigDecimal getFeeForProducedMaterial(final I_M_Product m_Product, final BigDecimal percentage)
{
final List<BigDecimal> percentages = new ArrayList<>(feeProductPercentage2fee.keySet());
// iterating from first to 2nd-last
for (int i = 0; i < percentages.size() - 1; i++)
{
final BigDecimal currentPercentage = percentages.get(i);
final BigDecimal nextPercentage = percentages.get(i + 1); | if (currentPercentage.compareTo(percentage) <= 0
&& nextPercentage.compareTo(percentage) > 0)
{
// found it: 'percentage' is in the interval that starts with 'currentPercentage'
return feeProductPercentage2fee.get(currentPercentage);
}
}
final BigDecimal lastInterval = percentages.get(percentages.size() - 1);
return feeProductPercentage2fee.get(lastInterval);
}
@Override
public int getOverallNumberOfInvoicings()
{
return numberOfInspections;
}
@Override
public BigDecimal getWithholdingPercent()
{
return Env.ONEHUNDRED.divide(BigDecimal.valueOf(numberOfInspections), 2, RoundingMode.HALF_UP);
}
@Override
public Currency getCurrency()
{
return currency;
}
@Override
public I_M_Product getRegularPPOrderProduct()
{
return regularPPOrderProduct;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public Timestamp getValidToDate()
{
return validToDate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\RecordBackedQualityBasedConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CRUDController {
@GetMapping
public List<CrudInput> read(@RequestBody @Valid CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
returnList.add(crudInput);
return returnList;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri());
return httpHeaders;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK) | HttpHeaders delete(@PathVariable("id") long id) {
return new HttpHeaders();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
}
@PatchMapping("/{id}")
public List<CrudInput> patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
crudInput.setId(id);
returnList.add(crudInput);
return returnList;
}
} | repos\tutorials-master\spring-5-rest-docs\src\main\java\com\baeldung\restdocs\CRUDController.java | 2 |
请完成以下Java代码 | protected void initializeActivity(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
super.initializeActivity(element, activity, context);
initializeResultVariable(element, activity, context);
initializeDecisionTableResultMapper(element, activity, context);
}
protected void initializeResultVariable(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask decisionTask = getDefinition(element);
DmnDecisionTaskActivityBehavior behavior = getActivityBehavior(activity);
String resultVariable = decisionTask.getCamundaResultVariable();
behavior.setResultVariable(resultVariable);
}
protected void initializeDecisionTableResultMapper(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask decisionTask = getDefinition(element);
DmnDecisionTaskActivityBehavior behavior = getActivityBehavior(activity);
String mapper = decisionTask.getCamundaMapDecisionResult();
DecisionResultMapper decisionResultMapper = getDecisionResultMapperForName(mapper);
behavior.setDecisionTableResultMapper(decisionResultMapper);
}
protected BaseCallableElement createCallableElement() {
return new BaseCallableElement();
}
protected CmmnActivityBehavior getActivityBehavior() {
return new DmnDecisionTaskActivityBehavior();
}
protected DmnDecisionTaskActivityBehavior getActivityBehavior(CmmnActivity activity) {
return (DmnDecisionTaskActivityBehavior) activity.getActivityBehavior();
}
protected String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask definition = getDefinition(element);
String decision = definition.getDecision();
if (decision == null) {
DecisionRefExpression decisionExpression = definition.getDecisionExpression();
if (decisionExpression != null) {
decision = decisionExpression.getText(); | }
}
return decision;
}
protected String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask definition = getDefinition(element);
return definition.getCamundaDecisionBinding();
}
protected String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask definition = getDefinition(element);
return definition.getCamundaDecisionVersion();
}
protected String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
DecisionTask definition = getDefinition(element);
return definition.getCamundaDecisionTenantId();
}
protected DecisionTask getDefinition(CmmnElement element) {
return (DecisionTask) super.getDefinition(element);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\DecisionTaskItemHandler.java | 1 |
请完成以下Java代码 | public KeyValues getHighCardinalityKeyValues(AuthorizationObservationContext<?> context) {
return KeyValues.of("spring.security.authentication.authorities", getAuthorities(context))
.and("spring.security.authorization.decision.details", getDecisionDetails(context));
}
@Override
public boolean supportsContext(Observation.Context context) {
return context instanceof AuthorizationObservationContext<?>;
}
private String getAuthenticationType(AuthorizationObservationContext<?> context) {
if (context.getAuthentication() == null) {
return "n/a";
}
return context.getAuthentication().getClass().getSimpleName();
}
private String getObjectType(AuthorizationObservationContext<?> context) {
if (context.getObject() == null) {
return "unknown";
}
if (context.getObject() instanceof MethodInvocation) {
return "method";
}
String className = context.getObject().getClass().getSimpleName();
if (className.contains("Method")) {
return "method";
}
if (className.contains("Request")) {
return "request";
}
if (className.contains("Message")) {
return "message";
}
if (className.contains("Exchange")) {
return "exchange";
} | return className;
}
private String getAuthorizationDecision(AuthorizationObservationContext<?> context) {
if (context.getAuthorizationResult() == null) {
return "unknown";
}
return String.valueOf(context.getAuthorizationResult().isGranted());
}
private String getAuthorities(AuthorizationObservationContext<?> context) {
if (context.getAuthentication() == null) {
return "n/a";
}
return String.valueOf(context.getAuthentication().getAuthorities());
}
private String getDecisionDetails(AuthorizationObservationContext<?> context) {
if (context.getAuthorizationResult() == null) {
return "unknown";
}
AuthorizationResult decision = context.getAuthorizationResult();
return String.valueOf(decision);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationObservationConvention.java | 1 |
请完成以下Java代码 | public class User {
private String name;
private int age;
private String pass;
public User(String name, int age, String pass) {
this.name = name;
this.age = age;
this.pass = pass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age; | }
public void setAge(int age) {
this.age = age;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return ("name=" + this.name + ",age=" + this.age + ",pass=" + this.pass);
}
} | repos\spring-boot-leaning-master\1.x\第05课:模板引擎 Thymeleaf\spring-boot-thymeleaf\src\main\java\com\neo\domain\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected OtaPackage prepare(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackage oldOtaPackage, OtaPackageExportData exportData, IdProvider idProvider) {
otaPackage.setDeviceProfileId(idProvider.getInternalId(otaPackage.getDeviceProfileId()));
return otaPackage;
}
@Override
protected OtaPackage findExistingEntity(EntitiesImportCtx ctx, OtaPackage otaPackage, IdProvider idProvider) {
OtaPackage existingOtaPackage = super.findExistingEntity(ctx, otaPackage, idProvider);
if (existingOtaPackage == null && ctx.isFindExistingByName()) {
existingOtaPackage = otaPackageService.findOtaPackageByTenantIdAndTitleAndVersion(ctx.getTenantId(), otaPackage.getTitle(), otaPackage.getVersion());
}
return existingOtaPackage;
}
@Override
protected OtaPackage deepCopy(OtaPackage otaPackage) {
return new OtaPackage(otaPackage);
} | @Override
protected OtaPackage saveOrUpdate(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackageExportData exportData, IdProvider idProvider, CompareResult compareResult) {
if (otaPackage.hasUrl()) {
OtaPackageInfo info = new OtaPackageInfo(otaPackage);
return new OtaPackage(otaPackageService.saveOtaPackageInfo(info, info.hasUrl()));
}
return otaPackageService.saveOtaPackage(otaPackage);
}
@Override
public EntityType getEntityType() {
return EntityType.OTA_PACKAGE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\OtaPackageImportService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractProcessAutoDeploymentStrategy extends CommonAutoDeploymentStrategy<ProcessEngine> {
public AbstractProcessAutoDeploymentStrategy() {
super();
}
public AbstractProcessAutoDeploymentStrategy(CommonAutoDeploymentProperties deploymentProperties) {
super(deploymentProperties);
}
@Override
protected LockManager getLockManager(ProcessEngine engine, String deploymentNameHint) {
return engine.getManagementService().getLockManager(determineLockName(deploymentNameHint));
}
protected void addResource(Resource resource, DeploymentBuilder deploymentBuilder) {
String resourceName = determineResourceName(resource);
addResource(resource, resourceName, deploymentBuilder);
} | protected void addResource(Resource resource, String resourceName, DeploymentBuilder deploymentBuilder) {
try (InputStream inputStream = resource.getInputStream()) {
if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
try (ZipInputStream zipStream = new ZipInputStream(inputStream)) {
deploymentBuilder.addZipInputStream(zipStream);
}
} else {
deploymentBuilder.addInputStream(resourceName, inputStream);
}
} catch (IOException ex) {
throw new UncheckedIOException("Failed to read resource " + resource, ex);
}
}
} | repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\configurator\AbstractProcessAutoDeploymentStrategy.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getGroupId() {
return this.groupId;
}
void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* The type of the source. Usually this is the fully qualified name of a class that
* defines configuration items. This class may or may not be available at runtime.
* @return the type
*/
public String getType() {
return this.type;
}
void setType(String type) {
this.type = type;
}
/**
* A description of this source, if any. Can be multi-lines.
* @return the description
* @see #getShortDescription()
*/
public String getDescription() {
return this.description;
}
void setDescription(String description) {
this.description = description;
}
/**
* A single-line, single-sentence description of this source, if any.
* @return the short description
* @see #getDescription()
*/
public String getShortDescription() {
return this.shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
* The type where this source is defined. This can be identical to the
* {@link #getType() type} if the source is self-defined.
* @return the source type
*/
public String getSourceType() {
return this.sourceType;
} | void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
/**
* The method name that defines this source, if any.
* @return the source method
*/
public String getSourceMethod() {
return this.sourceMethod;
}
void setSourceMethod(String sourceMethod) {
this.sourceMethod = sourceMethod;
}
/**
* Return the properties defined by this source.
* @return the properties
*/
public Map<String, ConfigurationMetadataProperty> getProperties() {
return this.properties;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataSource.java | 2 |
请完成以下Java代码 | public class FreshQtyOnHandDAO implements IFreshQtyOnHandDAO
{
@Override
public List<I_Fresh_QtyOnHand_Line> retrieveLines(final I_Fresh_QtyOnHand qtyOnHandHeader)
{
final List<I_Fresh_QtyOnHand_Line> result = Services.get(IQueryBL.class)
.createQueryBuilder(I_Fresh_QtyOnHand_Line.class, qtyOnHandHeader)
.addEqualsFilter(I_Fresh_QtyOnHand_Line.COLUMN_Fresh_QtyOnHand_ID, qtyOnHandHeader.getFresh_QtyOnHand_ID())
.create()
.list();
// Optimization: set parent
for (final I_Fresh_QtyOnHand_Line line : result)
{
line.setFresh_QtyOnHand(qtyOnHandHeader);
} | return result;
}
@NonNull
public I_Fresh_QtyOnHand getById(@NonNull final FreshQtyOnHandId freshQtyOnHandId)
{
final I_Fresh_QtyOnHand freshQtyOnHandRecord = InterfaceWrapperHelper.load(freshQtyOnHandId, I_Fresh_QtyOnHand.class);
if (freshQtyOnHandRecord == null)
{
throw new AdempiereException("@NotFound@: " + freshQtyOnHandId);
}
return freshQtyOnHandRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\freshQtyOnHand\api\impl\FreshQtyOnHandDAO.java | 1 |
请完成以下Java代码 | public boolean isMarshallableAsElement() {
return true;
}
}
/**
* Marshall a list of objects.
*/
private static class ObjectListMarshaller extends AttributeMarshaller {
private ObjectListMarshaller() {}
@Override
public boolean isMarshallableAsElement() {
return true;
}
@Override
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
assert attribute instanceof ObjectListAttributeDefinition;
ObjectListAttributeDefinition list = ((ObjectListAttributeDefinition) attribute);
ObjectTypeAttributeDefinition objectType = (ObjectTypeAttributeDefinition) CustomMarshaller.getValueType(list, ObjectListAttributeDefinition.class);
AttributeDefinition[] valueTypes = CustomMarshaller.getValueTypes(list, ObjectTypeAttributeDefinition.class); | if (resourceModel.hasDefined(attribute.getName())) {
writer.writeStartElement(attribute.getXmlName());
for (ModelNode element: resourceModel.get(attribute.getName()).asList()) {
writer.writeStartElement(objectType.getXmlName());
for (AttributeDefinition valueType : valueTypes) {
valueType.getMarshaller().marshallAsElement(valueType, element, false, writer);
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
public static final AttributeAsElementMarshaller ATTRIBUTE_AS_ELEMENT = new AttributeAsElementMarshaller();
public static final PluginObjectTypeMarshaller OBJECT_AS_ELEMENT = new PluginObjectTypeMarshaller();
public static final ObjectListMarshaller OBJECT_LIST = new ObjectListMarshaller();
public static final PropertiesAttributeMarshaller PROPERTIES_MARSHALLER = new PropertiesAttributeMarshaller();
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\util\CustomMarshaller.java | 1 |
请完成以下Java代码 | public class API_Audit_Repeat extends JavaProcess implements IProcessPrecondition
{
private final ApiRequestReplayService apiRequestReplayService = SpringContextHolder.instance.getBean(ApiRequestReplayService.class);
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final static String ONLY_WITH_ERROR = "IsOnlyWithError";
@Param(parameterName = ONLY_WITH_ERROR)
private boolean isOnlyWithError;
@Override
protected String doIt() throws Exception
{
final ApiRequestIterator apiRequestIterator = getSelectedRequests();
apiRequestReplayService.replayApiRequests(apiRequestIterator);
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@NonNull
private ApiRequestIterator getSelectedRequests()
{
final IQueryBuilder<I_API_Request_Audit> selectedApiRequestsQueryBuilder = retrieveSelectedRecordsQueryBuilder(I_API_Request_Audit.class); | if (isOnlyWithError)
{
selectedApiRequestsQueryBuilder.addEqualsFilter(I_API_Request_Audit.COLUMNNAME_Status, Status.ERROR.getCode());
}
final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_API_Request_Audit.class)
.addColumnAscending(I_API_Request_Audit.COLUMNNAME_Time)
.createQueryOrderBy();
final Iterator<I_API_Request_Audit> timeSortedApiRequests = selectedApiRequestsQueryBuilder.create()
.setOrderBy(orderBy)
.iterate(I_API_Request_Audit.class);
return ApiRequestIterator.of(timeSortedApiRequests, ApiRequestAuditRepository::recordToRequestAudit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\process\API_Audit_Repeat.java | 1 |
请完成以下Java代码 | public class BOMCostPrice
{
@Getter
private final ProductId productId;
@Getter
private final UomId uomId;
private final HashMap<CostElementId, BOMCostElementPrice> pricesByElementId;
@Builder
private BOMCostPrice(
@NonNull final ProductId productId,
@NonNull final UomId uomId,
@NonNull @Singular final Collection<BOMCostElementPrice> costElementPrices)
{
if (!costElementPrices.isEmpty())
{
final UomId priceUomId = BOMCostElementPrice.extractUniqueUomId(costElementPrices);
if (!UomId.equals(uomId, priceUomId))
{
throw new AdempiereException("Expected " + uomId + " to " + costElementPrices);
}
}
this.productId = productId;
this.uomId = uomId;
pricesByElementId = costElementPrices
.stream()
.collect(GuavaCollectors.toHashMapByKey(BOMCostElementPrice::getCostElementId));
}
public Stream<CostElementId> streamCostElementIds()
{
return pricesByElementId.keySet().stream();
}
public BOMCostElementPrice getCostElementPriceOrNull(@NonNull final CostElementId costElementId)
{
return pricesByElementId.get(costElementId);
}
public void clearOwnCostPrice(@NonNull final CostElementId costElementId)
{
final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId);
if (elementCostPrice != null)
{
elementCostPrice.clearOwnCostPrice();
}
} | public void setComponentsCostPrice(
@NonNull final CostAmount costPrice,
@NonNull final CostElementId costElementId)
{
pricesByElementId.computeIfAbsent(costElementId, k -> BOMCostElementPrice.zero(costElementId, costPrice.getCurrencyId(), uomId))
.setComponentsCostPrice(costPrice);
}
public void clearComponentsCostPrice(@NonNull final CostElementId costElementId)
{
final BOMCostElementPrice elementCostPrice = getCostElementPriceOrNull(costElementId);
if (elementCostPrice != null)
{
elementCostPrice.clearComponentsCostPrice();
}
}
ImmutableList<BOMCostElementPrice> getElementPrices()
{
return ImmutableList.copyOf(pricesByElementId.values());
}
<T extends RepoIdAware> Stream<T> streamIds(@NonNull final Class<T> idType)
{
return getElementPrices()
.stream()
.map(elementCostPrice -> elementCostPrice.getId(idType))
.filter(Objects::nonNull);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMCostPrice.java | 1 |
请完成以下Java代码 | public void startOrStopEmbeddedClient(@NonNull final I_AD_Printer_Config printerConfig)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(printerConfig);
final String hostKey = printClientsBL.getHostKeyOrNull(ctx);
if (Check.isBlank(hostKey) || !Objects.equals(hostKey, printerConfig.getConfigHostKey()))
{
return; // 'printerConfig' does not belong the host which we run on
}
if (!Ini.isSwingClient())
{
return; // task 08569: we only start the embedded client is we are inside the swing client (and *not* when running in the server)
}
final IPrintingClientDelegate printingClientDelegate = Services.get(IPrintingClientDelegate.class);
if (printerConfig.getAD_Printer_Config_Shared_ID() > 0
&& printingClientDelegate.isStarted())
{
printingClientDelegate.stop();
}
else if (!printingClientDelegate.isStarted())
{
printingClientDelegate.start();
}
} | /**
* Needed because we want to order by ConfigHostKey and "unspecified" shall always be last.
*/
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_AD_Printer_Config.COLUMNNAME_ConfigHostKey)
public void trimBlankHostKeyToNull(@NonNull final I_AD_Printer_Config printerConfig)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(printerConfig))
{
final String normalizedString = StringUtils.trimBlankToNull(printerConfig.getConfigHostKey());
printerConfig.setConfigHostKey(normalizedString);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_Printer_Config.java | 1 |
请完成以下Java代码 | public Mono<String> getData(String stockId) {
return webClient.get()
.uri(PATH_BY_ID, stockId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.error(new ServiceException("Server error", response.statusCode().value())))
.bodyToMono(String.class)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
.filter(throwable -> throwable instanceof ServiceException)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
throw new ServiceException("External Service failed to process after max retries", HttpStatus.SERVICE_UNAVAILABLE.value());
}));
}
public Mono<String> getDataWithRetry(String stockId) {
return webClient.get()
.uri(PATH_BY_ID, stockId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.max(3));
}
public Mono<String> getDataWithRetryFixedDelay(String stockId) {
return webClient.get()
.uri(PATH_BY_ID, stockId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(2)));
} | public Mono<String> getDataWithRetryBackoff(String stockId) {
return webClient.get()
.uri(PATH_BY_ID, stockId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2)));
}
public Mono<String> getDataWithRetryBackoffJitter(String stockId) {
return webClient.get()
.uri(PATH_BY_ID, stockId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
.jitter(1));
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\retry\ExternalConnector.java | 1 |
请完成以下Java代码 | public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getHistoryConfiguration() {
return historyConfiguration; | }
public void setHistoryConfiguration(String historicConfiguration) {
this.historyConfiguration = historicConfiguration;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\IncidentContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Class getObjectType() {
return MySpringShiroFilter.class;
}
@Override
protected AbstractShiroFilter createInstance() throws Exception {
SecurityManager securityManager = getSecurityManager();
if (securityManager == null) {
String msg = "SecurityManager property must be set.";
throw new BeanInitializationException(msg);
}
if (!(securityManager instanceof WebSecurityManager)) {
String msg = "The security manager does not implement the WebSecurityManager interface.";
throw new BeanInitializationException(msg);
}
FilterChainManager manager = createFilterChainManager();
//Expose the constructed FilterChainManager by first wrapping it in a
// FilterChainResolver implementation. The AbstractShiroFilter implementations
// do not know about FilterChainManagers - only resolvers:
PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
chainResolver.setFilterChainManager(manager);
Map<String, Filter> filterMap = manager.getFilters();
Filter invalidRequestFilter = filterMap.get(DefaultFilter.invalidRequest.name());
if (invalidRequestFilter instanceof InvalidRequestFilter) {
//此处是关键,设置false跳过URL携带中文400,servletPath中文校验bug
((InvalidRequestFilter) invalidRequestFilter).setBlockNonAscii(false);
} | //Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built
//FilterChainResolver. It doesn't matter that the instance is an anonymous inner class
//here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts
//injection of the SecurityManager and FilterChainResolver:
return new MySpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
}
private static final class MySpringShiroFilter extends AbstractShiroFilter {
protected MySpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
} else {
this.setSecurityManager(webSecurityManager);
if (resolver != null) {
this.setFilterChainResolver(resolver);
}
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\filters\CustomShiroFilterFactoryBean.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AopConfig {
/**
* Aspects monitor multiple annotations, because one annotation is Check and multiple annotations are compiled to CheckContainer
*/
@Pointcut("@annotation(com.et.annotation.CheckContainer) || @annotation(com.et.annotation.Check)")
public void pointcut() {
}
@Before("pointcut()")
public Object before(JoinPoint point) {
//get params
Object[] args = point.getArgs();
//get param name
Method method = ((MethodSignature) point.getSignature()).getMethod();
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
CheckContainer checkContainer = method.getDeclaredAnnotation(CheckContainer.class);
List<Check> value = new ArrayList<>();
if (checkContainer != null) {
value.addAll(Arrays.asList(checkContainer.value()));
} else {
Check check = method.getDeclaredAnnotation(Check.class);
value.add(check); | }
for (int i = 0; i < value.size(); i++) {
Check check = value.get(i);
String ex = check.ex();
//In the rule engine, null is represented by nil
ex = ex.replaceAll("null", "nil");
String msg = check.msg();
if (StringUtils.isEmpty(msg)) {
msg = "server exception...";
}
Map<String, Object> map = new HashMap<>(16);
for (int j = 0; j < paramNames.length; j++) {
//Prevent index out of bounds
if (j > args.length) {
continue;
}
map.put(paramNames[j], args[j]);
}
Boolean result = (Boolean) AviatorEvaluator.execute(ex, map);
if (!result) {
throw new UserFriendlyException(msg);
}
}
return null;
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\annotation\AopConfig.java | 2 |
请完成以下Java代码 | public class RelationsSearchParameters {
@Schema(description = "Root entity id to start search from.", example = "784f394c-42b6-435a-983c-b7beff2784f9")
private UUID rootId;
@Schema(description = "Type of the root entity.")
private EntityType rootType;
@Schema(description = "Type of the root entity.")
private EntitySearchDirection direction;
@Schema(description = "Type of the relation.")
private RelationTypeGroup relationTypeGroup;
@Schema(description = "Maximum level of the search depth.")
private int maxLevel = 1;
@Schema(description = "Fetch entities that match the last level of search. Useful to find Devices that are strictly 'maxLevel' relations away from the root entity.")
private boolean fetchLastLevelOnly;
public RelationsSearchParameters(EntityId entityId, EntitySearchDirection direction, int maxLevel, boolean fetchLastLevelOnly) {
this(entityId, direction, maxLevel, RelationTypeGroup.COMMON, fetchLastLevelOnly);
} | public RelationsSearchParameters(EntityId entityId, EntitySearchDirection direction, int maxLevel, RelationTypeGroup relationTypeGroup, boolean fetchLastLevelOnly) {
this.rootId = entityId.getId();
this.rootType = entityId.getEntityType();
this.direction = direction;
this.maxLevel = maxLevel;
this.relationTypeGroup = relationTypeGroup;
this.fetchLastLevelOnly = fetchLastLevelOnly;
}
@JsonIgnore
public EntityId getEntityId() {
return EntityIdFactory.getByTypeAndUuid(rootType, rootId);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\relation\RelationsSearchParameters.java | 1 |
请完成以下Java代码 | protected List<ProcessEnginePluginXml> getPlugins(ModelNode plugins) {
List<ProcessEnginePluginXml> pluginConfigurations = new ArrayList<>();
if (plugins.isDefined()) {
for (final ModelNode plugin : plugins.asList()) {
ProcessEnginePluginXml processEnginePluginXml = new ProcessEnginePluginXml() {
@Override
public String getPluginClass() {
return plugin.get(Element.PLUGIN_CLASS.getLocalName()).asString();
}
@Override
public Map<String, String> getProperties() {
return ProcessEngineAdd.this.getProperties(plugin.get(Element.PROPERTIES.getLocalName()));
}
};
pluginConfigurations.add(processEnginePluginXml);
} | }
return pluginConfigurations;
}
protected Map<String, String> getProperties(ModelNode properties) {
Map<String, String> propertyMap = new HashMap<>();
if (properties.isDefined()) {
for (Property property : properties.asPropertyList()) {
propertyMap.put(property.getName(), property.getValue().asString());
}
}
return propertyMap;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\ProcessEngineAdd.java | 1 |
请完成以下Java代码 | private void updateShipmentOrderRequestPO(@NonNull final DeliveryOrder deliveryOrder)
{
for (final DeliveryOrderParcel deliveryOrderParcel : deliveryOrder.getDeliveryOrderParcels())
{
final PackageId packageId = deliveryOrderParcel.getPackageId();
final DhlCustomDeliveryData customDeliveryData = DhlCustomDeliveryData.cast(deliveryOrder.getCustomDeliveryData());
final I_DHL_ShipmentOrder shipmentOrder = getShipmentOrderByRequestIdAndPackageId(deliveryOrder.getId().getRepoId(), packageId.getRepoId());
final DhlCustomDeliveryDataDetail deliveryDetail = customDeliveryData.getDetailBySequenceNumber(DhlSequenceNumber.of(shipmentOrder.getDHL_ShipmentOrder_ID()));
final String awb = deliveryDetail.getAwb();
if (awb != null)
{
shipmentOrder.setawb(awb);
}
final byte[] pdfData = deliveryDetail.getPdfLabelData();
if (pdfData != null)
{
shipmentOrder.setPdfLabelData(pdfData);
}
final String trackingUrl = deliveryDetail.getTrackingUrl();
if (trackingUrl != null)
{
shipmentOrder.setTrackingURL(trackingUrl);
}
saveRecord(shipmentOrder);
} | }
@VisibleForTesting
I_DHL_ShipmentOrder getShipmentOrderByRequestIdAndPackageId(final int requestId, final int packageId)
{
return queryBL
.createQueryBuilder(I_DHL_ShipmentOrder.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_DHL_ShipmentOrderRequest_ID, requestId)
.addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_M_Package_ID, packageId)
.create()
.first();
}
public Optional<I_DHL_ShipmentOrder> getShipmentOrderByPackageId(@NonNull final PackageId packageId)
{
return queryBL.createQueryBuilder(I_DHL_ShipmentOrder.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_M_Package_ID, packageId)
.create()
.firstOnlyOptional();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlDeliveryOrderRepository.java | 1 |
请完成以下Java代码 | public void dispose()
{
if (p_data != null)
{
p_data.clear();
}
p_data = null;
m_selectedObject = null;
m_tempData = null;
m_loaded = false;
} // dispose
/**
* Wait until async Load Complete
*/
public void loadComplete()
{
} // loadComplete
/**
* Set lookup model as mandatory, use in loading data
* @param flag
*/
public void setMandatory(boolean flag)
{
m_mandatory = flag;
}
/**
* Is lookup model mandatory
* @return boolean
*/
public boolean isMandatory()
{
return m_mandatory;
}
/**
* Is this lookup model populated
* @return boolean
*/
public boolean isLoaded()
{
return m_loaded;
}
/**
* Returns a list of parameters on which this lookup depends.
*
* Those parameters will be fetched from context on validation time.
*
* @return list of parameter names
*/
public Set<String> getParameters()
{ | return ImmutableSet.of();
}
/**
*
* @return evaluation context
*/
public IValidationContext getValidationContext()
{
return IValidationContext.NULL;
}
/**
* Suggests a valid value for given value
*
* @param value
* @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned
*/
public NamePair suggestValidValue(final NamePair value)
{
return null;
}
/**
* Returns true if given <code>display</code> value was rendered for a not found item.
* To be used together with {@link #getDisplay} methods.
*
* @param display
* @return true if <code>display</code> contains not found markers
*/
public boolean isNotFoundDisplayValue(String display)
{
return false;
}
} // Lookup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReactiveJwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder
.decode(token)
.doOnError(e -> {
if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (e.getMessage().contains("Failed to validate the token")) {
metersService.trackTokenInvalidSignature();
} else if (
e.getMessage().contains("Invalid JWT serialization:") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE header:")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT reactive error {}", e.getMessage());
}
});
} catch (Exception e) {
if (e.getMessage().contains("An error occurred while attempting to decode the Jwt")) {
metersService.trackTokenMalformed();
} else if (e.getMessage().contains("Failed to validate the token")) {
metersService.trackTokenInvalidSignature();
} else {
log.error("Unknown JWT error {}", e.getMessage());
}
throw e;
} | };
}
@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public ReactiveJwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(
new ReactiveJwtGrantedAuthoritiesConverterAdapter(grantedAuthoritiesConverter)
);
return jwtAuthenticationConverter;
}
private SecretKey getSecretKey() {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\SecurityJwtConfiguration.java | 2 |
请完成以下Spring Boot application配置 | ##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### 项目启动端口 ###################
server.port: 8092
################### spring配置 ###################
spring:
profiles:
active: dev
---
#####################################################################
######################## 开发环境profile ############# | #############
#####################################################################
spring:
profiles: dev
logging:
level:
root: INFO
com.xncoding: DEBUG
path: D:/logs/springboot-aop | repos\SpringBootBucket-master\springboot-aop\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public StatusUpdater timeout(Duration timeout) {
this.timeout = timeout;
return this;
}
public Mono<Void> updateStatus(InstanceId id) {
return this.repository.computeIfPresent(id, (key, instance) -> this.doUpdateStatus(instance)).then();
}
protected Mono<Instance> doUpdateStatus(Instance instance) {
if (!instance.isRegistered()) {
return Mono.empty();
}
log.debug("Update status for {}", instance);
return this.instanceWebClient.instance(instance)
.get()
.uri(Endpoint.HEALTH)
.exchangeToMono(this::convertStatusInfo)
.log(log.getName(), Level.FINEST)
.timeout(getTimeoutWithMargin())
.doOnError((ex) -> logError(instance, ex))
.onErrorResume(this::handleError)
.map(instance::withStatusInfo);
}
/*
* return a timeout less than the given one to prevent backdrops in concurrent get
* request. This prevents flakiness of health checks.
*/
private Duration getTimeoutWithMargin() {
return this.timeout.minusSeconds(1).abs();
}
protected Mono<StatusInfo> convertStatusInfo(ClientResponse response) {
boolean hasCompatibleContentType = response.headers()
.contentType()
.filter((mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON)
|| this.apiMediaTypeHandler.isApiMediaType(mt))
.isPresent();
StatusInfo statusInfoFromStatus = this.getStatusInfoFromStatus(response.statusCode(), emptyMap());
if (hasCompatibleContentType) {
return response.bodyToMono(RESPONSE_TYPE).map((body) -> {
if (body.get("status") instanceof String) {
return StatusInfo.from(body);
}
return getStatusInfoFromStatus(response.statusCode(), body);
}).defaultIfEmpty(statusInfoFromStatus);
}
return response.releaseBody().then(Mono.just(statusInfoFromStatus));
}
@SuppressWarnings("unchecked")
protected StatusInfo getStatusInfoFromStatus(HttpStatusCode httpStatus, Map<String, ?> body) {
if (httpStatus.is2xxSuccessful()) {
return StatusInfo.ofUp();
}
Map<String, Object> details = new LinkedHashMap<>(); | details.put("status", httpStatus.value());
details.put("error", Objects.requireNonNull(HttpStatus.resolve(httpStatus.value())).getReasonPhrase());
if (body.get("details") instanceof Map) {
details.putAll((Map<? extends String, ?>) body.get("details"));
}
else {
details.putAll(body);
}
return StatusInfo.ofDown(details);
}
protected Mono<StatusInfo> handleError(Throwable ex) {
Map<String, Object> details = new HashMap<>();
details.put("message", ex.getMessage());
details.put("exception", ex.getClass().getName());
return Mono.just(StatusInfo.ofOffline(details));
}
protected void logError(Instance instance, Throwable ex) {
if (instance.getStatusInfo().isOffline()) {
log.debug("Couldn't retrieve status for {}", instance, ex);
}
else {
log.info("Couldn't retrieve status for {}", instance, ex);
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\StatusUpdater.java | 2 |
请完成以下Java代码 | public int getSpeedKmPerS() {
return speedKmPerS;
}
public void setSpeedKmPerS(int speedKmPerS) {
this.speedKmPerS = speedKmPerS;
}
}
class Coordinates {
@JsonProperty("latitude")
private double latitude;
@JsonProperty("longitude")
private double longitude;
public double getLatitude() {
return latitude; | }
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
} | repos\tutorials-master\json-modules\json-operations\src\main\java\com\baeldung\sorting\SolarEvent.java | 1 |
请完成以下Java代码 | public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false; | }
Role role = (Role) obj;
if (!role.equals(role.name)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
return builder.toString();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\Role.java | 1 |
请完成以下Java代码 | public String toStandardFormat() {
return this.property;
}
private static String validateFormat(String property) {
for (char c : property.toCharArray()) {
if (Character.isUpperCase(c)) {
throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case");
}
if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) {
throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'");
}
}
return property;
}
@Override
public int compareTo(VersionProperty o) {
return this.property.compareTo(o.property);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false; | }
VersionProperty that = (VersionProperty) o;
return this.internal == that.internal && this.property.equals(that.property);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.internal);
}
@Override
public String toString() {
return this.property;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionProperty.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig extends AbstractHttpConfigurer<SecurityConfig, HttpSecurity> {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(HttpSecurity http) {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http.addFilterBefore(authenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class);
}
public static SecurityConfig securityConfig() {
return new SecurityConfig();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeRequests()
.requestMatchers("/css/**", "/index")
.permitAll()
.requestMatchers("/user/**")
.authenticated()
.and()
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login"))
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/logout"))
.authenticationProvider(authProvider()) | .with(securityConfig(), Customizer.withDefaults());
return http.build();
}
public CustomAuthenticationFilter authenticationFilter(AuthenticationManager authenticationManager) {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager);
filter.setAuthenticationFailureHandler(failureHandler());
filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
return filter;
}
public AuthenticationProvider authProvider() {
return new CustomUserDetailsAuthenticationProvider(passwordEncoder, userDetailsService);
}
public SimpleUrlAuthenticationFailureHandler failureHandler() {
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TimeBookingRepository
{
private final IQueryBL queryBL;
public TimeBookingRepository(final IQueryBL queryBL)
{
this.queryBL = queryBL;
}
public TimeBookingId save(@NonNull final TimeBooking timeBooking)
{
final I_S_TimeBooking record = InterfaceWrapperHelper.loadOrNew(timeBooking.getTimeBookingId(), I_S_TimeBooking.class);
record.setAD_Org_ID(timeBooking.getOrgId().getRepoId());
record.setAD_User_Performing_ID(timeBooking.getPerformingUserId().getRepoId());
record.setS_Issue_ID(timeBooking.getIssueId().getRepoId());
record.setHoursAndMinutes(timeBooking.getHoursAndMins());
record.setBookedSeconds(BigDecimal.valueOf(timeBooking.getBookedSeconds()));
record.setBookedDate(Timestamp.from(timeBooking.getBookedDate()));
InterfaceWrapperHelper.saveRecord(record);
return TimeBookingId.ofRepoId(record.getS_TimeBooking_ID());
}
public Optional<TimeBooking> getByIdOptional(@NonNull final TimeBookingId timeBookingId)
{
return queryBL
.createQueryBuilder(I_S_TimeBooking.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_TimeBooking_ID, timeBookingId.getRepoId())
.create()
.firstOnlyOptional(I_S_TimeBooking.class)
.map(this::buildTimeBooking);
}
public ImmutableList<TimeBooking> getAllByIssueId(@NonNull final IssueId issueId) | {
return queryBL
.createQueryBuilder(I_S_TimeBooking.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_Issue_ID, issueId.getRepoId())
.create()
.list()
.stream()
.map(this::buildTimeBooking)
.collect(ImmutableList.toImmutableList());
}
private TimeBooking buildTimeBooking(@NonNull final I_S_TimeBooking record)
{
return TimeBooking.builder()
.timeBookingId(TimeBookingId.ofRepoId(record.getS_TimeBooking_ID()))
.issueId(IssueId.ofRepoId(record.getS_Issue_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.performingUserId(UserId.ofRepoId(record.getAD_User_Performing_ID()))
.bookedDate(record.getBookedDate().toInstant())
.bookedSeconds(record.getBookedSeconds().longValue())
.hoursAndMins(record.getHoursAndMinutes())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\TimeBookingRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class Saml2ResponseValidatorResult {
static final Saml2ResponseValidatorResult NO_ERRORS = new Saml2ResponseValidatorResult(Collections.emptyList());
private final Collection<Saml2Error> errors;
private Saml2ResponseValidatorResult(Collection<Saml2Error> errors) {
Assert.notNull(errors, "errors cannot be null");
this.errors = new ArrayList<>(errors);
}
/**
* Say whether this result indicates success
* @return whether this result has errors
*/
public boolean hasErrors() {
return !this.errors.isEmpty();
}
/**
* Return error details regarding the validation attempt
* @return the collection of results in this result, if any; returns an empty list
* otherwise
*/
public Collection<Saml2Error> getErrors() {
return Collections.unmodifiableCollection(this.errors);
}
/**
* Return a new {@link Saml2ResponseValidatorResult} that contains both the given
* {@link Saml2Error} and the errors from the result
* @param error the {@link Saml2Error} to append
* @return a new {@link Saml2ResponseValidatorResult} for further reporting
*/
public Saml2ResponseValidatorResult concat(Saml2Error error) {
Assert.notNull(error, "error cannot be null");
Collection<Saml2Error> errors = new ArrayList<>(this.errors);
errors.add(error);
return failure(errors);
}
/**
* Return a new {@link Saml2ResponseValidatorResult} that contains the errors from the
* given {@link Saml2ResponseValidatorResult} as well as this result.
* @param result the {@link Saml2ResponseValidatorResult} to merge with this one
* @return a new {@link Saml2ResponseValidatorResult} for further reporting
*/
public Saml2ResponseValidatorResult concat(Saml2ResponseValidatorResult result) {
Assert.notNull(result, "result cannot be null");
Collection<Saml2Error> errors = new ArrayList<>(this.errors);
errors.addAll(result.getErrors());
return failure(errors);
} | /**
* Construct a successful {@link Saml2ResponseValidatorResult}
* @return an {@link Saml2ResponseValidatorResult} with no errors
*/
public static Saml2ResponseValidatorResult success() {
return NO_ERRORS;
}
/**
* Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail
* @param errors the list of errors
* @return an {@link Saml2ResponseValidatorResult} with the errors specified
*/
public static Saml2ResponseValidatorResult failure(Saml2Error... errors) {
return failure(Arrays.asList(errors));
}
/**
* Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail
* @param errors the list of errors
* @return an {@link Saml2ResponseValidatorResult} with the errors specified
*/
public static Saml2ResponseValidatorResult failure(Collection<Saml2Error> errors) {
if (errors.isEmpty()) {
return NO_ERRORS;
}
return new Saml2ResponseValidatorResult(errors);
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2ResponseValidatorResult.java | 2 |
请完成以下Java代码 | public void setM_CostQueue_ID (int M_CostQueue_ID)
{
if (M_CostQueue_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostQueue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostQueue_ID, Integer.valueOf(M_CostQueue_ID));
}
/** Get Kosten-Reihe.
@return FiFo/LiFo Cost Queue
*/
@Override
public int getM_CostQueue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostQueue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_CostType getM_CostType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class);
}
@Override
public void setM_CostType(org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
/** Set Kostenkategorie.
@param M_CostType_ID
Type of Cost (e.g. Current, Plan, Future)
*/
@Override
public void setM_CostType_ID (int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID));
}
/** Get Kostenkategorie.
@return Type of Cost (e.g. Current, Plan, Future)
*/
@Override
public int getM_CostType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID);
if (ii == null) | return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostQueue.java | 1 |
请完成以下Java代码 | public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(namespaceURI, localName);
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(prefix, localName, namespaceURI);
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(localName);
}
@Override
public void writeEndElement() throws XMLStreamException {
onEndElement();
super.writeEndElement(); | }
@Override
public void writeCharacters(String text) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text, start, len);
}
@Override
public void writeCData(String data) throws XMLStreamException {
state = SEEN_DATA;
super.writeCData(data);
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\IndentingXMLStreamWriter.java | 1 |
请完成以下Java代码 | 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 UseDate.
@param UseDate UseDate */
public void setUseDate (Timestamp UseDate)
{
set_Value (COLUMNNAME_UseDate, UseDate);
}
/** Get UseDate.
@return UseDate */
public Timestamp getUseDate ()
{
return (Timestamp)get_Value(COLUMNNAME_UseDate);
}
/** Set Use units.
@param UseUnits | Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
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_A_Asset_Use.java | 1 |
请完成以下Java代码 | private static NotificationGroupMap ofCollection(@NonNull final Collection<NotificationGroup> collection)
{
return collection.isEmpty() ? EMPTY : new NotificationGroupMap(collection);
}
public static Collector<NotificationGroup, ?, NotificationGroupMap> collect()
{
return GuavaCollectors.collectUsingListAccumulator(NotificationGroupMap::ofCollection);
}
public Set<NotificationGroupName> getNames()
{
return byName.keySet();
} | public Optional<NotificationGroupName> getNameById(@NonNull final NotificationGroupId notificationGroupId)
{
return Optional.ofNullable(byId.get(notificationGroupId)).map(NotificationGroup::getName);
}
public Optional<NotificationGroupId> getIdByName(final NotificationGroupName name)
{
return getByName(name).map(NotificationGroup::getId);
}
public Optional<NotificationGroup> getByName(final NotificationGroupName name)
{
return Optional.ofNullable(byName.get(name));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationGroupMap.java | 1 |
请完成以下Java代码 | public void setBpmnModel(BpmnModel bpmnModel) {
this.bpmnModel = bpmnModel;
}
public ActivityBehaviorFactory getActivityBehaviorFactory() {
return activityBehaviorFactory;
}
public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) {
this.activityBehaviorFactory = activityBehaviorFactory;
}
public ListenerFactory getListenerFactory() {
return listenerFactory;
}
public void setListenerFactory(ListenerFactory listenerFactory) {
this.listenerFactory = listenerFactory;
}
public Map<String, SequenceFlow> getSequenceFlows() {
return sequenceFlows;
}
public ProcessDefinitionEntity getCurrentProcessDefinition() {
return currentProcessDefinition;
}
public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) {
this.currentProcessDefinition = currentProcessDefinition; | }
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
public void setCurrentFlowElement(FlowElement currentFlowElement) {
this.currentFlowElement = currentFlowElement;
}
public Process getCurrentProcess() {
return currentProcess;
}
public void setCurrentProcess(Process currentProcess) {
this.currentProcess = currentProcess;
}
public void setCurrentSubProcess(SubProcess subProcess) {
currentSubprocessStack.push(subProcess);
}
public SubProcess getCurrentSubProcess() {
return currentSubprocessStack.peek();
}
public void removeCurrentSubProcess() {
currentSubprocessStack.pop();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java | 1 |
请完成以下Java代码 | public void postPurchaseCandidateUpdatedEvent(
@NonNull final I_C_PurchaseCandidate purchaseCandidateRecord,
@NonNull final ModelChangeType type)
{
final boolean isNewPurchaseCandidateRecord = type.isNew() || ModelChangeUtil.isJustActivated(purchaseCandidateRecord);
if (isNewPurchaseCandidateRecord)
{
return;
}
final PurchaseCandidateUpdatedEvent purchaseCandidateUpdatedEvent = createUpdatedEvent(purchaseCandidateRecord);
postMaterialEventService.enqueueEventAfterNextCommit(purchaseCandidateUpdatedEvent);
}
@VisibleForTesting
PurchaseCandidateUpdatedEvent createUpdatedEvent(@NonNull final I_C_PurchaseCandidate purchaseCandidateRecord)
{
final MaterialDescriptor materialDescriptor = createMaterialDescriptor(purchaseCandidateRecord);
final MinMaxDescriptor minMaxDescriptor = replenishInfoRepository.getBy(materialDescriptor).toMinMaxDescriptor();
return PurchaseCandidateUpdatedEvent.builder()
.eventDescriptor(EventDescriptor.ofClientAndOrg(purchaseCandidateRecord.getAD_Client_ID(), purchaseCandidateRecord.getAD_Org_ID()))
.purchaseCandidateRepoId(purchaseCandidateRecord.getC_PurchaseCandidate_ID())
.vendorId(purchaseCandidateRecord.getVendor_ID())
.purchaseMaterialDescriptor(materialDescriptor)
.minMaxDescriptor(minMaxDescriptor)
.build(); | }
private MaterialDescriptor createMaterialDescriptor(@NonNull final I_C_PurchaseCandidate purchaseCandidateRecord)
{
final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(purchaseCandidateRecord);
final ProductId productId = ProductId.ofRepoId(purchaseCandidateRecord.getM_Product_ID());
final I_C_UOM uom = uomDAO.getById(purchaseCandidateRecord.getC_UOM_ID());
final Quantity purchaseQty = Services.get(IUOMConversionBL.class)
.convertToProductUOM(
Quantity.of(purchaseCandidateRecord.getQtyToPurchase(), uom),
productId);
// .customerId() we don't have a customer
return MaterialDescriptor.builder()
.date(TimeUtil.asInstant(purchaseCandidateRecord.getPurchaseDatePromised()))
.warehouseId(WarehouseId.ofRepoId(purchaseCandidateRecord.getM_WarehousePO_ID()))
.productDescriptor(productDescriptor)
// .customerId() we don't have a customer
.quantity(purchaseQty.toBigDecimal())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\material\interceptor\C_PurchaseCandidate_PostMaterialEvent.java | 1 |
请完成以下Java代码 | public void deleteSelections(@NonNull final Set<String> selectionIds)
{
if (selectionIds.isEmpty())
{
return;
}
final SqlViewSelectionQueryBuilder viewQueryBuilder = newSqlViewSelectionQueryBuilder();
// Delete selection lines
{
final SqlAndParams sql = viewQueryBuilder.buildSqlDeleteSelectionLines(selectionIds);
final int countDeleted = DB.executeUpdateAndThrowExceptionOnFail(sql.getSql(), sql.getSqlParamsArray(), ITrx.TRXNAME_ThreadInherited);
logger.trace("Delete {} selection lines for {}", countDeleted, selectionIds);
}
// Delete selection rows
{
final SqlAndParams sql = viewQueryBuilder.buildSqlDeleteSelection(selectionIds);
final int countDeleted = DB.executeUpdateAndThrowExceptionOnFail(sql.getSql(), sql.getSqlParamsArray(), ITrx.TRXNAME_ThreadInherited);
logger.trace("Delete {} selection rows for {}", countDeleted, selectionIds);
}
}
@Override
public void scheduleDeleteSelections(@NonNull final Set<String> selectionIds)
{
SqlViewSelectionToDeleteHelper.scheduleDeleteSelections(selectionIds);
}
public static Set<DocumentId> retrieveRowIdsForLineIds(
@NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap,
final ViewId viewId,
final Set<Integer> lineIds)
{
final SqlAndParams sqlAndParams = SqlViewSelectionQueryBuilder.buildSqlSelectRowIdsForLineIds(keyColumnNamesMap, viewId.getViewId(), lineIds);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sqlAndParams.getSql(), ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlAndParams.getSqlParams()); | rs = pstmt.executeQuery();
final ImmutableSet.Builder<DocumentId> rowIds = ImmutableSet.builder();
while (rs.next())
{
final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs, "", false);
if (rowId != null)
{
rowIds.add(rowId);
}
}
return rowIds.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sqlAndParams.getSql(), sqlAndParams.getSqlParams());
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewRowIdsOrderedSelectionFactory.java | 1 |
请完成以下Java代码 | public String getByteArrayValueId() {
return byteArrayField.getByteArrayId();
}
public byte[] getByteArrayValue() {
return byteArrayField.getByteArrayValue();
}
public void setByteArrayValue(byte[] bytes) {
byteArrayField.setByteArrayValue(bytes);
}
public String getName() {
return getVariableName();
}
// entity lifecycle /////////////////////////////////////////////////////////
public void postLoad() {
// make sure the serializer is initialized
typedValueField.postLoad();
}
// getters and setters //////////////////////////////////////////////////////
public String getTypeName() {
return typedValueField.getTypeName();
}
public String getVariableTypeName() {
return getTypeName();
}
public Date getTime() {
return timestamp;
}
@Override
public String toString() {
return this.getClass().getSimpleName() | + "[variableName=" + variableName
+ ", variableInstanceId=" + variableInstanceId
+ ", revision=" + revision
+ ", serializerName=" + serializerName
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", byteArrayId=" + byteArrayId
+ ", activityInstanceId=" + activityInstanceId
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", id=" + id
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", timestamp=" + timestamp
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java | 1 |
请完成以下Java代码 | public void setProcessInstance(ExecutionEntity processInstance) {
this.processInstance = processInstance;
this.processInstanceId = processInstance.getId();
}
public ProcessDefinitionEntity getProcessDef() {
if ((processDef == null) && (processDefId != null)) {
this.processDef = Context.getCommandContext().getProcessDefinitionEntityManager().findById(processDefId);
}
return processDef;
}
public void setProcessDef(ProcessDefinitionEntity processDef) {
this.processDef = processDef;
this.processDefId = processDef.getId();
}
@Override
public String getProcessDefinitionId() {
return this.processDefId;
}
public void setDetails(byte[] details) {
this.details = details;
}
public byte[] getDetails() {
return this.details;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) {
sb.append(", userId=").append(userId);
} | if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
if (details != null) {
sb.append(", details=").append(new String(details));
}
sb.append("]");
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityImpl.java | 1 |
请完成以下Java代码 | public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request)
{
final PickingJob pickingJob = getPickingJob(request.getWfProcess());
final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob);
return toJson(pickingSlotSuggestions);
}
private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions)
{
if (pickingSlotSuggestions.isEmpty())
{
return JsonScannedBarcodeSuggestions.EMPTY;
}
return pickingSlotSuggestions.stream()
.map(SetPickingSlotWFActivityHandler::toJson) | .collect(JsonScannedBarcodeSuggestions.collect());
}
private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion)
{
return JsonScannedBarcodeSuggestion.builder()
.caption(pickingSlotSuggestion.getCaption())
.detail(pickingSlotSuggestion.getDeliveryAddress())
.qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString())
.property1("HU")
.value1(String.valueOf(pickingSlotSuggestion.getCountHUs()))
.additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java | 1 |
请完成以下Java代码 | public void setProductValue (final @Nullable java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java | 1 |
请完成以下Java代码 | public final String getPIName()
{
final I_M_HU hu = getM_HU();
final String piNameRaw;
if (handlingUnitsBL.isAggregateHU(hu))
{
piNameRaw = getAggregateHuPiName(hu);
}
else
{
final I_M_HU_PI pi = handlingUnitsBL.getPI(hu);
piNameRaw = pi != null ? pi.getName() : "?";
}
return escape(piNameRaw);
}
private String getAggregateHuPiName(final I_M_HU hu)
{
// note: if HU is an aggregate HU, then there won't be an NPE here.
final I_M_HU_Item parentItem = hu.getM_HU_Item_Parent();
final I_M_HU_PI_Item parentPIItem = handlingUnitsBL.getPIItem(parentItem);
if (parentPIItem == null)
{
// new HUException("Aggregate HU's parent item has no M_HU_PI_Item; parent-item=" + parentItem)
// .setParameter("parent M_HU_PI_Item_ID", parentItem != null ? parentItem.getM_HU_PI_Item_ID() : null)
// .throwIfDeveloperModeOrLogWarningElse(logger);
return "?";
}
HuPackingInstructionsId includedPIId = HuPackingInstructionsId.ofRepoIdOrNull(parentPIItem.getIncluded_HU_PI_ID());
if (includedPIId == null)
{
//noinspection ThrowableNotThrown
new HUException("Aggregate HU's parent item has M_HU_PI_Item without an Included_HU_PI; parent-item=" + parentItem).throwIfDeveloperModeOrLogWarningElse(logger); | return "?";
}
final I_M_HU_PI included_HU_PI = handlingUnitsBL.getPI(includedPIId);
return included_HU_PI.getName();
}
// NOTE: this method can be overridden by extending classes in order to optimize how the HUs are counted.
@Override
public int getIncludedHUsCount()
{
// NOTE: we need to iterate the HUs and count them (instead of doing a COUNT directly on database),
// because we rely on HU&Items caching
// and also because in case of aggregated HUs, we need special handling
final IncludedHUsCounter includedHUsCounter = new IncludedHUsCounter(getM_HU());
final HUIterator huIterator = new HUIterator();
huIterator.setListener(includedHUsCounter.toHUIteratorListener());
huIterator.setEnableStorageIteration(false);
huIterator.iterate(getM_HU());
return includedHUsCounter.getHUsCount();
}
protected String escape(final String string)
{
return StringUtils.maskHTML(string);
}
@Override
public IHUDisplayNameBuilder setShowIfDestroyed(final boolean showIfDestroyed)
{
this.showIfDestroyed = showIfDestroyed;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDisplayNameBuilder.java | 1 |
请完成以下Java代码 | boolean is_tree_travel(int now, List<List<Integer>> tree, boolean visited[])
{
if (visited[now])
{
return false;
}
visited[now] = true;
for (int c = 0; c < tree.get(now).size(); ++c)
{
int next = tree.get(now).get(c);
if (!is_tree_travel(next, tree, visited))
{
return false;
}
}
return true;
}
boolean is_projective()
{
return !is_non_projective();
}
boolean is_non_projective()
{
for (int modifier = 0; modifier < heads.size(); ++modifier)
{
int head = heads.get(modifier);
if (head < modifier)
{
for (int from = head + 1; from < modifier; ++from)
{
int to = heads.get(from);
if (to < head || to > modifier) | {
return true;
}
}
}
else
{
for (int from = modifier + 1; from < head; ++from)
{
int to = heads.get(from);
if (to < modifier || to > head)
{
return true;
}
}
}
}
return false;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Instance.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.