instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); }
static DocumentId convertPaymentIdToDocumentId(@NonNull final PaymentId paymentId) { return DocumentId.of(paymentId); } static PaymentId convertDocumentIdToPaymentId(@NonNull final DocumentId rowId) { return rowId.toId(PaymentId::ofRepoId); } public Amount getPayAmtNegateIfOutbound() { return getPayAmt().negateIf(!inboundPayment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentToReconcileRow.java
1
请在Spring Boot框架中完成以下Java代码
public class CsvService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private CommonProperties p; @Resource private JobLauncher jobLauncher; @Resource @Qualifier("commonJob") private Job commonJob; private static final String KEY_JOB_NAME = "input.job.name"; private static final String KEY_FILE_NAME = "input.file.name"; private static final String KEY_VO_NAME = "input.vo.name"; private static final String KEY_COLUMNS = "input.columns"; private static final String KEY_SQL = "input.sql"; /** * 导入数据库数据 * @throws Exception ex */ public void importTables() throws Exception { runTask(BscCanton.class); runTask(BscOfficeExeItem.class); runTask(BscExeOffice.class); runTask(BscTollItem.class); } /** * 根据类名反射运行相应的任务 * * @param c 定义的Bean类 */ public void runTask(Class c) throws Exception { TableName a = (TableName) c.getAnnotation(TableName.class); String tableName = a.value(); Field[] fields = c.getDeclaredFields(); List<String> fieldNames = new ArrayList<>(); List<String> paramNames = new ArrayList<>(); for (Field f : fields) { fieldNames.add(f.getName());
paramNames.add(":" + f.getName()); } String columnsStr = String.join(",", fieldNames); String paramsStr = String.join(",", paramNames); String csvFileName; if (p.getLocation() == 1) { csvFileName = p.getCsvDir() + tableName + ".csv"; } else { csvFileName = tableName + ".csv"; } JobParameters jobParameters1 = new JobParametersBuilder() .addLong("time", System.currentTimeMillis()) .addString(KEY_JOB_NAME, tableName) .addString(KEY_FILE_NAME, csvFileName) .addString(KEY_VO_NAME, c.getCanonicalName()) .addString(KEY_COLUMNS, String.join(",", fieldNames)) .addString(KEY_SQL, "insert into " + tableName + " (" + columnsStr + ")" + " values(" + paramsStr + ")") .toJobParameters(); jobLauncher.run(commonJob, jobParameters1); } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\service\CsvService.java
2
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "flowable-examples.bar") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00") public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @ApiModelProperty(example = "examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category;
} @ApiModelProperty(example = "12") public String getParentDeploymentId() { return parentDeploymentId; } public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10") public String getUrl() { return url; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CmmnDeploymentResponse.java
2
请完成以下Java代码
public String modelChange(PO po, int type) throws Exception { // @formatter:off // if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE) // { // final List<MIndexTable> indexes = MIndexTable.getAllByTable(po.getCtx(), false).get(po.get_TableName()); // if (indexes != null) // { // final Properties ctx = po.getCtx(); // final String trxName = po.get_TrxName(); // final String poWhereClause = po.get_WhereClause(true); // // for (final MIndexTable index : indexes) // { // // Skip inactive indexes // if (!index.isActive()) // { // continue; // } // // // Only UNIQUE indexes need to be validated // if (!index.isUnique()) // { // continue; // } // // if (!index.isWhereClauseMatched(ctx, poWhereClause, trxName)) // { // // there is no need to go with further validation since our PO is not subject of current index
// continue; // } // // index.validateData(po, trxName); // } // } // } // @formatter:on return null; } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexValidator.java
1
请完成以下Java代码
public void reportEntityDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("entityDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEntityCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("entityCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEdqsDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("edqsDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEdqsCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("edqsCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportStringCompressed() { getCounter("stringsCompressed").increment(); } @Override public void reportStringUncompressed() { getCounter("stringsUncompressed").increment(); } private void checkTiming(TenantId tenantId, EntityCountQuery query, long timingNanos) { double timingMs = timingNanos / 1000_000.0; String queryType = query instanceof EntityDataQuery ? "data" : "count"; if (timingMs < slowQueryThreshold) { log.debug("[{}] Executed " + queryType + " query in {} ms: {}", tenantId, timingMs, query);
} else { log.warn("[{}] Executed slow " + queryType + " query in {} ms: {}", tenantId, timingMs, query); } } private StatsTimer getTimer(String name) { return timers.computeIfAbsent(name, __ -> statsFactory.createStatsTimer("edqsTimers", name)); } private StatsCounter getCounter(String name) { return counters.computeIfAbsent(name, __ -> statsFactory.createStatsCounter("edqsCounters", name)); } private AtomicInteger getObjectGauge(ObjectType objectType) { return objectCounters.computeIfAbsent(objectType, type -> statsFactory.createGauge("edqsGauges", "objectsCount", new AtomicInteger(), "objectType", type.name())); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\stats\DefaultEdqsStatsService.java
1
请在Spring Boot框架中完成以下Java代码
public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public void setC_Project_Repair_Consumption_Summary_ID (final int C_Project_Repair_Consumption_Summary_ID) { if (C_Project_Repair_Consumption_Summary_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, C_Project_Repair_Consumption_Summary_ID); } @Override public int getC_Project_Repair_Consumption_Summary_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Repair_Consumption_Summary_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override
public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请完成以下Java代码
public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day)
*/ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr ()
{ return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override 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_Invoice_Candidate_Agg_ID (final int C_Invoice_Candidate_Agg_ID) { if (C_Invoice_Candidate_Agg_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Agg_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Agg_ID, C_Invoice_Candidate_Agg_ID); } @Override public int getC_Invoice_Candidate_Agg_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Agg_ID); } @Override public void setClassname (final @Nullable java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } @Override public java.lang.String getClassname() { return get_ValueAsString(COLUMNNAME_Classname); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override
public de.metas.invoicecandidate.model.I_M_ProductGroup getM_ProductGroup() { return get_ValueAsPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class); } @Override public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup) { set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup); } @Override public void setM_ProductGroup_ID (final int M_ProductGroup_ID) { if (M_ProductGroup_ID < 1) set_Value (COLUMNNAME_M_ProductGroup_ID, null); else set_Value (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID); } @Override public int getM_ProductGroup_ID() { return get_ValueAsInt(COLUMNNAME_M_ProductGroup_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 setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Agg.java
1
请在Spring Boot框架中完成以下Java代码
public class SurveyService { private static List<Survey> surveys = new ArrayList<>(); static { Question question1 = new Question("Question1", "Largest Country in the World", "Russia", Arrays.asList( "India", "Russia", "United States", "China")); Question question2 = new Question("Question2", "Most Populus Country in the World", "China", Arrays.asList( "India", "Russia", "United States", "China")); Question question3 = new Question("Question3", "Highest GDP in the World", "United States", Arrays.asList( "India", "Russia", "United States", "China")); Question question4 = new Question("Question4", "Second largest english speaking country", "India", Arrays .asList("India", "Russia", "United States", "China")); List<Question> questions = new ArrayList<>(Arrays.asList(question1, question2, question3, question4)); Survey survey = new Survey("Survey1", "My Favorite Survey", "Description of the Survey", questions); surveys.add(survey); } public List<Survey> retrieveAllSurveys() { return surveys; } public Survey retrieveSurvey(String surveyId) { for (Survey survey : surveys) { if (survey.getId().equals(surveyId)) { return survey; } } return null; } public List<Question> retrieveQuestions(String surveyId) { Survey survey = retrieveSurvey(surveyId);
if (survey == null) { return null; } return survey.getQuestions(); } public Question retrieveQuestion(String surveyId, String questionId) { Survey survey = retrieveSurvey(surveyId); if (survey == null) { return null; } for (Question question : survey.getQuestions()) { if (question.getId().equals(questionId)) { return question; } } return null; } private SecureRandom random = new SecureRandom(); public Question addQuestion(String surveyId, Question question) { Survey survey = retrieveSurvey(surveyId); if (survey == null) { return null; } String randomId = new BigInteger(130, random).toString(32); question.setId(randomId); survey.getQuestions().add(question); return question; } }
repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\service\SurveyService.java
2
请完成以下Java代码
public UserNotificationRequest deriveByNotificationsConfig(@NonNull final UserNotificationsConfig notificationsConfig) { if (Objects.equals(this.notificationsConfig, notificationsConfig)) { return this; } return toBuilder().notificationsConfig(notificationsConfig).build(); } public UserNotificationRequest deriveByRecipient(@NonNull final Recipient recipient) { if (Objects.equals(this.recipient, recipient)) { return this; } return toBuilder().recipient(recipient).notificationsConfig(null).build(); } // // // // // public static class UserNotificationRequestBuilder { public UserNotificationRequestBuilder recipientUserId(@NonNull final UserId userId) { return recipient(Recipient.user(userId)); } public UserNotificationRequestBuilder topic(final Topic topic) { return notificationGroupName(NotificationGroupName.of(topic)); } } public interface TargetAction { } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @lombok.Value @lombok.Builder(toBuilder = true) public static class TargetRecordAction implements TargetAction { @NonNull public static TargetRecordAction of(@NonNull final TableRecordReference record) { return builder().record(record).build(); } @Nullable public static TargetRecordAction ofNullable(@Nullable final TableRecordReference record) { return record == null ? null : of(record); } public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, final int adWindowId)
{ return builder().record(record).adWindowId(AdWindowId.optionalOfRepoId(adWindowId)).build(); } public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, @NonNull final AdWindowId adWindowId) { return builder().record(record).adWindowId(Optional.of(adWindowId)).build(); } public static TargetRecordAction of(@NonNull final String tableName, final int recordId) { return of(TableRecordReference.of(tableName, recordId)); } public static TargetRecordAction cast(final TargetAction targetAction) { return (TargetRecordAction)targetAction; } @NonNull @Builder.Default Optional<AdWindowId> adWindowId = Optional.empty(); @NonNull TableRecordReference record; String recordDisplayText; } @lombok.Value @lombok.Builder public static class TargetViewAction implements TargetAction { public static TargetViewAction cast(final TargetAction targetAction) { return (TargetViewAction)targetAction; } @Nullable AdWindowId adWindowId; @NonNull String viewId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Phonecall_Schema_Version { private static final AdMessageKey MSG_Existing_Phonecall_Schema_Version_Same_ValidFrom = AdMessageKey.of("C_Phonecall_Schema_Version_ExistingVersionSameValidFrom"); @Autowired private PhonecallSchemaRepository phonecallSchemaRepo; @Init public void init(final IModelValidationEngine engine) { CopyRecordFactory.enableForTableName(I_C_Phonecall_Schema_Version.Table_Name); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_ValidFrom }) public void forbidNewVersionWithSameValidFromDate(final I_C_Phonecall_Schema_Version phonecallSchemaVersion) { final PhonecallSchemaId schemaId = PhonecallSchemaId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID()); final PhonecallSchemaVersionId versionId = PhonecallSchemaVersionId.ofRepoIdOrNull(schemaId, phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID()); final LocalDate validFrom = TimeUtil.asLocalDate(phonecallSchemaVersion.getValidFrom()); final PhonecallSchema phonecallSchema = phonecallSchemaRepo.getById(schemaId); final PhonecallSchemaVersion existingVersion = phonecallSchema.getVersionByValidFrom(validFrom).orElse(null); if (existingVersion != null && (versionId == null || !versionId.equals(existingVersion.getId()))) { throw new AdempiereException(MSG_Existing_Phonecall_Schema_Version_Same_ValidFrom,
phonecallSchemaVersion.getName(), validFrom); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_C_Phonecall_Schema_ID }) public void updateLinesOnSchemaChanged(final I_C_Phonecall_Schema_Version phonecallSchemaVersion) { phonecallSchemaRepo.updateLinesOnSchemaChanged(PhonecallSchemaVersionId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID(), phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID())); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_C_Phonecall_Schema_ID }) public void updateSchedulesOnSchemaChanged(final I_C_Phonecall_Schema_Version phonecallSchemaVersion) { phonecallSchemaRepo.updateSchedulesOnSchemaChanged(PhonecallSchemaVersionId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID(), phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\model\interceptor\C_Phonecall_Schema_Version.java
2
请完成以下Java代码
public class CStageValidate extends JavaProcess { private int p_CM_CStage_ID = 0; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.error("Unknown Parameter: " + name);
} p_CM_CStage_ID = getRecord_ID(); } // prepare /** * Process * @return info * @throws Exception */ protected String doIt () throws Exception { log.info("CM_CStage_ID=" + p_CM_CStage_ID); MCStage stage = new MCStage (getCtx(), p_CM_CStage_ID, get_TrxName()); return stage.validate(); } // doIt } // CStageValidate
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\CStageValidate.java
1
请完成以下Java代码
public IMRPSegment createMRPSegment(final I_PP_MRP mrp) { Check.assumeNotNull(mrp, "mrp not null"); final int adClientId = mrp.getAD_Client_ID(); final I_AD_Org adOrg = mrp.getAD_Org(); final I_M_Warehouse warehouse = mrp.getM_Warehouse(); final I_S_Resource plant = mrp.getS_Resource(); final I_M_Product product = mrp.getM_Product(); return new MRPSegment(adClientId, adOrg, warehouse, plant, product); } @Override public boolean isQtyOnHandReservation(final I_PP_MRP mrpSupply) { Check.assumeNotNull(mrpSupply, "mrpSupply not null"); final String typeMRP = mrpSupply.getTypeMRP(); if (!X_PP_MRP.TYPEMRP_Supply.equals(typeMRP)) { return false; } final String orderType = mrpSupply.getOrderType();
return X_PP_MRP.ORDERTYPE_QuantityOnHandReservation.equals(orderType); } @Override public boolean isQtyOnHandInTransit(final I_PP_MRP mrpSupply) { Check.assumeNotNull(mrpSupply, "mrpSupply not null"); final String typeMRP = mrpSupply.getTypeMRP(); if (!X_PP_MRP.TYPEMRP_Supply.equals(typeMRP)) { return false; } final String orderType = mrpSupply.getOrderType(); return X_PP_MRP.ORDERTYPE_QuantityOnHandInTransit.equals(orderType); } @Override public boolean isQtyOnHandAnyReservation(final I_PP_MRP mrpSupply) { return isQtyOnHandReservation(mrpSupply) || isQtyOnHandInTransit(mrpSupply); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPBL.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return ("[" + this.author + " " + this.url + "]"); } }
repos\tutorials-master\spring-boot-modules\spring-boot-flowable\src\main\java\com\baeldung\domain\Article.java
1
请完成以下Java代码
public class PostalAddressType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected String pobox; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected String street; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice", required = true) protected ZipType zip; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice", required = true) protected String city; /** * Gets the value of the pobox property. * * @return * possible object is * {@link String } * */ public String getPobox() { return pobox; } /** * Sets the value of the pobox property. * * @param value * allowed object is * {@link String } * */ public void setPobox(String value) { this.pobox = value; } /** * Gets the value of the street property. * * @return * possible object is * {@link String } * */ public String getStreet() { return street; } /** * Sets the value of the street property. * * @param value * allowed object is * {@link String } * */ public void setStreet(String value) { this.street = value; } /** * Gets the value of the zip property. * * @return * possible object is * {@link ZipType } *
*/ public ZipType getZip() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link ZipType } * */ public void setZip(ZipType value) { this.zip = value; } /** * Gets the value of the city property. * * @return * possible object is * {@link String } * */ public String getCity() { return city; } /** * Sets the value of the city property. * * @param value * allowed object is * {@link String } * */ public void setCity(String value) { this.city = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PostalAddressType.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ConstantStringExpression other = (ConstantStringExpression)obj; return Objects.equals(expressionStr, other.expressionStr); } @Override public String getExpressionString() { return expressionStr; } @Override public String getFormatedExpressionString() { return expressionStr; } @Override public Set<CtxName> getParameters() {
return ImmutableSet.of(); } @Override public String evaluate(final Evaluatee ctx, final boolean ignoreUnparsable) { return expressionStr; } @Override public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) { return expressionStr; } public String getConstantValue() { return expressionStr; } @Override public final IStringExpression resolvePartial(final Evaluatee ctx) { return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ConstantStringExpression.java
1
请完成以下Java代码
public class DocumentLocationAdapter implements IDocumentLocationAdapter, RecordBasedLocationAdapter<DocumentLocationAdapter> { private final I_M_InOut delegate; DocumentLocationAdapter(@NonNull final I_M_InOut delegate) { this.delegate = delegate; } @Override public int getC_BPartner_ID() { return delegate.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int C_BPartner_ID) { delegate.setC_BPartner_ID(C_BPartner_ID); } @Override public int getC_BPartner_Location_ID() { return delegate.getC_BPartner_Location_ID(); } @Override public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID) { delegate.setC_BPartner_Location_ID(C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_Value_ID() { return delegate.getC_BPartner_Location_Value_ID(); } @Override public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID) { delegate.setC_BPartner_Location_Value_ID(C_BPartner_Location_Value_ID); } @Override public int getAD_User_ID() { return delegate.getAD_User_ID(); } @Override public void setAD_User_ID(final int AD_User_ID) { delegate.setAD_User_ID(AD_User_ID); } @Override public String getBPartnerAddress() {
return delegate.getBPartnerAddress(); } @Override public void setBPartnerAddress(String address) { delegate.setBPartnerAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentLocationAdapter.super.setRenderedAddress(from); } public void setFrom(@NonNull final I_M_InOut from) { setFrom(new DocumentLocationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } public void setFrom(@NonNull final I_C_Invoice from) { setFrom(InvoiceDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentLocationAdapter.java
1
请完成以下Java代码
BeforeAfterType getBeforeAfter() { return beforeAfter; } public boolean isBefore() { return beforeAfter == BeforeAfterType.Before; } public boolean isAfter() { return beforeAfter == BeforeAfterType.After; } private boolean matches(final String docAction, final BeforeAfterType beforeAfter) { return isDocAction(docAction) && this.beforeAfter == beforeAfter; } public static DocTimingType valueOf(final int timing) { final DocTimingType value = timingInt2type.get(timing); if (value == null) { throw new IllegalArgumentException("No enum constant found for timing=" + timing + " in " + timingInt2type); } return value; } private static final Map<Integer, DocTimingType> timingInt2type = Stream.of(values()).collect(GuavaCollectors.toImmutableMapByKey(DocTimingType::toInt)); public static DocTimingType forAction(final String docAction, final BeforeAfterType beforeAfterType) {
Check.assumeNotEmpty(docAction, "docAction not null"); Check.assumeNotNull(beforeAfterType, "beforeAfterType not null"); // NOTE: no need to use an indexed map because this method is not used very often for (final DocTimingType timing : values()) { if (timing.matches(docAction, beforeAfterType)) { return timing; } } throw new IllegalArgumentException("Unknown DocAction: " + docAction + ", " + beforeAfterType); } public boolean isVoid() { return this == BEFORE_VOID || this == AFTER_VOID; } public boolean isReverse() { return this == BEFORE_REVERSECORRECT || this == AFTER_REVERSECORRECT || this == BEFORE_REVERSEACCRUAL || this == AFTER_REVERSEACCRUAL; } public boolean isReactivate() { return this == BEFORE_REACTIVATE || this == AFTER_REACTIVATE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\DocTimingType.java
1
请在Spring Boot框架中完成以下Java代码
public class EmailServiceImpl implements EmailService { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private JavaMailSender mailSender; @Autowired private Environment env; @Override public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException { final String subject = env.getProperty(type.getSubject()); final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName()); MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipient.getEmail()); helper.setSubject(subject); helper.setText(text); if (StringUtils.hasLength(attachment)) { helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes())); } mailSender.send(message); log.info("{} email notification has been send to {}", type, recipient.getEmail()); } }
repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\EmailServiceImpl.java
2
请完成以下Java代码
public void debugDestroyScope(PvmExecutionImpl execution, PvmExecutionImpl propagatingExecution) { logDebug( "004", "Execution {} leaves parent scope {}", execution, propagatingExecution); } public void destroying(PvmExecutionImpl pvmExecutionImpl) { logDebug( "005", "Detroying scope {}", pvmExecutionImpl); } public void removingEventScope(PvmExecutionImpl childExecution) { logDebug( "006", "Removeing event scope {}", childExecution); } public void interruptingExecution(String reason, boolean skipCustomListeners) { logDebug( "007", "Interrupting execution execution {}, {}", reason, skipCustomListeners); } public void debugEnterActivityInstance(PvmExecutionImpl pvmExecutionImpl, String parentActivityInstanceId) { logDebug( "008", "Enter activity instance {} parent: {}", pvmExecutionImpl, parentActivityInstanceId); } public void exceptionWhileCompletingSupProcess(PvmExecutionImpl execution, Exception e) { logError( "009", "Exception while completing subprocess of execution {}", execution, e);
} public void createScope(PvmExecutionImpl execution, PvmExecutionImpl propagatingExecution) { logDebug( "010", "Create scope: parent exection {} continues as {}", execution, propagatingExecution); } public ProcessEngineException scopeNotFoundException(String activityId, String executionId) { return new ProcessEngineException(exceptionMessage( "011", "Scope with specified activity Id {} and execution {} not found", activityId,executionId )); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\PvmLogger.java
1
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < nature.length; ++i) { sb.append(nature[i]).append(' ').append(frequency[i]).append(' '); } return sb.toString(); } public void save(DataOutputStream out) throws IOException { out.writeInt(totalFrequency); out.writeInt(nature.length); for (int i = 0; i < nature.length; ++i) { out.writeInt(nature[i].ordinal()); out.writeInt(frequency[i]); } } } /** * 获取词语的ID * * @param a 词语 * @return ID, 如果不存在, 则返回-1
*/ public static int getWordID(String a) { return CoreDictionary.trie.exactMatchSearch(a); } /** * 热更新核心词典<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件 * * @return 是否成功 */ public static boolean reload() { String path = CoreDictionary.path; IOUtil.deleteFile(path + Predefine.BIN_EXT); return load(path); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreDictionary.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_GL_Budget[") .append(get_ID()).append("]"); return sb.toString(); } /** BudgetStatus AD_Reference_ID=178 */ public static final int BUDGETSTATUS_AD_Reference_ID=178; /** Draft = D */ public static final String BUDGETSTATUS_Draft = "D"; /** Approved = A */ public static final String BUDGETSTATUS_Approved = "A"; /** Set Budget Status. @param BudgetStatus Indicates the current status of this budget */ public void setBudgetStatus (String BudgetStatus) { set_Value (COLUMNNAME_BudgetStatus, BudgetStatus); } /** Get Budget Status. @return Indicates the current status of this budget */ public String getBudgetStatus () { return (String)get_Value(COLUMNNAME_BudgetStatus); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Budget. @param GL_Budget_ID General Ledger Budget */ public void setGL_Budget_ID (int GL_Budget_ID) { if (GL_Budget_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); } /** Get Budget. @return General Ledger Budget */ public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Primary. @param IsPrimary Indicates if this is the primary budget */ public void setIsPrimary (boolean IsPrimary) { set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary));
} /** Get Primary. @return Indicates if this is the primary budget */ public boolean isPrimary () { Object oo = get_Value(COLUMNNAME_IsPrimary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java
1
请完成以下Java代码
public java.lang.String getDecimalPoint () { return (java.lang.String)get_Value(COLUMNNAME_DecimalPoint); } /** Set Durch 100 teilen. @param DivideBy100 Divide number by 100 to get correct amount */ @Override public void setDivideBy100 (boolean DivideBy100) { set_Value (COLUMNNAME_DivideBy100, Boolean.valueOf(DivideBy100)); } /** Get Durch 100 teilen. @return Divide number by 100 to get correct amount */ @Override public boolean isDivideBy100 () { Object oo = get_Value(COLUMNNAME_DivideBy100); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set End-Nr.. @param EndNo End-Nr. */ @Override public void setEndNo (int EndNo) { set_Value (COLUMNNAME_EndNo, Integer.valueOf(EndNo)); } /** Get End-Nr.. @return End-Nr. */ @Override public int getEndNo () { Integer ii = (Integer)get_Value(COLUMNNAME_EndNo); if (ii == null) return 0; return ii.intValue(); } /** 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 Skript. @param Script Dynamic Java Language Script to calculate result */ @Override public void setScript (java.lang.String Script) {
set_Value (COLUMNNAME_Script, Script); } /** Get Skript. @return Dynamic Java Language Script to calculate result */ @Override public java.lang.String getScript () { return (java.lang.String)get_Value(COLUMNNAME_Script); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Start No. @param StartNo Starting number/position */ @Override public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ @Override public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat_Row.java
1
请完成以下Java代码
public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { throw new IllegalArgumentException ("Timestamp is virtual column"); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount) { set_Value (COLUMNNAME_UnlockAccount, UnlockAccount); } @Override public java.lang.String getUnlockAccount() { return get_ValueAsString(COLUMNNAME_UnlockAccount); } @Override public void setUserPIN (final @Nullable java.lang.String UserPIN) { set_Value (COLUMNNAME_UserPIN, UserPIN);
} @Override public java.lang.String getUserPIN() { return get_ValueAsString(COLUMNNAME_UserPIN); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java
1
请完成以下Java代码
public void setDebugTrxCloseStacktrace(boolean debugTrxCloseStacktrace) { getTrxManager().setDebugTrxCloseStacktrace(debugTrxCloseStacktrace); } @Override public boolean isDebugTrxCloseStacktrace() { return getTrxManager().isDebugTrxCloseStacktrace(); } @Override public void setDebugTrxCreateStacktrace(boolean debugTrxCreateStacktrace) { getTrxManager().setDebugTrxCreateStacktrace(debugTrxCreateStacktrace); } @Override public boolean isDebugTrxCreateStacktrace() { return getTrxManager().isDebugTrxCreateStacktrace(); } @Override public void setDebugClosedTransactions(boolean enabled) { getTrxManager().setDebugClosedTransactions(enabled); } @Override public boolean isDebugClosedTransactions() { return getTrxManager().isDebugClosedTransactions(); } @Override public String[] getActiveTransactionInfos() { final List<ITrx> trxs = getTrxManager().getActiveTransactionsList(); return toStringArray(trxs); } @Override public String[] getDebugClosedTransactionInfos() { final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions(); return toStringArray(trxs); } private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; } @Override public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName);
} final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
public void setM_FreightCostShipper(final org.adempiere.model.I_M_FreightCostShipper M_FreightCostShipper) { set_ValueFromPO(COLUMNNAME_M_FreightCostShipper_ID, org.adempiere.model.I_M_FreightCostShipper.class, M_FreightCostShipper); } @Override public void setM_FreightCostShipper_ID (final int M_FreightCostShipper_ID) { if (M_FreightCostShipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, M_FreightCostShipper_ID); } @Override public int getM_FreightCostShipper_ID() { return get_ValueAsInt(COLUMNNAME_M_FreightCostShipper_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo()
{ return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setShipmentValueAmt (final BigDecimal ShipmentValueAmt) { set_Value (COLUMNNAME_ShipmentValueAmt, ShipmentValueAmt); } @Override public BigDecimal getShipmentValueAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ShipmentValueAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostDetail.java
1
请完成以下Java代码
public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * Type AD_Reference_ID=540533 * Reference name: C_Aggregation_Attribute_Type */ public static final int TYPE_AD_Reference_ID=540533; /** Attribute = A */ public static final String TYPE_Attribute = "A"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language)
*/ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public static class Group extends HealthProperties { public static final String SERVER_PREFIX = "server:"; public static final String MANAGEMENT_PREFIX = "management:"; /** * Health indicator IDs that should be included or '*' for all. */ private @Nullable Set<String> include; /** * Health indicator IDs that should be excluded or '*' for all. */ private @Nullable Set<String> exclude; /** * When to show full health details. Defaults to the value of * 'management.endpoint.health.show-details'. */ private @Nullable Show showDetails; /** * Additional path that this group can be made available on. The additional path * must start with a valid prefix, either `server` or `management` to indicate if * it will be available on the main port or the management port. For instance, * `server:/healthz` will configure the group on the main port at `/healthz`. */ private @Nullable String additionalPath; public @Nullable Set<String> getInclude() { return this.include; } public void setInclude(@Nullable Set<String> include) { this.include = include; } public @Nullable Set<String> getExclude() { return this.exclude; } public void setExclude(@Nullable Set<String> exclude) { this.exclude = exclude; } @Override public @Nullable Show getShowDetails() { return this.showDetails;
} public void setShowDetails(@Nullable Show showDetails) { this.showDetails = showDetails; } public @Nullable String getAdditionalPath() { return this.additionalPath; } public void setAdditionalPath(@Nullable String additionalPath) { this.additionalPath = additionalPath; } } /** * Health logging properties. */ public static class Logging { /** * Threshold after which a warning will be logged for slow health indicators. */ private Duration slowIndicatorThreshold = Duration.ofSeconds(10); public Duration getSlowIndicatorThreshold() { return this.slowIndicatorThreshold; } public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) { this.slowIndicatorThreshold = slowIndicatorThreshold; } } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java
2
请完成以下Java代码
public @Nullable String getPermissionPolicyHeaderValue() { return permissionPolicyHeaderValue; } public void setPermissionPolicyHeaderValue(@Nullable String permissionPolicyHeaderValue) { this.permissionPolicyHeaderValue = permissionPolicyHeaderValue; } /** * bind the route specific/opt-in header names to enable, in lower case. */ void setEnable(Set<String> enable) { if (enable != null) { this.routeFilterConfigProvided = true; this.routeEnabledHeaders = enable.stream() .map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } } /** * @return the route specific/opt-in header names to enable, in lower case. */ Set<String> getRouteEnabledHeaders() { return routeEnabledHeaders; } /** * bind the route specific/opt-out header names to disable, in lower case. */ void setDisable(Set<String> disable) { if (disable != null) { this.routeFilterConfigProvided = true; this.routeDisabledHeaders = disable.stream() .map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } } /** * @return the route specific/opt-out header names to disable, in lower case */ Set<String> getRouteDisabledHeaders() { return routeDisabledHeaders; } /**
* @return the route specific/opt-out permission policies. */ protected @Nullable String getRoutePermissionsPolicyHeaderValue() { return routePermissionsPolicyHeaderValue; } /** * bind the route specific/opt-out permissions policy. */ void setPermissionsPolicy(@Nullable String permissionsPolicy) { this.routeFilterConfigProvided = true; this.routePermissionsPolicyHeaderValue = permissionsPolicy; } /** * @return flag whether route specific arguments were bound. */ boolean isRouteFilterConfigProvided() { return routeFilterConfigProvided; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java
1
请完成以下Java代码
protected int getTabLabelShiftY(int tabIndex, boolean isSelected) { return isSelected ? -1 : 0; } @Override protected int getTabRunOverlay(int tabRunOverlay) { return tabRunOverlay - 2; } @Override protected int getTabRunIndent(int run) { return 6 * run; } @Override protected Insets getSelectedTabPadInsets() { return NORTH_INSETS; } @Override protected Insets getTabInsets(int tabIndex, Insets tabInsets) { return new Insets(tabInsets.top - 1, tabInsets.left - 4, tabInsets.bottom, tabInsets.right - 4); } @Override protected void paintFocusIndicator( Graphics g, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { if (!tabPane.hasFocus() || !isSelected) return; Rectangle tabRect = rects[tabIndex]; int top = tabRect.y + 1; int left = tabRect.x + 4; int height = tabRect.height - 3; int width = tabRect.width - 9; g.setColor(focus); g.drawRect(left, top, width, height); } @Override protected void paintTabBackground(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int sel = (isSelected) ? 0 : 1; g.setColor(selectColor); g.fillRect(x, y + sel, w, h / 2); g.fillRect(x - 1, y + sel + h / 2, w + 2, h - h / 2); } @Override protected void paintTabBorder(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { g.translate(x - 4, y); int top = 0; int right = w + 6; // Paint Border g.setColor(selectHighlight); // Paint left g.drawLine(1, h - 1, 4, top + 4); g.fillRect(5, top + 2, 1, 2); g.fillRect(6, top + 1, 1, 1); // Paint top g.fillRect(7, top, right - 12, 1); // Paint right g.setColor(darkShadow); g.drawLine(right, h - 1, right - 3, top + 4); g.fillRect(right - 4, top + 2, 1, 2); g.fillRect(right - 5, top + 1, 1, 1); g.translate(-x + 4, -y); } @Override protected void paintContentBorderTopEdge(
Graphics g, int x, int y, int w, int h, boolean drawBroken, Rectangle selRect, boolean isContentBorderPainted) { int right = x + w - 1; int top = y; g.setColor(selectHighlight); if (drawBroken && selRect.x >= x && selRect.x <= x + w) { // Break line to show visual connection to selected tab g.fillRect(x, top, selRect.x - 2 - x, 1); if (selRect.x + selRect.width < x + w - 2) { g.fillRect(selRect.x + selRect.width + 2, top, right - 2 - selRect.x - selRect.width, 1); } else { g.fillRect(x + w - 2, top, 1, 1); } } else { g.fillRect(x, top, w - 1, 1); } } @Override protected int getTabsOverlay() { return 6; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTabbedPaneUI.java
1
请完成以下Java代码
public boolean isCreationLog() { return state == JobState.CREATED.getStateCode(); } public boolean isFailureLog() { return state == JobState.FAILED.getStateCode(); } public boolean isSuccessLog() { return state == JobState.SUCCESSFUL.getStateCode(); } public boolean isDeletionLog() { return state == JobState.DELETED.getStateCode(); } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; }
public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java
1
请完成以下Java代码
public String getOrderId() { return orderId; } public String getProductId() { return productId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} AddProductCommand that = (AddProductCommand) o; return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId); } @Override public int hashCode() { return Objects.hash(orderId, productId); } @Override public String toString() { return "AddProductCommand{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\commands\AddProductCommand.java
1
请完成以下Java代码
public int exactMatchSearch(byte[] key) { int unit = _array[0]; int nodePos = 0; for (byte b : key) { // nodePos ^= unit.offset() ^ b nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)) ^ (b & 0xFF); unit = _array[nodePos]; // if (unit.label() != b) if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff)) { return -1; } } // if (!unit.has_leaf()) { if (((unit >>> 8) & 1) != 1) { return -1; } // unit = _array[nodePos ^ unit.offset()]; unit = _array[nodePos ^ ((unit >>> 10) << ((unit & (1 << 9)) >>> 6))]; // return unit.value(); return unit & ((1 << 31) - 1); } /** * Returns the keys that begins with the given key and its corresponding values. * The first of the returned pair represents the length of the found key. * * @param key * @param offset * @param maxResults * @return found keys and values */ public List<Pair<Integer, Integer>> commonPrefixSearch(byte[] key, int offset, int maxResults) { ArrayList<Pair<Integer, Integer>> result = new ArrayList<Pair<Integer, Integer>>(); int unit = _array[0]; int nodePos = 0; // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); for (int i = offset; i < key.length; ++i) { byte b = key[i];
nodePos ^= (b & 0xff); unit = _array[nodePos]; // if (unit.label() != b) { if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff)) { return result; } // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); // if (unit.has_leaf()) { if (((unit >>> 8) & 1) == 1) { if (result.size() < maxResults) { // result.add(new Pair<i, _array[nodePos].value()); result.add(new Pair<Integer, Integer>(i + 1, _array[nodePos] & ((1 << 31) - 1))); } } } return result; } /** * 大小 * * @return */ public int size() { return _array.length; } private static final int UNIT_SIZE = 4; // sizeof(int) private int[] _array; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DoubleArray.java
1
请完成以下Spring Boot application配置
server.port=9991 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://121.196.XXX.XXX:3306/spring_security_jwt?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=XXXXXX logging.level.org.springframewor
k.security=info spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=true
repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class KPIDataContext { public static final CtxName CTXNAME_AD_User_ID = CtxNames.parse("AD_User_ID"); public static final CtxName CTXNAME_AD_Role_ID = CtxNames.parse("AD_Role_ID"); public static final CtxName CTXNAME_AD_Client_ID = CtxNames.parse("AD_Client_ID"); public static final CtxName CTXNAME_AD_Org_ID = CtxNames.parse("AD_Org_ID"); @Nullable Instant from; @Nullable Instant to; @Nullable UserId userId; @Nullable RoleId roleId; @Nullable ClientId clientId; @Nullable OrgId orgId; public static KPIDataContext ofUserSession(@NonNull final UserSession userSession) { return builderFromUserSession(userSession).build(); } public static KPIDataContextBuilder builderFromUserSession(@NonNull final UserSession userSession) { return builder() .userId(userSession.getLoggedUserId()) .roleId(userSession.getLoggedRoleId()) .clientId(userSession.getClientId()) .orgId(userSession.getOrgId()); } public static KPIDataContext ofEnvProperties(@NonNull final Properties ctx) { return builder() .userId(Env.getLoggedUserIdIfExists(ctx).orElse(null)) .roleId(Env.getLoggedRoleIdIfExists(ctx).orElse(null)) .clientId(Env.getClientId(ctx)) .orgId(Env.getOrgId(ctx)) .build(); } public KPIDataContext retainOnlyRequiredParameters(@NonNull final Set<CtxName> requiredParameters) { UserId userId_new = null; RoleId roleId_new = null; ClientId clientId_new = null; OrgId orgId_new = null; for (final CtxName requiredParam : requiredParameters) { final String requiredParamName = requiredParam.getName(); if (CTXNAME_AD_User_ID.getName().equals(requiredParamName) || Env.CTXNAME_AD_User_ID.equals(requiredParamName)) { userId_new = this.userId;
} else if (CTXNAME_AD_Role_ID.getName().equals(requiredParamName) || Env.CTXNAME_AD_Role_ID.equals(requiredParamName)) { roleId_new = this.roleId; } else if (CTXNAME_AD_Client_ID.getName().equals(requiredParamName) || Env.CTXNAME_AD_Client_ID.equals(requiredParamName)) { clientId_new = this.clientId; } else if (CTXNAME_AD_Org_ID.getName().equals(requiredParamName) || Env.CTXNAME_AD_Org_ID.equals(requiredParamName)) { orgId_new = this.orgId; } } return toBuilder() .userId(userId_new) .roleId(roleId_new) .clientId(clientId_new) .orgId(orgId_new) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataContext.java
2
请在Spring Boot框架中完成以下Java代码
public ODataResponse updateEntity(final PutMergePatchUriInfo uriParserResultView, final InputStream content, final String requestContentType, final boolean merge, final String contentType) throws ODataException, ODataJPAModelException, ODataJPARuntimeException, ODataNotFoundException { logger.info("PUT: Entity {} called with key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral()); ODataResponse response = null; try { Object updatedEntity = jpaProcessor.process(uriParserResultView, content, requestContentType); response = responseBuilder.build(uriParserResultView, updatedEntity); } finally { this.close(); } return response; } @Override public ODataResponse deleteEntity(DeleteUriInfo uriParserResultView, String contentType) throws ODataException { logger.info("DELETE: Entity {} called with key {}", uriParserResultView.getTargetEntitySet().getName(), uriParserResultView.getKeyPredicates().get(0).getLiteral()); ODataResponse oDataResponse = null; try { this.oDataJPAContext.setODataContext(this.getContext()); Object deletedEntity = this.jpaProcessor.process(uriParserResultView, contentType); oDataResponse = this.responseBuilder.build(uriParserResultView, deletedEntity); } finally { this.close();
} return oDataResponse; } private ODataResponse postProcessCreateChild(Object createdEntity, PostUriInfo uriParserResultView, String contentType) throws ODataJPARuntimeException, ODataNotFoundException { Child child = (Child) createdEntity; if (child.getSurname() == null || child.getSurname().equalsIgnoreCase("")) { if (child.getMother().getSurname() != null && !child.getMother().getSurname().equalsIgnoreCase("")) { child.setSurname(child.getMother().getSurname()); } else if (child.getMother().getSurname() != null && !child.getFather().getSurname().equalsIgnoreCase("")) { child.setSurname(child.getFather().getSurname()); } else { child.setSurname("Gashi"); } } return responseBuilder.build(uriParserResultView, createdEntity, contentType); } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\service\CustomODataJpaProcessor.java
2
请完成以下Java代码
public static ExternalBusinessKey of(@NonNull final String identifier) { final Matcher externalBusinessKeyMatcher = Type.EXTERNAL_REFERENCE.pattern.matcher(identifier); if (externalBusinessKeyMatcher.matches()) { final ExternalReferenceValueAndSystem valueAndSystem = ExternalReferenceValueAndSystem.builder() .externalSystem(externalBusinessKeyMatcher.group(1)) .value(externalBusinessKeyMatcher.group(2)) .build(); return new ExternalBusinessKey(Type.EXTERNAL_REFERENCE, identifier, valueAndSystem); } else { return new ExternalBusinessKey(Type.VALUE, identifier, null); } } @NonNull public ExternalReferenceValueAndSystem asExternalValueAndSystem() { Check.assume(Type.EXTERNAL_REFERENCE.equals(type), "The type of this instance needs to be {}; this={}", Type.EXTERNAL_REFERENCE, this); Check.assumeNotNull(externalReferenceValueAndSystem, "externalReferenceValueAndSystem cannot be null to EXTERNAL_REFERENCE type!"); return externalReferenceValueAndSystem; }
@NonNull public String asValue() { Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this); return rawValue; } @AllArgsConstructor @Getter public enum Type { VALUE(Pattern.compile("(.*?)")), EXTERNAL_REFERENCE(Pattern.compile("(?:^ext-)([a-zA-Z0-9]+)-(.+)")); private final Pattern pattern; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalBusinessKey.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloWorldController { @RequestMapping("/hello") public Map<String, Object> showHelloWorld(){ Map<String, Object> map = new HashMap<>(); map.put("msg", "HelloWorld"); return map; } @PostMapping("/user") public boolean insert(@RequestBody User user) { System.out.println("add..."); if(user.getName()==null){ throw new BizException("-1","username is empty!"); } return true; } @PutMapping("/user") public boolean update(@RequestBody User user) { System.out.println("update..."); //mock NullException
String str=null; str.equals("111"); return true; } @DeleteMapping("/user") public boolean delete(@RequestBody User user) { System.out.println("delete..."); //mock Exception Integer.parseInt("abc123"); return true; } }
repos\springboot-demo-master\Exception\src\main\java\com\et\exception\controller\HelloWorldController.java
2
请完成以下Java代码
private PropertyChangeListener createTablePropertyChangeListener() { return new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { final String propertyName = evt.getPropertyName(); // Column Model Changed if (CTable.PROPERTY_ColumnModel.equals(propertyName)) { final TableColumnModel oldModel = (TableColumnModel)evt.getOldValue(); updateFromColumnModelChange(oldModel); } // Table Column settings were changed else if (CTable.PROPERTY_TableColumnChanged.equals(propertyName)) { final TableColumnModel oldModel = table.getColumnModel(); updateFromColumnModelChange(oldModel); } // else if ("enabled".equals(propertyName)) { updateFromTableEnabledChanged(); } } }; } /** * Returns the listener to table's column model. The listener is lazily created if necessary. * * @return the <code>TableColumnModelListener</code> for use with the table's column model, guaranteed to be not <code>null</code>. */ private TableColumnModelListener getColumnModelListener() { if (columnModelListener == null) { columnModelListener = createColumnModelListener(); } return columnModelListener; } /** * Creates the listener to columnModel. Subclasses are free to roll their own. * <p> * Implementation note: this listener reacts to "real" columnRemoved/-Added by populating the popups content from scratch. * * @return the <code>TableColumnModelListener</code> for use with the table's columnModel. */ private TableColumnModelListener createColumnModelListener() { return new TableColumnModelListener() { /** Tells listeners that a column was added to the model. */ @Override public void columnAdded(TableColumnModelEvent e) { markPopupStaled(); }
/** Tells listeners that a column was removed from the model. */ @Override public void columnRemoved(TableColumnModelEvent e) { markPopupStaled(); } /** Tells listeners that a column was repositioned. */ @Override public void columnMoved(TableColumnModelEvent e) { if (e.getFromIndex() == e.getToIndex()) { // not actually a change return; } // mark popup stalled because we want to have the same ordering there as we have in table column markPopupStaled(); } /** Tells listeners that a column was moved due to a margin change. */ @Override public void columnMarginChanged(ChangeEvent e) { // nothing to do } /** * Tells listeners that the selection model of the TableColumnModel changed. */ @Override public void columnSelectionChanged(ListSelectionEvent e) { // nothing to do } }; } } // end class ColumnControlButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CColumnControlButton.java
1
请完成以下Java代码
public Builder issuedAt(Instant issuedAt) { return this.claim(IdTokenClaimNames.IAT, issuedAt); } /** * Use this issuer in the resulting {@link OidcIdToken} * @param issuer The issuer to use * @return the {@link Builder} for further configurations */ public Builder issuer(String issuer) { return this.claim(IdTokenClaimNames.ISS, issuer); } /** * Use this nonce in the resulting {@link OidcIdToken} * @param nonce The nonce to use * @return the {@link Builder} for further configurations */ public Builder nonce(String nonce) { return this.claim(IdTokenClaimNames.NONCE, nonce); } /** * Use this subject in the resulting {@link OidcIdToken} * @param subject The subject to use
* @return the {@link Builder} for further configurations */ public Builder subject(String subject) { return this.claim(IdTokenClaimNames.SUB, subject); } /** * Build the {@link OidcIdToken} * @return The constructed {@link OidcIdToken} */ public OidcIdToken build() { Instant iat = toInstant(this.claims.get(IdTokenClaimNames.IAT)); Instant exp = toInstant(this.claims.get(IdTokenClaimNames.EXP)); return new OidcIdToken(this.tokenValue, iat, exp, this.claims); } private Instant toInstant(Object timestamp) { if (timestamp != null) { Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant"); } return (Instant) timestamp; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcIdToken.java
1
请完成以下Java代码
public class NotificationType { @XmlAttribute(name = "code", required = true) protected String code; @XmlAttribute(name = "text", required = true) protected String text; /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the text property.
* * @return * possible object is * {@link String } * */ public String getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link String } * */ public void setText(String value) { this.text = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\NotificationType.java
1
请完成以下Java代码
public void usingCoreJava(ExecutionPlan plan) { plan.validate(subject::usingCoreJava); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingRegularExpressions(ExecutionPlan plan) { plan.validate(subject::usingPreCompiledRegularExpressions); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isCreatable(ExecutionPlan plan) { plan.validate(subject::usingNumberUtils_isCreatable); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isParsable(ExecutionPlan plan) { plan.validate(subject::usingNumberUtils_isParsable);
} @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumeric(ExecutionPlan plan) { plan.validate(subject::usingStringUtils_isNumeric); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumericSpace(ExecutionPlan plan) { plan.validate(subject::usingStringUtils_isNumericSpace); } private enum TestMode { SIMPLE, DIVERS } }
repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\Benchmarking.java
1
请完成以下Java代码
public ModelAndView signup(HttpServletRequest httpServletRequest, @RequestBody SignupRequest request) { var userRegistry = new UserRegistry( request.user().email(), request.user().username(), request.user().password()); userService.signup(userRegistry); // Redirect to login API to automatically login when signup is complete var loginRequest = new LoginUserRequest(request.user().email(), request.user().password()); httpServletRequest.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); return new ModelAndView("redirect:" + LOGIN_URL, "user", Map.of("user", loginRequest)); } @ResponseStatus(HttpStatus.CREATED) @PostMapping(LOGIN_URL) public UsersResponse login(@RequestBody LoginUserRequest request) { var email = request.user().email(); var password = request.user().password(); var user = userService.login(email, password); var authToken = bearerTokenProvider.createAuthToken(user); return UsersResponse.from(user, authToken); } @GetMapping("/api/user") public UsersResponse getUser(AuthToken actorsToken) { var actor = userService.getUser(actorsToken.userId());
return UsersResponse.from(actor, actorsToken.tokenValue()); } @PutMapping("/api/user") public UsersResponse updateUser(AuthToken actorsToken, @RequestBody UpdateUserRequest request) { User actor = userService.updateUserDetails( actorsToken.userId(), request.user().email(), request.user().username(), request.user().password(), request.user().bio(), request.user().image()); return UsersResponse.from(actor, actorsToken.tokenValue()); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\api\UserController.java
1
请完成以下Java代码
public boolean isPrimary () { Object oo = get_Value(COLUMNNAME_IsPrimary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo)
{ set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkbenchWindow.java
1
请完成以下Java代码
public String getValueSql(final Object value, final List<Object> ignored_params) { final StringBuilder result = new StringBuilder(); final String stringVal = (String)value; result.append(" '"); // we need one space after the "LIKE" result.append(supplementWildCards(stringVal)); result.append("'"); return result.toString(); } private String supplementWildCards(@NonNull final String stringVal) { final StringBuilder result = new StringBuilder(); if (!stringVal.startsWith("%")) { result.append("%"); } result.append(stringVal.replace("'", "''")); // escape quotes within the string if (!stringVal.endsWith("%")) { result.append("%"); } return result.toString(); } /** * Just prepends a space to the given <code>columnSql</code>. */ @Override public @NonNull String getColumnSql(final @NonNull String columnName) { return columnName + " "; // nothing more to do } /** * Uppercases the given {@code value} if {@code ignoreCase} was specified. */ @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return ""; // shall not happen, see constructor } final String str; if (ignoreCase) { // will return the uppercase version of both operands str = ((String)value).toUpperCase(); }
else { str = (String)value; } return supplementWildCards(str); } @Override public String toString() { return "Modifier[ignoreCase=" + ignoreCase + "]"; } } public StringLikeFilter( @NonNull final String columnName, @NonNull final String substring, final boolean ignoreCase) { super(columnName, ignoreCase ? Operator.STRING_LIKE_IGNORECASE : Operator.STRING_LIKE, substring, new StringLikeQueryFilterModifier(ignoreCase)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringLikeFilter.java
1
请完成以下Java代码
public static void enqueueOnTrxCommit( @NonNull final ShipmentScheduleId shipmentScheduleId, @Nullable final AsyncBatchId asyncBatchId) { final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class); workPackageQueueFactory .getQueueForEnqueuing(AdviseDeliveryOrderWorkpackageProcessor.class) .newWorkPackage() .setAsyncBatchId(asyncBatchId) .setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null)) .bindToThreadInheritedTrx() .parameters() .setParameter(PARAM_ShipmentScheduleId, shipmentScheduleId) .end() .buildAndEnqueue(); } private static final String PARAM_ShipmentScheduleId = "ShipmentScheduleId";
@Override public boolean isRunInTransaction() { return false; } @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName_NOTUSED) { final int shipmentSchedule = getParameters().getParameterAsInt(PARAM_ShipmentScheduleId, -1); CarrierAdviseCommand.of(ShipmentScheduleId.ofRepoId(shipmentSchedule)) .execute(); return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\async\AdviseDeliveryOrderWorkpackageProcessor.java
1
请完成以下Java代码
protected boolean isScriptPresent(UUID scriptId) { return scriptInfoMap.containsKey(scriptId); } @Override protected boolean isExecEnabled(TenantId tenantId) { return !apiUsageStateClient.isPresent() || apiUsageStateClient.get().getApiUsageState(tenantId).isJsExecEnabled(); } @Override protected void reportExecution(TenantId tenantId, CustomerId customerId) { apiUsageReportClient.ifPresent(client -> client.report(tenantId, customerId, ApiUsageRecordKey.JS_EXEC_COUNT, 1)); } @Override protected JsScriptExecutionTask doInvokeFunction(UUID scriptId, Object[] args) { return new JsScriptExecutionTask(doInvokeFunction(scriptId, scriptInfoMap.get(scriptId), args)); } @Override protected ListenableFuture<UUID> doEvalScript(TenantId tenantId, ScriptType scriptType, String scriptBody, UUID scriptId, String[] argNames) { String scriptHash = hash(tenantId, scriptBody); String functionName = constructFunctionName(scriptId, scriptHash); String jsScript = generateJsScript(scriptType, functionName, scriptBody, argNames); return doEval(scriptId, new JsScriptInfo(scriptHash, functionName), jsScript); } @Override protected void doRelease(UUID scriptId) throws Exception { doRelease(scriptId, scriptInfoMap.remove(scriptId)); } @Override public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; } protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody);
protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception; private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); } throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); } protected String constructFunctionName(UUID scriptId, String scriptHash) { return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1
请完成以下Java代码
public AmountSourceAndAcct negate() { return isZero() ? this : toBuilder().amtSource(this.amtSource.negate()).amtAcct(this.amtAcct.negate()).build(); } public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other) { assertCurrencyAndRateMatching(other); if (other.isZero()) { return this; } else if (this.isZero()) { return other; } else { return toBuilder() .amtSource(this.amtSource.add(other.amtSource))
.amtAcct(this.amtAcct.add(other.amtAcct)) .build(); } } public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other) { return add(other.negate()); } private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other) { if (!Objects.equals(this.currencyAndRate, other.currencyAndRate)) { throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate); } } } } // Doc_Bank
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
1
请完成以下Java代码
public static SessionFactory getSessionFactory() { return sessionFactory; } private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(FootballPlayer.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder(); } private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getHibernateProperties(); return new StandardServiceRegistryBuilder().applySettings(properties).build(); } private static Properties getHibernateProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties"); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream);
} return properties; } public static List<EntityEntry> getManagedEntities(Session session) { Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries(); return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); } public static Transaction startTransaction(Session s) { Transaction tx = s.getTransaction(); tx.begin(); return tx; } public static int queryCount(String query) throws Exception { try (ResultSet rs = connection.createStatement().executeQuery(query)) { rs.next(); return rs.getInt(1); } } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\lifecycle\HibernateLifecycleUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class RetrievePatientsProcessor implements Processor { @Override public void process(@NonNull final Exchange exchange) throws Exception { final var request = exchange.getIn().getBody(JsonExternalSystemRequest.class); exchange.getIn().setHeader(GetPatientsRouteConstants.HEADER_ORG_CODE, request.getOrgCode()); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); } final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); final Instant updatedAfter = routeContext.getUpdatedAfterValue(); final List<Patient> patientsToImport = getPatientsToImport(routeContext, String.valueOf(updatedAfter)); exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_ORG_CODE, request.getOrgCode()); exchange.getIn().setBody(patientsToImport); } private List<Patient> getPatientsToImport(@NonNull final GetPatientsRouteContext routeContext, @NonNull final String updatedAfter) throws ApiException { final PatientApi patientApi = routeContext.getPatientApi(); final AlbertaConnectionDetails connectionDetails = routeContext.getAlbertaConnectionDetails(); final var createdPatients = patientApi .getCreatedPatients(connectionDetails.getApiKey(), GetPatientsRouteConstants.PatientStatus.CREATED.getValue(), updatedAfter);
final List<Patient> patientsToImport = createdPatients == null || createdPatients.isEmpty() ? new ArrayList<>() : createdPatients; final Set<String> createdPatientIds = patientsToImport.stream() .map(Patient::getId) .filter(Objects::nonNull) .map(UUID::toString) .collect(Collectors.toSet()); final List<Patient> updatedPatients = patientApi .getCreatedPatients(connectionDetails.getApiKey(), GetPatientsRouteConstants.PatientStatus.UPDATED.getValue(), updatedAfter); if (updatedPatients != null && !updatedPatients.isEmpty()) { updatedPatients.stream() .filter(patient -> patient.getId() != null && !createdPatientIds.contains(patient.getId().toString())) .forEach(patientsToImport::add); } return patientsToImport; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\RetrievePatientsProcessor.java
2
请完成以下Java代码
public BPartnerLocationId getBPartnerLocationId() { return bpartnerLocationId; } public void setBPartnerLocationId(final BPartnerLocationId bpartnerLocationId) { this.bpartnerLocationId = bpartnerLocationId; } @Override public boolean isToBeFetched() { Check.assumeNotNull(toBeFetched, "toBeFetched set"); return toBeFetched; } /** * @param toBeFetched * @see #isToBeFetched() */ public void setToBeFetched(final boolean toBeFetched) { this.toBeFetched = toBeFetched; } @Override public Boolean getProcessed() { return processed; } public void setProcessed(final Boolean processed) { this.processed = processed;
} @Override public ZonedDateTime getCalculationTime() { return calculationTime; } /** * See {@link IDeliveryDayQueryParams#getCalculationTime()}. * * @param calculationTime */ public void setCalculationTime(final ZonedDateTime calculationTime) { this.calculationTime = calculationTime; } @Nullable @Override public LocalDate getPreparationDay() { return preparationDay; } public void setPreparationDay(@Nullable LocalDate preparationDay) { this.preparationDay = preparationDay; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\PlainDeliveryDayQueryParams.java
1
请完成以下Java代码
public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) { if (PP_Product_BOMLine_ID < 1) set_Value (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_Value (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID); } @Override public void setQtyBatch (final BigDecimal QtyBatch) { set_Value (COLUMNNAME_QtyBatch, QtyBatch); } @Override public BigDecimal getQtyBatch() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatch); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyBOM (final @Nullable BigDecimal QtyBOM) { set_Value (COLUMNNAME_QtyBOM, QtyBOM); } @Override public BigDecimal getQtyBOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScrap (final @Nullable BigDecimal Scrap) { set_Value (COLUMNNAME_Scrap, Scrap); } @Override public BigDecimal getScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTM_Product_ID (final int TM_Product_ID) { if (TM_Product_ID < 1) set_Value (COLUMNNAME_TM_Product_ID, null); else set_Value (COLUMNNAME_TM_Product_ID, TM_Product_ID); } @Override public int getTM_Product_ID() { return get_ValueAsInt(COLUMNNAME_TM_Product_ID); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Product_BOMLine.java
1
请完成以下Java代码
private I_AD_PInstance createPInstance() { final I_AD_PInstance pinstance = Services.get(IADPInstanceDAO.class).createAD_PInstance(adProcessId); pinstance.setIsProcessing(true); InterfaceWrapperHelper.save(pinstance); final BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(paramsInterfaceClass); } catch (IntrospectionException e) { throw new AdempiereException(e.getLocalizedMessage(), e); } final List<ProcessInfoParameter> piParams = new ArrayList<>(); for (final PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { final Object value; try { value = pd.getReadMethod().invoke(params); } catch (Exception e) { logger.info(e.getLocalizedMessage(), e); continue; } if (value == null) {
continue; } piParams.add(ProcessInfoParameter.ofValueObject(pd.getName(), value)); } Services.get(IADPInstanceDAO.class).saveParameterToDB(PInstanceId.ofRepoId(pinstance.getAD_PInstance_ID()), piParams); return pinstance; } public void setClientUIInstance(IClientUIInstance clientUIInstance) { this.clientUIInstance = clientUIInstance; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ProcessLoggerExporterMonitor.java
1
请完成以下Java代码
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package) { set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package); } @Override public void setC_Print_Package_ID (int C_Print_Package_ID) { if (C_Print_Package_ID < 1) set_Value (COLUMNNAME_C_Print_Package_ID, null); else set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID)); } @Override public int getC_Print_Package_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); }
@Override public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java
1
请完成以下Java代码
/* for testing */ Config loadConfiguration(String routeId) { Config routeConfig = getConfig().getOrDefault(routeId, defaultConfig); if (routeConfig == null) { routeConfig = getConfig().get(RouteDefinitionRouteLocator.DEFAULT_FILTERS); } if (routeConfig == null) { throw new IllegalArgumentException("No Configuration found for route " + routeId + " or defaultFilters"); } return routeConfig; } public Map<String, String> getHeaders(Config config, Long tokensLeft) { Map<String, String> headers = new HashMap<>(); if (isIncludeHeaders()) { headers.put(this.remainingHeader, tokensLeft.toString()); headers.put(this.replenishRateHeader, String.valueOf(config.getReplenishRate())); headers.put(this.burstCapacityHeader, String.valueOf(config.getBurstCapacity())); headers.put(this.requestedTokensHeader, String.valueOf(config.getRequestedTokens())); } return headers; } @Validated public static class Config { @Min(1) private int replenishRate; @Min(0) private long burstCapacity = 1; @Min(1) private int requestedTokens = 1; public int getReplenishRate() { return replenishRate; } public Config setReplenishRate(int replenishRate) { this.replenishRate = replenishRate; return this; } public long getBurstCapacity() { return burstCapacity;
} public Config setBurstCapacity(long burstCapacity) { Assert.isTrue(burstCapacity >= this.replenishRate, "BurstCapacity(" + burstCapacity + ") must be greater than or equal than replenishRate(" + this.replenishRate + ")"); Assert.isTrue(burstCapacity <= REDIS_LUA_MAX_SAFE_INTEGER, "BurstCapacity(" + burstCapacity + ") must not exceed the maximum allowed value of " + REDIS_LUA_MAX_SAFE_INTEGER); this.burstCapacity = burstCapacity; return this; } public int getRequestedTokens() { return requestedTokens; } public Config setRequestedTokens(int requestedTokens) { this.requestedTokens = requestedTokens; return this; } @Override public String toString() { return new ToStringCreator(this).append("replenishRate", replenishRate) .append("burstCapacity", burstCapacity) .append("requestedTokens", requestedTokens) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\ratelimit\RedisRateLimiter.java
1
请完成以下Java代码
public void setNull(int index) { jsonNode.setNull(index); } @Override public void set(int index, FlowableJsonNode value) { jsonNode.set(index, asJsonNode(value)); } @Override public void add(Short value) { jsonNode.add(value); } @Override public void add(Integer value) { jsonNode.add(value); } @Override public void add(Long value) { jsonNode.add(value); } @Override public void add(Float value) { jsonNode.add(value); } @Override public void add(Double value) { jsonNode.add(value); } @Override public void add(byte[] value) { jsonNode.add(value); } @Override
public void add(String value) { jsonNode.add(value); } @Override public void add(Boolean value) { jsonNode.add(value); } @Override public void add(BigDecimal value) { jsonNode.add(value); } @Override public void add(BigInteger value) { jsonNode.add(value); } @Override public void add(FlowableJsonNode value) { jsonNode.add(asJsonNode(value)); } @Override public void addNull() { jsonNode.addNull(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ArrayNode.java
1
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; }
public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\domain\User.java
1
请完成以下Java代码
public void setUserName(@Nullable UserName userName) { this.userName = userName; } public void setEmail(@Nullable Email email) { this.email = email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; var user = (User) o; return Objects.equals(id, user.id) && Objects.equals(userName, user.userName) && Objects.equals(email, user.email); }
@Override public int hashCode() { return Objects.hash(id, userName, email); } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", userName=" + userName + ", email=" + email + '}'; } }
repos\spring-data-examples-main\mongodb\example\src\main\java\example\springdata\mongodb\unwrapping\User.java
1
请完成以下Java代码
public class FieldExtension extends BaseElement { protected String fieldName; protected String stringValue; protected String expression; public FieldExtension() {} public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; }
public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public FieldExtension clone() { FieldExtension clone = new FieldExtension(); clone.setValues(this); return clone; } public void setValues(FieldExtension otherExtension) { setFieldName(otherExtension.getFieldName()); setStringValue(otherExtension.getStringValue()); setExpression(otherExtension.getExpression()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FieldExtension.java
1
请在Spring Boot框架中完成以下Java代码
public class ValueProvider implements Serializable { private String name; private final Map<String, Object> parameters = new LinkedHashMap<>(); /** * Return the name of the provider. * @return the name */ public String getName() { return this.name; } public void setName(String name) { this.name = name;
} /** * Return the parameters. * @return the parameters */ public Map<String, Object> getParameters() { return this.parameters; } @Override public String toString() { return "ValueProvider{name='" + this.name + ", parameters=" + this.parameters + '}'; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ValueProvider.java
2
请在Spring Boot框架中完成以下Java代码
public class PublishSubscibeChannelExample { @MessagingGateway public interface NumbersClassifier { @Gateway(requestChannel = "classify.input") void classify(Collection<Integer> numbers); } @Bean QueueChannel multipleofThreeChannel() { return new QueueChannel(); } @Bean QueueChannel remainderIsOneChannel() { return new QueueChannel(); } @Bean QueueChannel remainderIsTwoChannel() { return new QueueChannel(); } boolean isMultipleOfThree(Integer number) { return number % 3 == 0; } boolean isRemainderOne(Integer number) { return number % 3 == 1; }
boolean isRemainderTwo(Integer number) { return number % 3 == 2; } @Bean public IntegrationFlow classify() { return flow -> flow.split() .publishSubscribeChannel(subscription -> subscription.subscribe(subflow -> subflow.<Integer> filter(this::isMultipleOfThree) .channel("multipleofThreeChannel")) .subscribe(subflow -> subflow.<Integer> filter(this::isRemainderOne) .channel("remainderIsOneChannel")) .subscribe(subflow -> subflow.<Integer> filter(this::isRemainderTwo) .channel("remainderIsTwoChannel"))); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\publishsubscribechannel\PublishSubscibeChannelExample.java
2
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception {
final ClearanceStatusInfo clearanceStatusInfo = ClearanceStatusInfo.builder() .clearanceStatus(ClearanceStatus.ofCode(clearanceStatus)) .clearanceNote(clearanceNote) .clearanceDate(InstantAndOrgId.ofInstant(clearanceDate, getOrgId())) .build(); streamSelectedHUs(HUEditorRowFilter.Select.ALL) .forEach(hu -> handlingUnitsBL.setClearanceStatusRecursively(HuId.ofRepoId(hu.getM_HU_ID()), clearanceStatusInfo)); final HUEditorView view = getView(); view.invalidateAll(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Clearance.java
1
请完成以下Java代码
public static EventLogEntryEntityManager getEventLogEntryEntityManager() { return getEventLogEntryEntityManager(getCommandContext()); } public static EventLogEntryEntityManager getEventLogEntryEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getEventLogEntryEntityManager(); } public static FlowableEventDispatcher getEventDispatcher() { return getEventDispatcher(getCommandContext()); } public static FlowableEventDispatcher getEventDispatcher(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getEventDispatcher(); } public static FailedJobCommandFactory getFailedJobCommandFactory() { return getFailedJobCommandFactory(getCommandContext()); }
public static FailedJobCommandFactory getFailedJobCommandFactory(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getFailedJobCommandFactory(); } public static ProcessInstanceHelper getProcessInstanceHelper() { return getProcessInstanceHelper(getCommandContext()); } public static ProcessInstanceHelper getProcessInstanceHelper(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getProcessInstanceHelper(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("name", name); persistentState.put("description", description); return persistentState; } @Override public int getRevisionNext() { return revision + 1; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId;
} @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content; } public void setUserId(String userId) { this.userId = userId; } @Override public String getUserId() { return userId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntity.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException { return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name) .getPO(getM_PromotionGroup_ID(), get_TrxName()); } /** Set Promotion Group. @param M_PromotionGroup_ID Promotion Group */ public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID));
} /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Group Line. @param M_PromotionGroupLine_ID Promotion Group Line */ public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID) { if (M_PromotionGroupLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID)); } /** Get Promotion Group Line. @return Promotion Group Line */ public int getM_PromotionGroupLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_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_PromotionGroupLine.java
1
请完成以下Java代码
public Map<String, VariableInstance> getVariableInstancesLocal(String taskId) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, true)); } @Override public Map<String, VariableInstance> getVariableInstancesLocal(String taskId, Collection<String> variableNames) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, true)); } @Override public Map<String, DataObject> getDataObjects(String taskId) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null)); } @Override public Map<String, DataObject> getDataObjects(String taskId, String locale, boolean withLocalizationFallback) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null, locale, withLocalizationFallback)); } @Override public Map<String, DataObject> getDataObjects(String taskId, Collection<String> dataObjectNames) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, dataObjectNames)); } @Override public Map<String, DataObject> getDataObjects( String taskId, Collection<String> dataObjectNames, String locale, boolean withLocalizationFallback
) { return commandExecutor.execute( new GetTaskDataObjectsCmd(taskId, dataObjectNames, locale, withLocalizationFallback) ); } @Override public DataObject getDataObject(String taskId, String dataObject) { return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObject)); } @Override public DataObject getDataObject( String taskId, String dataObjectName, String locale, boolean withLocalizationFallback ) { return commandExecutor.execute( new GetTaskDataObjectCmd(taskId, dataObjectName, locale, withLocalizationFallback) ); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java
1
请完成以下Java代码
public ResponseEntity<BookDTO> updateBook(@Valid @RequestBody BookDTO bookDTO) throws URISyntaxException { log.debug("REST request to update Book : {}", bookDTO); if (bookDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } BookDTO result = bookService.save(bookDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, bookDTO.getId().toString())) .body(result); } /** * GET /books : get all the books. * * @return the ResponseEntity with status 200 (OK) and the list of books in body */ @GetMapping("/books") public List<BookDTO> getAllBooks() { log.debug("REST request to get all Books"); return bookService.findAll(); } /** * GET /books/:id : get the "id" book. * * @param id the id of the bookDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the bookDTO, or with status 404 (Not Found)
*/ @GetMapping("/books/{id}") public ResponseEntity<BookDTO> getBook(@PathVariable Long id) { log.debug("REST request to get Book : {}", id); Optional<BookDTO> bookDTO = bookService.findOne(id); return ResponseUtil.wrapOrNotFound(bookDTO); } /** * DELETE /books/:id : delete the "id" book. * * @param id the id of the bookDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/books/{id}") public ResponseEntity<Void> deleteBook(@PathVariable Long id) { log.debug("REST request to delete Book : {}", id); bookService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } @GetMapping("/books/purchase/{id}") public ResponseEntity<BookDTO> purchase(@PathVariable Long id) { Optional<BookDTO> bookDTO = bookService.purchase(id); return ResponseUtil.wrapOrNotFound(bookDTO); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\BookResource.java
1
请完成以下Java代码
public br addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public br addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */
public br addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public br removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\br.java
1
请完成以下Java代码
protected String getDeploymentMode() { return DEPLOYMENT_MODE; } @Override protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, DmnEngine engine) { DmnRepositoryService repositoryService = engine.getDmnRepositoryService(); // Create a single deployment for all resources using the name hint as the literal name final DmnDeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentNameHint); for (final Resource resource : resources) { addResource(resource, deploymentBuilder); } try {
deploymentBuilder.deploy(); } catch (Exception e) { if (isThrowExceptionOnDeploymentFailure()) { throw e; } else { LOGGER.warn("Exception while autodeploying DMN definitions. " + "This exception can be ignored if the root cause indicates a unique constraint violation, " + "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", e); } } } }
repos\flowable-engine-main\modules\flowable-dmn-spring\src\main\java\org\flowable\dmn\spring\autodeployment\DefaultAutoDeploymentStrategy.java
1
请完成以下Java代码
private IQueryFilter<I_M_Transaction> createReferencedModelQueryFilter(@NonNull final Object referencedModel) { final String tableName = InterfaceWrapperHelper.getModelTableName(referencedModel); final int id = InterfaceWrapperHelper.getId(referencedModel); if (I_M_InOutLine.Table_Name.equals(tableName)) { return new EqualsQueryFilter<>(I_M_Transaction.COLUMNNAME_M_InOutLine_ID, id); } else if (I_M_InventoryLine.Table_Name.equals(tableName)) { return new EqualsQueryFilter<>(I_M_Transaction.COLUMNNAME_M_InventoryLine_ID, id); } else if (I_M_MovementLine.Table_Name.equals(tableName)) { return new EqualsQueryFilter<>(I_M_Transaction.COLUMNNAME_M_MovementLine_ID, id); } else if (I_C_ProjectIssue.Table_Name.equals(tableName)) { return new EqualsQueryFilter<>(I_M_Transaction.COLUMNNAME_C_ProjectIssue_ID, id); } else if (I_PP_Cost_Collector.Table_Name.equals(tableName)) { return new EqualsQueryFilter<>(I_M_Transaction.COLUMNNAME_PP_Cost_Collector_ID, id); } else { throw new IllegalArgumentException("Referenced model not supported: " + referencedModel); } } @Override public I_M_Transaction retrieveReversalTransaction(final Object referencedModelReversal, final I_M_Transaction originalTrx) { Check.assumeNotNull(referencedModelReversal, "referencedModelReversal not null");
Check.assumeNotNull(originalTrx, "originalTrx not null"); final IQueryFilter<I_M_Transaction> referencedModelFilter = createReferencedModelQueryFilter(referencedModelReversal); final ICompositeQueryFilter<I_M_Transaction> filters = Services.get(IQueryBL.class).createCompositeQueryFilter(I_M_Transaction.class); filters.addFilter(referencedModelFilter) .addEqualsFilter(I_M_Transaction.COLUMNNAME_M_Product_ID, originalTrx.getM_Product_ID()) .addEqualsFilter(I_M_Transaction.COLUMNNAME_M_AttributeSetInstance_ID, originalTrx.getM_AttributeSetInstance_ID()) .addEqualsFilter(I_M_Transaction.COLUMNNAME_MovementType, originalTrx.getMovementType()) .addEqualsFilter(I_M_Transaction.COLUMNNAME_MovementQty, originalTrx.getMovementQty().negate()) // ; final I_M_Transaction reversalTrx = Services.get(IQueryBL.class).createQueryBuilder(I_M_Transaction.class, referencedModelReversal) .filter(filters) .create() .setOnlyActiveRecords(true) .firstOnly(I_M_Transaction.class); if (reversalTrx == null) { throw new AdempiereException("@NotFound@ @Reversal_ID@ @M_Transaction_ID@ (" + "@ReversalLine_ID@: " + referencedModelFilter + ", @M_Transaction_ID@: " + originalTrx + ")"); } return reversalTrx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\materialtransaction\impl\MTransactionDAO.java
1
请完成以下Java代码
public boolean add(Pipe<List<IWord>, List<IWord>> pipe) { return pipeList.add(pipe); } @Override public boolean remove(Object o) { return pipeList.remove(o); } @Override public boolean containsAll(Collection<?> c) { return pipeList.containsAll(c); } @Override public boolean addAll(Collection<? extends Pipe<List<IWord>, List<IWord>>> c) { return pipeList.addAll(c); } @Override public boolean addAll(int index, Collection<? extends Pipe<List<IWord>, List<IWord>>> c) { return pipeList.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return pipeList.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return pipeList.retainAll(c); } @Override public void clear() { pipeList.clear(); } @Override public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<List<IWord>, List<IWord>> get(int index) { return pipeList.get(index); } @Override public Pipe<List<IWord>, List<IWord>> set(int index, Pipe<List<IWord>, List<IWord>> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<List<IWord>, List<IWord>> element) { pipeList.add(index, element); }
@Override public Pipe<List<IWord>, List<IWord>> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<List<IWord>, List<IWord>>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\SegmentPipeline.java
1
请完成以下Java代码
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) { messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(createXmlHttpMessageConverter()); } /** * There is another possibility to add a message converter, see {@link ConverterExtensionsConfig} */ private HttpMessageConverter<Object> createXmlHttpMessageConverter() { final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller(); xmlConverter.setMarshaller(xstreamMarshaller); xmlConverter.setUnmarshaller(xstreamMarshaller); return xmlConverter; } // Etags // If we're not using Spring Boot we can make use of // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters
@Bean public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() { FilterRegistrationBean<ShallowEtagHeaderFilter> filterRegistrationBean = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter()); filterRegistrationBean.addUrlPatterns("/foos/*"); filterRegistrationBean.setName("etagFilter"); return filterRegistrationBean; } // We can also just declare the filter directly // @Bean // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { // return new ShallowEtagHeaderFilter(); // } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\spring\WebConfig.java
1
请完成以下Java代码
public boolean tryAdvance(Consumer<? super E> action) { Node<E> p; if (action == null) throw new NullPointerException(); final ConcurrentLinkedQueue<E> q = this.queue; if (!exhausted && ((p = current) != null || (p = q.first()) != null)) { E e; do { e = p.item; if (p == (p = p.next)) p = q.first(); } while (e == null && p != null); if ((current = p) == null) exhausted = true; if (e != null) { action.accept(e); return true; } } return false; } public long estimateSize() { return Long.MAX_VALUE; } public int characteristics() { return Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.CONCURRENT; } } /** * Returns a {@link Spliterator} over the elements in this queue. * * <p>The returned spliterator is * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. * * @return a {@code Spliterator} over the elements in this queue * @implNote The {@code Spliterator} implements {@code trySplit} to permit limited * parallelism. * @since 1.8 */ @Override public Spliterator<E> spliterator() {
return new CLQSpliterator<E>(this); } /** * Throws NullPointerException if argument is null. * * @param v the element */ private static void checkNotNull(Object v) { if (v == null) throw new NullPointerException(); } private boolean casTail(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); } private boolean casHead(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long headOffset; private static final long tailOffset; static { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); UNSAFE = (Unsafe) f.get(null); Class<?> k = ConcurrentLinkedQueue.class; headOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("head")); tailOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("tail")); } catch (Exception e) { throw new Error(e); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ConcurrentLinkedQueue.java
1
请在Spring Boot框架中完成以下Java代码
public int getSubscriptionsPerConnection() { return subscriptionsPerConnection; } public void setSubscriptionsPerConnection(int subscriptionsPerConnection) { this.subscriptionsPerConnection = subscriptionsPerConnection; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public int getSubscriptionConnectionMinimumIdleSize() { return subscriptionConnectionMinimumIdleSize; } public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) { this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize; } public int getSubscriptionConnectionPoolSize() { return subscriptionConnectionPoolSize; } public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) { this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize; } public int getConnectionMinimumIdleSize() { return connectionMinimumIdleSize; } public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) { this.connectionMinimumIdleSize = connectionMinimumIdleSize; } public int getConnectionPoolSize() { return connectionPoolSize; } public void setConnectionPoolSize(int connectionPoolSize) { this.connectionPoolSize = connectionPoolSize; }
public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public boolean isDnsMonitoring() { return dnsMonitoring; } public void setDnsMonitoring(boolean dnsMonitoring) { this.dnsMonitoring = dnsMonitoring; } public int getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(int dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } public String getCodec() { return codec; } public void setCodec(String codec) { this.codec = codec; } }
repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java
2
请完成以下Java代码
public String toString() { return "RequirePrivacyCallCredentials [callCredentials=" + this.callCredentials + "]"; } } /** * Wraps the given call credentials in a new layer, that will only include the credentials if the connection * guarantees privacy. If the connection doesn't do that, the call will continue without the credentials. * * <p> * <b>Note:</b> This method uses experimental grpc-java-API features. * </p> * * @param callCredentials The call credentials to wrap. * @return The newly created call credentials. */ public static CallCredentials includeWhenPrivate(final CallCredentials callCredentials) { return new IncludeWhenPrivateCallCredentials(callCredentials); } /** * A call credentials implementation with increased security requirements. It ensures that the credentials and * requests aren't send via an insecure connection. This wrapper does not have any other influence on the security * of the underlying {@link CallCredentials} implementation. */ private static final class IncludeWhenPrivateCallCredentials extends CallCredentials { private final CallCredentials callCredentials; IncludeWhenPrivateCallCredentials(final CallCredentials callCredentials) { this.callCredentials = callCredentials; }
@Override public void applyRequestMetadata(final RequestInfo requestInfo, final Executor appExecutor, final MetadataApplier applier) { if (isPrivacyGuaranteed(requestInfo.getSecurityLevel())) { this.callCredentials.applyRequestMetadata(requestInfo, appExecutor, applier); } } @Override public void thisUsesUnstableApi() {} // API evolution in progress @Override public String toString() { return "IncludeWhenPrivateCallCredentials [callCredentials=" + this.callCredentials + "]"; } } private CallCredentialsHelper() {} }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\security\CallCredentialsHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class PurchaseDetail implements BusinessCaseDetail { public static PurchaseDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail) { final boolean canBeCast = businessCaseDetail != null && businessCaseDetail instanceof PurchaseDetail; return canBeCast ? cast(businessCaseDetail) : null; } public static PurchaseDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (PurchaseDetail)businessCaseDetail; } BigDecimal qty; /** the quantity (if any) that was ordered at the vendor */ BigDecimal orderedQty; /** also this field can be <= 0, if the purchase candidate was only advised but not created so far. */ int purchaseCandidateRepoId; /** id of the purchase order line (if it already exists) */ int orderLineRepoId; int receiptScheduleRepoId; int vendorRepoId; int productPlanningRepoId; Flag advised; @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.PURCHASE; } @Builder(toBuilder = true) private PurchaseDetail( @NonNull final BigDecimal qty, @Nullable final BigDecimal orderedQty,
@NonNull Flag advised, final int orderLineRepoId, final int purchaseCandidateRepoId, final int receiptScheduleRepoId, final int vendorRepoId, final int productPlanningRepoId) { Check.errorIf(qty.signum() < 0, "The given plannedQty={} needs to be >= 0", qty); this.qty = qty; Check.errorIf(orderedQty != null && orderedQty.signum() < 0, "The given orderedQty={} needs to be >= 0", orderedQty); this.orderedQty = orderedQty; this.vendorRepoId = vendorRepoId; this.productPlanningRepoId = productPlanningRepoId; this.purchaseCandidateRepoId = purchaseCandidateRepoId; this.orderLineRepoId = orderLineRepoId; this.receiptScheduleRepoId = receiptScheduleRepoId; this.advised = advised; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\PurchaseDetail.java
2
请在Spring Boot框架中完成以下Java代码
public class OrderDO { /** * 订单编号 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY, // strategy 设置使用数据库主键自增策略; generator = "JDBC") // generator 设置插入完成后,查询最后生成的 ID 填充到该属性中。 private Integer id; /** * 用户编号 */ @Column(name = "user_id") private Integer userId; public Integer getId() { return id; } public OrderDO setId(Integer id) { this.id = id; return this; } public Integer getUserId() {
return userId; } public OrderDO setUserId(Integer userId) { this.userId = userId; return this; } @Override public String toString() { return "OrderDO{" + "id=" + id + ", userId=" + userId + '}'; } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-springdatajpa\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\dataobject\OrderDO.java
2
请在Spring Boot框架中完成以下Java代码
public class C_OrderLine { private final ProfitPriceActualFactory profitPriceActualFactory; private final OrderLineRepository orderLineRepository; public C_OrderLine( @NonNull final ProfitPriceActualFactory profitPriceActualFactory, @NonNull final OrderLineRepository orderLineRepository) { this.orderLineRepository = orderLineRepository; this.profitPriceActualFactory = profitPriceActualFactory; } @ModelChange(// timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = I_C_OrderLine.COLUMNNAME_PriceActual) public void updateProfitPriceActual(@NonNull final I_C_OrderLine orderLineRecord) { final OrderLine orderLine = orderLineRepository.ofRecord(orderLineRecord);
final CalculateProfitPriceActualRequest request = CalculateProfitPriceActualRequest.builder() .bPartnerId(orderLine.getBPartnerId()) .productId(orderLine.getProductId()) .date(orderLine.getDatePromised().toLocalDate()) .baseAmount(orderLine.getPriceActual().toMoney()) .paymentTermId(orderLine.getPaymentTermId()) .quantity(orderLine.getOrderedQty()) .build(); final Money profitBasePrice = profitPriceActualFactory.calculateProfitPriceActual(request); orderLineRecord.setProfitPriceActual(profitBasePrice.toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\grossprofit\interceptor\C_OrderLine.java
2
请完成以下Java代码
public void updateUserPassword(User user) { getIdmIdentityService().updateUserPassword(user); } @Override public UserQuery createUserQuery() { return getIdmIdentityService().createUserQuery(); } @Override public NativeUserQuery createNativeUserQuery() { return getIdmIdentityService().createNativeUserQuery(); } @Override public GroupQuery createGroupQuery() { return getIdmIdentityService().createGroupQuery(); } @Override public NativeGroupQuery createNativeGroupQuery() { return getIdmIdentityService().createNativeGroupQuery(); } @Override public void createMembership(String userId, String groupId) { getIdmIdentityService().createMembership(userId, groupId); } @Override public void deleteGroup(String groupId) { getIdmIdentityService().deleteGroup(groupId); } @Override public void deleteMembership(String userId, String groupId) { getIdmIdentityService().deleteMembership(userId, groupId); } @Override public boolean checkPassword(String userId, String password) { return getIdmIdentityService().checkPassword(userId, password); }
@Override public void deleteUser(String userId) { getIdmIdentityService().deleteUser(userId); } @Override public void setUserPicture(String userId, Picture picture) { getIdmIdentityService().setUserPicture(userId, picture); } public Picture getUserPicture(String userId) { return getIdmIdentityService().getUserPicture(userId); } @Override public void setAuthenticatedUserId(String authenticatedUserId) { Authentication.setAuthenticatedUserId(authenticatedUserId); } @Override public String getUserInfo(String userId, String key) { return getIdmIdentityService().getUserInfo(userId, key); } @Override public List<String> getUserInfoKeys(String userId) { return getIdmIdentityService().getUserInfoKeys(userId); } @Override public void setUserInfo(String userId, String key, String value) { getIdmIdentityService().setUserInfo(userId, key, value); } @Override public void deleteUserInfo(String userId, String key) { getIdmIdentityService().deleteUserInfo(userId, key); } protected IdmIdentityService getIdmIdentityService() { return CommandContextUtil.getIdmIdentityService(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\IdentityServiceImpl.java
1
请完成以下Java代码
public Collection<? extends GrantedAuthority> getAuthorities() { //返回当前用户的权限 return Arrays.asList(new SimpleGrantedAuthority("TEST")); } @Override public String getPassword() { return umsAdmin.getPassword(); } @Override public String getUsername() { return umsAdmin.getUsername(); } @Override public boolean isAccountNonExpired() { return true;
} @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\bo\AdminUserDetails.java
1
请完成以下Java代码
public void execute() { while (!steps.isEmpty()) { currentStep = steps.remove(0); try { LOG.debugPerformOperationStep(currentStep.getName()); currentStep.performOperationStep(this); successfulSteps.add(currentStep); LOG.debugSuccessfullyPerformedOperationStep(currentStep.getName()); } catch (Exception e) { if(isRollbackOnFailure) { try { rollbackOperation(); } catch(Exception e2) { LOG.exceptionWhileRollingBackOperation(e2); } // re-throw the original exception throw LOG.exceptionWhilePerformingOperationStep(name, currentStep.getName(), e); } else { LOG.exceptionWhilePerformingOperationStep(currentStep.getName(), e); } } } } protected void rollbackOperation() { // first, rollback all successful steps for (DeploymentOperationStep step : successfulSteps) { try { step.cancelOperationStep(this); } catch(Exception e) { LOG.exceptionWhileRollingBackOperation(e); } } // second, remove services for (String serviceName : installedServices) { try { serviceContainer.stopService(serviceName); } catch(Exception e) { LOG.exceptionWhileStopping("service", serviceName, e); } } } public List<String> getInstalledServices() { return installedServices; } // builder /////////////////////////////
public static class DeploymentOperationBuilder { protected PlatformServiceContainer container; protected String name; protected boolean isUndeploymentOperation = false; protected List<DeploymentOperationStep> steps = new ArrayList<DeploymentOperationStep>(); protected Map<String, Object> initialAttachments = new HashMap<String, Object>(); public DeploymentOperationBuilder(PlatformServiceContainer container, String name) { this.container = container; this.name = name; } public DeploymentOperationBuilder addStep(DeploymentOperationStep step) { steps.add(step); return this; } public DeploymentOperationBuilder addSteps(Collection<DeploymentOperationStep> steps) { for (DeploymentOperationStep step: steps) { addStep(step); } return this; } public DeploymentOperationBuilder addAttachment(String name, Object value) { initialAttachments.put(name, value); return this; } public DeploymentOperationBuilder setUndeploymentOperation() { isUndeploymentOperation = true; return this; } public void execute() { DeploymentOperation operation = new DeploymentOperation(name, container, steps); operation.isRollbackOnFailure = !isUndeploymentOperation; operation.attachments.putAll(initialAttachments); container.executeDeploymentOperation(operation); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\spi\DeploymentOperation.java
1
请在Spring Boot框架中完成以下Java代码
public SessionRepository<MapSession> sessionRepository( final SessionProperties properties, final ApplicationEventPublisher applicationEventPublisher) { final FixedMapSessionRepository sessionRepository = FixedMapSessionRepository.builder() .applicationEventPublisher(applicationEventPublisher) .defaultMaxInactiveInterval(properties.getTimeout()) .build(); logger.info("Using session repository: {}", sessionRepository); if (checkExpiredSessionsRateInMinutes > 0) { final ScheduledExecutorService scheduledExecutor = sessionScheduledExecutorService(); scheduledExecutor.scheduleAtFixedRate( sessionRepository::purgeExpiredSessionsNoFail, // command, don't fail because on failure the task won't be re-scheduled so it's game over checkExpiredSessionsRateInMinutes, // initialDelay checkExpiredSessionsRateInMinutes, // period TimeUnit.MINUTES // timeUnit ); logger.info("Checking expired sessions each {} minutes", checkExpiredSessionsRateInMinutes);
} return sessionRepository; } @Bean(BEANNAME_SessionScheduledExecutorService) public ScheduledExecutorService sessionScheduledExecutorService() { return Executors.newScheduledThreadPool( 1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix(SessionConfig.class.getName()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\SessionConfig.java
2
请完成以下Java代码
public void generate(ScopeImpl sourceScope, ScopeImpl targetScope, ProcessDefinitionImpl sourceProcessDefinition, ProcessDefinitionImpl targetProcessDefinition, ValidatingMigrationInstructions existingInstructions, boolean updateEventTriggers) { List<ValidatingMigrationInstruction> flowScopeInstructions = generateInstructionsForActivities( sourceScope.getActivities(), targetScope.getActivities(), updateEventTriggers, existingInstructions); existingInstructions.addAll(flowScopeInstructions); List<ValidatingMigrationInstruction> eventScopeInstructions = generateInstructionsForActivities( sourceScope.getEventActivities(), targetScope.getEventActivities(), updateEventTriggers, existingInstructions); existingInstructions.addAll(eventScopeInstructions); existingInstructions.filterWith(migrationInstructionValidators); for (ValidatingMigrationInstruction generatedInstruction : flowScopeInstructions) { if (existingInstructions.contains(generatedInstruction)) { generate( generatedInstruction.getSourceActivity(),
generatedInstruction.getTargetActivity(), sourceProcessDefinition, targetProcessDefinition, existingInstructions, updateEventTriggers); } } } protected boolean isValidActivity(ActivityImpl activity) { for (MigrationActivityValidator migrationActivityValidator : migrationActivityValidators) { if (!migrationActivityValidator.valid(activity)) { return false; } } return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\DefaultMigrationInstructionGenerator.java
1
请完成以下Java代码
public LookupValue findById(final Object id) { return toUnknownLookupValue(id); } @Nullable private static LookupValue toUnknownLookupValue(final Object id) { if (id == null) { return null; } if (id instanceof Integer) { return IntegerLookupValue.unknown((int)id); } else { return StringLookupValue.unknown(id.toString()); } } @Override public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids) { if (ids.isEmpty()) {
return LookupValuesList.EMPTY; } return ids.stream() .map(NullLookupDataSource::toUnknownLookupValue) .filter(Objects::nonNull) .collect(LookupValuesList.collect()); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(); } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\NullLookupDataSource.java
1
请完成以下Java代码
public static void searchEmails(Store store, String from) throws MessagingException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_ONLY); SearchTerm senderTerm = new FromStringTerm(from); Message[] messages = inbox.search(senderTerm); Message[] getFirstFiveEmails = Arrays.copyOfRange(messages, 0, 5); for (Message message : getFirstFiveEmails) { LOGGER.info("Subject: " + message.getSubject()); LOGGER.info("From: " + Arrays.toString(message.getFrom())); } inbox.close(true); } public static void deleteEmail(Store store) throws MessagingException { Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); if (messages.length >= 7) { Message seventhLatestMessage = messages[messages.length - 7]; seventhLatestMessage.setFlag(Flags.Flag.DELETED, true); LOGGER.info("Delete the seventh message: " + seventhLatestMessage.getSubject()); } else { LOGGER.info("There are less than seven messages in the inbox."); } inbox.close(true); } public static void markLatestUnreadAsRead(Store store) throws MessagingException {
Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); if (messages.length > 0) { Message latestUnreadMessage = messages[messages.length - 1]; latestUnreadMessage.setFlag(Flags.Flag.SEEN, true); } inbox.close(true); } public static void moveToFolder(Store store, Message message, String folderName) throws MessagingException { Folder destinationFolder = store.getFolder(folderName); if (!destinationFolder.exists()) { destinationFolder.create(Folder.HOLDS_MESSAGES); } Message[] messagesToMove = new Message[] { message }; message.getFolder() .copyMessages(messagesToMove, destinationFolder); message.setFlag(Flags.Flag.DELETED, true); } }
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\accessemailwithimap\GmailApp.java
1
请完成以下Java代码
public class HibernateUtil { public static SessionFactory getSessionFactory(String propertyFileName, List<Class<?>> classes) throws IOException { ServiceRegistry serviceRegistry = configureServiceRegistry(propertyFileName); return makeSessionFactory(serviceRegistry, classes); } private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry, List<Class<?>> classes) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<?> clazz: classes) { metadataSources = metadataSources.addAnnotatedClass(clazz); } Metadata metadata = metadataSources .getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder().build(); } private static ServiceRegistry configureServiceRegistry(String propertyFileName) throws IOException { return configureServiceRegistry(getProperties(propertyFileName)); }
private static ServiceRegistry configureServiceRegistry(Properties properties) { return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } public static Properties getProperties(String propertyFileName) throws IOException { Properties properties = new Properties(); String file = getResourceURL(propertyFileName).getFile(); try (FileInputStream inputStream = new FileInputStream(file)) { properties.load(inputStream); } return properties; } private static URL getResourceURL(String propertyFileName) { return requireNonNull(Thread.currentThread() .getContextClassLoader() .getResource(StringUtils.defaultString(propertyFileName, "hibernate.properties"))); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\HibernateUtil.java
1
请完成以下Java代码
public int getC_ProjectType_ID() { return get_ValueAsInt(COLUMNNAME_C_ProjectType_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @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); } /** * ProjectCategory AD_Reference_ID=288 * Reference name: C_ProjectType Category */ public static final int PROJECTCATEGORY_AD_Reference_ID=288; /** General = N */ public static final String PROJECTCATEGORY_General = "N"; /** AssetProject = A */ public static final String PROJECTCATEGORY_AssetProject = "A"; /** WorkOrderJob = W */ public static final String PROJECTCATEGORY_WorkOrderJob = "W"; /** ServiceChargeProject = S */ public static final String PROJECTCATEGORY_ServiceChargeProject = "S"; /** ServiceOrRepair = R */ public static final String PROJECTCATEGORY_ServiceOrRepair = "R"; /** SalesPurchaseOrder = O */ public static final String PROJECTCATEGORY_SalesPurchaseOrder = "O"; @Override public void setProjectCategory (final java.lang.String ProjectCategory) { set_ValueNoCheck (COLUMNNAME_ProjectCategory, ProjectCategory); } @Override public java.lang.String getProjectCategory() { return get_ValueAsString(COLUMNNAME_ProjectCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectType.java
1
请完成以下Java代码
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { ProcessTask processTask = new ProcessTask(); convertCommonTaskAttributes(xtr, processTask); processTask.setProcessRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_PROCESS_REF)); String businessKey = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_BUSINESS_KEY); if (businessKey != null) { processTask.setBusinessKey(businessKey); } String inheritBusinessKey = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INHERIT_BUSINESS_KEY); if (inheritBusinessKey != null) { processTask.setInheritBusinessKey(Boolean.parseBoolean(inheritBusinessKey)); } String fallbackToDefaultTenantValue = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_FALLBACK_TO_DEFAULT_TENANT); if (fallbackToDefaultTenantValue != null) { processTask.setFallbackToDefaultTenant(Boolean.parseBoolean(fallbackToDefaultTenantValue));
} String sameDeploymentValue = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_SAME_DEPLOYMENT); if (sameDeploymentValue != null) { processTask.setSameDeployment(Boolean.parseBoolean(sameDeploymentValue)); } String idVariableName = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_ID_VARIABLE_NAME); if (StringUtils.isNotEmpty(idVariableName)) { processTask.setProcessInstanceIdVariableName(idVariableName); } return processTask; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ProcessTaskXmlConverter.java
1
请完成以下Java代码
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.eventPublisher = applicationEventPublisher; } public void setAuthenticationManager(AuthenticationManager newManager) { this.authenticationManager = newManager; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } /** * Only {@code AuthorizationFailureEvent} will be published. If you set this property * to {@code true}, {@code AuthorizedEvent}s will also be published. * @param publishAuthorizationSuccess default value is {@code false} */ public void setPublishAuthorizationSuccess(boolean publishAuthorizationSuccess) { this.publishAuthorizationSuccess = publishAuthorizationSuccess; } /** * By rejecting public invocations (and setting this property to <tt>true</tt>), * essentially you are ensuring that every secure object invocation advised by * <code>AbstractSecurityInterceptor</code> has a configuration attribute defined. * This is useful to ensure a "fail safe" mode where undeclared secure objects will be * rejected and configuration omissions detected early. An * <tt>IllegalArgumentException</tt> will be thrown by the * <tt>AbstractSecurityInterceptor</tt> if you set this property to <tt>true</tt> and * an attempt is made to invoke a secure object that has no configuration attributes. * @param rejectPublicInvocations set to <code>true</code> to reject invocations of * secure objects that have no configuration attributes (by default it is * <code>false</code> which treats undeclared secure objects as "public" or
* unauthorized). */ public void setRejectPublicInvocations(boolean rejectPublicInvocations) { this.rejectPublicInvocations = rejectPublicInvocations; } public void setRunAsManager(RunAsManager runAsManager) { this.runAsManager = runAsManager; } public void setValidateConfigAttributes(boolean validateConfigAttributes) { this.validateConfigAttributes = validateConfigAttributes; } private void publishEvent(ApplicationEvent event) { if (this.eventPublisher != null) { this.eventPublisher.publishEvent(event); } } private static class NoOpAuthenticationManager implements AuthenticationManager { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { throw new AuthenticationServiceException("Cannot authenticate " + authentication); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AbstractSecurityInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getLoginName() { return loginName; } /** * 登录名 * * @return */ public void setLoginName(String loginName) { this.loginName = loginName; } /** * 登录密码 * * @return */ public String getLoginPwd() { return loginPwd; } /** * 登录密码 * * @return */ public void setLoginPwd(String loginPwd) { this.loginPwd = loginPwd; } /** * 姓名 * * @return */ public String getRealName() { return realName; } /** * 姓名 * * @return */ public void setRealName(String realName) { this.realName = realName; } /** * 手机号 * * @return */ public String getMobileNo() { return mobileNo; } /** * 手机号 * * @return */ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo;
} /** * 操作员类型 * * @return */ public String getType() { return type; } /** * 操作员类型 * * @return */ public void setType(String type) { this.type = type; } /** * 盐 * * @return */ public String getsalt() { return salt; } /** * 盐 * * @param salt */ public void setsalt(String salt) { this.salt = salt; } /** * 认证加密的盐 * * @return */ public String getCredentialsSalt() { return loginName + salt; } public PmsOperator() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperator.java
2
请在Spring Boot框架中完成以下Java代码
public class ImportTableDescriptorRepository { private final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class); private static final String COLUMNNAME_C_DataImport_ID = I_C_DataImport.COLUMNNAME_C_DataImport_ID; private static final String COLUMNNAME_AD_Issue_ID = I_AD_Issue.COLUMNNAME_AD_Issue_ID; private static final String COLUMNNAME_I_LineContent = "I_LineContent"; private static final String COLUMNNAME_I_LineNo = "I_LineNo"; private final CCache<AdTableId, ImportTableDescriptor> // importTableDescriptors = CCache.<AdTableId, ImportTableDescriptor> builder() .additionalTableNameToResetFor(I_AD_Table.Table_Name) .additionalTableNameToResetFor(I_AD_Column.Table_Name) .build(); public ImportTableDescriptor getByTableId(@NonNull final AdTableId adTableId) { return importTableDescriptors.getOrLoad(adTableId, this::retrieveByTableId); } public ImportTableDescriptor getByTableName(@NonNull final String tableName) { final AdTableId adTableId = AdTableId.ofRepoId(adTablesRepo.retrieveTableId(tableName)); return getByTableId(adTableId); } private ImportTableDescriptor retrieveByTableId(@NonNull final AdTableId adTableId) { final POInfo poInfo = POInfo.getPOInfo(adTableId); Check.assumeNotNull(poInfo, "poInfo is not null for AD_Table_ID={}", adTableId); final String tableName = poInfo.getTableName(); final String keyColumnName = poInfo.getKeyColumnName();
if (keyColumnName == null) { throw new AdempiereException("Table " + tableName + " has not primary key"); } assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, poInfo); assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, poInfo); return ImportTableDescriptor.builder() .tableName(tableName) .keyColumnName(keyColumnName) // .dataImportConfigIdColumnName(columnNameIfExists(COLUMNNAME_C_DataImport_ID, poInfo)) .adIssueIdColumnName(columnNameIfExists(COLUMNNAME_AD_Issue_ID, poInfo)) .importLineContentColumnName(columnNameIfExists(COLUMNNAME_I_LineContent, poInfo)) .importLineNoColumnName(columnNameIfExists(COLUMNNAME_I_LineNo, poInfo)) .errorMsgMaxLength(poInfo.getFieldLength(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg)) // .build(); } private static void assertColumnNameExists(@NonNull final String columnName, @NonNull final POInfo poInfo) { if (!poInfo.hasColumnName(columnName)) { throw new AdempiereException("No " + poInfo.getTableName() + "." + columnName + " defined"); } } private static String columnNameIfExists(@NonNull final String columnName, @NonNull final POInfo poInfo) { return poInfo.hasColumnName(columnName) ? columnName : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImportTableDescriptorRepository.java
2
请完成以下Java代码
public void commit() { LOG.debugTransactionOperation("firing event committing..."); fireTransactionEvent(TransactionState.COMMITTING); LOG.debugTransactionOperation("committing the persistence session..."); getPersistenceProvider().commit(); LOG.debugTransactionOperation("firing event committed..."); fireTransactionEvent(TransactionState.COMMITTED); } protected void fireTransactionEvent(TransactionState transactionState) { this.setLastTransactionState(transactionState); if (stateTransactionListeners==null) { return; } List<TransactionListener> transactionListeners = stateTransactionListeners.get(transactionState); if (transactionListeners==null) { return; } for (TransactionListener transactionListener: transactionListeners) { transactionListener.execute(commandContext); } } protected void setLastTransactionState(TransactionState transactionState) { this.lastTransactionState = transactionState; } private PersistenceSession getPersistenceProvider() { return commandContext.getSession(PersistenceSession.class); } public void rollback() { try { try { LOG.debugTransactionOperation("firing event rollback..."); fireTransactionEvent(TransactionState.ROLLINGBACK); } catch (Throwable exception) { LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception);
Context.getCommandInvocationContext().trySetThrowable(exception); } finally { LOG.debugTransactionOperation("rolling back the persistence session..."); getPersistenceProvider().rollback(); } } catch (Throwable exception) { LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception); Context.getCommandInvocationContext().trySetThrowable(exception); } finally { LOG.debugFiringEventRolledBack(); fireTransactionEvent(TransactionState.ROLLED_BACK); } } public boolean isTransactionActive() { return !TransactionState.ROLLINGBACK.equals(lastTransactionState) && !TransactionState.ROLLED_BACK.equals(lastTransactionState); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\standalone\StandaloneTransactionContext.java
1
请完成以下Java代码
public java.sql.Timestamp getQtyStockEstimateTime_AtDate() { return get_ValueAsTimestamp(COLUMNNAME_QtyStockEstimateTime_AtDate); } @Override public void setQtySupply_DD_Order_AtDate (final @Nullable BigDecimal QtySupply_DD_Order_AtDate) { set_Value (COLUMNNAME_QtySupply_DD_Order_AtDate, QtySupply_DD_Order_AtDate); } @Override public BigDecimal getQtySupply_DD_Order_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_DD_Order_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupply_PP_Order_AtDate (final @Nullable BigDecimal QtySupply_PP_Order_AtDate) { set_Value (COLUMNNAME_QtySupply_PP_Order_AtDate, QtySupply_PP_Order_AtDate); } @Override public BigDecimal getQtySupply_PP_Order_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PP_Order_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupply_PurchaseOrder_AtDate (final @Nullable BigDecimal QtySupply_PurchaseOrder_AtDate) { set_Value (COLUMNNAME_QtySupply_PurchaseOrder_AtDate, QtySupply_PurchaseOrder_AtDate); } @Override public BigDecimal getQtySupply_PurchaseOrder_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupply_PurchaseOrder_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyRequired_AtDate (final @Nullable BigDecimal QtySupplyRequired_AtDate) { set_Value (COLUMNNAME_QtySupplyRequired_AtDate, QtySupplyRequired_AtDate);
} @Override public BigDecimal getQtySupplyRequired_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyRequired_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplySum_AtDate (final @Nullable BigDecimal QtySupplySum_AtDate) { set_Value (COLUMNNAME_QtySupplySum_AtDate, QtySupplySum_AtDate); } @Override public BigDecimal getQtySupplySum_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplySum_AtDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtySupplyToSchedule_AtDate (final @Nullable BigDecimal QtySupplyToSchedule_AtDate) { set_Value (COLUMNNAME_QtySupplyToSchedule_AtDate, QtySupplyToSchedule_AtDate); } @Override public BigDecimal getQtySupplyToSchedule_AtDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtySupplyToSchedule_AtDate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit.java
1
请在Spring Boot框架中完成以下Java代码
PropagatingSenderTracingObservationHandler<?> propagatingSenderTracingObservationHandler(Tracer tracer, Propagator propagator) { return new PropagatingSenderTracingObservationHandler<>(tracer, propagator); } @Bean @ConditionalOnMissingBean @ConditionalOnBean(Propagator.class) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) PropagatingReceiverTracingObservationHandler<?> propagatingReceiverTracingObservationHandler(Tracer tracer, Propagator propagator) { return new PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Advice.class) @ConditionalOnBooleanProperty("management.observations.annotations.enabled") static class SpanAspectConfiguration { @Bean @ConditionalOnMissingBean(NewSpanParser.class) DefaultNewSpanParser newSpanParser() { return new DefaultNewSpanParser(); } @Bean
@ConditionalOnMissingBean @ConditionalOnBean(ValueExpressionResolver.class) SpanTagAnnotationHandler spanTagAnnotationHandler(BeanFactory beanFactory, ValueExpressionResolver valueExpressionResolver) { return new SpanTagAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver); } @Bean @ConditionalOnMissingBean(MethodInvocationProcessor.class) ImperativeMethodInvocationProcessor imperativeMethodInvocationProcessor(NewSpanParser newSpanParser, Tracer tracer, ObjectProvider<SpanTagAnnotationHandler> spanTagAnnotationHandler) { return new ImperativeMethodInvocationProcessor(newSpanParser, tracer, spanTagAnnotationHandler.getIfAvailable()); } @Bean @ConditionalOnMissingBean SpanAspect spanAspect(MethodInvocationProcessor methodInvocationProcessor) { return new SpanAspect(methodInvocationProcessor); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\MicrometerTracingAutoConfiguration.java
2
请完成以下Java代码
class FindOperatorCellEditor extends FindCellEditor { private static final long serialVersionUID = 6655568524454256089L; private CComboBox<Operator> _editor = null; private final ListComboBoxModel<Operator> modelForLookupColumns = new ListComboBoxModel<>(MQuery.Operator.operatorsForLookups); private final ListComboBoxModel<Operator> modelForYesNoColumns = new ListComboBoxModel<>(MQuery.Operator.operatorsForBooleans); private final ListComboBoxModel<Operator> modelDefault = new ListComboBoxModel<>(MQuery.Operator.values()); private final ListComboBoxModel<Operator> modelEmpty = new ListComboBoxModel<>(); public FindOperatorCellEditor() { super(); } @Override public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int col) { updateEditor(table, row); return super.getTableCellEditorComponent(table, value, isSelected, row, col); } @Override protected CComboBox<Operator> getEditor() { if (_editor == null) { _editor = new CComboBox<>(); _editor.enableAutoCompletion(); } return _editor; } private void updateEditor(final JTable table, final int viewRowIndex) { final CComboBox<Operator> editor = getEditor(); final IUserQueryRestriction row = getRow(table, viewRowIndex); final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField()); if (searchField != null) { // check if the column is columnSQL with reference (08757) // final String columnName = searchField.getColumnName(); final int displayType = searchField.getDisplayType(); final boolean isColumnSQL = searchField.isVirtualColumn(); final boolean isReference = searchField.getAD_Reference_Value_ID() != null; if (isColumnSQL && isReference) { // make sure also the columnSQLs with reference are only getting the ID operators (08757) editor.setModel(modelForLookupColumns); } else if (DisplayType.isAnyLookup(displayType))
{ editor.setModel(modelForLookupColumns); } else if (DisplayType.YesNo == displayType) { editor.setModel(modelForYesNoColumns); } else { editor.setModel(modelDefault); } } else { editor.setModel(modelEmpty); } } private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex) { final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel(); final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex); return model.getRow(modelRowIndex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindOperatorCellEditor.java
1
请完成以下Java代码
public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { final int size = getSize(); final List<Object> list = new ArrayList<Object>(size); for (int i = 0; i < size; i++) { final Object oo = getElementAt(i); list.add(oo); } // Sort Data if (m_keyColumn.endsWith("_ID")) { KeyNamePair p = KeyNamePair.EMPTY; if (!mandatory) list.add (p); Collections.sort (list, p); } else { ValueNamePair p = ValueNamePair.EMPTY; if (!mandatory) list.add (p); Collections.sort (list, p); } return list; } // getArray /** * Refresh Values (nop) * @return number of cache */ @Override public int refresh() { return getSize(); } // refresh @Override public String getTableName() { if (Check.isEmpty(m_keyColumn, true)) { return null;
} return MQuery.getZoomTableName(m_keyColumn); } /** * Get underlying fully qualified Table.Column Name * @return column name */ @Override public String getColumnName() { return m_keyColumn; } // getColumnName @Override public String getColumnNameNotFQ() { return m_keyColumn; } } // XLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\XLookup.java
1
请完成以下Java代码
public class X_AD_LabelPrinter extends PO implements I_AD_LabelPrinter, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_AD_LabelPrinter (Properties ctx, int AD_LabelPrinter_ID, String trxName) { super (ctx, AD_LabelPrinter_ID, trxName); /** if (AD_LabelPrinter_ID == 0) { setAD_LabelPrinter_ID (0); setName (null); } */ } /** Load Constructor */ public X_AD_LabelPrinter (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_LabelPrinter[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Label printer. @param AD_LabelPrinter_ID Label Printer Definition */ public void setAD_LabelPrinter_ID (int AD_LabelPrinter_ID) { if (AD_LabelPrinter_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, Integer.valueOf(AD_LabelPrinter_ID)); } /** Get Label printer. @return Label Printer Definition
*/ public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinter.java
1
请在Spring Boot框架中完成以下Java代码
public OrderedArticleLineDuration amount(BigDecimal amount) { this.amount = amount; return this; } /** * Anzahl der Tage, Wochen, Monate * @return amount **/ @Schema(example = "30", description = "Anzahl der Tage, Wochen, Monate") public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public OrderedArticleLineDuration timePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; return this; } /** * Zeitintervall (Unbekannt &#x3D; 0, Minute &#x3D; 1, Stunde &#x3D; 2, Tag &#x3D; 3, Woche &#x3D; 4, Monat &#x3D; 5, Quartal &#x3D; 6, Halbjahr &#x3D; 7, Jahr &#x3D; 8) * @return timePeriod **/ @Schema(example = "3", description = "Zeitintervall (Unbekannt = 0, Minute = 1, Stunde = 2, Tag = 3, Woche = 4, Monat = 5, Quartal = 6, Halbjahr = 7, Jahr = 8)") public BigDecimal getTimePeriod() { return timePeriod; } public void setTimePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedArticleLineDuration orderedArticleLineDuration = (OrderedArticleLineDuration) o; return Objects.equals(this.amount, orderedArticleLineDuration.amount) &&
Objects.equals(this.timePeriod, orderedArticleLineDuration.timePeriod); } @Override public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderedArticleLineDuration {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLineDuration.java
2
请完成以下Java代码
protected void afterPost() { postDependingMatchInvsIfNeeded(); } private void postDependingMatchInvsIfNeeded() { if (!services.getSysConfigBooleanValue(SYSCONFIG_PostMatchInvs, DEFAULT_PostMatchInvs)) { return; } final ImmutableSet<InOutLineId> inoutLineIds = getDocLines() .stream() .map(DocLine_InOut::getInOutLineId) .collect(ImmutableSet.toImmutableSet()); if (inoutLineIds.isEmpty()) { return; } final Set<MatchInvId> matchInvIds = matchInvoiceService.getIdsProcessedButNotPostedByInOutLineIds(inoutLineIds); postDependingDocuments(I_M_MatchInv.Table_Name, matchInvIds); } @NonNull private CostAmount roundToStdPrecision(@NonNull final CostAmount costs) { return costs.round(services::getCurrencyStandardPrecision); } public CurrencyConversionContext getCurrencyConversionContext(final AcctSchema ignoredAcctSchema) { final I_M_InOut inout = getModel(I_M_InOut.class); return inOutBL.getCurrencyConversionContext(inout); } @Nullable @Override protected OrderId getSalesOrderId()
{ final Optional<OrderId> optionalSalesOrderId = CollectionUtils.extractSingleElementOrDefault( getDocLines(), docLine -> Optional.ofNullable(docLine.getSalesOrderId()), Optional.empty()); //noinspection DataFlowIssue return optionalSalesOrderId.orElse(null); } // // // // // @Value static class InOutDocBaseType { @NonNull DocBaseType docBaseType; boolean isSOTrx; public boolean isCustomerShipment() {return isSOTrx && docBaseType.isShipment();} public boolean isCustomerReturn() {return isSOTrx && docBaseType.isReceipt();} public boolean isVendorReceipt() {return !isSOTrx && docBaseType.isReceipt();} public boolean isVendorReturn() {return !isSOTrx && docBaseType.isShipment();} public boolean isReturn() {return isCustomerReturn() || isVendorReturn();} } } // Doc_InOut
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_InOut.java
1