instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public DataSource ordersDataSource() { // 获得 DataSourceProperties 对象 DataSourceProperties properties = this.ordersDataSourceProperties(); // 创建 HikariDataSource 对象 return createHikariDataSource(properties); } /** * 创建 users 数据源的配置对象 */ @Bean(name = "usersDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.users") // 读取 spring.datasource.users 配置到 DataSourceProperties 对象 public DataSourceProperties usersDataSourceProperties() { return new DataSourceProperties(); } /** * 创建 users 数据源 */ @Bean(name = "usersDataSource") @ConfigurationProperties(prefix = "spring.datasource.users.hikari") public DataSource usersDataSource() { // 获得 DataSourceProperties 对象 DataSourceProperties properties = this.usersDataSourceProperties(); // 创建 HikariDataSource 对象 return createHikariDataSource(properties); } private static HikariDataSource createHikariDataSource(DataSourceProperties properties) { // 创建 HikariDataSource 对象 HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
// 设置线程池名 if (StringUtils.hasText(properties.getName())) { dataSource.setPoolName(properties.getName()); } return dataSource; } // /** // * 创建 orders 数据源 // */ // @Bean(name = "ordersDataSource") // @ConfigurationProperties(prefix = "spring.datasource.orders") // public DataSource ordersDataSource() { // return DataSourceBuilder.create().build(); // } }
repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-hikaricp-multiple\src\main\java\cn\iocoder\springboot\lab19\datasourcepool\config\DataSourceConfig.java
2
请完成以下Java代码
public int getI_Pharma_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_Pharma_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_BPartner.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthProgramInitParamVo implements Serializable{ private static final long serialVersionUID = 8312768816414393880L; /** * 支付Key */ @Size(max = 32, message = "支付Key[payKey]长度最大32位") @NotNull(message = "支付Key[payKey]不能为空") private String payKey; /** * 订单号 */ @Size(max = 32, message = "订单号[orderNo]长度最大32位") @NotNull(message = "订单号[orderNo]不能为空") private String orderNo; /** * 用户姓名 */ @Size(max = 50, message = "用户姓名[userName]长度最大50位") @NotNull(message = "用户姓名[userName]不能为空") private String userName; /** * 手机号 */ @Size(max = 11, message = "手机号码[phone]长度最大11位") @NotNull(message = "手机号码[phone]不能为空") private String phone; /** * 身份证号 */ @Size(max = 18, message = "身份证号[idNo]长度最大18位") @NotNull(message = "身份证号[idNo]不能为空") private String idNo; /** * 银行卡号 */ @Size(max = 20, message = "银行卡号[bankAccountNo]长度最大20位") @NotNull(message = "银行卡号[bankAccountNo]不能为空") private String bankAccountNo; @NotNull(message = "用户标识[openId]不能为空") private String openId; @NotNull(message = "支付类型[payWayCode]不能为空") private String payWayCode; /** * 备注 */ private String remark; /** * 签名 */ @NotNull(message = "数据签名[sign]不能为空") private String sign; public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) {
this.orderNo = orderNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthProgramInitParamVo.java
2
请完成以下Java代码
public boolean isSuppressZeroLine() { return this.get_ValueAsBoolean("IsSuppressZeroLine"); } @Override public MReportLineSet getPA_ReportLineSet() { if (parent == null) { parent = (MReportLineSet)super.getPA_ReportLineSet(); } return parent; } void setParent(MReportLineSet lineSet) { this.parent = lineSet; } private MReportLineSet parent = null; public boolean isInclInParentCalc() { return this.get_ValueAsBoolean("IsInclInParentCalc"); } public static void checkIncludedReportLineSetCycles(MReportLine line) { checkIncludedReportLineSetCycles(line, new TreeSet<Integer>(), new StringBuffer()); } private static void checkIncludedReportLineSetCycles(MReportLine line, Collection<Integer> trace, StringBuffer traceStr) { StringBuffer traceStr2 = new StringBuffer(traceStr); if (traceStr2.length() > 0) traceStr2.append(" - ");
traceStr2.append(line.getName()); if (trace.contains(line.getPA_ReportLine_ID())) { throw new AdempiereException("@PA_ReportLine_ID@ Loop Detected: "+traceStr2.toString()); // TODO: translate } Collection<Integer> trace2 = new TreeSet<Integer>(trace); trace2.add(line.getPA_ReportLine_ID()); if (line.isLineTypeIncluded() && line.getPA_ReportLineSet() != null) { MReportLineSet includedSet = line.getIncluded_ReportLineSet(); traceStr2.append("(").append(includedSet.getName()).append(")"); for (MReportLine includedLine : includedSet.getLiness()) { checkIncludedReportLineSetCycles(includedLine, trace2, traceStr2); } } } } // MReportLine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportLine.java
1
请完成以下Java代码
public ReceiptCorrectHUsProcessor build() { return new ReceiptCorrectHUsProcessor(this); } public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule) { this.receiptSchedule = receiptSchedule; return this; } private I_M_ReceiptSchedule getM_ReceiptSchedule() { Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null"); return receiptSchedule;
} public Builder tolerateNoHUsFound() { tolerateNoHUsFound = true; return this; } private boolean isFailOnNoHUsFound() { return !tolerateNoHUsFound; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java
1
请完成以下Java代码
public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board_Lane getWEBUI_Board_Lane() {
return get_ValueAsPO(COLUMNNAME_WEBUI_Board_Lane_ID, de.metas.ui.web.base.model.I_WEBUI_Board_Lane.class); } @Override public void setWEBUI_Board_Lane(final de.metas.ui.web.base.model.I_WEBUI_Board_Lane WEBUI_Board_Lane) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_Lane_ID, de.metas.ui.web.base.model.I_WEBUI_Board_Lane.class, WEBUI_Board_Lane); } @Override public void setWEBUI_Board_Lane_ID (final int WEBUI_Board_Lane_ID) { if (WEBUI_Board_Lane_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, WEBUI_Board_Lane_ID); } @Override public int getWEBUI_Board_Lane_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_Lane_ID); } @Override public void setWEBUI_Board_RecordAssignment_ID (final int WEBUI_Board_RecordAssignment_ID) { if (WEBUI_Board_RecordAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_RecordAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_RecordAssignment_ID, WEBUI_Board_RecordAssignment_ID); } @Override public int getWEBUI_Board_RecordAssignment_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_RecordAssignment_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_RecordAssignment.java
1
请完成以下Java代码
public void setVerfalldatum(XMLGregorianCalendar value) { this.verfalldatum = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="AuftragsID" type="{urn:msv3:v2}uuid" /&gt; * &lt;attribute name="Menge" use="required"&gt; * &lt;simpleType&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}int"&gt; * &lt;minInclusive value="1"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * &lt;/attribute&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Fehlmenge { @XmlAttribute(name = "AuftragsID") protected String auftragsID; @XmlAttribute(name = "Menge", required = true) protected int menge; /** * Gets the value of the auftragsID property. * * @return * possible object is * {@link String } * */ public String getAuftragsID() { return auftragsID; } /** * Sets the value of the auftragsID property. * * @param value * allowed object is * {@link String }
* */ public void setAuftragsID(String value) { this.auftragsID = value; } /** * Gets the value of the menge property. * */ public int getMenge() { return menge; } /** * Sets the value of the menge property. * */ public void setMenge(int value) { this.menge = value; } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfragenAntwort.java
1
请完成以下Java代码
public void thisUsesUnstableApi() {} // API evolution in progress @Override 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
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_MembershipMonth_ID (final int C_MembershipMonth_ID) { if (C_MembershipMonth_ID < 1) set_ValueNoCheck (COLUMNNAME_C_MembershipMonth_ID, null); else set_ValueNoCheck (COLUMNNAME_C_MembershipMonth_ID, C_MembershipMonth_ID); } @Override public int getC_MembershipMonth_ID() { return get_ValueAsInt(COLUMNNAME_C_MembershipMonth_ID); } @Override public org.compiere.model.I_C_Year getC_Year() { return get_ValueAsPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class); } @Override public void setC_Year(final org.compiere.model.I_C_Year C_Year) { set_ValueFromPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class, C_Year); } @Override public void setC_Year_ID (final int C_Year_ID)
{ if (C_Year_ID < 1) set_Value (COLUMNNAME_C_Year_ID, null); else set_Value (COLUMNNAME_C_Year_ID, C_Year_ID); } @Override public int getC_Year_ID() { return get_ValueAsInt(COLUMNNAME_C_Year_ID); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_ValueNoCheck (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\compiere\model\X_C_MembershipMonth.java
1
请完成以下Java代码
public String getTotalWhere () { StringBuffer sql = new StringBuffer ("<= "); sql.append(DB.TO_DATE(m_EndDate)); return sql.toString(); } // getPeriodWhere /** * Is date in period * @param date date * @return true if in period */ public boolean inPeriod (Timestamp date) { if (date == null) return false; if (date.before(m_StartDate)) return false; if (date.after(m_EndDate)) return false; return true; } // inPeriod /** * Get Name * @return name */ public String getName() { return m_Name; } /** * Get C_Period_ID * @return period */ public int getC_Period_ID() { return m_C_Period_ID; } /** * Get End Date * @return end date */ public Timestamp getEndDate() { return m_EndDate; } /** * Get Start Date
* @return start date */ public Timestamp getStartDate() { return m_StartDate; } /** * Get Year Start Date * @return year start date */ public Timestamp getYearStartDate() { return m_YearStartDate; } /** * Get natural balance dateacct filter * @param alias table name or alias name * @return is balance sheet a/c and <= end or BETWEEN start AND end */ public String getNaturalWhere(String alias) { String yearWhere = getYearWhere(); String totalWhere = getTotalWhere(); String bs = " EXISTS (SELECT C_ElementValue_ID FROM C_ElementValue WHERE C_ElementValue_ID = " + alias + ".Account_ID AND AccountType NOT IN ('R', 'E'))"; String full = totalWhere + " AND ( " + bs + " OR TRUNC(" + alias + ".DateAcct) " + yearWhere + " ) "; return full; } } // FinReportPeriod
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinReportPeriod.java
1
请完成以下Java代码
public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public String getErrorMessage() { return typedValueField.getErrorMessage(); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) {
this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", executionId=" + executionId + ", tenantId=" + tenantId + ", activityInstanceId=" + activityInstanceId + ", caseDefinitionKey=" + caseDefinitionKey + ", caseDefinitionId=" + caseDefinitionId + ", caseInstanceId=" + caseInstanceId + ", caseExecutionId=" + caseExecutionId + ", name=" + name + ", createTime=" + createTime + ", revision=" + revision + ", serializerName=" + getSerializerName() + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", state=" + state + ", byteArrayId=" + getByteArrayId() + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请在Spring Boot框架中完成以下Java代码
public SignAuthInterceptor signAuthInterceptor() { return new SignAuthInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { //------------------------------------------------------------ //查询需要进行签名拦截的接口 signUrls String signUrls = jeecgBaseConfig.getSignUrls(); String[] signUrlsArray = null; if (StringUtils.isNotBlank(signUrls)) { signUrlsArray = signUrls.split(","); } else { signUrlsArray = PathMatcherUtil.SIGN_URL_LIST; } //------------------------------------------------------------ registry.addInterceptor(signAuthInterceptor()).addPathPatterns(signUrlsArray); } // 代码逻辑说明: issues/I53J5E post请求X_SIGN签名拦截校验后报错, request body 为空 @Bean public RequestBodyReserveFilter requestBodyReserveFilter(){ return new RequestBodyReserveFilter(); } @Bean
public FilterRegistrationBean reqBodyFilterRegistrationBean(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(requestBodyReserveFilter()); registration.setName("requestBodyReserveFilter"); //------------------------------------------------------------ //查询需要进行签名拦截的接口 signUrls String signUrls = jeecgBaseConfig.getSignUrls(); String[] signUrlsArray = null; if (StringUtils.isNotBlank(signUrls)) { signUrlsArray = signUrls.split(","); } else { signUrlsArray = PathMatcherUtil.SIGN_URL_LIST; } //------------------------------------------------------------ // 建议此处只添加post请求地址而不是所有的都需要走过滤器 registration.addUrlPatterns(signUrlsArray); return registration; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\interceptor\SignAuthConfiguration.java
2
请完成以下Java代码
public void setPartitionSize(final int PartitionSize) { set_ValueNoCheck(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize)); } /** * Get Anz. zugeordneter Datensätze. * * @return Anz. zugeordneter Datensätze */ @Override public int getPartitionSize() { final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize); if (ii == null) { return 0; } return ii.intValue(); } /**
* Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { set_ValueNoCheck(COLUMNNAME_TableName, TableName); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Size_Per_Table_V.java
1
请完成以下Java代码
public String getFactoryClassName() { return className; } public void setFactoryClassName(String className) { this.className = className; } public Class<?> getFactoryClass() { return ref != null ? ref.get() : null; } public void setFactoryClass(Class<?> clazz) { ref = new WeakReference<>(clazz); } } /** * Discover the name of class that implements ExpressionFactory. * * @param tccl {@code ClassLoader} * @return Class name. There is default, so it is never {@code null}. */ private static String discoverClassName(ClassLoader tccl) { // First services API String className = getClassNameServices(tccl); if (className == null) { // Second el.properties file className = getClassNameJreDir(); } if (className == null) { // Third system property className = getClassNameSysProp(); } if (className == null) { // Fourth - default className = "org.flowable.common.engine.impl.de.odysseus.el.ExpressionFactoryImpl"; } return className; } private static String getClassNameServices(ClassLoader tccl) { ExpressionFactory result = null; ServiceLoader<ExpressionFactory> serviceLoader = ServiceLoader.load(ExpressionFactory.class, tccl); Iterator<ExpressionFactory> iter = serviceLoader.iterator(); while (result == null && iter.hasNext()) { result = iter.next(); } if (result == null) { return null; } return result.getClass().getName(); }
private static String getClassNameJreDir() { File file = new File(PROPERTY_FILE); if (file.canRead()) { try (InputStream is = new FileInputStream(file)) { Properties props = new Properties(); props.load(is); String value = props.getProperty(PROPERTY_NAME); if (value != null && !value.trim().isEmpty()) { return value.trim(); } } catch (FileNotFoundException e) { // Should not happen - ignore it if it does } catch (IOException ioe) { throw new ELException("Failed to read " + PROPERTY_NAME, ioe); } } return null; } private static String getClassNameSysProp() { String value = System.getProperty(PROPERTY_NAME); if (value != null && !value.trim().isEmpty()) { return value.trim(); } return null; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ExpressionFactory.java
1
请完成以下Java代码
public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } public boolean isDoNotUpdateToLatestVersionAutomatically() { return doNotUpdateToLatestVersionAutomatically; } public String getTenantId() { return tenantId; } @Override public EventSubscription subscribe() { checkValidInformation();
return runtimeService.registerProcessInstanceStartEventSubscription(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionKey)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the key for the subscription to be registered."); } if (correlationParameterValues.isEmpty()) { throw new FlowableIllegalArgumentException( "At least one correlation parameter value must be provided for a dynamic process start event subscription, " + "otherwise the process would get started on all events, regardless their correlation parameter values."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionBuilderImpl.java
1
请完成以下Java代码
static final class AuthUserImpl implements AuthUser { @Override public boolean authTarget(String target, PrivilegeType privilegeType) { // fake implementation, always return true return true; } @Override public boolean isSuperUser() { // fake implementation, always return true return true; } @Override
public String getNickName() { return "FAKE_NICK_NAME"; } @Override public String getLoginName() { return "FAKE_LOGIN_NAME"; } @Override public String getId() { return "FAKE_EMP_ID"; } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\FakeAuthServiceImpl.java
1
请完成以下Java代码
public static String desDecrypt(String source) throws Exception { Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] src = hex2byte(source.getBytes(StandardCharsets.UTF_8)); DESKeySpec desKeySpec = getDesKeySpec(source); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); cipher.init(Cipher.DECRYPT_MODE, secretKey, IV); byte[] retByte = cipher.doFinal(src); return new String(retByte); } private static String byte2hex(byte[] inStr) { String stmp; StringBuilder out = new StringBuilder(inStr.length * 2); for (byte b : inStr) { stmp = Integer.toHexString(b & 0xFF); if (stmp.length() == 1) { out.append("0").append(stmp); } else { out.append(stmp); } }
return out.toString(); } private static byte[] hex2byte(byte[] b) { int size = 2; if ((b.length % size) != 0) { throw new IllegalArgumentException("长度不是偶数"); } byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += size) { String item = new String(b, n, 2); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\EncryptUtils.java
1
请在Spring Boot框架中完成以下Java代码
final class OidcLogoutAuthenticationConverter implements AuthenticationConverter { private static final String DEFAULT_LOGOUT_URI = "/logout/connect/back-channel/{registrationId}"; private final Log logger = LogFactory.getLog(getClass()); private final ClientRegistrationRepository clientRegistrationRepository; private RequestMatcher requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.POST, DEFAULT_LOGOUT_URI); OidcLogoutAuthenticationConverter(ClientRegistrationRepository clientRegistrationRepository) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); this.clientRegistrationRepository = clientRegistrationRepository; } @Override public Authentication convert(HttpServletRequest request) { RequestMatcher.MatchResult result = this.requestMatcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = result.getVariables().get("registrationId"); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) {
this.logger.debug("Did not process OIDC Back-Channel Logout since no ClientRegistration was found"); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } String logoutToken = request.getParameter("logout_token"); if (logoutToken == null) { this.logger.debug("Failed to process OIDC Back-Channel Logout since no logout token was found"); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } return new OidcLogoutAuthenticationToken(logoutToken, clientRegistration); } /** * The logout endpoint. Defaults to * {@code /logout/connect/back-channel/{registrationId}}. * @param requestMatcher the {@link RequestMatcher} to use */ void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutAuthenticationConverter.java
2
请完成以下Java代码
public boolean accept(final File dir, final String name) { return name.endsWith(".xml"); } }); for (final File migrationFile : migrationFiles) { final XMLLoader loader = new XMLLoader(migrationFile.getAbsolutePath()); load(loader); } } private void load(final XMLLoader loader) { loader.load(ITrx.TRXNAME_None); for (Object o : loader.getObjects()) { if (o instanceof I_AD_Migration) { final I_AD_Migration migration = (I_AD_Migration)o; execute(migration); }
else { logger.warn("Unhandled type " + o + " [SKIP]"); } } } private void execute(I_AD_Migration migration) { final Properties ctx = InterfaceWrapperHelper.getCtx(migration); final int migrationId = migration.getAD_Migration_ID(); final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class); final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(ctx); migrationCtx.setFailOnFirstError(true); final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationId); executor.setCommitLevel(IMigrationExecutor.CommitLevel.Batch); executor.execute(IMigrationExecutor.Action.Apply); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\MigrationLoader.java
1
请完成以下Java代码
private void invokeDelegate(List<ConsumerRecord<K, V>> consumerRecords, @Nullable Acknowledgment acknowledgment, @Nullable Consumer<?, ?> consumer) { switch (this.delegateType) { case ACKNOWLEDGING_CONSUMER_AWARE: this.delegate.onMessage(consumerRecords, acknowledgment, consumer); break; case ACKNOWLEDGING: this.delegate.onMessage(consumerRecords, acknowledgment); break; case CONSUMER_AWARE: this.delegate.onMessage(consumerRecords, consumer); break; case SIMPLE: this.delegate.onMessage(consumerRecords); } } /* * Since the container uses the delegate's type to determine which method to call, we * must implement them all. */
@Override public void onMessage(List<ConsumerRecord<K, V>> data) { onMessage(data, null, null); // NOSONAR } @Override public void onMessage(List<ConsumerRecord<K, V>> data, @Nullable Acknowledgment acknowledgment) { onMessage(data, acknowledgment, null); // NOSONAR } @Override public void onMessage(List<ConsumerRecord<K, V>> data, @Nullable Consumer<?, ?> consumer) { onMessage(data, null, consumer); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\FilteringBatchMessageListenerAdapter.java
1
请完成以下Java代码
public class MissingReturnStatement { public static void main(String[] args) { int a = -12; int result = pow(a); System.out.println(result); Map<String, Integer> dictionary = createDictionary(); dictionary.forEach((s, integer) -> System.out.println(s + " " + integer)); } public static int pow(int number) { int pow = number * number; return pow; } public static String checkNumber(int number) { if (number == 0) { return "It's equals to zero"; }
for (int i = 0; i < number; i++) { if (i > 100) { return "It's a big number"; } } return "It's a negative number"; } public static Map<String, Integer> createDictionary() { List<String> words = Arrays.asList("Hello", "World"); return words.stream() .collect(Collectors.toMap(s -> s, s -> 1)); } }
repos\tutorials-master\core-java-modules\core-java-exceptions-4\src\main\java\com\baeldung\exception\missingreturnstatement\MissingReturnStatement.java
1
请完成以下Java代码
public void setDeactivationReason(@Nullable final String deactivationReason) { this.deactivationReason = deactivationReason; this.deactivationReasonSet = true; } public void setDeactivationDate(@Nullable final LocalDate deactivationDate) { this.deactivationDate = deactivationDate; this.deactivationDateSet = true; } public void setDeactivationComment(@Nullable final String deactivationComment) { this.deactivationComment = deactivationComment; this.deactivationCommentSet = true; } public void setClassification(@Nullable final String classification) { this.classification = classification; this.classificationSet = true; } public void setCareDegree(@Nullable final BigDecimal careDegree) { this.careDegree = careDegree; this.careDegreeSet = true; } public void setCreatedAt(@Nullable final Instant createdAt) { this.createdAt = createdAt; this.createdAtSet = true; } public void setCreatedByIdentifier(@Nullable final String createdByIdentifier)
{ this.createdByIdentifier = createdByIdentifier; this.createdByIdentifierSet = true; } public void setUpdatedAt(@Nullable final Instant updatedAt) { this.updatedAt = updatedAt; this.updatedAtSet = true; } public void setUpdateByIdentifier(@Nullable final String updateByIdentifier) { this.updateByIdentifier = updateByIdentifier; this.updateByIdentifierSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java
1
请完成以下Java代码
public List<I_M_MatchPO> getByReceiptId(final InOutId inOutId) { final String sql = "SELECT * FROM M_MatchPO m" + " INNER JOIN M_InOutLine l ON (m.M_InOutLine_ID=l.M_InOutLine_ID) " + "WHERE l.M_InOut_ID=?"; final List<Object> sqlParams = Collections.singletonList(inOutId); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); final List<I_M_MatchPO> result = new ArrayList<>(); while (rs.next()) { result.add(new MMatchPO(Env.getCtx(), rs, ITrx.TRXNAME_ThreadInherited)); } return result; } catch (final Exception e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } } // getInOut @Override public List<I_M_MatchPO> getByInvoiceId(@NonNull final InvoiceId invoiceId) { final String sql = "SELECT * FROM M_MatchPO mi" + " INNER JOIN C_InvoiceLine il ON (mi.C_InvoiceLine_ID=il.C_InvoiceLine_ID) " + "WHERE il.C_Invoice_ID=?"; final List<Object> sqlParams = Arrays.asList(invoiceId); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery();
final List<I_M_MatchPO> result = new ArrayList<>(); while (rs.next()) { result.add(new MMatchPO(Env.getCtx(), rs, ITrx.TRXNAME_ThreadInherited)); } return result; } catch (final Exception e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } @Override public List<I_M_MatchPO> getByOrderLineId(final OrderLineId orderLineId) { if (orderLineId == null) { return ImmutableList.of(); } return Services.get(IQueryBL.class) .createQueryBuilder(I_M_MatchPO.class) .addEqualsFilter(I_M_MatchPO.COLUMN_C_OrderLine_ID, orderLineId) .orderBy(I_M_MatchPO.COLUMN_C_OrderLine_ID) .create() .listImmutable(I_M_MatchPO.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\MatchPODAO.java
1
请完成以下Java代码
public int getM_InOut_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOut_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bestätigung Versand/Wareneingang. @param M_InOutConfirm_ID Material Shipment or Receipt Confirmation */ @Override public void setM_InOutConfirm_ID (int M_InOutConfirm_ID) { if (M_InOutConfirm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutConfirm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutConfirm_ID, Integer.valueOf(M_InOutConfirm_ID)); } /** Get Bestätigung Versand/Wareneingang. @return Material Shipment or Receipt Confirmation */ @Override public int getM_InOutConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutConfirm_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Inventory getM_Inventory() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setM_Inventory(org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } /** Set Inventur. @param M_Inventory_ID Parameters for a Physical Inventory */ @Override public void setM_Inventory_ID (int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID)); } /** Get Inventur. @return Parameters for a Physical Inventory */ @Override public int getM_Inventory_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutConfirm.java
1
请完成以下Java代码
public class SysTenantPack implements Serializable { private static final long serialVersionUID = 1L; /**主键id*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "主键id") private String id; /**租户id*/ @Excel(name = "租户id", width = 15) @Schema(description = "租户id") private Integer tenantId; /**产品包名*/ @Excel(name = "产品包名", width = 15) @Schema(description = "产品包名") private String packName; /**开启状态(0 未开启 1开启)*/ @Excel(name = "开启状态(0 未开启 1开启)", width = 15) @Schema(description = "开启状态(0 未开启 1开启)") private String status; /**备注*/ @Excel(name = "备注", width = 15) @Schema(description = "备注") private String remarks; /**创建人*/ @Schema(description = "创建人") private String createBy; /**创建时间*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") @Schema(description = "创建时间") private Date createTime; /**更新人*/ @Schema(description = "更新人") private String updateBy; /**更新时间*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") @Schema(description = "更新时间") private Date updateTime; /**产品包类型(default 默认产品包 custom 自定义产品包)*/ @Excel(name = "产品包类型", width = 15) @Schema(description = "产品包类型") private String packType; /** * 是否自动分配给用户(0 否 1是)
*/ @Excel(name = "是否自动分配给用户(0 否 1是)", width = 15) @Schema(description = "是否自动分配给用户") private String izSysn; /**菜单id 临时字段用于新增编辑菜单id传递*/ @TableField(exist = false) private String permissionIds; /** * 编码 */ private String packCode; public SysTenantPack(){ } public SysTenantPack(Integer tenantId, String packName, String packCode){ this.tenantId = tenantId; this.packCode = packCode; this.packName = packName; this.status = "1"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysTenantPack.java
1
请完成以下Java代码
public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public List<String> getRepositories() { return this.repositories; } public List<String> getAdditionalBoms() { return this.additionalBoms; } public VersionRange getRange() { return this.range; }
public void setRepositories(List<String> repositories) { this.repositories = repositories; } public void setAdditionalBoms(List<String> additionalBoms) { this.additionalBoms = additionalBoms; } public void setRange(VersionRange range) { this.range = range; } @Override public String toString() { return "Mapping [" + ((this.compatibilityRange != null) ? "compatibilityRange=" + this.compatibilityRange + ", " : "") + ((this.groupId != null) ? "groupId=" + this.groupId + ", " : "") + ((this.artifactId != null) ? "artifactId=" + this.artifactId + ", " : "") + ((this.version != null) ? "version=" + this.version + ", " : "") + ((this.repositories != null) ? "repositories=" + this.repositories + ", " : "") + ((this.additionalBoms != null) ? "additionalBoms=" + this.additionalBoms + ", " : "") + ((this.range != null) ? "range=" + this.range : "") + "]"; } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\BillOfMaterials.java
1
请完成以下Java代码
public Date getEndedAfter() { return endedAfter; } public boolean isEnded() { return ended; } public boolean isIncludeEnded() { return includeEnded; } public String getStartUserId() { return startUserId; } public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public boolean isCompletable() { return completable; } public boolean isOnlyStages() { return onlyStages; } public String getEntryCriterionId() { return entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public String getFormKey() { return formKey; } public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; }
public String getTenantId() { return tenantId; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } @Override protected void ensureVariablesInitialized() { super.ensureVariablesInitialized(); for (PlanItemInstanceQueryImpl orQueryObject : orQueryObjects) { orQueryObject.ensureVariablesInitialized(); } } public List<PlanItemInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceQueryImpl.java
1
请完成以下Java代码
public final List<ISqlQueryFilter> getSqlFilters() { compileIfNeeded(); return _sqlFilters; } @Override public final boolean isPureSql() { // Case: a composite filter without any filters inside shall be considered pure SQL if (filters.isEmpty()) { return true; } final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFilters(); return nonSqlFilters == null || nonSqlFilters.isEmpty(); } @Override public final boolean isPureNonSql() { // Case: a composite filter without any filters inside shall not be considered pure nonSQL if (filters.isEmpty()) { return false; } final List<ISqlQueryFilter> sqlFilters = getSqlFilters(); return sqlFilters == null || sqlFilters.isEmpty(); } @Override public boolean isJoinAnd() { return and; } @Override public boolean isJoinOr() { return !and; } @Override public String getSql() { if (!isPureSql()) { throw new IllegalStateException("Cannot get SQL for a filter which is not pure SQL: " + this); } return getSqlFiltersWhereClause(); } @Override
public List<Object> getSqlParams(final Properties ctx) { if (!isPureSql()) { throw new IllegalStateException("Cannot get SQL Parameters for a filter which is not pure SQL: " + this); } return getSqlFiltersParams(ctx); } @Override public ISqlQueryFilter asSqlQueryFilter() { if (!isPureSql()) { throw new IllegalStateException("Cannot convert to pure SQL filter when this filter is not pure SQL: " + this); } return this; } @Override public ISqlQueryFilter asPartialSqlQueryFilter() { return partialSqlQueryFilter; } @Override public IQueryFilter<T> asPartialNonSqlFilterOrNull() { final List<IQueryFilter<T>> nonSqlFilters = getNonSqlFiltersToUse(); if (nonSqlFilters == null || nonSqlFilters.isEmpty()) { return null; } return partialNonSqlQueryFilter; } @Override public CompositeQueryFilter<T> allowSqlFilters(final boolean allowSqlFilters) { if (this._allowSqlFilters == allowSqlFilters) { return this; } this._allowSqlFilters = allowSqlFilters; _compiled = false; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryFilter.java
1
请完成以下Java代码
public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public Date getEvaluationTime() { return evaluationTime; } public void setEvaluationTime(Date evaluationTime) { this.evaluationTime = evaluationTime; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public List<HistoricDecisionInputInstance> getInputs() { if(inputs != null) { return inputs; } else { throw LOG.historicDecisionInputInstancesNotFetchedException(); } } @Override public List<HistoricDecisionOutputInstance> getOutputs() { if(outputs != null) { return outputs; } else { throw LOG.historicDecisionOutputInstancesNotFetchedException(); } } public void setInputs(List<HistoricDecisionInputInstance> inputs) { this.inputs = inputs; } public void setOutputs(List<HistoricDecisionOutputInstance> outputs) { this.outputs = outputs; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); } public void addInput(HistoricDecisionInputInstance decisionInputInstance) { if(inputs == null) {
inputs = new ArrayList<HistoricDecisionInputInstance>(); } inputs.add(decisionInputInstance); } public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) { if(outputs == null) { outputs = new ArrayList<HistoricDecisionOutputInstance>(); } outputs.add(decisionOutputInstance); } public Double getCollectResultValue() { return collectResultValue; } public void setCollectResultValue(Double collectResultValue) { this.collectResultValue = collectResultValue; } public String getRootDecisionInstanceId() { return rootDecisionInstanceId; } public void setRootDecisionInstanceId(String rootDecisionInstanceId) { this.rootDecisionInstanceId = rootDecisionInstanceId; } public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java
1
请完成以下Java代码
public String getAD_Language() { Check.assumeNotNull(adLanguage, "Parameter adLanguage is not null"); return adLanguage; } public String extractString(final TranslatableParameterizedString trlString) { if (trlString == null) { return null; } else if (isUseBaseLanguage()) { return trlString.getStringBaseLanguage(); } else if (isUseTranslantionLanguage())
{ return trlString.getStringTrlPattern(); } else if (isUseSpecificLanguage()) { return trlString.translate(getAD_Language()); } else { // internal error: shall never happen throw new IllegalStateException("Cannot extract string from " + trlString + " using " + this); } } } } // MLookupFactory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookupFactory.java
1
请完成以下Java代码
public int getPO_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Query. @param Query SQL */ public void setQuery (String Query) { set_Value (COLUMNNAME_Query, Query); } /** Get Query. @return SQL */ public String getQuery () { return (String)get_Value(COLUMNNAME_Query); } /** Set Search Type. @param SearchType Which kind of search is used (Query or Table) */
public void setSearchType (String SearchType) { set_Value (COLUMNNAME_SearchType, SearchType); } /** Get Search Type. @return Which kind of search is used (Query or Table) */ public String getSearchType () { return (String)get_Value(COLUMNNAME_SearchType); } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ public void setTransactionCode (String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ public String getTransactionCode () { return (String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
1
请完成以下Java代码
public SuspendedJobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public SuspendedJobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public SuspendedJobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public SuspendedJobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public SuspendedJobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public SuspendedJobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobCountByQueryCriteria(this); } public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); } public boolean isWithException() {
return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\SuspendedJobQueryImpl.java
1
请完成以下Java代码
public SimpleAsyncTaskSchedulerBuilder additionalCustomizers(SimpleAsyncTaskSchedulerCustomizer... customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return additionalCustomizers(Arrays.asList(customizers)); } /** * Add {@link SimpleAsyncTaskSchedulerCustomizer customizers} that should be applied * to the {@link SimpleAsyncTaskScheduler}. Customizers are applied in the order that * they were added after builder configuration has been applied. * @param customizers the customizers to add * @return a new builder instance * @see #customizers(Iterable) */ public SimpleAsyncTaskSchedulerBuilder additionalCustomizers( Iterable<? extends SimpleAsyncTaskSchedulerCustomizer> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return new SimpleAsyncTaskSchedulerBuilder(this.threadNamePrefix, this.concurrencyLimit, this.virtualThreads, this.taskTerminationTimeout, this.taskDecorator, append(this.customizers, customizers)); } /** * Build a new {@link SimpleAsyncTaskScheduler} instance and configure it using this * builder. * @return a configured {@link SimpleAsyncTaskScheduler} instance. * @see #configure(SimpleAsyncTaskScheduler) */ public SimpleAsyncTaskScheduler build() { return configure(new SimpleAsyncTaskScheduler()); } /** * Configure the provided {@link SimpleAsyncTaskScheduler} instance using this * builder. * @param <T> the type of task scheduler * @param taskScheduler the {@link SimpleAsyncTaskScheduler} to configure * @return the task scheduler instance * @see #build() */ public <T extends SimpleAsyncTaskScheduler> T configure(T taskScheduler) {
PropertyMapper map = PropertyMapper.get(); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); map.from(this.concurrencyLimit).to(taskScheduler::setConcurrencyLimit); map.from(this.virtualThreads).to(taskScheduler::setVirtualThreads); map.from(this.taskTerminationTimeout).as(Duration::toMillis).to(taskScheduler::setTaskTerminationTimeout); map.from(this.taskDecorator).to(taskScheduler::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\SimpleAsyncTaskSchedulerBuilder.java
1
请完成以下Java代码
private ResponseEntity<String> performRequest(final UriComponentsBuilder uri, final HttpMethod method) { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON)); httpHeaders.set(HTTP_HEADER_AUTHORIZATION, getAuthorizationHttpHeader()); final HttpEntity<?> entity = new HttpEntity<>(httpHeaders); return apiRestTemplate.exchange(uri.toUriString(), method, entity, String.class); } private UriComponentsBuilder prepareActionURL( @NonNull final ProductDetails productDetails, @NonNull final SecurPharmAction action) { return prepareProductURL(productDetails) .replaceQueryParam(QUERY_PARAM_SID, config.getApplicationUUID()) .replaceQueryParam(QUERY_PARAM_ACT, action.getCode()); } private UriComponentsBuilder prepareProductURL(@NonNull final ProductDetails productDetails) { return UriComponentsBuilder.fromPath(API_RELATIVE_PATH_PRODUCTS) .path(productDetails.getProductCode()) .path(API_RELATIVE_PATH_PACKS) .path(encodeBase64url(productDetails.getSerialNumber())) // .queryParam(QUERY_PARAM_CTX, clientTransactionId) // .queryParam(QUERY_PARAM_SID, config.getApplicationUUID()) .queryParam(QUERY_PARAM_LOT, encodeBase64url(productDetails.getLot()))
.queryParam(QUERY_PARAM_EXP, productDetails.getExpirationDate().toYYMMDDString()) .queryParam(QUERY_PARAM_PCS, productDetails.getProductCodeType().getCode()); } public void authenticate() { authenticator.authenticate(); } private String getAuthorizationHttpHeader() { return authenticator.getAuthorizationHttpHeader(); } @Value(staticConstructor = "of") private static class APIReponseWithLog { @NonNull SecurPharmLog log; @NonNull JsonAPIResponse response; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\SecurPharmClient.java
1
请完成以下Java代码
public java.math.BigDecimal getGrandTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set In Dispute. @param IsInDispute Document is in dispute */ @Override public void setIsInDispute (boolean IsInDispute) { set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute)); } /** Get In Dispute. @return Document is in dispute */ @Override public boolean isInDispute () { Object oo = get_Value(COLUMNNAME_IsInDispute); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Offener Betrag. @param OpenAmt Offener Betrag */ @Override
public void setOpenAmt (java.math.BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Offener Betrag. @return Offener Betrag */ @Override public java.math.BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java
1
请完成以下Java代码
public class LazyInitRegistration implements ApplicationContextAware { protected static final String RESOURCE_LOADER_DEPENDING_INIT_HOOK = "resourceLoaderDependingInitHook"; protected static final Set<LazyDelegateFilter<? extends Filter>> REGISTRATION = new HashSet<LazyDelegateFilter<? extends Filter>>(); protected static ApplicationContext APPLICATION_CONTEXT; private static final Logger LOGGER = LoggerFactory.getLogger(LazyInitRegistration.class); static void register(LazyDelegateFilter<? extends Filter> lazyDelegateFilter) { REGISTRATION.add(lazyDelegateFilter); } @SuppressWarnings("unchecked") protected static <T extends Filter> InitHook<T> getInitHook() { if (APPLICATION_CONTEXT != null && APPLICATION_CONTEXT.containsBean(RESOURCE_LOADER_DEPENDING_INIT_HOOK)) { return APPLICATION_CONTEXT.getBean(RESOURCE_LOADER_DEPENDING_INIT_HOOK, InitHook.class); } return null; } static boolean isRegistered(LazyDelegateFilter<? extends Filter> lazyDelegateFilter) { return REGISTRATION.contains(lazyDelegateFilter); } static <T extends Filter> boolean lazyInit(LazyDelegateFilter<T> lazyDelegateFilter) { if (APPLICATION_CONTEXT != null) { if (isRegistered(lazyDelegateFilter)) { lazyDelegateFilter.setInitHook(LazyInitRegistration.<T> getInitHook()); lazyDelegateFilter.lazyInit(); REGISTRATION.remove(lazyDelegateFilter); LOGGER.info("lazy initialized {}", lazyDelegateFilter); return true; } else { LOGGER.debug("skipping lazy init for {} because of no init hook registration", lazyDelegateFilter); }
} else { LOGGER.debug("skipping lazy init for {} because application context not initialized yet", lazyDelegateFilter); } return false; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { APPLICATION_CONTEXT = applicationContext; for (LazyDelegateFilter<? extends Filter> lazyDelegateFilter : getRegistrations()) { lazyInit(lazyDelegateFilter); } } @EventListener protected void onContextClosed(ContextClosedEvent ev) { APPLICATION_CONTEXT = null; } static Set<LazyDelegateFilter<? extends Filter>> getRegistrations() { return Collections.unmodifiableSet(new HashSet<LazyDelegateFilter<? extends Filter>>(REGISTRATION)); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\LazyInitRegistration.java
1
请完成以下Java代码
public class CourseRatingKey implements Serializable { @Column(name = "student_id") private Long studentId; @Column(name = "course_id") private Long courseId; public CourseRatingKey() { } public CourseRatingKey(Long studentId, Long courseId) { this.studentId = studentId; this.courseId = courseId; } public Long getStudentId() { return studentId; } public void setStudentId(Long studentId) { this.studentId = studentId; } public Long getCourseId() { return courseId; } public void setCourseId(Long courseId) { this.courseId = courseId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((courseId == null) ? 0 : courseId.hashCode()); result = prime * result + ((studentId == null) ? 0 : studentId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj)
return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CourseRatingKey other = (CourseRatingKey) obj; if (courseId == null) { if (other.courseId != null) return false; } else if (!courseId.equals(other.courseId)) return false; if (studentId == null) { if (other.studentId != null) return false; } else if (!studentId.equals(other.studentId)) return false; return true; } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRatingKey.java
1
请完成以下Java代码
protected void configureAuthorizationCheck(QueryParameters query) { Authentication currentAuthentication = getCurrentAuthentication(); AuthorizationCheck authCheck = query.getAuthCheck(); authCheck.getPermissionChecks().clear(); if (isAuthorizationEnabled() && currentAuthentication != null) { authCheck.setAuthorizationCheckEnabled(true); String currentUserId = currentAuthentication.getUserId(); List<String> currentGroupIds = currentAuthentication.getGroupIds(); authCheck.setAuthUserId(currentUserId); authCheck.setAuthGroupIds(currentGroupIds); } } /** * Configure the tenant check for the given {@link QueryParameters}. */ protected void configureTenantCheck(QueryParameters query) { TenantCheck tenantCheck = query.getTenantCheck(); if (isTenantCheckEnabled()) { Authentication currentAuthentication = getCurrentAuthentication(); tenantCheck.setTenantCheckEnabled(true); tenantCheck.setAuthTenantIds(currentAuthentication.getTenantIds()); } else { tenantCheck.setTenantCheckEnabled(false); tenantCheck.setAuthTenantIds(null); }
} /** * Add a new {@link PermissionCheck} with the given values. */ protected void addPermissionCheck(QueryParameters query, Resource resource, String queryParam, Permission permission) { if(!isPermissionDisabled(permission)){ PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceIdQueryParam(queryParam); permCheck.setPermission(permission); query.getAuthCheck().addAtomicPermissionCheck(permCheck); } } protected boolean isPermissionDisabled(Permission permission) { List<String> disabledPermissions = getProcessEngine().getProcessEngineConfiguration().getDisabledPermissions(); for (String disabledPerm : disabledPermissions) { if (!disabledPerm.equals(permission.getName())) { return true; } } return false; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\plugin\resource\AbstractCockpitPluginResource.java
1
请完成以下Java代码
public class ErrorInfo<T> { public static final Integer OK = 0; public static final Integer ERROR = 100; private Integer code; private String message; private String url; private T data; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public static Integer getOK() { return OK; } public static Integer getERROR() { return ERROR; } public Integer getCode() { return code; }
public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
repos\SpringBoot-Learning-master\1.x\Chapter3-1-6\src\main\java\com\didispace\dto\ErrorInfo.java
1
请完成以下Java代码
protected ChildElementCollectionImpl<T> createCollectionInstance() { return new ChildElementImpl<T>(childElementType, parentElementType); } public ChildElementBuilder<T> immutable() { super.immutable(); return this; } public ChildElementBuilder<T> required() { super.required(); return this; } public ChildElementBuilder<T> minOccurs(int i) { super.minOccurs(i); return this; } public ChildElementBuilder<T> maxOccurs(int i) { super.maxOccurs(i); return this; } public ChildElement<T> build() { return (ChildElement<T>) super.build(); } public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> qNameElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); QNameElementReferenceBuilderImpl<V,T> builder = new QNameElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; }
public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> idElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); ElementReferenceBuilderImpl<V, T> builder = new ElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; } public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> uriElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); ElementReferenceBuilderImpl<V, T> builder = new UriElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementBuilderImpl.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_DesktopWorkbench[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_Desktop getAD_Desktop() throws RuntimeException { return (I_AD_Desktop)MTable.get(getCtx(), I_AD_Desktop.Table_Name) .getPO(getAD_Desktop_ID(), get_TrxName()); } /** Set Desktop. @param AD_Desktop_ID Collection of Workbenches */ public void setAD_Desktop_ID (int AD_Desktop_ID) { if (AD_Desktop_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, Integer.valueOf(AD_Desktop_ID)); } /** Get Desktop. @return Collection of Workbenches */ public int getAD_Desktop_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Desktop Workbench. @param AD_DesktopWorkbench_ID Desktop Workbench */ public void setAD_DesktopWorkbench_ID (int AD_DesktopWorkbench_ID) { if (AD_DesktopWorkbench_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_DesktopWorkbench_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_DesktopWorkbench_ID, Integer.valueOf(AD_DesktopWorkbench_ID)); } /** Get Desktop Workbench. @return Desktop Workbench */ public int getAD_DesktopWorkbench_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_DesktopWorkbench_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Workbench getAD_Workbench() throws RuntimeException {
return (I_AD_Workbench)MTable.get(getCtx(), I_AD_Workbench.Table_Name) .getPO(getAD_Workbench_ID(), get_TrxName()); } /** Set Workbench. @param AD_Workbench_ID Collection of windows, reports */ public void setAD_Workbench_ID (int AD_Workbench_ID) { if (AD_Workbench_ID < 1) set_Value (COLUMNNAME_AD_Workbench_ID, null); else set_Value (COLUMNNAME_AD_Workbench_ID, Integer.valueOf(AD_Workbench_ID)); } /** Get Workbench. @return Collection of windows, reports */ public int getAD_Workbench_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workbench_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_Workbench_ID())); } /** 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_DesktopWorkbench.java
1
请完成以下Java代码
public ExplainedOptional<Mailbox> mergeFrom(@Nullable final UserEMailConfig userEmailConfig) { if (userEmailConfig == null) { logger.debug("userEmailConfig can't be used because it has no user config"); return ExplainedOptional.of(this); } final EMailAddress userEmail = userEmailConfig.getEmail(); if (userEmail == null) { logger.debug("userEmailConfig can't be used because it has no Mail-Address: {}", userEmailConfig); return ExplainedOptional.emptyBecause("userEmailConfig can't be used because it has no Mail-Address: " + userEmailConfig); } switch (type) { case SMTP: { final SMTPConfig smtpConfig = getSmtpConfigNotNull(); if (smtpConfig.isSmtpAuthorization() && (Check.isBlank(userEmailConfig.getUsername()) || Check.isBlank(userEmailConfig.getPassword()))) { return ExplainedOptional.emptyBecause("userEmailConfig can't be used because it has no SMTP-UserName or SMTP-Password: " + userEmailConfig); } return ExplainedOptional.of( toBuilder() .email(userEmail) .smtpConfig(smtpConfig.mergeFrom(userEmailConfig)) .build() ); } case MICROSOFT_GRAPH: { final MicrosoftGraphConfig microsoftGraphConfig = getMicrosoftGraphConfigNotNull(); return ExplainedOptional.of( toBuilder() .microsoftGraphConfig(microsoftGraphConfig.withDefaultReplyTo(userEmail)) .build() ); }
default: throw new AdempiereException("Unknown type: " + type); } } public Mailbox withUserToColumnName(final String userToColumnName) { final String userToColumnNameNorm = StringUtils.trimBlankToNull(userToColumnName); if (Objects.equals(this.userToColumnName, userToColumnNameNorm)) { return this; } else { return toBuilder().userToColumnName(userToColumnName).build(); } } public SMTPConfig getSmtpConfigNotNull() {return Check.assumeNotNull(smtpConfig, "smtpConfig cannot be null");} public MicrosoftGraphConfig getMicrosoftGraphConfigNotNull() {return Check.assumeNotNull(microsoftGraphConfig, "microsoftGraphConfig cannot be null");} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\mailboxes\Mailbox.java
1
请完成以下Java代码
public static <T> Map<String, T> mapOfClass(Class<T> clazz, Object... objects) { if (objects.length % 2 != 0) { throw new ActivitiIllegalArgumentException( "The input should always be even since we expect a list of key-value pairs!" ); } Map<String, T> map = new HashMap(); for (int i = 0; i < objects.length; i += 2) { int keyIndex = i; int valueIndex = i + 1; Object key = objects[keyIndex]; Object value = objects[valueIndex]; if (!String.class.isInstance(key)) { throw new ActivitiIllegalArgumentException( "key at index " + keyIndex + " should be a String but is a " + key.getClass() ); } if (value != null && !clazz.isInstance(value)) {
throw new ActivitiIllegalArgumentException( "value at index " + valueIndex + " should be a " + clazz + " but is a " + value.getClass() ); } map.put((String) key, (T) value); } return map; } public static boolean isEmpty(Collection<?> collection) { return (collection == null || collection.isEmpty()); } public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\CollectionUtil.java
1
请完成以下Spring Boot application配置
# logging level #logging.level.org.springframework=ERROR #logging.level.com.mkyong=DEBUG # logging.file was deprecated and renamed to logging.file.name in 2.2. It was then removed in 2.3. ### 1. file output #logging.file.name=logs/app.log #logging.file.path= ### 2. file rotation #The filename pattern used to create log archives. #logging.logback.rollingpolicy.file-name-pattern=logs/%d{yyyy-MM, aux}/app.%d{yyyy-MM-dd}.%i.log #If log archive cleanup should occur when the application starts. #logging.logback.rollingpolicy.clean-history-on-start=true #The maximum size of log file before it is archived. #logging.logback.rollingpolicy.max-file-size=100MB #The maximum amount of size log archives can take before being deleted. #logging.logback.rollingpolicy.total-size-cap=10GB #The ma
ximum number of archive log files to keep (defaults to 7). #logging.logback.rollingpolicy.max-history=10 # logging.pattern.file=%d %p %c{1.} [%t] %m%n # logging.pattern.console=%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n ## if no active profile, default is 'default' # spring.profiles.active=prod # root level #logging.level.=INFO
repos\spring-boot-master\spring-boot-logging-slf4j-logback\src\main\resources\application.properties
2
请完成以下Java代码
public final class RequestMatcherRedirectFilter extends OncePerRequestFilter { private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private final RequestMatcher requestMatcher; private final String redirectUrl; /** * Create and initialize an instance of the filter. * @param requestMatcher the request matcher * @param redirectUrl the redirect URL */ public RequestMatcherRedirectFilter(RequestMatcher requestMatcher, String redirectUrl) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); Assert.hasText(redirectUrl, "redirectUrl cannot be empty"); this.requestMatcher = requestMatcher; this.redirectUrl = redirectUrl; } /**
* {@inheritDoc} */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (this.requestMatcher.matches(request)) { this.redirectStrategy.sendRedirect(request, response, this.redirectUrl); } else { filterChain.doFilter(request, response); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\RequestMatcherRedirectFilter.java
1
请完成以下Java代码
public class PlainListScriptScanner extends AbstractScriptScanner { private final Iterator<IFileRef> fileRefs; private final Iterator<IScript> scripts; public static PlainListScriptScanner fromScripts(final List<IScript> scripts) { return new PlainListScriptScanner(null, scripts); } public static PlainListScriptScanner fromFileRefs(final List<IFileRef> fileRefs) { return new PlainListScriptScanner(fileRefs, null); } private PlainListScriptScanner(final List<IFileRef> fileRefs, final List<IScript> scripts) { super(null); this.fileRefs = fileRefs == null ? null : fileRefs.iterator(); this.scripts = scripts == null ? null : scripts.iterator(); } @Override public boolean hasNext() { if (fileRefs != null) { return fileRefs.hasNext(); } return scripts.hasNext(); } @Override
public IScript next() { if (!hasNext()) { throw new NoSuchElementException(); } if (fileRefs != null) { return getScript(fileRefs.next()); } return scripts.next(); } private IScript getScript(final IFileRef fileRef) { final IScriptFactory scriptFactory = getScriptFactoryToUse(); return scriptFactory.createScript(fileRef); } @Override public String toString() { return "PlainListScriptScanner [fileRef=" + fileRefs + ", scripts= " + scripts + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\PlainListScriptScanner.java
1
请完成以下Java代码
final class FindValueEditor extends AbstractCellEditor implements TableCellEditor { /** * */ private static final long serialVersionUID = 7409932376841865389L; // services private final transient ISwingEditorFactory swingEditorFactory = Services.get(ISwingEditorFactory.class); /** Is ValueTo Column? */ private final boolean isValueToColumn; /** Between selected */ private boolean isValueToEnabled = false; /** Editor */ private VEditor editor = null; /** * Constructor * * @param valueTo true if it is the "to" value column */ public FindValueEditor(final boolean valueTo) { super(); isValueToColumn = valueTo; } /** * Get Value Need to convert to String * * @return current value */ @Override public Object getCellEditorValue() { if (editor == null) { return null; } return editor.getValue(); } @Override public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int rowIndex, final int columnIndex) { final IUserQueryRestriction row = getRow(table, rowIndex); // // Update valueTo enabled final Operator operator = row.getOperator(); isValueToEnabled = isValueToColumn && operator != null && operator.isRangeOperator(); final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField()); if (searchField == null) { // shall not happen return null; } // Make sure the old editor is destroyed destroyEditor(); // Create editor editor = searchField.createEditor(true);
editor.setReadWrite(isValueDisplayed()); editor.setValue(value); return swingEditorFactory.getEditorComponent(editor); } private final boolean isValueDisplayed() { return !isValueToColumn || isValueToColumn && isValueToEnabled; } @Override public boolean isCellEditable(final EventObject e) { return true; } @Override public boolean shouldSelectCell(final EventObject e) { return isValueDisplayed(); } private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex) { final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel(); final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex); return model.getRow(modelRowIndex); } /** * Destroy existing editor. * * Very important to be called because this will also unregister the listeners from editor to underlying lookup (if any). */ private final void destroyEditor() { if (editor == null) { return; } editor.dispose(); editor = null; } @Override public boolean stopCellEditing() { if (!super.stopCellEditing()) { return false; } destroyEditor(); return true; } @Override public void cancelCellEditing() { super.cancelCellEditing(); destroyEditor(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindValueEditor.java
1
请完成以下Java代码
private void auditHUResponse( @NonNull final JsonGetSingleHUResponse jsonGetSingleHUResponse, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { final JsonHU jsonHU = jsonGetSingleHUResponse.getResult(); auditHU(jsonHU, /*parentExportAuditId*/ null, externalSystemParentConfigId, pInstanceId); } private void auditHU( @NonNull final JsonHU jsonHU, @Nullable final DataExportAuditId parentExportAuditId, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { if(jsonHU.getId() == null) { return; } final HuId huId = HuId.ofObject(jsonHU.getId()); final Action exportAction = parentExportAuditId != null ? Action.AlongWithParent : Action.Standalone; final DataExportAuditRequest huDataExportAuditRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_M_HU.Table_Name, huId.getRepoId())) .action(exportAction)
.externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(parentExportAuditId) .build(); final DataExportAuditId dataExportAuditId = dataExportAuditService.createExportAudit(huDataExportAuditRequest); if (jsonHU.getIncludedHUs() == null) { return; } jsonHU.getIncludedHUs().forEach(includedHU -> auditHU(includedHU, dataExportAuditId, externalSystemParentConfigId, pInstanceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HUAuditService.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getStartDate())); } /** Set Training Class. @param S_Training_Class_ID The actual training class instance */ public void setS_Training_Class_ID (int S_Training_Class_ID) { if (S_Training_Class_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, Integer.valueOf(S_Training_Class_ID)); } /** Get Training Class. @return The actual training class instance */ public int getS_Training_Class_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_Class_ID); if (ii == null)
return 0; return ii.intValue(); } public I_S_Training getS_Training() throws RuntimeException { return (I_S_Training)MTable.get(getCtx(), I_S_Training.Table_Name) .getPO(getS_Training_ID(), get_TrxName()); } /** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_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_S_Training_Class.java
1
请完成以下Java代码
public class UpdateFlowRuleReqVo { private Long id; private String app; private Integer grade; private Double count; private Long interval; private Integer intervalUnit; private Integer controlBehavior; private Integer burst; private Integer maxQueueingTimeoutMs; private GatewayParamFlowItemVo paramItem; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public Double getCount() { return count; } public void setCount(Double count) { this.count = count; } public Long getInterval() { return interval; } public void setInterval(Long interval) { this.interval = interval; } public Integer getIntervalUnit() { return intervalUnit; }
public void setIntervalUnit(Integer intervalUnit) { this.intervalUnit = intervalUnit; } public Integer getControlBehavior() { return controlBehavior; } public void setControlBehavior(Integer controlBehavior) { this.controlBehavior = controlBehavior; } public Integer getBurst() { return burst; } public void setBurst(Integer burst) { this.burst = burst; } public Integer getMaxQueueingTimeoutMs() { return maxQueueingTimeoutMs; } public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; } public GatewayParamFlowItemVo getParamItem() { return paramItem; } public void setParamItem(GatewayParamFlowItemVo paramItem) { this.paramItem = paramItem; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\UpdateFlowRuleReqVo.java
1
请在Spring Boot框架中完成以下Java代码
private <T> T getBeanOrNull(String name, Class<T> type) { Map<String, T> beans = this.context.getBeansOfType(type); return beans.get(name); } private void configureCsrf(SimpleUrlHandlerMapping mapping) { Map<String, Object> mappings = mapping.getHandlerMap(); for (Object object : mappings.values()) { if (object instanceof SockJsHttpRequestHandler) { setHandshakeInterceptors((SockJsHttpRequestHandler) object); } else if (object instanceof WebSocketHttpRequestHandler) { setHandshakeInterceptors((WebSocketHttpRequestHandler) object); } else { throw new IllegalStateException( "Bean " + SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME + " is expected to contain mappings to either a " + "SockJsHttpRequestHandler or a WebSocketHttpRequestHandler but got " + object); } } } private void setHandshakeInterceptors(SockJsHttpRequestHandler handler) {
SockJsService sockJsService = handler.getSockJsService(); Assert.state(sockJsService instanceof TransportHandlingSockJsService, () -> "sockJsService must be instance of TransportHandlingSockJsService got " + sockJsService); TransportHandlingSockJsService transportHandlingSockJsService = (TransportHandlingSockJsService) sockJsService; List<HandshakeInterceptor> handshakeInterceptors = transportHandlingSockJsService.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); transportHandlingSockJsService.setHandshakeInterceptors(interceptorsToSet); } private void setHandshakeInterceptors(WebSocketHttpRequestHandler handler) { List<HandshakeInterceptor> handshakeInterceptors = handler.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); handler.setHandshakeInterceptors(interceptorsToSet); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\socket\WebSocketMessageBrokerSecurityConfiguration.java
2
请完成以下Java代码
public class DefaultJaasAuthenticationProvider extends AbstractJaasAuthenticationProvider { @SuppressWarnings("NullAway.Init") private Configuration configuration; @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); Assert.notNull(this.configuration, "configuration cannot be null."); } /** * Creates a LoginContext using the Configuration that was specified in * {@link #setConfiguration(Configuration)}. */ @Override protected LoginContext createLoginContext(CallbackHandler handler) throws LoginException { return new LoginContext(getLoginContextName(), null, handler, getConfiguration());
} protected Configuration getConfiguration() { return this.configuration; } /** * Sets the Configuration to use for Authentication. * @param configuration the Configuration that is used when * {@link #createLoginContext(CallbackHandler)} is called. */ public void setConfiguration(Configuration configuration) { this.configuration = configuration; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProvider.java
1
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容 datasource: url: jdbc:mysql://47.112.193.81:3306/testb5f4?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name:
com.mysql.jdbc.Driver username: testb5f4 password: F4df4db0ed86@11
repos\SpringBoot-Labs-master\lab-14-spring-jdbc-template\lab-14-jdbctemplate\src\main\resources\application.yaml
2
请完成以下Java代码
public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setUomCode(final String uomCode) { this.uomCode = uomCode; this.uomCodeSet = true; } @NonNull public String getOrgCode() { return orgCode; } @NonNull
public String getProductIdentifier() { return productIdentifier; } @NonNull public TaxCategory getTaxCategory() { return taxCategory; } @NonNull public BigDecimal getPriceStd() { return priceStd; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
1
请完成以下Java代码
public class BlogDTO { private long blogId; private String title; private String body; private String author; private String category; private Date publishedDate; public long getBlogId() { return blogId; } public void setBlogId(long blogId) { this.blogId = blogId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) {
this.body = body; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getPublishedDate() { return publishedDate; } public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-3\src\main\java\com\baeldung\thymeleaf\blog\BlogDTO.java
1
请完成以下Java代码
public int getC_Invoice_Candidate_Commission_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Commission_ID); } /** * Commission_Fact_State AD_Reference_ID=541042 * Reference name: C_Commission_Fact_State */ public static final int COMMISSION_FACT_STATE_AD_Reference_ID=541042; /** FORECASTED = FORECASTED */ public static final String COMMISSION_FACT_STATE_FORECASTED = "FORECASTED"; /** INVOICEABLE = INVOICEABLE */ public static final String COMMISSION_FACT_STATE_INVOICEABLE = "INVOICEABLE"; /** INVOICED = INVOICED */ public static final String COMMISSION_FACT_STATE_INVOICED = "INVOICED"; /** SETTLED = SETTLED */ public static final String COMMISSION_FACT_STATE_SETTLED = "SETTLED"; /** TO_SETTLE = TO_SETTLE */ public static final String COMMISSION_FACT_STATE_TO_SETTLE = "TO_SETTLE"; @Override public void setCommission_Fact_State (final java.lang.String Commission_Fact_State) { set_ValueNoCheck (COLUMNNAME_Commission_Fact_State, Commission_Fact_State); } @Override public java.lang.String getCommission_Fact_State() {
return get_ValueAsString(COLUMNNAME_Commission_Fact_State); } @Override public void setCommissionFactTimestamp (final java.lang.String CommissionFactTimestamp) { set_ValueNoCheck (COLUMNNAME_CommissionFactTimestamp, CommissionFactTimestamp); } @Override public java.lang.String getCommissionFactTimestamp() { return get_ValueAsString(COLUMNNAME_CommissionFactTimestamp); } @Override public void setCommissionPoints (final BigDecimal CommissionPoints) { set_ValueNoCheck (COLUMNNAME_CommissionPoints, CommissionPoints); } @Override public BigDecimal getCommissionPoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CommissionPoints); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Fact.java
1
请完成以下Java代码
protected Entry<String, List<Double>> composeOutputValues(ELExecutionContext executionContext) { Collection<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values()); if (executionContext.isForceDMN11()) { // create distinct rule results ruleResults = new HashSet<>(ruleResults); } return createOutputDoubleValues(ruleResults); } protected Entry<String, List<Double>> createOutputDoubleValues(Collection<Map<String, Object>> ruleResults) { Map<String, List<Double>> distinctOutputDoubleValues = new HashMap<>(); for (Map<String, Object> ruleResult : ruleResults) { for (Entry<String, Object> entry : ruleResult.entrySet()) { if (distinctOutputDoubleValues.containsKey(entry.getKey()) && distinctOutputDoubleValues.get(entry.getKey()) != null) { distinctOutputDoubleValues.get(entry.getKey()).add((Double) entry.getValue()); } else { List<Double> valuesList = new ArrayList<>(); valuesList.add((Double) entry.getValue()); distinctOutputDoubleValues.put(entry.getKey(), valuesList); } } } // get first entry Entry<String, List<Double>> firstEntry = null; if (!distinctOutputDoubleValues.isEmpty()) { firstEntry = distinctOutputDoubleValues.entrySet().iterator().next(); } return firstEntry;
} protected Double aggregateSum(List<Double> values) { double aggregate = 0; for (Double value : values) { aggregate += value; } return aggregate; } protected Double aggregateMin(List<Double> values) { return Collections.min(values); } protected Double aggregateMax(List<Double> values) { return Collections.max(values); } protected Double aggregateCount(List<Double> values) { return (double) values.size(); } protected Map<String, Object> createDecisionResults(String outputName, Double outputValue) { Map<String, Object> ruleResult = new HashMap<>(); ruleResult.put(outputName, outputValue); return ruleResult; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyCollect.java
1
请完成以下Java代码
public void init(TbContext ctx) { this.forceAck = ctx.isExternalNodeForceAck(); } protected void tellSuccess(TbContext ctx, TbMsg tbMsg) { if (forceAck) { ctx.enqueueForTellNext(tbMsg.copyWithNewCtx(), TbNodeConnectionType.SUCCESS); } else { ctx.tellSuccess(tbMsg); } } protected void tellFailure(TbContext ctx, TbMsg tbMsg, Throwable t) { if (forceAck) { if (t == null) { ctx.enqueueForTellNext(tbMsg.copyWithNewCtx(), TbNodeConnectionType.FAILURE); } else { ctx.enqueueForTellFailure(tbMsg.copyWithNewCtx(), t); }
} else { if (t == null) { ctx.tellNext(tbMsg, TbNodeConnectionType.FAILURE); } else { ctx.tellFailure(tbMsg, t); } } } protected TbMsg ackIfNeeded(TbContext ctx, TbMsg msg) { if (forceAck) { ctx.ack(msg); return msg.copyWithNewCtx(); } else { return msg; } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\external\TbAbstractExternalNode.java
1
请完成以下Java代码
public List<ExecutionTreeNode> getChildren() { return children; } public void setChildren(List<ExecutionTreeNode> children) { this.children = children; } @Override public Iterator<ExecutionTreeNode> iterator() { return new ExecutionTreeBfsIterator(this); } public ExecutionTreeBfsIterator leafsFirstIterator() { return new ExecutionTreeBfsIterator(this, true); } /* See http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram */ @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append(getExecutionEntity().getId()); if (getExecutionEntity().getActivityId() != null) { strb.append(" : " + getExecutionEntity().getActivityId()); } if (getExecutionEntity().getParentId() != null) { strb.append(", parent id " + getExecutionEntity().getParentId()); } if (getExecutionEntity().isProcessInstanceType()) { strb.append(" (process instance)"); } strb.append(System.lineSeparator()); if (children != null) { for (ExecutionTreeNode childNode : children) { childNode.internalToString(strb, "", true); } } return strb.toString(); } protected void internalToString(StringBuilder strb, String prefix, boolean isTail) {
strb.append( prefix + (isTail ? "└── " : "├── ") + getExecutionEntity().getId() + " : " + getCurrentFlowElementId() + ", parent id " + getExecutionEntity().getParentId() + (getExecutionEntity().isActive() ? " (active)" : " (not active)") + (getExecutionEntity().isScope() ? " (scope)" : "") + (getExecutionEntity().isMultiInstanceRoot() ? " (multi instance root)" : "") + (getExecutionEntity().isEnded() ? " (ended)" : "") + System.lineSeparator() ); if (children != null) { for (int i = 0; i < children.size() - 1; i++) { children.get(i).internalToString(strb, prefix + (isTail ? " " : "│ "), false); } if (children.size() > 0) { children.get(children.size() - 1).internalToString(strb, prefix + (isTail ? " " : "│ "), true); } } } protected String getCurrentFlowElementId() { FlowElement flowElement = getExecutionEntity().getCurrentFlowElement(); if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; return sequenceFlow.getSourceRef() + " -> " + sequenceFlow.getTargetRef(); } else if (flowElement != null) { return flowElement.getId() + " (" + flowElement.getClass().getSimpleName(); } else { return ""; } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTreeNode.java
1
请完成以下Java代码
public ReturnInOutUserNotificationsProducer notify(final Collection<? extends I_M_InOut> inouts) { if (inouts == null || inouts.isEmpty()) { return this; } postNotifications(inouts.stream() .map(this::createUserNotification) .collect(ImmutableList.toImmutableList())); return this; } /** * Post events about given shipment/receipts that were processed, i.e. * <ul> * <li>if inout's DocStatus is Completed, a "generated" notification will be sent * <li>if inout's DocStatus is Voided or Reversed, a "reversed" notification will be sent * </ul> */ public final ReturnInOutUserNotificationsProducer notify(@NonNull final I_M_InOut inout) { notify(ImmutableList.of(inout)); return this; } private UserNotificationRequest createUserNotification(@NonNull final I_M_InOut inout) { final I_C_BPartner bpartner = InterfaceWrapperHelper.load(inout.getC_BPartner_ID(), I_C_BPartner.class); final String bpValue = bpartner.getValue(); final String bpName = bpartner.getName(); final AdMessageKey adMessage = getNotificationAD_Message(inout); final UserId recipientUserId = getNotificationRecipientUserId(inout); final TableRecordReference inoutRef = TableRecordReference.of(inout); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(adMessage) .contentADMessageParam(inoutRef) .contentADMessageParam(bpValue) .contentADMessageParam(bpName) .targetAction(TargetRecordAction.ofRecordAndWindow(inoutRef, getWindowId(inout))) .build(); } private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private AdWindowId getWindowId(final I_M_InOut inout) { return inout.isSOTrx() ? WINDOW_RETURN_FROM_CUSTOMER : WINDOW_RETURN_TO_VENDOR; } private AdMessageKey getNotificationAD_Message(final I_M_InOut inout) {return inout.isSOTrx() ? MSG_Event_RETURN_FROM_CUSTOMER_Generated : MSG_Event_RETURN_TO_VENDOR_Generated;}
private UserId getNotificationRecipientUserId(final I_M_InOut inout) { // // In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofCode(inout.getDocStatus()); if (docStatus.isReversedOrVoided()) { final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user if (currentUserId > 0) { return UserId.ofRepoId(currentUserId); } return UserId.ofRepoId(inout.getUpdatedBy()); // last updated } // // Fallback: notify only the creator else { return UserId.ofRepoId(inout.getCreatedBy()); } } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\ReturnInOutUserNotificationsProducer.java
1
请完成以下Java代码
public String doInRedis(RedisConnection connection) throws DataAccessException { Object nativeConnection = connection.getNativeConnection(); String result = null; if (nativeConnection instanceof JedisCommands) { result = ((JedisCommands) nativeConnection).set(key, value, NX, EX, seconds); } if (!StringUtils.isEmpty(lockKeyLog) && !StringUtils.isEmpty(result)) { logger.info("获取锁{}的时间:{}", lockKeyLog, System.currentTimeMillis()); } return result; } }); } /** * 获取redis里面的值 * * @param key key * @param aClass class * @return T */ private <T> T get(final String key, Class<T> aClass) { Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空"); return redisTemplate.execute((RedisConnection connection) -> { Object nativeConnection = connection.getNativeConnection(); Object result = null; if (nativeConnection instanceof JedisCommands) { result = ((JedisCommands) nativeConnection).get(key); } return (T) result; }); } /** * @param millis 毫秒 * @param nanos 纳秒 * @Title: seleep * @Description: 线程等待时间 * @author yuhao.wang */ private void seleep(long millis, int nanos) { try { Thread.sleep(millis, random.nextInt(nanos)); } catch (InterruptedException e) { logger.info("获取分布式锁休眠被中断:", e); } }
public String getLockKeyLog() { return lockKeyLog; } public void setLockKeyLog(String lockKeyLog) { this.lockKeyLog = lockKeyLog; } public int getExpireTime() { return expireTime; } public void setExpireTime(int expireTime) { this.expireTime = expireTime; } public long getTimeOut() { return timeOut; } public void setTimeOut(long timeOut) { this.timeOut = timeOut; } }
repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\redis\lock\RedisLock3.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain filterChainApp2(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/user/**") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/user/**")).hasRole("USER")) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginProcessingUrl("/user/login") .failureUrl("/userLogin?error=loginError") .defaultSuccessUrl("/user/myUserPage")) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/user/logout") .logoutSuccessUrl("/multipleHttpLinks") .deleteCookies("JSESSIONID")) .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPointWithWarning(), new AntPathRequestMatcher("/user/private/**")) .defaultAuthenticationEntryPointFor(loginUrlauthenticationEntryPoint(), new AntPathRequestMatcher("/user/general/**")) .accessDeniedPage("/403")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public AuthenticationEntryPoint loginUrlauthenticationEntryPoint(){ return new LoginUrlAuthenticationEntryPoint("/userLogin"); } @Bean public AuthenticationEntryPoint loginUrlauthenticationEntryPointWithWarning(){ return new LoginUrlAuthenticationEntryPoint("/userLoginWithWarning");
} } @Configuration @Order(3) public static class App3ConfigurationAdapter { @Bean public SecurityFilterChain filterChainApp3(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/guest/**") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/guest/**")).permitAll()); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multipleentrypoints\MultipleEntryPointsSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class HttpClientProperties { /** * 建立连接的超时时间 */ private int connectTimeout = 20000; /** * 连接不够用的等待时间 */ private int requestTimeout = 20000; /** * 每次请求等待返回的超时时间 */ private int socketTimeout = 30000; /** * 每个主机最大连接数 */ private int defaultMaxPerRoute = 100; /** * 最大连接数 */ private int maxTotalConnections = 300; /** * 默认连接保持活跃的时间 */ private int defaultKeepAliveTimeMillis = 20000; /** * 空闲连接生的存时间 */ private int closeIdleConnectionWaitTimeSecs = 30; public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getRequestTimeout() { return requestTimeout; } public void setRequestTimeout(int requestTimeout) { this.requestTimeout = requestTimeout; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; }
public int getDefaultMaxPerRoute() { return defaultMaxPerRoute; } public void setDefaultMaxPerRoute(int defaultMaxPerRoute) { this.defaultMaxPerRoute = defaultMaxPerRoute; } public int getMaxTotalConnections() { return maxTotalConnections; } public void setMaxTotalConnections(int maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; } public int getDefaultKeepAliveTimeMillis() { return defaultKeepAliveTimeMillis; } public void setDefaultKeepAliveTimeMillis(int defaultKeepAliveTimeMillis) { this.defaultKeepAliveTimeMillis = defaultKeepAliveTimeMillis; } public int getCloseIdleConnectionWaitTimeSecs() { return closeIdleConnectionWaitTimeSecs; } public void setCloseIdleConnectionWaitTimeSecs(int closeIdleConnectionWaitTimeSecs) { this.closeIdleConnectionWaitTimeSecs = closeIdleConnectionWaitTimeSecs; } }
repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\config\properties\HttpClientProperties.java
2
请完成以下Java代码
protected ProcessInstance execute(CommandContext commandContext, ProcessDefinitionEntity processDefinition) { if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); return compatibilityHandler.submitStartFormData(processDefinition.getId(), businessKey, properties); } ExecutionEntity processInstance = null; ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ProcessInstanceHelper processInstanceHelper = processEngineConfiguration.getProcessInstanceHelper(); // TODO: backwards compatibility? Only create the process instance and not start it? How? if (businessKey != null) { processInstance = (ExecutionEntity) processInstanceHelper.createProcessInstance(processDefinition, businessKey, null, null, null, null, null, null); } else { processInstance = (ExecutionEntity) processInstanceHelper.createProcessInstance(processDefinition, null, null, null, null, null, null, null); } CommandContextUtil.getHistoryManager(commandContext).recordFormPropertiesSubmitted(processInstance.getExecutions().get(0), properties, null, processEngineConfiguration.getClock().getCurrentTime()); FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper();
StartFormHandler startFormHandler = formHandlerHelper.getStartFormHandler(commandContext, processDefinition); startFormHandler.submitFormProperties(properties, processInstance); processInstanceHelper.startProcessInstance(processInstance, commandContext, convertPropertiesToVariablesMap()); return processInstance; } protected Map<String, Object> convertPropertiesToVariablesMap() { Map<String, Object> vars = new HashMap<>(properties.size()); for (String key : properties.keySet()) { vars.put(key, properties.get(key)); } return vars; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SubmitStartFormCmd.java
1
请完成以下Java代码
public void setValidateProcess(boolean validateProcess) { this.validateProcess = validateProcess; } public List<ProcessDefinitionEntity> getProcessDefinitions() { return processDefinitions; } public String getTargetNamespace() { return targetNamespace; } public BpmnParseHandlers getBpmnParserHandlers() { return bpmnParserHandlers; } public void setBpmnParserHandlers(BpmnParseHandlers bpmnParserHandlers) { this.bpmnParserHandlers = bpmnParserHandlers; } public DeploymentEntity getDeployment() { return deployment; } public void setDeployment(DeploymentEntity deployment) { this.deployment = deployment; } public BpmnModel getBpmnModel() { return bpmnModel; } public void setBpmnModel(BpmnModel bpmnModel) { this.bpmnModel = bpmnModel; } public ActivityBehaviorFactory getActivityBehaviorFactory() { return activityBehaviorFactory; } public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) { this.activityBehaviorFactory = activityBehaviorFactory; } public ListenerFactory getListenerFactory() { return listenerFactory; } public void setListenerFactory(ListenerFactory listenerFactory) { this.listenerFactory = listenerFactory; } public Map<String, SequenceFlow> getSequenceFlows() {
return sequenceFlows; } public ProcessDefinitionEntity getCurrentProcessDefinition() { return currentProcessDefinition; } public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public Process getCurrentProcess() { return currentProcess; } public void setCurrentProcess(Process currentProcess) { this.currentProcess = currentProcess; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek(); } public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1
请完成以下Java代码
private static final class SessionConfiguringInitializer implements ServletContextInitializer { private final Session session; private SessionConfiguringInitializer(Session session) { this.session = session; } @Override public void onStartup(ServletContext servletContext) throws ServletException { if (this.session.getTrackingModes() != null) { servletContext.setSessionTrackingModes(unwrap(this.session.getTrackingModes())); } configureSessionCookie(servletContext.getSessionCookieConfig()); } private void configureSessionCookie(SessionCookieConfig config) { Cookie cookie = this.session.getCookie(); PropertyMapper map = PropertyMapper.get(); map.from(cookie::getName).to(config::setName); map.from(cookie::getDomain).to(config::setDomain); map.from(cookie::getPath).to(config::setPath); map.from(cookie::getHttpOnly).to(config::setHttpOnly); map.from(cookie::getSecure).to(config::setSecure); map.from(cookie::getMaxAge).asInt(Duration::getSeconds).to(config::setMaxAge); map.from(cookie::getPartitioned)
.as(Object::toString) .to((partitioned) -> config.setAttribute("Partitioned", partitioned)); } @Contract("!null -> !null") private @Nullable Set<jakarta.servlet.SessionTrackingMode> unwrap( @Nullable Set<Session.SessionTrackingMode> modes) { if (modes == null) { return null; } Set<jakarta.servlet.SessionTrackingMode> result = new LinkedHashSet<>(); for (Session.SessionTrackingMode mode : modes) { result.add(jakarta.servlet.SessionTrackingMode.valueOf(mode.name())); } return result; } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletContextInitializers.java
1
请在Spring Boot框架中完成以下Java代码
public DeviceAppraisalLine repairsReason(String repairsReason) { this.repairsReason = repairsReason; return this; } /** * Grund für die Reparatur * @return repairsReason **/ @Schema(example = "Pumpe defekt", description = "Grund für die Reparatur") public String getRepairsReason() { return repairsReason; } public void setRepairsReason(String repairsReason) { this.repairsReason = repairsReason; } public DeviceAppraisalLine repairsResolution(String repairsResolution) { this.repairsResolution = repairsResolution; return this; } /** * Reparaturlösung * @return repairsResolution **/ @Schema(example = "Pumpe getauscht", description = "Reparaturlösung") public String getRepairsResolution() { return repairsResolution; } public void setRepairsResolution(String repairsResolution) { this.repairsResolution = repairsResolution; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceAppraisalLine deviceAppraisalLine = (DeviceAppraisalLine) o; return Objects.equals(this.description, deviceAppraisalLine.description) && Objects.equals(this.additionalDescription, deviceAppraisalLine.additionalDescription) && Objects.equals(this.repairsReason, deviceAppraisalLine.repairsReason) && Objects.equals(this.repairsResolution, deviceAppraisalLine.repairsResolution); } @Override public int hashCode() {
return Objects.hash(description, additionalDescription, repairsReason, repairsResolution); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceAppraisalLine {\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" additionalDescription: ").append(toIndentedString(additionalDescription)).append("\n"); sb.append(" repairsReason: ").append(toIndentedString(repairsReason)).append("\n"); sb.append(" repairsResolution: ").append(toIndentedString(repairsResolution)).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(java.lang.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-article-api\src\main\java\io\swagger\client\model\DeviceAppraisalLine.java
2
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set 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); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java
1
请完成以下Java代码
public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2AuthorizationConsentAuthenticationToken { @Serial private static final long serialVersionUID = 3789252233721827596L; private final String userCode; private final Set<String> requestedScopes; /** * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the * provided parameters. * @param authorizationUri the authorization URI * @param clientId the client identifier * @param principal the {@code Principal} (Resource Owner) * @param userCode the user code associated with the device authorization response * @param state the state * @param authorizedScopes the authorized scope(s) * @param additionalParameters the additional parameters */ public OAuth2DeviceAuthorizationConsentAuthenticationToken(String authorizationUri, String clientId, Authentication principal, String userCode, String state, @Nullable Set<String> authorizedScopes, @Nullable Map<String, Object> additionalParameters) { super(authorizationUri, clientId, principal, state, authorizedScopes, additionalParameters); Assert.hasText(userCode, "userCode cannot be empty"); this.userCode = userCode; this.requestedScopes = null; setAuthenticated(false); } /** * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the * provided parameters. * @param authorizationUri the authorization URI * @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner) * @param userCode the user code associated with the device authorization response * @param state the state * @param requestedScopes the requested scope(s) * @param authorizedScopes the authorized scope(s) */ public OAuth2DeviceAuthorizationConsentAuthenticationToken(String authorizationUri, String clientId, Authentication principal, String userCode, String state, @Nullable Set<String> requestedScopes, @Nullable Set<String> authorizedScopes) { super(authorizationUri, clientId, principal, state, authorizedScopes, null); Assert.hasText(userCode, "userCode cannot be empty"); this.userCode = userCode; this.requestedScopes = Collections .unmodifiableSet((requestedScopes != null) ? new HashSet<>(requestedScopes) : Collections.emptySet()); setAuthenticated(true); } /** * Returns the user code. * @return the user code */ public String getUserCode() { return this.userCode; } /** * Returns the requested scopes. * @return the requested scopes */ public Set<String> getRequestedScopes() { return this.requestedScopes; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationConsentAuthenticationToken.java
1
请完成以下Java代码
public List<EntityInfo> findAssetProfileNamesByTenantId(TenantId tenantId, boolean activeOnly) { log.trace("Executing findAssetProfileNamesByTenantId, tenantId [{}]", tenantId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); return assetProfileDao.findTenantAssetProfileNames(tenantId.getId(), activeOnly) .stream().sorted(Comparator.comparing(EntityInfo::getName)) .collect(Collectors.toList()); } @Override public List<AssetProfileInfo> findAssetProfilesByIds(TenantId tenantId, List<AssetProfileId> assetProfileIds) { log.trace("Executing findAssetProfilesByIds, tenantId [{}], assetProfileIds [{}]", tenantId, assetProfileIds); return assetProfileDao.findAssetProfilesByTenantIdAndIds(tenantId.getId(), toUUIDs(assetProfileIds)); } private final PaginatedRemover<TenantId, AssetProfile> tenantAssetProfilesRemover = new PaginatedRemover<>() {
@Override protected PageData<AssetProfile> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return assetProfileDao.findAssetProfiles(id, pageLink); } @Override protected void removeEntity(TenantId tenantId, AssetProfile entity) { removeAssetProfile(tenantId, entity); } }; private AssetProfileInfo toAssetProfileInfo(AssetProfile profile) { return profile == null ? null : new AssetProfileInfo(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(), profile.getDefaultDashboardId()); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\asset\AssetProfileServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
private GetWarehouseFromFileRouteBuilder getWarehousesFromFileRouteBuilder(@NonNull final JsonExternalSystemRequest request, @NonNull final CamelContext camelContext) { return GetWarehouseFromFileRouteBuilder .builder() .fileEndpointConfig(PCMConfigUtil.extractLocalFileConfig(request, camelContext)) .camelContext(camelContext) .enabledByExternalSystemRequest(request) .processLogger(processLogger) .routeId(getWarehousesFromLocalFileRouteId(request)) .build(); } @NonNull @VisibleForTesting public static String getWarehousesFromLocalFileRouteId(@NonNull final JsonExternalSystemRequest externalSystemRequest) { return "GetWarehouseFromLocalFile#" + externalSystemRequest.getExternalSystemChildConfigValue(); } @Override public String getServiceValue() { return "LocalFileSyncWarehouses"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME; } @Override public String getEnableCommand() { return START_WAREHOUSE_SYNC_LOCAL_FILE_ROUTE; }
@Override public String getDisableCommand() { return STOP_WAREHOUSE_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartWarehouseRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopWarehouseRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\warehouse\LocalFileWarehouseSyncServicePCMRouteBuilder.java
2
请完成以下Java代码
protected String doIt() { pickQtyToNewHUs(this::pickQtyToNewHU); invalidatePackablesView(); // left side view invalidatePickingSlotsView(); // right side view return MSG_OK; } protected final void pickQtyToNewHUs(@NonNull final Consumer<Quantity> pickQtyConsumer) { Quantity qtyToPack = getQtyToPack(); if (qtyToPack.signum() <= 0) { throw new AdempiereException("@QtyCU@ > 0"); } final Capacity piipCapacity = getPIIPCapacity(); if (piipCapacity.isInfiniteCapacity()) { pickQtyConsumer.accept(qtyToPack); return; } final Quantity piipQtyCapacity = piipCapacity.toQuantity(); while (qtyToPack.toBigDecimal().signum() > 0) { final Quantity qtyToProcess = piipQtyCapacity.min(qtyToPack); pickQtyConsumer.accept(qtyToProcess); qtyToPack = qtyToPack.subtract(qtyToProcess);
} } @NonNull private QuantityTU getQtyTU() { return getPIIPCapacity().calculateQtyTU(qtyCUsPerTU, getCurrentShipmentScheuduleUOM(), uomConversionBL) .orElseThrow(() -> new AdempiereException("QtyTU cannot be obtained for the current request!") .appendParametersToMessage() .setParameter("QtyCU", qtyCUsPerTU) .setParameter("ShipmentScheduleId", getCurrentShipmentScheduleId())); } @NonNull protected final Capacity getPIIPCapacity() { final I_M_ShipmentSchedule currentShipmentSchedule = getCurrentShipmentSchedule(); final ProductId productId = ProductId.ofRepoId(currentShipmentSchedule.getM_Product_ID()); final I_C_UOM stockUOM = productBL.getStockUOM(productId); return huCapacityBL.getCapacity(huPIItemProduct, productId, stockUOM); } @NonNull private BigDecimal getDefaultNrOfHUs() { if (qtyCUsPerTU == null || huPIItemProduct == null) { return BigDecimal.ONE; } return getQtyTU().toBigDecimal(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToComputedHU.java
1
请完成以下Java代码
public class X_C_Greeting extends org.compiere.model.PO implements I_C_Greeting, org.compiere.model.I_Persistent { private static final long serialVersionUID = 425853958L; /** Standard Constructor */ public X_C_Greeting (final Properties ctx, final int C_Greeting_ID, @Nullable final String trxName) { super (ctx, C_Greeting_ID, trxName); } /** Load Constructor */ public X_C_Greeting (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Greeting_ID (final int C_Greeting_ID) { if (C_Greeting_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Greeting_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Greeting_ID, C_Greeting_ID); } @Override public int getC_Greeting_ID() { return get_ValueAsInt(COLUMNNAME_C_Greeting_ID); } @Override public void setGreeting (final @Nullable java.lang.String Greeting) { set_Value (COLUMNNAME_Greeting, Greeting); } @Override public java.lang.String getGreeting() { return get_ValueAsString(COLUMNNAME_Greeting); } /** * GreetingStandardType AD_Reference_ID=541326 * Reference name: GreetingStandardType */ public static final int GREETINGSTANDARDTYPE_AD_Reference_ID=541326; /** MR = MR */ public static final String GREETINGSTANDARDTYPE_MR = "MR"; /** MRS = MRS */ public static final String GREETINGSTANDARDTYPE_MRS = "MRS"; /** MR+MRS = MR+MRS */ public static final String GREETINGSTANDARDTYPE_MRPlusMRS = "MR+MRS"; /** MRS+MR = MRS+MR */ public static final String GREETINGSTANDARDTYPE_MRSPlusMR = "MRS+MR"; @Override public void setGreetingStandardType (final @Nullable java.lang.String GreetingStandardType) { set_Value (COLUMNNAME_GreetingStandardType, GreetingStandardType); } @Override public java.lang.String getGreetingStandardType() { return get_ValueAsString(COLUMNNAME_GreetingStandardType); }
@Override public void setIsDefault (final boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, IsDefault); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setIsFirstNameOnly (final boolean IsFirstNameOnly) { set_Value (COLUMNNAME_IsFirstNameOnly, IsFirstNameOnly); } @Override public boolean isFirstNameOnly() { return get_ValueAsBoolean(COLUMNNAME_IsFirstNameOnly); } @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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Greeting.java
1
请完成以下Java代码
public void setFolder (String Folder) { set_Value (COLUMNNAME_Folder, Folder); } /** Get Folder. @return A folder on a local or remote system to store data into */ public String getFolder () { return (String)get_Value(COLUMNNAME_Folder); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set IP Address. @param IP_Address Defines the IP address to transfer data to */ public void setIP_Address (String IP_Address) { set_Value (COLUMNNAME_IP_Address, IP_Address); } /** Get IP Address. @return Defines the IP address to transfer data to */ public String getIP_Address () { return (String)get_Value(COLUMNNAME_IP_Address); } /** Set Transfer passive. @param IsPassive FTP passive transfer */ public void setIsPassive (boolean IsPassive) { set_Value (COLUMNNAME_IsPassive, Boolean.valueOf(IsPassive)); } /** Get Transfer passive. @return FTP passive transfer */ public boolean isPassive () { Object oo = get_Value(COLUMNNAME_IsPassive); 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()); } /** Set Password. @param Password Password of any length (case sensitive) */ public void setPassword (String Password)
{ set_Value (COLUMNNAME_Password, Password); } /** Get Password. @return Password of any length (case sensitive) */ public String getPassword () { return (String)get_Value(COLUMNNAME_Password); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ public void setUserName (String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ public String getUserName () { return (String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
1
请完成以下Java代码
public void dataRefresh() { final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshAll() { // NOTE: there is no "All" concept here, so we are just refreshing this document final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshRecursively() { // TODO dataRefreshRecursively: refresh document and it's children
throw new UnsupportedOperationException(); } @Override public boolean dataSave(final boolean manualCmd) { // TODO dataSave: save document but also update the DocumentsCollection! throw new UnsupportedOperationException(); } @Override public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id) { //Querying all values because getLookupValueById doesn't take validation rul into consideration. // TODO: Implement possibility to fetch sqllookupbyid with validation rule considered. return getDocument().getFieldLookupValues(columnName).containsId(id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java
1
请完成以下Java代码
private void addCheck(MethodTree method, VariableTree parameter, Context context) { JCTree.JCIf check = createCheck(parameter, context); JCTree.JCBlock body = (JCTree.JCBlock) method.getBody(); body.stats = body.stats.prepend(check); } private static JCTree.JCIf createCheck(VariableTree parameter, Context context) { TreeMaker factory = TreeMaker.instance(context); Names symbolsTable = Names.instance(context); return factory.at(((JCTree) parameter).pos) .If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)), createIfBlock(factory, symbolsTable, parameter), null); } private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) { Name parameterId = symbolsTable.fromString(parameter.getName().toString()); return factory.Binary(JCTree.Tag.LE, factory.Ident(parameterId), factory.Literal(TypeTag.INT, 0)); }
private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) { String parameterName = parameter.getName().toString(); Name parameterId = symbolsTable.fromString(parameterName); String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '", parameterName, parameter.getType(), Positive.class.getSimpleName()); String errorMessageSuffix = "' for it"; return factory.Block(0, com.sun.tools.javac.util.List.of( factory.Throw( factory.NewClass(null, nil(), factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())), com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS, factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix), factory.Ident(parameterId)), factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null)))); } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\javac\SampleJavacPlugin.java
1
请完成以下Java代码
public class WebClientFilters { private static final Logger LOG = LoggerFactory.getLogger(WebClientFilters.class); public static ExchangeFilterFunction demoFilter() { ExchangeFilterFunction filterFunction = (clientRequest, nextFilter) -> { LOG.info("WebClient fitler executed"); return nextFilter.exchange(clientRequest); }; return filterFunction; } public static ExchangeFilterFunction countingFilter(AtomicInteger getCounter) { ExchangeFilterFunction countingFilter = (clientRequest, nextFilter) -> { HttpMethod httpMethod = clientRequest.method(); if (httpMethod == HttpMethod.GET) { getCounter.incrementAndGet(); } return nextFilter.exchange(clientRequest); }; return countingFilter; } public static ExchangeFilterFunction urlModifyingFilter(String version) { ExchangeFilterFunction urlModifyingFilter = (clientRequest, nextFilter) -> { String oldUrl = clientRequest.url() .toString();
URI newUrl = URI.create(oldUrl + "/" + version); ClientRequest filteredRequest = ClientRequest.from(clientRequest) .url(newUrl) .build(); return nextFilter.exchange(filteredRequest); }; return urlModifyingFilter; } public static ExchangeFilterFunction loggingFilter(PrintStream printStream) { ExchangeFilterFunction loggingFilter = (clientRequest, nextFilter) -> { printStream.print("Sending request " + clientRequest.method() + " " + clientRequest.url()); return nextFilter.exchange(clientRequest); }; return loggingFilter; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-filters\src\main\java\com\baeldung\reactive\filters\WebClientFilters.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("documentPath", document.getDocumentPath()) .add("tableName", tableName) .add("adTabId", adTabId) .add("selectedIncludedRecords", selectedIncludedRecords) .toString(); } @Override public AdWindowId getAdWindowId() { return document.getDocumentPath().getAdWindowIdOrNull(); } @Override public <T> T getSelectedModel(final Class<T> modelClass) { return InterfaceWrapperHelper.create(document, modelClass); } @Override public <T> List<T> getSelectedModels(final Class<T> modelClass) { return streamSelectedModels(modelClass) .collect(ImmutableList.toImmutableList()); } @NonNull @Override public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass) { return Stream.of(getSelectedModel(modelClass));
} @Override public int getSingleSelectedRecordId() { return document.getDocumentIdAsInt(); } @Override public SelectionSize getSelectionSize() { return SelectionSize.ofSize(1); } @Override public <T> IQueryFilter<T> getQueryFilter(@NonNull final Class<T> recordClass) { final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName); return EqualsQueryFilter.of(keyColumnName, getSingleSelectedRecordId()); } @Override public OptionalBoolean isExistingDocument() { return OptionalBoolean.ofBoolean(!document.isNew()); } @Override public OptionalBoolean isProcessedDocument() { return OptionalBoolean.ofBoolean(document.isProcessed()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\DocumentPreconditionsAsContext.java
1
请完成以下Java代码
public IViewRow getRow(final int rowIndex) { Check.assume(rowIndex >= 0, "rowIndex >= 0"); final int rowsCount = rows.size(); Check.assume(rowIndex < rowsCount, "rowIndex < {}", rowsCount); return rows.get(rowIndex); } @Override public int getRowCount() { return rows.size(); } } @Override
protected List<CellValue> getNextRow() { final ArrayList<CellValue> result = new ArrayList<>(); for (int i = 0; i < getColumnCount(); i++) { result.add(getValueAt(rowNumber, i)); } rowNumber++; return result; } @Override protected boolean hasNextRow() { return rowNumber < getRowCount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewExcelExporter.java
1
请完成以下Java代码
public class Article { private String id; private String content; private String author; private String datePublished; private int wordCount; public Article(String id, String content, String author, String datePublished, int wordCount) { super(); this.id = id; this.content = content; this.author = author; this.datePublished = datePublished; this.wordCount = wordCount; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; } public String getDatePublished() { return datePublished; } public void setDatePublished(String datePublished) { this.datePublished = datePublished; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } }
repos\tutorials-master\vertx-modules\vertx\src\main\java\com\baeldung\model\Article.java
1
请完成以下Java代码
public @Nullable String getFallbackPath() { return fallbackPath; } public CircuitBreakerConfig setFallbackUri(String fallbackUri) { Objects.requireNonNull(fallbackUri, "fallbackUri String may not be null"); setFallbackUri(URI.create(fallbackUri)); return this; } public CircuitBreakerConfig setFallbackUri(@Nullable URI fallbackUri) { if (fallbackUri != null) { Assert.isTrue(fallbackUri.getScheme().equalsIgnoreCase("forward"), () -> "Scheme must be forward, but is " + fallbackUri.getScheme()); fallbackPath = fallbackUri.getPath(); } else { fallbackPath = null; } return this; } public CircuitBreakerConfig setFallbackPath(String fallbackPath) { this.fallbackPath = fallbackPath; return this; } public Set<String> getStatusCodes() { return statusCodes; } public CircuitBreakerConfig setStatusCodes(String... statusCodes) { return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes))); } public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes; return this; } public boolean isResumeWithoutError() { return resumeWithoutError; } public CircuitBreakerConfig setResumeWithoutError(boolean resumeWithoutError) { this.resumeWithoutError = resumeWithoutError; return this; } } public static class CircuitBreakerStatusCodeException extends ResponseStatusException { public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) { super(statusCode); } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(CircuitBreakerFilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\CircuitBreakerFilterFunctions.java
1
请完成以下Java代码
private Map<String, String> buildMap(Element xml) { Map<String, String> map = new HashMap<>(); map.put("heading", xml .getElementsByTagName("heading") .item(0) .getTextContent()); map.put("from", String.format("from: %s", xml .getElementsByTagName("from") .item(0) .getTextContent())); map.put("content", xml .getElementsByTagName("content") .item(0) .getTextContent()); return map; } private Element buildHead(Map<String, String> map, Document doc) { Element head = doc.createElement("head"); Element title = doc.createElement("title");
title.setTextContent(map.get("heading")); head.appendChild(title); return head; } private Element buildBody(Map<String, String> map, Document doc) { Element body = doc.createElement("body"); Element from = doc.createElement("p"); from.setTextContent(map.get("from")); Element success = doc.createElement("p"); success.setTextContent(map.get("content")); body.appendChild(from); body.appendChild(success); return body; } }
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xmlhtml\jaxp\JaxpTransformer.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductForm { private Long id; private String description; private BigDecimal price; private String imageUrl; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) {
this.description = description; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
repos\SpringBootVulExploit-master\repository\springboot-mysql-jdbc-rce\src\main\java\code\landgrey\commands\ProductForm.java
2
请在Spring Boot框架中完成以下Java代码
public String getFaultCode() { return faultCode; } /** * Sets the value of the faultCode property. * * @param value * allowed object is * {@link String } * */ public void setFaultCode(String value) { this.faultCode = value; } /** * Gets the value of the message property. * * @return * possible object is * {@link String }
* */ public String getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is * {@link String } * */ public void setMessage(String value) { this.message = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\FaultCodeType.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public GroupEntity getGroup() { return group; } public void setGroup(GroupEntity group) { this.group = group; } public String getTenantId() { return tenant.getId(); } public String getUserId() { if (user != null) { return user.getId(); } else { return null; } } public String getGroupId() {
if (group != null) { return group.getId(); } else { return null; } } public TenantEntity getTenant() { return tenant; } public void setTenant(TenantEntity tenant) { this.tenant = tenant; } @Override public String toString() { return "TenantMembershipEntity [id=" + id + ", tenant=" + tenant + ", user=" + user + ", group=" + group + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TenantMembershipEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class DistributionJobQueries { public static DDOrderQueryBuilder newDDOrdersQuery() { return DDOrderQuery.builder() .docStatus(DocStatus.Completed) .orderBys(DistributionJobSorting.DEFAULT.toDDOrderQueryOrderBys()); } public static DDOrderQuery ddOrdersAssignedToUser(@NonNull final DDOrderReferenceQuery query) { return ddOrdersAssignedToUser(query.getResponsibleId(), query.getSorting()).build(); } public static DDOrderQueryBuilder ddOrdersAssignedToUser(@NonNull final UserId responsibleId) { return ddOrdersAssignedToUser(responsibleId, DistributionJobSorting.DEFAULT); } private static DDOrderQueryBuilder ddOrdersAssignedToUser(@NonNull final UserId responsibleId, @NonNull DistributionJobSorting sorting) { return newDDOrdersQuery() .orderBys(sorting.toDDOrderQueryOrderBys()) .responsibleId(ValueRestriction.equalsTo(responsibleId)); } public static DDOrderQuery toActiveNotAssignedDDOrderQuery(final @NonNull DDOrderReferenceQuery query) { final DistributionFacetIdsCollection activeFacetIds = query.getActiveFacetIds(); final InSetPredicate<WarehouseId> warehouseToIds = extractWarehouseToIds(query); return newDDOrdersQuery() .orderBys(query.getSorting().toDDOrderQueryOrderBys()) .responsibleId(ValueRestriction.isNull()) .warehouseFromIds(activeFacetIds.getWarehouseFromIds()) .warehouseToIds(warehouseToIds) .locatorToIds(InSetPredicate.onlyOrAny(query.getLocatorToId())) .salesOrderIds(activeFacetIds.getSalesOrderIds()) .manufacturingOrderIds(activeFacetIds.getManufacturingOrderIds()) .datesPromised(activeFacetIds.getDatesPromised()) .productIds(activeFacetIds.getProductIds()) .qtysEntered(activeFacetIds.getQuantities()) .plantIds(activeFacetIds.getPlantIds()) .build(); }
@Nullable private static InSetPredicate<WarehouseId> extractWarehouseToIds(final @NotNull DDOrderReferenceQuery query) { final Set<WarehouseId> facetWarehouseToIds = query.getActiveFacetIds().getWarehouseToIds(); final WarehouseId onlyWarehouseToId = query.getWarehouseToId(); if (onlyWarehouseToId != null) { if (facetWarehouseToIds.isEmpty() || facetWarehouseToIds.contains(onlyWarehouseToId)) { return InSetPredicate.only(onlyWarehouseToId); } else { return InSetPredicate.none(); } } else if (!facetWarehouseToIds.isEmpty()) { return InSetPredicate.only(facetWarehouseToIds); } else { return InSetPredicate.any(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobQueries.java
2
请完成以下Java代码
public HttpComponentsClientHttpRequestFactoryBuilder withTlsSocketStrategyFactory( TlsSocketStrategyFactory tlsSocketStrategyFactory) { Assert.notNull(tlsSocketStrategyFactory, "'tlsSocketStrategyFactory' must not be null"); return new HttpComponentsClientHttpRequestFactoryBuilder(getCustomizers(), this.httpClientBuilder.withTlsSocketStrategyFactory(tlsSocketStrategyFactory)); } /** * Return a new {@link HttpComponentsClientHttpRequestFactoryBuilder} that applies * additional customization to the underlying * {@link org.apache.hc.client5.http.config.RequestConfig.Builder} used for default * requests. * @param defaultRequestConfigCustomizer the customizer to apply * @return a new {@link HttpComponentsClientHttpRequestFactoryBuilder} instance */ public HttpComponentsClientHttpRequestFactoryBuilder withDefaultRequestConfigCustomizer( Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer) { Assert.notNull(defaultRequestConfigCustomizer, "'defaultRequestConfigCustomizer' must not be null"); return new HttpComponentsClientHttpRequestFactoryBuilder(getCustomizers(), this.httpClientBuilder.withDefaultRequestConfigCustomizer(defaultRequestConfigCustomizer)); } /** * Return a new {@link HttpComponentsClientHttpRequestFactoryBuilder} that applies the * given customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply * @return a new {@link HttpComponentsClientHttpRequestFactoryBuilder} * @since 4.0.0 */ public HttpComponentsClientHttpRequestFactoryBuilder with( UnaryOperator<HttpComponentsClientHttpRequestFactoryBuilder> customizer) { return customizer.apply(this); } @Override protected HttpComponentsClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) { HttpClient httpClient = this.httpClientBuilder.build(settings); return new HttpComponentsClientHttpRequestFactory(httpClient); } static class Classes { static final String HTTP_CLIENTS = "org.apache.hc.client5.http.impl.classic.HttpClients"; static boolean present(@Nullable ClassLoader classLoader) { return ClassUtils.isPresent(HTTP_CLIENTS, classLoader); } } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\HttpComponentsClientHttpRequestFactoryBuilder.java
1
请完成以下Java代码
private boolean isCreatingNewFileSystem() { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (StackTraceElement element : stack) { if (FILE_SYSTEMS_CLASS_NAME.equals(element.getClassName())) { return "newFileSystem".equals(element.getMethodName()); } } return false; } @Override public FileSystemProvider provider() { return this.provider; } Path getJarPath() { return this.jarPath; } @Override public void close() throws IOException { if (this.closed) { return; } this.closed = true; synchronized (this.zipFileSystems) { this.zipFileSystems.values() .stream() .filter(FileSystem.class::isInstance) .map(FileSystem.class::cast) .forEach(this::closeZipFileSystem); } this.provider.removeFileSystem(this); } private void closeZipFileSystem(FileSystem zipFileSystem) { try { zipFileSystem.close(); } catch (Exception ex) { // Ignore } } @Override public boolean isOpen() { return !this.closed; } @Override public boolean isReadOnly() { return true; } @Override public String getSeparator() { return "/!"; } @Override public Iterable<Path> getRootDirectories() { assertNotClosed(); return Collections.emptySet(); } @Override public Iterable<FileStore> getFileStores() { assertNotClosed(); return Collections.emptySet(); } @Override public Set<String> supportedFileAttributeViews() { assertNotClosed(); return SUPPORTED_FILE_ATTRIBUTE_VIEWS; } @Override public Path getPath(String first, String... more) { assertNotClosed(); if (more.length != 0) { throw new IllegalArgumentException("Nested paths must contain a single element"); }
return new NestedPath(this, first); } @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException("Nested paths do not support path matchers"); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service"); } @Override public WatchService newWatchService() throws IOException { throw new UnsupportedOperationException("Nested paths do not support the WatchService"); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } NestedFileSystem other = (NestedFileSystem) obj; return this.jarPath.equals(other.jarPath); } @Override public int hashCode() { return this.jarPath.hashCode(); } @Override public String toString() { return this.jarPath.toAbsolutePath().toString(); } private void assertNotClosed() { if (this.closed) { throw new ClosedFileSystemException(); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java
1
请完成以下Java代码
protected String getHUValue() { final I_M_HU hu = getM_HU(); String huValue = hu.getValue(); if (Check.isEmpty(huValue, true)) { huValue = String.valueOf(hu.getM_HU_ID()); } return huValue; } @Override public final String getPIName() { final I_M_HU hu = getM_HU(); final String piNameRaw; if (handlingUnitsBL.isAggregateHU(hu)) { piNameRaw = getAggregateHuPiName(hu); } else { final I_M_HU_PI pi = handlingUnitsBL.getPI(hu); piNameRaw = pi != null ? pi.getName() : "?"; } return escape(piNameRaw); } private String getAggregateHuPiName(final I_M_HU hu) { // note: if HU is an aggregate HU, then there won't be an NPE here. final I_M_HU_Item parentItem = hu.getM_HU_Item_Parent(); final I_M_HU_PI_Item parentPIItem = handlingUnitsBL.getPIItem(parentItem); if (parentPIItem == null) { // new HUException("Aggregate HU's parent item has no M_HU_PI_Item; parent-item=" + parentItem) // .setParameter("parent M_HU_PI_Item_ID", parentItem != null ? parentItem.getM_HU_PI_Item_ID() : null) // .throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } HuPackingInstructionsId includedPIId = HuPackingInstructionsId.ofRepoIdOrNull(parentPIItem.getIncluded_HU_PI_ID()); if (includedPIId == null) { //noinspection ThrowableNotThrown new HUException("Aggregate HU's parent item has M_HU_PI_Item without an Included_HU_PI; parent-item=" + parentItem).throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } final I_M_HU_PI included_HU_PI = handlingUnitsBL.getPI(includedPIId); return included_HU_PI.getName(); }
// NOTE: this method can be overridden by extending classes in order to optimize how the HUs are counted. @Override public int getIncludedHUsCount() { // NOTE: we need to iterate the HUs and count them (instead of doing a COUNT directly on database), // because we rely on HU&Items caching // and also because in case of aggregated HUs, we need special handling final IncludedHUsCounter includedHUsCounter = new IncludedHUsCounter(getM_HU()); final HUIterator huIterator = new HUIterator(); huIterator.setListener(includedHUsCounter.toHUIteratorListener()); huIterator.setEnableStorageIteration(false); huIterator.iterate(getM_HU()); return includedHUsCounter.getHUsCount(); } protected String escape(final String string) { return StringUtils.maskHTML(string); } @Override public IHUDisplayNameBuilder setShowIfDestroyed(final boolean showIfDestroyed) { this.showIfDestroyed = showIfDestroyed; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDisplayNameBuilder.java
1
请完成以下Java代码
private static <E> Consumer<Members<E>> customized(Consumer<Members<E>> members, @Nullable StructuredLoggingJsonMembersCustomizer<?> customizer) { return (customizer != null) ? members.andThen(customizeWith(customizer)) : members; } @SuppressWarnings("unchecked") private static <E> Consumer<Members<E>> customizeWith(StructuredLoggingJsonMembersCustomizer<?> customizer) { return (members) -> LambdaSafe.callback(StructuredLoggingJsonMembersCustomizer.class, customizer, members) .invoke((instance) -> instance.customize(members)); } /** * Create a new {@link JsonWriterStructuredLogFormatter} instance with the given * {@link JsonWriter}. * @param jsonWriter the {@link JsonWriter}
*/ protected JsonWriterStructuredLogFormatter(JsonWriter<E> jsonWriter) { this.jsonWriter = jsonWriter; } @Override public String format(E event) { return this.jsonWriter.writeToString(event); } @Override public byte[] formatAsBytes(E event, Charset charset) { return this.jsonWriter.write(event).toByteArray(charset); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\JsonWriterStructuredLogFormatter.java
1
请在Spring Boot框架中完成以下Java代码
public class AvailabilityMultiResult { public static AvailabilityMultiResult of(final List<AvailabilityResult> results) { if (results.isEmpty()) { return EMPTY; } return new AvailabilityMultiResult(Multimaps.index(results, AvailabilityResult::getTrackingId)); } public static AvailabilityMultiResult of(@NonNull final AvailabilityResult result) { return of(ImmutableList.of(result)); } public static final AvailabilityMultiResult EMPTY = new AvailabilityMultiResult(); @Getter(AccessLevel.NONE) private final ImmutableListMultimap<TrackingId, AvailabilityResult> results; private AvailabilityMultiResult(final ListMultimap<TrackingId, AvailabilityResult> results) { this.results = ImmutableListMultimap.copyOf(results); } private AvailabilityMultiResult() { results = ImmutableListMultimap.of(); } public boolean isEmpty() { return results.isEmpty(); } public AvailabilityMultiResult merge(@NonNull final AvailabilityMultiResult other) { if (isEmpty()) { return other; }
else if (other.isEmpty()) { return this; } else { return new AvailabilityMultiResult(ImmutableListMultimap.<TrackingId, AvailabilityResult> builder() .putAll(results) .putAll(other.results) .build()); } } public Set<TrackingId> getTrackingIds() { return results.keySet(); } public List<AvailabilityResult> getByTrackingId(final TrackingId trackingId) { return results.get(trackingId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityMultiResult.java
2
请完成以下Java代码
public DmnElement getSource() { return sourceRef.getReferenceTargetElement(this); } public void setSource(DmnElement source) { sourceRef.setReferenceTargetElement(this, source); } public DmnElement getTarget() { return targetRef.getReferenceTargetElement(this); } public void setTarget(DmnElement target) { targetRef.setReferenceTargetElement(this, target); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, DMN_ELEMENT_ASSOCIATION) .namespaceUri(LATEST_DMN_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); } }); associationDirectionAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .defaultValue(AssociationDirection.None) .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); sourceRef = sequenceBuilder.element(SourceRef.class) .required() .uriElementReference(DmnElement.class) .build(); targetRef = sequenceBuilder.element(TargetRef.class) .required() .uriElementReference(DmnElement.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\AssociationImpl.java
1
请完成以下Java代码
public int getDropShip_User_ID() { return delegate.getDropShip_User_ID(); } @Override public void setDropShip_User_ID(final int DropShip_User_ID) { delegate.setDropShip_User_ID(DropShip_User_ID); } @Override public int getM_Warehouse_ID() { return delegate.getM_Warehouse_ID(); } @Override public boolean isDropShip() { return delegate.isDropShip(); } @Override public String getDeliveryToAddress() { return delegate.getDeliveryToAddress(); } @Override public void setDeliveryToAddress(final String address) { delegate.setDeliveryToAddress(address); }
@Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from); } @Override public I_M_InOut getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public DocumentDeliveryLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new DocumentDeliveryLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentDeliveryLocationAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public ListenableFuture<Void> processRelationMsgFromEdge(TenantId tenantId, Edge edge, RelationUpdateMsg relationUpdateMsg) { log.trace("[{}] executing processRelationMsgFromEdge [{}] from edge [{}]", tenantId, relationUpdateMsg, edge.getId()); try { edgeSynchronizationManager.getEdgeId().set(edge.getId()); return processRelationMsg(tenantId, relationUpdateMsg); } finally { edgeSynchronizationManager.getEdgeId().remove(); } } @Override public ListenableFuture<Void> processEntityNotification(TenantId tenantId, TransportProtos.EdgeNotificationMsgProto edgeNotificationMsg) { EntityRelation relation = JacksonUtil.fromString(edgeNotificationMsg.getBody(), EntityRelation.class); if (relation == null) { return Futures.immediateFuture(null); } EdgeId originatorEdgeId = safeGetEdgeId(edgeNotificationMsg.getOriginatorEdgeIdMSB(), edgeNotificationMsg.getOriginatorEdgeIdLSB()); Set<EdgeId> uniqueEdgeIds = new HashSet<>(); uniqueEdgeIds.addAll(edgeCtx.getEdgeService().findAllRelatedEdgeIds(tenantId, relation.getTo())); uniqueEdgeIds.addAll(edgeCtx.getEdgeService().findAllRelatedEdgeIds(tenantId, relation.getFrom())); uniqueEdgeIds.remove(originatorEdgeId); if (uniqueEdgeIds.isEmpty()) { return Futures.immediateFuture(null); } List<ListenableFuture<Void>> futures = new ArrayList<>(); for (EdgeId edgeId : uniqueEdgeIds) {
futures.add(saveEdgeEvent(tenantId, edgeId, EdgeEventType.RELATION, EdgeEventActionType.valueOf(edgeNotificationMsg.getAction()), null, JacksonUtil.valueToTree(relation))); } return Futures.transform(Futures.allAsList(futures), voids -> null, dbCallbackExecutorService); } @Override public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { EntityRelation entityRelation = JacksonUtil.convertValue(edgeEvent.getBody(), EntityRelation.class); UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction()); RelationUpdateMsg relationUpdateMsg = EdgeMsgConstructorUtils.constructRelationUpdatedMsg(msgType, entityRelation); return DownlinkMsg.newBuilder() .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) .addRelationUpdateMsg(relationUpdateMsg) .build(); } @Override public EdgeEventType getEdgeEventType() { return EdgeEventType.RELATION; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\relation\RelationEdgeProcessor.java
2
请完成以下Java代码
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 class AD_Column_Delete extends JavaProcess { // services private final IADWindowDAO adWindowsRepo = Services.get(IADWindowDAO.class); @Param(parameterName = "IsDropDBColumn") private boolean p_IsDropDBColumn; @Param(parameterName = "IsDeleteFields") private boolean p_IsDeleteFields; @Override protected String doIt() throws Exception { final I_AD_Column adColumn = getRecord(I_AD_Column.class); if (p_IsDeleteFields) { final int adColumnId = adColumn.getAD_Column_ID(); adWindowsRepo.deleteFieldsByColumnId(adColumnId); } if (p_IsDropDBColumn) {
dropDBColumn(adColumn); } InterfaceWrapperHelper.delete(adColumn); addLog("AD_Column Deleted {}", adColumn); return MSG_OK; } private void dropDBColumn(final I_AD_Column adColumn) { final String tableName = Services.get(IADTableDAO.class).retrieveTableName(adColumn.getAD_Table_ID()); final String columnName = adColumn.getColumnName(); final String sqlStatement = "ALTER TABLE " + tableName + " DROP COLUMN IF EXISTS " + columnName; final String sql = MigrationScriptFileLoggerHolder.DDL_PREFIX + "SELECT public.db_alter_table(" + DB.TO_STRING(tableName) + "," + DB.TO_STRING(sqlStatement) + ")"; final Object[] sqlParams = null; // IMPORTANT: don't use any parameters because we want to log this command to migration script file DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited, sql, sqlParams); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_Column_Delete.java
1
请完成以下Java代码
public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Windows Archive Path. @param WindowsArchivePath Windows Archive Path */ @Override public void setWindowsArchivePath (java.lang.String WindowsArchivePath) { set_Value (COLUMNNAME_WindowsArchivePath, WindowsArchivePath); } /** Get Windows Archive Path. @return Windows Archive Path */ @Override public java.lang.String getWindowsArchivePath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsArchivePath); }
/** Set Windows Attachment Path. @param WindowsAttachmentPath Windows Attachment Path */ @Override public void setWindowsAttachmentPath (java.lang.String WindowsAttachmentPath) { set_Value (COLUMNNAME_WindowsAttachmentPath, WindowsAttachmentPath); } /** Get Windows Attachment Path. @return Windows Attachment Path */ @Override public java.lang.String getWindowsAttachmentPath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsAttachmentPath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Client.java
1
请完成以下Java代码
public boolean isEmptiesInOut(@NonNull final I_M_InOut inout) { final I_C_DocType docType = loadOutOfTrx(inout.getC_DocType_ID(), I_C_DocType.class); if (docType == null || docType.getC_DocType_ID() <= 0) { return false; } final String docSubType = docType.getDocSubType(); return X_C_DocType.DOCSUBTYPE_Leergutanlieferung.equals(docSubType) || X_C_DocType.DOCSUBTYPE_Leergutausgabe.equals(docSubType); } @Override public IReturnsInOutProducer newReturnsInOutProducer(final Properties ctx) { return new EmptiesInOutProducer(ctx); } @Override @Nullable public I_M_InOut createDraftEmptiesInOutFromReceiptSchedule(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final String movementType) {
// // Create a draft "empties inout" without any line; // Lines will be created manually by the user. return newReturnsInOutProducer(getCtx()) .setMovementType(movementType) .setMovementDate(SystemTime.asDayTimestamp()) .setC_BPartner(receiptScheduleBL.getC_BPartner_Effective(receiptSchedule)) .setC_BPartner_Location(receiptScheduleBL.getC_BPartner_Location_Effective(receiptSchedule)) .setM_Warehouse(receiptScheduleBL.getM_Warehouse_Effective(receiptSchedule)) .setC_Order(receiptSchedule.getC_Order()) // .dontComplete() .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\HUEmptiesService.java
1
请完成以下Java代码
public @NonNull CurrencyRate getCurrencyRate( @NonNull final CurrencyConversionContext conversionCtx, @NonNull final CurrencyId currencyFromId, @NonNull final CurrencyId currencyToId) { final CurrencyRate currencyRate = getCurrencyRateOrNull(conversionCtx, currencyFromId, currencyToId); if (currencyRate == null) { final CurrencyCode currencyFrom = currencyDAO.getCurrencyCodeById(currencyFromId); final CurrencyCode currencyTo = currencyDAO.getCurrencyCodeById(currencyToId); final ConversionTypeMethod conversionTypeMethod = currencyDAO.getConversionTypeMethodById(conversionCtx.getConversionTypeId()); throw new NoCurrencyRateFoundException( currencyFrom, currencyTo, conversionCtx.getConversionDate(), conversionTypeMethod) .setParameter("conversionCtx", conversionCtx); } return currencyRate; } @Override public @NonNull CurrencyCode getCurrencyCodeById(@NonNull final CurrencyId currencyId) { return currencyDAO.getCurrencyCodeById(currencyId); } @Override @NonNull public Currency getByCurrencyCode(@NonNull final CurrencyCode currencyCode) { return currencyDAO.getByCurrencyCode(currencyCode); } @Override @NonNull public Money convertToBase(@NonNull final CurrencyConversionContext conversionCtx, @NonNull final Money amt) { final CurrencyId currencyToId = getBaseCurrencyId(conversionCtx.getClientId(), conversionCtx.getOrgId()); final CurrencyConversionResult currencyConversionResult = convert(conversionCtx, amt, currencyToId); return Money.of(currencyConversionResult.getAmount(), currencyToId); } private static CurrencyConversionResult.CurrencyConversionResultBuilder prepareCurrencyConversionResult(@NonNull final CurrencyConversionContext conversionCtx) { return CurrencyConversionResult.builder() .clientId(conversionCtx.getClientId())
.orgId(conversionCtx.getOrgId()) .conversionDate(conversionCtx.getConversionDate()) .conversionTypeId(conversionCtx.getConversionTypeId()); } @Override public Money convert( @NonNull final Money amount, @NonNull final CurrencyId toCurrencyId, @NonNull final LocalDate conversionDate, @NonNull final ClientAndOrgId clientAndOrgId) { if (CurrencyId.equals(amount.getCurrencyId(), toCurrencyId)) { return amount; } else if(amount.isZero()) { return Money.zero(toCurrencyId); } final CurrencyConversionContext conversionCtx = createCurrencyConversionContext( LocalDateAndOrgId.ofLocalDate(conversionDate, clientAndOrgId.getOrgId()), (CurrencyConversionTypeId)null, clientAndOrgId.getClientId()); final CurrencyConversionResult conversionResult = convert( conversionCtx, amount.toBigDecimal(), amount.getCurrencyId(), toCurrencyId); return Money.of(conversionResult.getAmount(), toCurrencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyBL.java
1
请完成以下Java代码
public void setC_OrderLine_ID(final int c_OrderLine_ID) { C_OrderLine_ID = c_OrderLine_ID; } @Override public final void addQtysToInvoice(@NonNull final StockQtyAndUOMQty qtysToInvoiceToAdd) { final StockQtyAndUOMQty qtysToInvoiceOld = getQtysToInvoice(); final StockQtyAndUOMQty qtysToInvoiceNew; if (qtysToInvoiceOld == null) { qtysToInvoiceNew = qtysToInvoiceToAdd; } else { qtysToInvoiceNew = qtysToInvoiceOld.add(qtysToInvoiceToAdd); } setQtysToInvoice(qtysToInvoiceNew); } @Nullable @Override public String getDescription() { return description; } @Override public void setDescription(@Nullable final String description) { this.description = description; } @Override public Collection<Integer> getC_InvoiceCandidate_InOutLine_IDs() { return iciolIds; } @Override public void negateAmounts() { setQtysToInvoice(getQtysToInvoice().negate()); setNetLineAmt(getNetLineAmt().negate()); } @Override public int getC_Activity_ID() { return activityID; } @Override public void setC_Activity_ID(final int activityID) { this.activityID = activityID; } @Override public Tax getC_Tax() { return tax; } @Override public void setC_Tax(final Tax tax) { this.tax = tax; }
@Override public boolean isPrinted() { return printed; } @Override public void setPrinted(final boolean printed) { this.printed = printed; } @Override public int getLineNo() { return lineNo; } @Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); } @Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1