instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private void prepareBPartnerProducts(@NonNull final Exchange exchange) { final PushRawMaterialsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_PUSH_RAW_MATERIALS_CONTEXT, PushRawMaterialsRouteContext.class); if (Check.isEmpty(context.getJsonProduct().getBPartnerProducts())) { exchange.getIn().setBody(ImmutableList.of()); return; } final ImmutableList<JsonBPartnerProduct> bPartnerProducts = context.getJsonProduct().getBPartnerProducts() .stream() .filter(jsonBPartnerProduct -> jsonBPartnerProduct.getAttachmentAdditionalInfos() != null && !Check.isEmpty(jsonBPartnerProduct.getAttachmentAdditionalInfos().getAttachments())) .collect(ImmutableList.toImmutableList()); exchange.getIn().setBody(bPartnerProducts); } private void prepareAttachments(@NonNull final Exchange exchange) { final JsonBPartnerProduct bPartnerProduct = exchange.getIn().getBody(JsonBPartnerProduct.class); final JsonBPartnerProductAdditionalInfo additionalInfo = bPartnerProduct.getAttachmentAdditionalInfos(); if (additionalInfo == null || Check.isEmpty(additionalInfo.getAttachments())) {
exchange.getIn().setBody(ImmutableList.of()); return; } final JsonMetasfreshId bpartnerId = Optional.ofNullable(bPartnerProduct.getBPartnerMetasfreshId()) .map(Integer::parseInt) .map(JsonMetasfreshId::of) .orElseThrow(() -> new RuntimeCamelException("Missing mandatory JsonBPartnerProduct.METASFRESHID!")); final PushRawMaterialsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_PUSH_RAW_MATERIALS_CONTEXT, PushRawMaterialsRouteContext.class); context.setCurrentBPartnerID(bpartnerId); exchange.getIn().setBody(ImmutableList.copyOf(additionalInfo.getAttachments())); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\product\PushRawMaterialsRouteBuilder.java
2
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxGroup[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Tax Group. @param C_TaxGroup_ID Tax Group */ public void setC_TaxGroup_ID (int C_TaxGroup_ID) { if (C_TaxGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, Integer.valueOf(C_TaxGroup_ID)); } /** Get Tax Group. @return Tax Group */ public int getC_TaxGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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 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 Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxGroup.java
1
请完成以下Java代码
private static ReturnProductInfoProvider newInstance() { return new ReturnProductInfoProvider(); } private OrgId getOrgId(@NonNull final String orgCode) { return searchKey2Org.computeIfAbsent(orgCode, this::retrieveOrgId); } @NonNull private ProductId getProductId(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey); return ProductId.ofRepoId(product.getM_Product_ID()); } @NonNull private I_C_UOM getStockingUOM(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey); return uomDAO.getById(UomId.ofRepoId(product.getC_UOM_ID())); } @NonNull private I_M_Product getProductNotNull(@NonNull final String productSearchKey) { final I_M_Product product = searchKey2Product.computeIfAbsent(productSearchKey, this::loadProduct);
if (product == null) { throw new AdempiereException("No product could be found for the target search key!") .appendParametersToMessage() .setParameter("ProductSearchKey", productSearchKey); } return product; } private I_M_Product loadProduct(@NonNull final String productSearchKey) { return productRepo.retrieveProductByValue(productSearchKey); } private OrgId retrieveOrgId(@NonNull final String orgCode) { final OrgQuery query = OrgQuery.builder() .orgValue(orgCode) .failIfNotExists(true) .build(); return orgDAO.retrieveOrgIdBy(query).orElseThrow(() -> new AdempiereException("No AD_Org was found for the given search key!") .appendParametersToMessage() .setParameter("OrgSearchKey", orgCode)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\CustomerReturnRestService.java
1
请完成以下Java代码
public Collection<? extends GrantedAuthority> getAuthorities() { //返回当前用户所拥有的资源 return resourceList.stream() .map(resource ->new SimpleGrantedAuthority(resource.getId()+":"+resource.getName())) .collect(Collectors.toList()); } @Override public String getPassword() { return umsAdmin.getPassword(); } @Override public String getUsername() { return umsAdmin.getUsername(); } @Override public boolean isAccountNonExpired() {
return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return umsAdmin.getStatus().equals(1); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\bo\AdminUserDetails.java
1
请完成以下Java代码
protected String doIt() { final I_C_Async_Batch record = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(AsyncBatchId.ofRepoId(getRecord_ID())); final List<AttachmentEntry> attachments = getAttachmentEntries(record); if (!attachments.isEmpty()) { final AttachmentEntry attachment = attachments.get(0); // take first one final Resource data = attachmentEntryService.retrieveDataResource(attachment.getId()); getResult().setReportData(data, attachment.getFilename(), attachment.getMimeType()); } return MSG_OK; } private boolean hasAttachments(@NonNull final I_C_Async_Batch record) {
final List<AttachmentEntry> attachments = getAttachmentEntries(record); return !attachments.isEmpty(); } private List<AttachmentEntry> getAttachmentEntries(@NonNull final I_C_Async_Batch record) { final AttachmentEntryService.AttachmentEntryQuery attachmentQuery = AttachmentEntryService.AttachmentEntryQuery.builder() .referencedRecord(TableRecordReference.of(record)) .mimeType(MimeType.TYPE_PDF) .build(); return attachmentEntryService.getByQuery(attachmentQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\process\C_Async_Batch_DownloadFileFromAttachment.java
1
请完成以下Java代码
public PartyIdentification32 getOrgtr() { return orgtr; } /** * Sets the value of the orgtr property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setOrgtr(PartyIdentification32 value) { this.orgtr = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link ReturnReason5Choice } * */ public ReturnReason5Choice getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link ReturnReason5Choice } * */ public void setRsn(ReturnReason5Choice value) { this.rsn = value; } /** * Gets the value of the addtlInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addtlInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddtlInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddtlInf() { if (addtlInf == null) { addtlInf = new ArrayList<String>(); } return this.addtlInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ReturnReasonInformation10.java
1
请完成以下Java代码
public void cache(String key, String value) { valueOperations.set(key, value, AuthCacheConfig.timeout, TimeUnit.MILLISECONDS); } /** * 存入缓存 * * @param key 缓存key * @param value 缓存内容 * @param timeout 指定缓存过期时间(毫秒) */ @Override public void cache(String key, String value, long timeout) { valueOperations.set(key, value, timeout, TimeUnit.MILLISECONDS); } /** * 获取缓存内容 * * @param key 缓存key * @return 缓存内容 */
@Override public String get(String key) { return valueOperations.get(key); } /** * 是否存在key,如果对应key的value值已过期,也返回false * * @param key 缓存key * @return true:存在key,并且value没过期;false:key不存在或者已过期 */ @Override public boolean containsKey(String key) { return redisTemplate.hasKey(key); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\cache\AuthStateRedisCache.java
1
请完成以下Java代码
public void repair(String[] repairParts) { Assert.notEmpty(repairParts, "array of repairParts must not be empty"); // ... } public void repairWithNoNull(String[] repairParts) { Assert.noNullElements(repairParts, "array of repairParts must not contain null elements"); // ... } public static void main(String[] args) { Car car = new Car(); car.drive(50); car.stop(); car.fuel(); car.сhangeOil("oil"); CarBattery carBattery = new CarBattery(); car.replaceBattery(carBattery); car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" "); car.startWithHasText("t"); car.startWithNotContain("132"); List<String> repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); Map<String, String> repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); String[] repairPartsArray = { "part" }; car.repair(repairPartsArray); } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
1
请完成以下Java代码
public void setSubstitution(VerfuegbarkeitSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link VerfuegbarkeitAnteil } * * */ public List<VerfuegbarkeitAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<VerfuegbarkeitAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsantwortArtikel.java
1
请完成以下Java代码
public class UpdateProcessDefinitionHistoryTimeToLiveCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected Integer historyTimeToLive; public UpdateProcessDefinitionHistoryTimeToLiveCmd(String processDefinitionId, Integer historyTimeToLive) { this.processDefinitionId = processDefinitionId; this.historyTimeToLive = historyTimeToLive; } public Void execute(CommandContext context) { checkAuthorization(context); ensureNotNull(BadUserRequestException.class, "processDefinitionId", processDefinitionId); if (historyTimeToLive != null) { ensureGreaterThanOrEqual(BadUserRequestException.class, "", "historyTimeToLive", historyTimeToLive, 0); } HistoryTimeToLiveParser parser = HistoryTimeToLiveParser.create(context);
parser.validate(historyTimeToLive); ProcessDefinitionEntity processDefinitionEntity = context.getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); logUserOperation(context, processDefinitionEntity); processDefinitionEntity.setHistoryTimeToLive(historyTimeToLive); return null; } protected void checkAuthorization(CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessDefinitionById(processDefinitionId); } } protected void logUserOperation(CommandContext commandContext, ProcessDefinitionEntity processDefinitionEntity) { PropertyChange propertyChange = new PropertyChange("historyTimeToLive", processDefinitionEntity.getHistoryTimeToLive(), historyTimeToLive); commandContext.getOperationLogManager() .logProcessDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_UPDATE_HISTORY_TIME_TO_LIVE, processDefinitionId, processDefinitionEntity.getKey(), propertyChange); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateProcessDefinitionHistoryTimeToLiveCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class CountryAreaId implements RepoIdAware { @JsonCreator @NonNull public static CountryAreaId ofRepoId(final int repoId) { return new CountryAreaId(repoId); } @Nullable public static CountryAreaId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new CountryAreaId(repoId) : null; } public static int toRepoId(@Nullable final CountryAreaId id) { return id != null ? id.getRepoId() : -1; } int repoId; private CountryAreaId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_CountryArea_ID"); } @Override
@JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CountryAreaId countryAreaId1, @Nullable final CountryAreaId countryAreaId2) { return Objects.equals(countryAreaId1, countryAreaId2); } public boolean equalsToRepoId(final int repoId) { return this.repoId == repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\CountryAreaId.java
2
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPermissionUrl() { return permissionUrl; } public void setPermissionUrl(String permissionUrl) { this.permissionUrl = permissionUrl; } public String getMethod() { return method;
} public void setMethod(String method) { this.method = method; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Permission{" + "id=" + id + ", name=" + name + ", permissionUrl=" + permissionUrl + ", method=" + method + ", description=" + description + '}'; } }
repos\springBoot-master\springboot-dubbo\abel-user-api\src\main\java\cn\abel\user\models\Permission.java
1
请完成以下Java代码
public Connection getConnection() throws SQLException { return getCurrentDataSource().getConnection(); } @Override public Connection getConnection(String username, String password) throws SQLException { return getCurrentDataSource().getConnection(username, password); } protected DataSource getCurrentDataSource() { String tenantId = tenantInfoHolder.getCurrentTenantId(); DataSource dataSource = dataSources.get(tenantId); if (dataSource == null) { throw new FlowableException("Could not find a dataSource for tenant " + tenantId); } return dataSource; } @Override public int getLoginTimeout() throws SQLException { return 0; // Default } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; }
throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName()); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } public Map<Object, DataSource> getDataSources() { return dataSources; } public void setDataSources(Map<Object, DataSource> dataSources) { this.dataSources = dataSources; } // Unsupported ////////////////////////////////////////////////////////// @Override public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } @Override public void setLoginTimeout(int seconds) throws SQLException { throw new UnsupportedOperationException(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\multitenant\TenantAwareDataSource.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** ModerationType AD_Reference_ID=395 */ public static final int MODERATIONTYPE_AD_Reference_ID=395; /** Not moderated = N */ public static final String MODERATIONTYPE_NotModerated = "N"; /** Before Publishing = B */ public static final String MODERATIONTYPE_BeforePublishing = "B"; /** After Publishing = A */ public static final String MODERATIONTYPE_AfterPublishing = "A"; /** Set Moderation Type. @param ModerationType Type of moderation */ public void setModerationType (String ModerationType) { set_Value (COLUMNNAME_ModerationType, ModerationType); } /** Get Moderation Type. @return Type of moderation */ public String getModerationType ()
{ return (String)get_Value(COLUMNNAME_ModerationType); } /** 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_CM_ChatType.java
1
请在Spring Boot框架中完成以下Java代码
public void doFinally() { } }); return ok[0]; } @Override public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType) { final String sourceTableName = sourcePO.get_TableName(); final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName); if (sourceColumns == null || sourceColumns.isEmpty()) return false;
if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE) { return true; } for (String sourceColumn : sourceColumns) { if (sourcePO.is_ValueChanged(sourceColumn)) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java
2
请完成以下Java代码
public class BalanceSubType1Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; }
/** * Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BalanceSubType1Choice.java
1
请完成以下Java代码
public void setSourceState(String sourceState) { this.sourceState = sourceState; } public String getTargetState() { return targetState; } public void setTargetState(String targetState) { this.targetState = targetState; } public String getImplementationType() { return implementationType; } public void setImplementationType(String implementationType) { this.implementationType = implementationType; } public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } public List<FieldExtension> getFieldExtensions() { return fieldExtensions; } public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public String getOnTransaction() { return onTransaction; } public void setOnTransaction(String onTransaction) { this.onTransaction = onTransaction; } /** * Return the script info, if present. * <p> * ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when * implementationType is 'script'. * </p> */
public ScriptInfo getScriptInfo() { return scriptInfo; } /** * Sets the script info * * @see #getScriptInfo() */ public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } @Override public FlowableListener clone() { FlowableListener clone = new FlowableListener(); clone.setValues(this); return clone; } public void setValues(FlowableListener otherListener) { super.setValues(otherListener); setEvent(otherListener.getEvent()); setSourceState(otherListener.getSourceState()); setTargetState(otherListener.getTargetState()); setImplementation(otherListener.getImplementation()); setImplementationType(otherListener.getImplementationType()); setOnTransaction(otherListener.getOnTransaction()); Optional.ofNullable(otherListener.getScriptInfo()).map(ScriptInfo::clone).ifPresent(this::setScriptInfo); fieldExtensions = new ArrayList<>(); if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherListener.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\FlowableListener.java
1
请完成以下Java代码
public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Remote Client. @param Remote_Client_ID Remote Client to be used to replicate / synchronize data with. */ public void setRemote_Client_ID (int Remote_Client_ID) { if (Remote_Client_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID)); } /** Get Remote Client. @return Remote Client to be used to replicate / synchronize data with. */ public int getRemote_Client_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Organization. @param Remote_Org_ID Remote Organization to be used to replicate / synchronize data with. */ public void setRemote_Org_ID (int Remote_Org_ID) { if (Remote_Org_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID)); }
/** Get Remote Organization. @return Remote Organization to be used to replicate / synchronize data with. */ public int getRemote_Org_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
1
请完成以下Java代码
void encrypt(String content, String fileName) throws InvalidKeyException, IOException { cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] iv = cipher.getIV(); try ( FileOutputStream fileOut = new FileOutputStream(fileName); CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher) ) { fileOut.write(iv); cipherOut.write(content.getBytes()); } } String decrypt(String fileName) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException { String content; try (FileInputStream fileIn = new FileInputStream(fileName)) { byte[] fileIv = new byte[16]; fileIn.read(fileIv); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv)); try ( CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
InputStreamReader inputReader = new InputStreamReader(cipherIn); BufferedReader reader = new BufferedReader(inputReader) ) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } content = sb.toString(); } } return content; } }
repos\tutorials-master\core-java-modules\core-java-security-5\src\main\java\com\baeldung\encrypt\FileEncrypterDecrypter.java
1
请完成以下Java代码
public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public void setFinishedProcessInstanceCount(long finishedProcessInstanceCount) { this.finishedProcessInstanceCount = finishedProcessInstanceCount; } public void setCleanableProcessInstanceCount(long cleanableProcessInstanceCount) { this.cleanableProcessInstanceCount = cleanableProcessInstanceCount; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public int getProcessDefinitionVersion() { return processDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public Long getFinishedProcessInstanceCount() { return finishedProcessInstanceCount; } public Long getCleanableProcessInstanceCount() { return cleanableProcessInstanceCount; } public String getTenantId() {
return tenantId; } protected CleanableHistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricProcessInstanceReport(); } public static List<CleanableHistoricProcessInstanceReportResultDto> convert(List<CleanableHistoricProcessInstanceReportResult> reportResult) { List<CleanableHistoricProcessInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricProcessInstanceReportResultDto>(); for (CleanableHistoricProcessInstanceReportResult current : reportResult) { CleanableHistoricProcessInstanceReportResultDto dto = new CleanableHistoricProcessInstanceReportResultDto(); dto.setProcessDefinitionId(current.getProcessDefinitionId()); dto.setProcessDefinitionKey(current.getProcessDefinitionKey()); dto.setProcessDefinitionName(current.getProcessDefinitionName()); dto.setProcessDefinitionVersion(current.getProcessDefinitionVersion()); dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); dto.setFinishedProcessInstanceCount(current.getFinishedProcessInstanceCount()); dto.setCleanableProcessInstanceCount(current.getCleanableProcessInstanceCount()); dto.setTenantId(current.getTenantId()); dtos.add(dto); } return dtos; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricProcessInstanceReportResultDto.java
1
请完成以下Java代码
public class TransactionQuantities1Choice { @XmlElement(name = "Qty") protected FinancialInstrumentQuantityChoice qty; @XmlElement(name = "Prtry") protected ProprietaryQuantity1 prtry; /** * Gets the value of the qty property. * * @return * possible object is * {@link FinancialInstrumentQuantityChoice } * */ public FinancialInstrumentQuantityChoice getQty() { return qty; } /** * Sets the value of the qty property. * * @param value * allowed object is * {@link FinancialInstrumentQuantityChoice } * */ public void setQty(FinancialInstrumentQuantityChoice value) { this.qty = value; } /** * Gets the value of the prtry property. * * @return
* possible object is * {@link ProprietaryQuantity1 } * */ public ProprietaryQuantity1 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryQuantity1 } * */ public void setPrtry(ProprietaryQuantity1 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionQuantities1Choice.java
1
请完成以下Java代码
public boolean isEmpty() { return this.sections.stream().allMatch((section) -> section.items.isEmpty()); } public GitIgnoreSection getGeneral() { return this.general; } public GitIgnoreSection getSts() { return this.sts; } public GitIgnoreSection getIntellijIdea() { return this.intellijIdea; } public GitIgnoreSection getNetBeans() { return this.netBeans; } public GitIgnoreSection getVscode() { return this.vscode; } /** * Representation of a section of a {@code .gitignore} file. */ public static class GitIgnoreSection implements Section { private final String name; private final LinkedList<String> items; public GitIgnoreSection(String name) { this.name = name; this.items = new LinkedList<>(); }
public void add(String... items) { this.items.addAll(Arrays.asList(items)); } public LinkedList<String> getItems() { return this.items; } @Override public void write(PrintWriter writer) { if (!this.items.isEmpty()) { if (this.name != null) { writer.println(); writer.println(String.format("### %s ###", this.name)); } this.items.forEach(writer::println); } } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java
1
请在Spring Boot框架中完成以下Java代码
public class Person implements Serializable { private static final long serialVersionUID = 133938246231808718L; @Id @GeneratedValue private Long id; private String name; private Integer age; private String address; public Person() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) {
this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(Long id, String name, Integer age, String address) { super(); this.id = id; this.name = name; this.age = age; this.address = address; } @Override public String toString() { return "Person{" + "id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + '}'; } }
repos\springBoot-master\springboot-Cache2\src\main\java\com\us\example\bean\Person.java
2
请完成以下Java代码
public void setIsSingleRow (boolean IsSingleRow) { set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow)); } /** Get Single Row Layout. @return Default for toggle between Single- and Multi-Row (Grid) Layout */ public boolean isSingleRow () { Object oo = get_Value(COLUMNNAME_IsSingleRow); 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_AD_UserDef_Tab.java
1
请在Spring Boot框架中完成以下Java代码
public void addLog(LogDTO logDTO) { if(oConvertUtils.isEmpty(logDTO.getId())){ logDTO.setId(String.valueOf(IdWorker.getId())); } //保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)JT-238 try { logDTO.setCreateTime(new Date()); baseCommonMapper.saveLog(logDTO); } catch (Exception e) { log.warn(" LogContent length : "+logDTO.getLogContent().length()); log.warn(e.getMessage()); } } @Override public void addLog(String logContent, Integer logType, Integer operatetype, LoginUser user) { LogDTO sysLog = new LogDTO(); sysLog.setId(String.valueOf(IdWorker.getId())); //注解上的描述,操作日志内容 sysLog.setLogContent(logContent); sysLog.setLogType(logType); sysLog.setOperateType(operatetype); try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IpUtils.getIpAddr(request)); try { //设置客户端 if(BrowserUtils.isDesktop(request)){ sysLog.setClientType(ClientTerminalTypeEnum.PC.getKey()); }else{ sysLog.setClientType(ClientTerminalTypeEnum.APP.getKey()); } } catch (Exception e) { //e.printStackTrace(); } } catch (Exception e) { sysLog.setIp("127.0.0.1");
} //获取登录用户信息 if(user==null){ try { user = (LoginUser) SecurityUtils.getSubject().getPrincipal(); } catch (Exception e) { //e.printStackTrace(); } } if(user!=null){ sysLog.setUserid(user.getUsername()); sysLog.setUsername(user.getRealname()); } sysLog.setCreateTime(new Date()); //保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)JT-238 try { baseCommonMapper.saveLog(sysLog); } catch (Exception e) { log.warn(" LogContent length : "+sysLog.getLogContent().length()); log.warn(e.getMessage()); } } @Override public void addLog(String logContent, Integer logType, Integer operateType) { addLog(logContent, logType, operateType, null); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\modules\base\service\impl\BaseCommonServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public final class LogFileWebEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @Conditional(LogFileCondition.class) LogFileWebEndpoint logFileWebEndpoint(ObjectProvider<LogFile> logFile, LogFileWebEndpointProperties properties) { return new LogFileWebEndpoint(logFile.getIfAvailable(), properties.getExternalFile()); } private static final class LogFileCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String config = getLogFileConfig(environment, LogFile.FILE_NAME_PROPERTY); ConditionMessage.Builder message = ConditionMessage.forCondition("Log File"); if (StringUtils.hasText(config)) { return ConditionOutcome.match(message.found(LogFile.FILE_NAME_PROPERTY).items(config)); }
config = getLogFileConfig(environment, LogFile.FILE_PATH_PROPERTY); if (StringUtils.hasText(config)) { return ConditionOutcome.match(message.found(LogFile.FILE_PATH_PROPERTY).items(config)); } config = environment.getProperty("management.endpoint.logfile.external-file"); if (StringUtils.hasText(config)) { return ConditionOutcome.match(message.found("management.endpoint.logfile.external-file").items(config)); } return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll()); } private String getLogFileConfig(Environment environment, String configName) { return environment.resolvePlaceholders("${" + configName + ":}"); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\logging\LogFileWebEndpointAutoConfiguration.java
2
请完成以下Java代码
protected CmmnSentryPart newSentryPart() { return new CaseSentryPartImpl(); } // new case executions //////////////////////////////////////////////////////////// protected CaseExecutionImpl createCaseExecution(CmmnActivity activity) { CaseExecutionImpl child = newCaseExecution(); // set activity to execute child.setActivity(activity); // handle child/parent-relation child.setParent(this); getCaseExecutionsInternal().add(child); // set case instance child.setCaseInstance(getCaseInstance()); // set case definition child.setCaseDefinition(getCaseDefinition()); return child; } protected CaseExecutionImpl newCaseExecution() { return new CaseExecutionImpl(); } // variables ////////////////////////////////////////////////////////////// protected VariableStore<CoreVariableInstance> getVariableStore() { return (VariableStore) variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } // toString ///////////////////////////////////////////////////////////////// public String toString() {
if (isCaseInstanceExecution()) { return "CaseInstance[" + getToStringIdentity() + "]"; } else { return "CmmnExecution["+getToStringIdentity() + "]"; } } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } public String getId() { return String.valueOf(System.identityHashCode(this)); } public ProcessEngineServices getProcessEngineServices() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public ProcessEngine getProcessEngine() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public CmmnElement getCmmnModelElementInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } public CmmnModelInstance getCmmnModelInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected ExecutionContextSerializer getExecutionContextSerializer() { return (this.executionContextSerializer != null) ? this.executionContextSerializer : super.getExecutionContextSerializer(); } @Override @Deprecated(since = "4.0.0", forRemoval = true) @SuppressWarnings("removal") protected JobParametersConverter getJobParametersConverter() { return (this.jobParametersConverter != null) ? this.jobParametersConverter : super.getJobParametersConverter(); } @Override protected TaskExecutor getTaskExecutor() { return (this.taskExecutor != null) ? this.taskExecutor : super.getTaskExecutor(); } @Configuration(proxyBeanMethods = false) @Conditional(OnBatchDatasourceInitializationCondition.class) static class DataSourceInitializerConfiguration { @Bean @ConditionalOnMissingBean BatchDataSourceScriptDatabaseInitializer batchDataSourceInitializer(DataSource dataSource,
@BatchDataSource ObjectProvider<DataSource> batchDataSource, BatchJdbcProperties properties) { return new BatchDataSourceScriptDatabaseInitializer(batchDataSource.getIfAvailable(() -> dataSource), properties); } } static class OnBatchDatasourceInitializationCondition extends OnDatabaseInitializationCondition { OnBatchDatasourceInitializationCondition() { super("Batch", "spring.batch.jdbc.initialize-schema"); } } } }
repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcAutoConfiguration.java
2
请完成以下Java代码
public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(String item) { try { Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace(); } counter++; System.out.println("Processed item : " + item); subscription.request(1); } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onComplete() { completed = true; subscription.cancel(); } }
repos\tutorials-master\core-java-modules\core-java-9-new-features\src\main\java\com\baeldung\java9\reactive\BaeldungSubscriberImpl.java
1
请完成以下Java代码
public class ScriptBindingsFactory { protected AbstractEngineConfiguration engineConfiguration; protected List<ResolverFactory> resolverFactories; public ScriptBindingsFactory(AbstractEngineConfiguration engineConfiguration, List<ResolverFactory> resolverFactories) { this.engineConfiguration = engineConfiguration; this.resolverFactories = resolverFactories; } public Resolver createResolver(ScriptEngineRequest request) { List<Resolver> scriptResolvers = new ArrayList<>(); scriptResolvers.addAll(request.getAdditionalResolvers()); for (ResolverFactory scriptResolverFactory : resolverFactories) { Resolver resolver = scriptResolverFactory.createResolver(engineConfiguration, request.getScopeContainer(), request.getInputVariableContainer());
if (resolver != null) { scriptResolvers.add(resolver); } } return new CompositeResolver(scriptResolvers); } public List<ResolverFactory> getResolverFactories() { return resolverFactories; } public void setResolverFactories(List<ResolverFactory> resolverFactories) { this.resolverFactories = resolverFactories; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindingsFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void setKey(String key, String value, int timeToLive) throws Exception { try { Future<Boolean>[] _future = evCache.set(key, value, timeToLive); // Wait for all the Futures to complete. // In "verbose" mode, show the status for each. for (Future<Boolean> f : _future) { boolean didSucceed = f.get(); if (verboseMode) { System.out.println("per-shard set success code for key " + key + " is " + didSucceed); } } if (!verboseMode) { // Not verbose. Just give one line of output per "set," without a success code System.out.println("finished setting key " + key); } } catch (EVCacheException e) { e.printStackTrace(); } } public String getKey(String key) { try { String _response = evCache.<String>get(key); return _response; } catch (Exception e) { e.printStackTrace(); return null; } } public void setVerboseMode( boolean verboseMode ) { this.verboseMode = verboseMode; } public boolean setVerboseMode() { return this.verboseMode; } // public static void main(String[] args) {
// // // set verboseMode based on the environment variable // verboseMode = ("true".equals(System.getenv("EVCACHE_SAMPLE_VERBOSE"))); // // if (verboseMode) { // System.out.println("To run this sample app without using Gradle:"); // System.out.println("java -cp " + System.getProperty("java.class.path") + " com.netflix.evcache.sample.EVCacheClientSample"); // } // // try { // EVCacheClientSample evCacheClientSample = new EVCacheClientSample(); // // // Set ten keys to different values // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = "data_" + i; // // Set the TTL to 24 hours // int ttl = 10; // evCacheClientSample.setKey(key, value, ttl); // } // // // Do a "get" for each of those same keys // for (int i = 0; i < 10; i++) { // String key = "key_" + i; // String value = evCacheClientSample.getKey(key); // System.out.println("Get of " + key + " returned " + value); // } // } catch (Exception e) { // e.printStackTrace(); // } // // // System.exit(0); // } }
repos\Spring-Boot-In-Action-master\springbt_evcache\src\main\java\cn\codesheep\springbt_evcache\config\EVCacheClientSample.java
2
请完成以下Java代码
public class WrongDbException extends ProcessEngineException { private static final long serialVersionUID = 1L; String libraryVersion; String dbVersion; public WrongDbException(String libraryVersion, String dbVersion) { this("version mismatch: activiti library version is '" + libraryVersion + "', db version is " + dbVersion +" Hint: Set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in camunda.cfg.xml for automatic schema creation", libraryVersion, dbVersion); } public WrongDbException(String exceptionMessage, String libraryVersion, String dbVersion) { super(exceptionMessage); this.libraryVersion = libraryVersion; this.dbVersion = dbVersion;
} /** * The version of the Activiti library used. */ public String getLibraryVersion() { return libraryVersion; } /** * The version of the Activiti library that was used to create the database schema. */ public String getDbVersion() { return dbVersion; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\WrongDbException.java
1
请完成以下Java代码
public Properties getCtx() { return po.getCtx(); } @Override public String getTrxName() { return po.get_TrxName(); } @Override public Evaluatee createEvaluationContext() { final Properties privateCtx = Env.deriveCtx(getCtx()); final PO po = getPO(); final POInfo poInfo = po.getPOInfo(); for (int i = 0; i < poInfo.getColumnCount(); i++) { final Object val; final int dispType = poInfo.getColumnDisplayType(i); if (DisplayType.isID(dispType)) { // make sure we get a 0 instead of a null for foreign keys val = po.get_ValueAsInt(i); } else { val = po.get_Value(i); }
if (val == null) { continue; } if (val instanceof Integer) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (Integer)val); } else if (val instanceof String) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (String)val); } } return Evaluatees.ofCtx(privateCtx, Env.WINDOW_None, false); } @Override public boolean hasField(final String columnName) { return po.getPOInfo().hasColumnName(columnName); } @Override public Object getFieldValue(final String columnName) { return po.get_Value(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\POZoomSource.java
1
请完成以下Java代码
public class SpinBpmPlatformPlugin implements BpmPlatformPlugin { private static final SpinPluginLogger LOG = SpinPluginLogger.LOGGER; @Override public void postProcessApplicationDeploy(ProcessApplicationInterface processApplication) { ProcessApplicationInterface rawPa = processApplication.getRawObject(); if (rawPa instanceof AbstractProcessApplication) { initializeVariableSerializers((AbstractProcessApplication) rawPa); } else { LOG.logNoDataFormatsInitiailized("process application data formats", "process application is not a sub class of " + AbstractProcessApplication.class.getName()); } } protected void initializeVariableSerializers(AbstractProcessApplication abstractProcessApplication) { VariableSerializers paVariableSerializers = abstractProcessApplication.getVariableSerializers(); if (paVariableSerializers == null) { paVariableSerializers = new DefaultVariableSerializers(); abstractProcessApplication.setVariableSerializers(paVariableSerializers); } for (TypedValueSerializer<?> serializer : lookupSpinSerializers(abstractProcessApplication.getProcessApplicationClassloader())) { paVariableSerializers.addSerializer(serializer); } }
protected List<TypedValueSerializer<?>> lookupSpinSerializers(ClassLoader classLoader) { DataFormats paDataFormats = new DataFormats(); paDataFormats.registerDataFormats(classLoader); // does not create PA-local serializers for native Spin values; // this is still an open feature CAM-5246 return SpinVariableSerializers.createObjectValueSerializers(paDataFormats); } @Override public void postProcessApplicationUndeploy(ProcessApplicationInterface processApplication) { } }
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinBpmPlatformPlugin.java
1
请完成以下Java代码
public class GatewayPropagatingSenderTracingObservationHandler extends PropagatingSenderTracingObservationHandler<GatewayContext> { private final Propagator propagator; private final List<String> remoteFieldsLowerCase; /** * Creates a new instance of {@link PropagatingSenderTracingObservationHandler}. * @param tracer the tracer to use to record events * @param propagator the mechanism to propagate tracing information into the carrier * @param remoteFields remote fields to be propagated over the wire */ public GatewayPropagatingSenderTracingObservationHandler(Tracer tracer, Propagator propagator, List<String> remoteFields) { super(tracer, propagator); this.propagator = propagator;
this.remoteFieldsLowerCase = remoteFields.stream().map(s -> s.toLowerCase(Locale.ROOT)).toList(); } @Override public void onStart(GatewayContext context) { this.propagator.fields() .stream() .filter(field -> !remoteFieldsLowerCase.contains(field.toLowerCase(Locale.ROOT))) .forEach(s -> Objects.requireNonNull(context.getCarrier()).remove(s)); super.onStart(context); } @Override public boolean supportsContext(Observation.Context context) { return context instanceof GatewayContext; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\observation\GatewayPropagatingSenderTracingObservationHandler.java
1
请完成以下Java代码
public class InstrumentationExample { public static void printObjectSize(Object object) { System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes"); } public static void main(String[] arguments) { String emptyString = ""; String string = "Estimating Object Size Using Instrumentation"; String[] stringArray = { emptyString, string, "com.baeldung" }; String[] anotherStringArray = new String[100]; List<String> stringList = new ArrayList<>(); StringBuilder stringBuilder = new StringBuilder(100); int maxIntPrimitive = Integer.MAX_VALUE; int minIntPrimitive = Integer.MIN_VALUE; Integer maxInteger = Integer.MAX_VALUE; Integer minInteger = Integer.MIN_VALUE; long zeroLong = 0L; double zeroDouble = 0.0; boolean falseBoolean = false; Object object = new Object(); class EmptyClass { } EmptyClass emptyClass = new EmptyClass(); class StringClass { public String s; }
StringClass stringClass = new StringClass(); printObjectSize(emptyString); printObjectSize(string); printObjectSize(stringArray); printObjectSize(anotherStringArray); printObjectSize(stringList); printObjectSize(stringBuilder); printObjectSize(maxIntPrimitive); printObjectSize(minIntPrimitive); printObjectSize(maxInteger); printObjectSize(minInteger); printObjectSize(zeroLong); printObjectSize(zeroDouble); printObjectSize(falseBoolean); printObjectSize(Day.TUESDAY); printObjectSize(object); printObjectSize(emptyClass); printObjectSize(stringClass); } public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } }
repos\tutorials-master\core-java-modules\core-java-jvm\src\main\java\com\baeldung\objectsize\InstrumentationExample.java
1
请完成以下Java代码
public long count() { this.resultType = ResultType.COUNT; if (commandExecutor != null) { return (Long) commandExecutor.execute(this); } return executeCount(Context.getCommandContext(), getParameterMap()); } public Object execute(CommandContext commandContext) { if (resultType == ResultType.LIST) { return executeList(commandContext, getParameterMap(), 0, Integer.MAX_VALUE); } else if (resultType == ResultType.LIST_PAGE) { Map<String, Object> parameterMap = getParameterMap(); parameterMap.put("resultType", "LIST_PAGE"); parameterMap.put("firstResult", firstResult); parameterMap.put("maxResults", maxResults); if (StringUtils.isNotBlank(Objects.toString(parameterMap.get("orderBy")))) { parameterMap.put("orderByColumns", "RES." + parameterMap.get("orderBy")); } else { parameterMap.put("orderByColumns", "RES.ID_ asc"); } int firstRow = firstResult + 1; parameterMap.put("firstRow", firstRow); int lastRow = 0; if (maxResults == Integer.MAX_VALUE) { lastRow = maxResults; } else { lastRow = firstResult + maxResults + 1; } parameterMap.put("lastRow", lastRow); return executeList(commandContext, parameterMap, firstResult, maxResults); } else if (resultType == ResultType.SINGLE_RESULT) { return executeSingleResult(commandContext); } else { return executeCount(commandContext, getParameterMap()); } } public abstract long executeCount(CommandContext commandContext, Map<String, Object> parameterMap); /** * Executes the actual query to retrieve the list of results. * * @param maxResults * @param firstResult * * @param page * used if the results must be paged. If null, no paging will be applied. */ public abstract List<U> executeList( CommandContext commandContext,
Map<String, Object> parameterMap, int firstResult, int maxResults ); public U executeSingleResult(CommandContext commandContext) { List<U> results = executeList(commandContext, getParameterMap(), 0, Integer.MAX_VALUE); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new ActivitiException("Query return " + results.size() + " results instead of max 1"); } return null; } private Map<String, Object> getParameterMap() { HashMap<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("sql", sqlStatement); parameterMap.putAll(parameters); return parameterMap; } public Map<String, Object> getParameters() { return parameters; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\AbstractNativeQuery.java
1
请完成以下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); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ColumnCallout.java
1
请完成以下Java代码
public class AsyncTasks { public static Random random = new Random(); @Async public CompletableFuture<String> doTaskOne() throws Exception { log.info("开始做任务一"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任务一,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务一完成"); } @Async public CompletableFuture<String> doTaskTwo() throws Exception { log.info("开始做任务二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis(); log.info("完成任务二,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务二完成"); } @Async public CompletableFuture<String> doTaskThree() throws Exception { log.info("开始做任务三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任务三,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务三完成"); } }
repos\SpringBoot-Learning-master\2.x\chapter7-6\src\main\java\com\didispace\chapter76\AsyncTasks.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Zebra_Config_ID (final int AD_Zebra_Config_ID) { if (AD_Zebra_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Zebra_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Zebra_Config_ID, AD_Zebra_Config_ID); } @Override public int getAD_Zebra_Config_ID() { return get_ValueAsInt(COLUMNNAME_AD_Zebra_Config_ID); } @Override public void setEncoding (final java.lang.String Encoding) { set_Value (COLUMNNAME_Encoding, Encoding); } @Override public java.lang.String getEncoding() { return get_ValueAsString(COLUMNNAME_Encoding); } @Override public void setHeader_Line1 (final java.lang.String Header_Line1) { set_Value (COLUMNNAME_Header_Line1, Header_Line1); } @Override public java.lang.String getHeader_Line1() { return get_ValueAsString(COLUMNNAME_Header_Line1); } @Override public void setHeader_Line2 (final java.lang.String Header_Line2) { set_Value (COLUMNNAME_Header_Line2, Header_Line2); } @Override public java.lang.String getHeader_Line2() {
return get_ValueAsString(COLUMNNAME_Header_Line2); } @Override public void setIsDefault (final boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, IsDefault); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSQL_Select (final java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Zebra_Config.java
1
请完成以下Java代码
public String getConfigurationFileFormat() { return this.configurationFileFormat; } public void setConfigurationFileFormat(String configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return getGroupId() + "." + getArtifactId(); } return null; } public void setPackageName(String packageName) { this.packageName = packageName;
} public String getJavaVersion() { return this.javaVersion; } public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; } public String getBaseDir() { return this.baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java
1
请完成以下Java代码
public class XxlJobLogGlue { private int id; private int jobId; // 任务主键ID private String glueType; // GLUE类型 #com.xxl.job.core.glue.GlueTypeEnum private String glueSource; private String glueRemark; private Date addTime; private Date updateTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getJobId() { return jobId; } public void setJobId(int jobId) { this.jobId = jobId; } public String getGlueType() { return glueType; } public void setGlueType(String glueType) { this.glueType = glueType; } public String getGlueSource() { return glueSource; } public void setGlueSource(String glueSource) { this.glueSource = glueSource;
} public String getGlueRemark() { return glueRemark; } public void setGlueRemark(String glueRemark) { this.glueRemark = glueRemark; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLogGlue.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleMapping { @SerializedName("_id") private UUID _id = null; @SerializedName("customerId") private String customerId = null; @SerializedName("updated") private OffsetDateTime updated = null; public ArticleMapping _id(UUID _id) { this._id = _id; return this; } /** * Alberta-Id des Artikels * @return _id **/ @Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", required = true, description = "Alberta-Id des Artikels") public UUID getId() { return _id; } public void setId(UUID _id) { this._id = _id; } public ArticleMapping customerId(String customerId) { this.customerId = customerId; return this; } /** * eindeutige Artikelnummer aus WaWi * @return customerId **/ @Schema(example = "43435", required = true, description = "eindeutige Artikelnummer aus WaWi") public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public ArticleMapping updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; } ArticleMapping articleMapping = (ArticleMapping) o; return Objects.equals(this._id, articleMapping._id) && Objects.equals(this.customerId, articleMapping.customerId) && Objects.equals(this.updated, articleMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, customerId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArticleMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).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\ArticleMapping.java
2
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemId implements RepoIdAware { int repoId; public static ExternalSystemId ofRepoId(final int repoId) { return new ExternalSystemId(repoId); } @Nullable public static ExternalSystemId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new ExternalSystemId(repoId) : null; } @Nullable public static ExternalSystemId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ExternalSystemId(repoId) : null; } public static Optional<ExternalSystemId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } @JsonCreator public static ExternalSystemId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, ExternalSystemId.class, ExternalSystemId::ofRepoId); } public static int toRepoId(@Nullable final ExternalSystemId id) { return id != null ? id.getRepoId() : -1; }
private ExternalSystemId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, I_ExternalSystem.COLUMNNAME_ExternalSystem_ID); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final ExternalSystemId o1, @Nullable final ExternalSystemId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemId.java
2
请完成以下Java代码
protected void rescheduleRegularCall(CommandContext commandContext, JobEntity jobEntity) { final BatchWindow nextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager() .getNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration()); if (nextBatchWindow != null) { commandContext.getJobManager().reschedule(jobEntity, nextBatchWindow.getStart()); } else { LOG.warnHistoryCleanupBatchWindowNotFound(); suspendJob(jobEntity); } } protected void suspendJob(JobEntity jobEntity) { jobEntity.setSuspensionState(SuspensionState.SUSPENDED.getStateCode()); } protected void incrementCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) { configuration.setCountEmptyRuns(configuration.getCountEmptyRuns() + 1);
jobEntity.setJobHandlerConfiguration(configuration); } protected void cancelCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) { configuration.setCountEmptyRuns(0); jobEntity.setJobHandlerConfiguration(configuration); } protected void reportMetrics(CommandContext commandContext) { ProcessEngineConfigurationImpl engineConfiguration = commandContext.getProcessEngineConfiguration(); if (engineConfiguration.isHistoryCleanupMetricsEnabled()) { for (Map.Entry<String, Long> report : reports.entrySet()){ engineConfiguration.getDbMetricsReporter().reportValueAtOnce(report.getKey(), report.getValue()); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupSchedulerCmd.java
1
请在Spring Boot框架中完成以下Java代码
protected Logger getLogger() { return this.logger; } private int validateDistributedSystemId(int distributedSystemId) { Assert.isTrue(distributedSystemId >= -1 && distributedSystemId < 256, String.format("Distributed System ID [%d] must be between -1 and 255", distributedSystemId)); return distributedSystemId; } @Bean ClientCacheConfigurer clientCacheDistributedSystemIdConfigurer() { return (beanName, clientCacheFactoryBean) -> getDistributedSystemId().ifPresent(distributedSystemId -> { Logger logger = getLogger();
if (logger.isWarnEnabled()) { logger.warn("Distributed System Id [{}] was set on the ClientCache instance, which will not have any effect", distributedSystemId); } }); } @Bean PeerCacheConfigurer peerCacheDistributedSystemIdConfigurer() { return (beanName, cacheFactoryBean) -> getDistributedSystemId().ifPresent(id -> cacheFactoryBean.getProperties() .setProperty(GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY, String.valueOf(validateDistributedSystemId(id)))); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DistributedSystemIdConfiguration.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceActual (final @Nullable BigDecimal PriceActual) { set_Value (COLUMNNAME_PriceActual, PriceActual); } @Override public BigDecimal getPriceActual() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */ public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty);
} @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStartDate (final @Nullable java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } @Override public java.sql.Timestamp getStartDate() { return get_ValueAsTimestamp(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectPhase.java
1
请完成以下Java代码
public class ConsoleScannerClass { public static void main(String[] args) { System.out.println("Please enter your name and surname: "); Scanner scanner = new Scanner(System.in); String nameSurname = scanner.nextLine(); System.out.println("Please enter your gender: "); char gender = scanner.next().charAt(0); System.out.println("Please enter your age: "); int age = scanner.nextInt(); System.out.println("Please enter your height in meters: "); double height = scanner.nextDouble(); System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung."); System.out.print("Have a good"); System.out.print(" one!"); System.out.println("\nPlease enter number of years of experience as a developer: "); BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in)); int i = 0; try { i = Integer.parseInt(buffReader.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
int sum = 0, count = 0; System.out.println("Please enter your college degrees. To finish, enter baeldung website url"); while (scanner.hasNextInt()) { int nmbr = scanner.nextInt(); sum += nmbr; count++; } int mean = sum / count; System.out.println("Your average degree is " + mean); if (scanner.hasNext(Pattern.compile("www.baeldung.com"))) System.out.println("Correct!"); else System.out.println("Baeldung website url is www.baeldung.com"); if (scanner != null) scanner.close(); } }
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\console\ConsoleScannerClass.java
1
请完成以下Java代码
public Builder setContext(Context context) { this.context = context; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder useSynchronization() { this.useSynchronization = true; return this; } private Optional<DelegatingAppender> getDelegate() { return Optional.ofNullable(this.delegate); } private Optional<ch.qos.logback.classic.Logger> getLogger() { return Optional.ofNullable(this.logger); } private Context resolveContext() { return this.context != null ? this.context : Optional.ofNullable(LoggerFactory.getILoggerFactory()) .filter(Context.class::isInstance) .map(Context.class::cast) .orElse(null); } private String resolveName() { return this.name != null && !this.name.trim().isEmpty() ? this.name : DEFAULT_NAME; } private StringAppenderWrapper resolveStringAppenderWrapper() { return this.useSynchronization ? StringBufferAppenderWrapper.create() : StringBuilderAppenderWrapper.create(); } public StringAppender build() { StringAppender stringAppender = new StringAppender(resolveStringAppenderWrapper()); stringAppender.setContext(resolveContext()); stringAppender.setName(resolveName()); getDelegate().ifPresent(delegate -> { Appender appender = this.replace ? stringAppender : CompositeAppender.compose(delegate.getAppender(), stringAppender); delegate.setAppender(appender); }); getLogger().ifPresent(logger -> logger.addAppender(stringAppender));
return stringAppender; } public StringAppender buildAndStart() { StringAppender stringAppender = build(); stringAppender.start(); return stringAppender; } } private final StringAppenderWrapper stringAppenderWrapper; protected StringAppender(StringAppenderWrapper stringAppenderWrapper) { if (stringAppenderWrapper == null) { throw new IllegalArgumentException("StringAppenderWrapper must not be null"); } this.stringAppenderWrapper = stringAppenderWrapper; } public String getLogOutput() { return getStringAppenderWrapper().toString(); } protected StringAppenderWrapper getStringAppenderWrapper() { return this.stringAppenderWrapper; } @Override protected void append(ILoggingEvent loggingEvent) { Optional.ofNullable(loggingEvent) .map(event -> preProcessLogMessage(toString(event))) .filter(this::isValidLogMessage) .ifPresent(getStringAppenderWrapper()::append); } protected boolean isValidLogMessage(String message) { return message != null && !message.isEmpty(); } protected String preProcessLogMessage(String message) { return message != null ? message.trim() : null; } protected String toString(ILoggingEvent loggingEvent) { return loggingEvent != null ? loggingEvent.getFormattedMessage() : null; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\StringAppender.java
1
请完成以下Java代码
public void setAD_Table_Target_ID (int AD_Table_Target_ID) { if (AD_Table_Target_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, Integer.valueOf(AD_Table_Target_ID)); } /** Get Ziel-Tabelle. @return Ziel-Tabelle */ public int getAD_Table_Target_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Target_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quell-Datensatz-ID. @param Record_Source_ID Quell-Datensatz-ID */ public void setRecord_Source_ID (int Record_Source_ID) { if (Record_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_Record_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID)); } /** Get Quell-Datensatz-ID.
@return Quell-Datensatz-ID */ public int getRecord_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ziel-Datensatz-ID. @param Record_Target_ID Ziel-Datensatz-ID */ public void setRecord_Target_ID (int Record_Target_ID) { if (Record_Target_ID < 1) set_ValueNoCheck (COLUMNNAME_Record_Target_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID)); } /** Get Ziel-Datensatz-ID. @return Ziel-Datensatz-ID */ public int getRecord_Target_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Relation_Explicit_v1.java
1
请完成以下Java代码
private PrintingSegment createPrintingSegmentForQueueItem( @NonNull final I_C_Printing_Queue printingQueue) { final int trayRepoId = printingQueue.getAD_PrinterHW_MediaTray_ID(); final HardwarePrinterId printerId = HardwarePrinterId.ofRepoId(printingQueue.getAD_PrinterHW_ID()); final HardwareTrayId trayId = HardwareTrayId.ofRepoIdOrNull(printerId, trayRepoId); final HardwarePrinter hardwarePrinter = hardwarePrinterRepository.getById(printerId); return PrintingSegment.builder() .printer(hardwarePrinter) .trayId(trayId) .routingType(I_AD_PrinterRouting.ROUTINGTYPE_PageRange) .copies(printingQueue.getCopies()) .build(); } private PrintingSegment createPrintingSegment( @NonNull final I_AD_PrinterRouting printerRouting, @Nullable final UserId userToPrintId, @Nullable final String hostKey, final int copies) { final I_AD_Printer_Matching printerMatchingRecord = printingDAO.retrievePrinterMatchingOrNull(hostKey/*hostKey*/, userToPrintId, printerRouting.getAD_Printer()); if (printerMatchingRecord == null) { logger.debug("Found no AD_Printer_Matching record for AD_PrinterRouting_ID={}, AD_User_PrinterMatchingConfig_ID={} and hostKey={}; -> creating no PrintingSegment for routing", printerRouting, UserId.toRepoId(userToPrintId), hostKey); return null; }
final I_AD_PrinterTray_Matching trayMatchingRecord = printingDAO.retrievePrinterTrayMatching(printerMatchingRecord, printerRouting, false); final int trayRepoId = trayMatchingRecord == null ? -1 : trayMatchingRecord.getAD_PrinterHW_MediaTray_ID(); final HardwarePrinterId printerId = HardwarePrinterId.ofRepoId(printerMatchingRecord.getAD_PrinterHW_ID()); final HardwareTrayId trayId = HardwareTrayId.ofRepoIdOrNull(printerId, trayRepoId); final HardwarePrinter hardwarePrinter = hardwarePrinterRepository.getById(printerId); return PrintingSegment.builder() .printerRoutingId(PrinterRoutingId.ofRepoId(printerRouting.getAD_PrinterRouting_ID())) .initialPageFrom(printerRouting.getPageFrom()) .initialPageTo(printerRouting.getPageTo()) .lastPages(printerRouting.getLastPages()) .routingType(printerRouting.getRoutingType()) .printer(hardwarePrinter) .trayId(trayId) .copies(CoalesceUtil.firstGreaterThanZero(copies, 1)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataFactory.java
1
请完成以下Java代码
public void updateAndPostEventOnQtyEnteredChange(final I_PP_Order ppOrderRecord) { if (ppOrderBL.isSomethingProcessed(ppOrderRecord)) { throw new LiberoException("Cannot quantity is not allowed because there is something already processed on this order"); // TODO: trl } final PPOrderChangedEventFactory eventFactory = PPOrderChangedEventFactory.newWithPPOrderBeforeChange(ppOrderConverter, ppOrderRecord); final PPOrderId orderId = PPOrderId.ofRepoId(ppOrderRecord.getPP_Order_ID()); deleteWorkflowAndBOM(orderId); createWorkflowAndBOM(ppOrderRecord); final PPOrderChangedEvent event = eventFactory.inspectPPOrderAfterChange(); materialEventService.enqueueEventAfterNextCommit(event); } private void deleteWorkflowAndBOM(final PPOrderId orderId) { ppOrderRoutingRepository.deleteByOrderId(orderId); ppOrderBOMDAO.deleteByOrderId(orderId); } private void createWorkflowAndBOM(final I_PP_Order ppOrder) { ppOrderBL.createOrderRouting(ppOrder); ppOrderBOMBL.createOrderBOMAndLines(ppOrder); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void beforeDelete(@NonNull final I_PP_Order ppOrder) { // // Delete depending records final String docStatus = ppOrder.getDocStatus(); if (X_PP_Order.DOCSTATUS_Drafted.equals(docStatus) || X_PP_Order.DOCSTATUS_InProgress.equals(docStatus)) { final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); orderCostsService.deleteByOrderId(ppOrderId); deleteWorkflowAndBOM(ppOrderId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_PP_Order.COLUMNNAME_M_Product_ID, I_PP_Order.COLUMNNAME_PP_Product_BOM_ID }) public void validateBOMAndProduct(@NonNull final I_PP_Order ppOrder)
{ final ProductBOMId bomId = ProductBOMId.ofRepoId(ppOrder.getPP_Product_BOM_ID()); final ProductId productIdOfBOM = productBOMDAO.getBOMProductId(bomId); if (ppOrder.getM_Product_ID() != productIdOfBOM.getRepoId()) { throw new AdempiereException(AdMessageKey.of("PP_Order_BOM_Doesnt_Match")) .markAsUserValidationError() .appendParametersToMessage() .setParameter("PP_Order.M_Product_ID", ppOrder.getM_Product_ID()) .setParameter("PP_Order.PP_Product_BOM_ID.M_Product_ID", productIdOfBOM.getRepoId()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void setSeqNo(final I_PP_Order ppOrder) { if (ppOrder.getSeqNo() <= 0) { ppOrder.setSeqNo(ppOrderDAO.getNextSeqNoPerDateStartSchedule(ppOrder).toInt()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Order.java
1
请完成以下Java代码
public class ComplexClass { private List<?> genericList; private Set<Integer> integerSet; public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) { super(); this.genericList = genericArrayList; this.integerSet = integerHashSet; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((genericList == null) ? 0 : genericList.hashCode()); result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ComplexClass)) return false; ComplexClass other = (ComplexClass) obj; if (genericList == null) { if (other.genericList != null) return false; } else if (!genericList.equals(other.genericList)) return false; if (integerSet == null) { if (other.integerSet != null) return false; } else if (!integerSet.equals(other.integerSet)) return false;
return true; } protected List<?> getGenericList() { return genericList; } protected void setGenericArrayList(List<?> genericList) { this.genericList = genericList; } protected Set<Integer> getIntegerSet() { return integerSet; } protected void setIntegerSet(Set<Integer> integerSet) { this.integerSet = integerSet; } }
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\ComplexClass.java
1
请完成以下Java代码
public static AttributeSetInstanceId nullToNone(@Nullable final AttributeSetInstanceId asiId) {return asiId != null ? asiId : NONE;} public static int toRepoId(@Nullable final AttributeSetInstanceId attributeSetInstanceId) { return attributeSetInstanceId != null ? attributeSetInstanceId.getRepoId() : -1; } private AttributeSetInstanceId() { this.repoId = 0; } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isNone() { return repoId == NONE.repoId; } /** * @return true if this is about a "real" greater-than-zero {@code M_AttributeSetInstance_ID}. */ public boolean isRegular() { return repoId > NONE.repoId; } public static boolean isRegular(@Nullable final AttributeSetInstanceId asiId) { return asiId != null && asiId.isRegular();
} @Nullable public AttributeSetInstanceId asRegularOrNull() {return isRegular() ? this : null;} /** * Note that currently, according to this method, "NONE" ist not equal to an emptpy ASI */ public static boolean equals(@Nullable final AttributeSetInstanceId id1, @Nullable final AttributeSetInstanceId id2) { return Objects.equals(id1, id2); } @SuppressWarnings("unused") public void assertRegular() { if (!isRegular()) { throw new AdempiereException("Expected regular ASI but got " + this); } } @Contract("!null -> !null") public AttributeSetInstanceId orElseIfNone(final AttributeSetInstanceId other) {return isNone() ? other : this;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeSetInstanceId.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public LocalDateTime getRegisteredAt() { return registeredAt; } public void setRegisteredAt(LocalDateTime registeredAt) { this.registeredAt = registeredAt; } public int getGrade() { return grade; }
public void setGrade(int grade) { this.grade = grade; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; CourseRegistration other = (CourseRegistration) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRegistration.java
1
请完成以下Java代码
public Pet tags(List<Tag> tags) { this.tags = tags; return this; } public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { this.tags = new ArrayList<Tag>(); } this.tags.add(tagsItem); return this; } /** * Get tags * @return tags **/ @ApiModelProperty(value = "") public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public Pet status(StatusEnum status) { this.status = status; return this; } /** * pet status in the store * @return status **/ @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pet pet = (Pet) o; return Objects.equals(this.id, pet.id) && Objects.equals(this.category, pet.category) && Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && Objects.equals(this.status, pet.status); } @Override public int hashCode() { return Objects.hash(id, category, name, photoUrls, tags, status); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java
1
请完成以下Java代码
public class CostDetailCreateResultsList { public static final CostDetailCreateResultsList EMPTY = new CostDetailCreateResultsList(ImmutableList.of()); private final ImmutableList<CostDetailCreateResult> list; private CostDetailCreateResultsList(@NonNull final List<CostDetailCreateResult> list) { this.list = ImmutableList.copyOf(list); } public static CostDetailCreateResultsList ofList(@NonNull final List<CostDetailCreateResult> list) { if (list.isEmpty()) { return EMPTY; } return new CostDetailCreateResultsList(list); } public static CostDetailCreateResultsList ofNullable(@Nullable final CostDetailCreateResult result) { return result != null ? of(result) : EMPTY; } public static CostDetailCreateResultsList of(@NonNull final CostDetailCreateResult result) {return ofList(ImmutableList.of(result));} public static Collector<CostDetailCreateResult, ?, CostDetailCreateResultsList> collect() {return GuavaCollectors.collectUsingListAccumulator(CostDetailCreateResultsList::ofList);} public Stream<CostDetailCreateResult> stream() {return list.stream();} public CostDetailCreateResult getSingleResult() {return CollectionUtils.singleElement(list);} public Optional<CostAmountAndQty> getAmtAndQtyToPost(@NonNull final CostAmountType type, @NonNull AcctSchema as) { return list.stream() .filter(result -> isAccountable(result, as)) .map(result -> result.getAmtAndQty(type)) .reduce(CostAmountAndQty::add); } public CostAmount getMainAmountToPost(@NonNull final AcctSchema as) { return getAmtAndQtyToPost(CostAmountType.MAIN, as) .map(CostAmountAndQty::getAmt) .orElseThrow(() -> new NoSuchElementException("No value present"));
} public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as) { return toAggregatedCostAmount().getTotalAmountToPost(as); } public AggregatedCostAmount toAggregatedCostAmount() { final CostSegment costSegment = CollectionUtils.extractSingleElement(list, CostDetailCreateResult::getCostSegment); final Map<CostElement, CostAmountDetailed> amountsByCostElement = list.stream() .collect(Collectors.toMap( CostDetailCreateResult::getCostElement, // keyMapper CostDetailCreateResult::getAmt, // valueMapper CostAmountDetailed::add)); // mergeFunction return AggregatedCostAmount.builder() .costSegment(costSegment) .amounts(amountsByCostElement) .build(); } private static boolean isAccountable(@NonNull CostDetailCreateResult result, @NonNull final AcctSchema as) { return result.getCostElement().isAccountable(as.getCosting()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateResultsList.java
1
请在Spring Boot框架中完成以下Java代码
public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArticleMapping articleMapping = (ArticleMapping) o; return Objects.equals(this._id, articleMapping._id) && Objects.equals(this.customerId, articleMapping.customerId) && Objects.equals(this.updated, articleMapping.updated); } @Override public int hashCode() { return Objects.hash(_id, customerId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArticleMapping {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).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\ArticleMapping.java
2
请完成以下Java代码
private static void checkType(@Nullable Type paramType, Set<Class<?>> avroTypes) { if (paramType == null) { return; } boolean container = isContainer(paramType); if (!container && paramType instanceof Class) { MergedAnnotations mergedAnnotations = MergedAnnotations.from((Class<?>) paramType); if (mergedAnnotations.isPresent(AVRO_GENERATED_CLASS_NAME)) { avroTypes.add((Class<?>) paramType); } } else if (container && paramType instanceof ParameterizedType) { Type[] generics = ((ParameterizedType) paramType).getActualTypeArguments(); if (generics.length > 0) { checkAvro(generics[0], avroTypes); } if (generics.length == 2) { checkAvro(generics[1], avroTypes); } } } private static void checkAvro(@Nullable Type generic, Set<Class<?>> avroTypes) { if (generic instanceof Class) { MergedAnnotations methodAnnotations = MergedAnnotations.from((Class<?>) generic); if (methodAnnotations.isPresent(AVRO_GENERATED_CLASS_NAME)) { avroTypes.add((Class<?>) generic);
} } } private static boolean isContainer(Type paramType) { if (paramType instanceof ParameterizedType) { Type rawType = ((ParameterizedType) paramType).getRawType(); return (rawType.equals(List.class)) || rawType.getTypeName().equals(CONSUMER_RECORD_CLASS_NAME) || rawType.getTypeName().equals(CONSUMER_RECORDS_CLASS_NAME); } return false; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\aot\KafkaAvroBeanRegistrationAotProcessor.java
1
请在Spring Boot框架中完成以下Java代码
private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-5\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
protected final String doIt() throws Exception { countExported = 0; countErrors = 0; retrieveValidSelectedDocuments().forEach(this::performNestedProcessInvocation); if (countExported > 0 && countErrors == 0) { return MSG_OK; } return MSG_Error + Services.get(IMsgBL.class).getMsg(getCtx(), errorMsg, new Object[] { countExported, countErrors }); } private void performNestedProcessInvocation(@NonNull final InvoiceId invoiceId) { final StringBuilder logMessage = new StringBuilder("Export C_Invoice_ID={} ==>").append(invoiceId.getRepoId()); try { final ProcessExecutor processExecutor = ProcessInfo .builder() .setProcessCalledFrom(getProcessInfo().getProcessCalledFrom()) .setAD_ProcessByClassname(C_Invoice_EDI_Export_JSON.class.getName()) .addParameter(PARAM_C_INVOICE_ID, invoiceId.getRepoId()) .setRecord(I_C_Invoice.Table_Name, invoiceId.getRepoId()) // will be stored in the AD_Pinstance .buildAndPrepareExecution() .executeSync(); final ProcessExecutionResult result = processExecutor.getResult(); final String summary = result.getSummary(); if (MSG_OK.equals(summary)) countExported++; else countErrors++; logMessage.append("AD_PInstance_ID=").append(PInstanceId.toRepoId(processExecutor.getProcessInfo().getPinstanceId())) .append("; Summary=").append(summary);
} catch (final Exception e) { final AdIssueId issueId = errorManager.createIssue(e); logMessage .append("Failed with AD_Issue_ID=").append(issueId.getRepoId()) .append("; Exception: ").append(e.getMessage()); countErrors++; } finally { addLog(logMessage.toString()); } } @NonNull private Stream<InvoiceId> retrieveValidSelectedDocuments() { return createSelectedInvoicesQueryBuilder() .addOnlyActiveRecordsFilter() .addEqualsFilter(org.compiere.model.I_C_Invoice.COLUMNNAME_IsSOTrx, true) .addEqualsFilter(org.compiere.model.I_C_Invoice.COLUMNNAME_DocStatus, I_C_Invoice.DOCSTATUS_Completed) .addEqualsFilter(I_C_Invoice.COLUMNNAME_IsEdiEnabled, true) .addEqualsFilter(I_C_Invoice.COLUMNNAME_EDI_ExportStatus, I_EDI_Document.EDI_EXPORTSTATUS_Pending) .create() .iterateAndStreamIds(InvoiceId::ofRepoId); } protected IQueryBuilder<I_C_Invoice> createSelectedInvoicesQueryBuilder() { return queryBL .createQueryBuilder(I_C_Invoice.class) .filter(getProcessInfo().getQueryFilterOrElseFalse()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\json\C_Invoice_Selection_Export_JSON.java
1
请完成以下Java代码
public int getC_BankStatementLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_DirectDebit_ID. @param C_DirectDebit_ID C_DirectDebit_ID */ public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); } /** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dtafile. @param Dtafile Copy of the *.dta stored as plain text */ public void setDtafile (String Dtafile) { set_Value (COLUMNNAME_Dtafile, Dtafile); } /** Get Dtafile. @return Copy of the *.dta stored as plain text */ public String getDtafile ()
{ return (String)get_Value(COLUMNNAME_Dtafile); } /** Set IsRemittance. @param IsRemittance IsRemittance */ public void setIsRemittance (boolean IsRemittance) { set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance)); } /** Get IsRemittance. @return IsRemittance */ public boolean isRemittance () { Object oo = get_Value(COLUMNNAME_IsRemittance); 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java
1
请在Spring Boot框架中完成以下Java代码
public ExtendedDateType getPaymentDueDate() { return paymentDueDate; } /** * Sets the value of the paymentDueDate property. * * @param value * allowed object is * {@link ExtendedDateType } * */ public void setPaymentDueDate(ExtendedDateType value) { this.paymentDueDate = 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;sequence&gt; * &lt;element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}AdditionalReference" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "additionalReference" }) public static class RelatedReferences { @XmlElement(name = "AdditionalReference") protected List<ReferenceType> additionalReference; /** * Other references if no dedicated field is available.Gets the value of the additionalReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\REMADVListLineItemExtensionType.java
2
请完成以下Java代码
public class Generics { // definition of a generic method public static <T> List<T> fromArrayToList(T[] a) { return Arrays.stream(a).collect(Collectors.toList()); } // definition of a generic method public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) { return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList()); } // example of a generic method that has Number as an upper bound for T public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) { return Arrays.stream(a).collect(Collectors.toList()); } // example of a generic method with a wild card, this method can be used // with a list of any subtype of Building
public static void paintAllBuildings(List<? extends Building> buildings) { buildings.forEach(Building::paint); } public static List<Integer> createList(int a) { List<Integer> list = new ArrayList<>(); list.add(a); return list; } public <T> List<T> genericMethod(List<T> list) { return list.stream().collect(Collectors.toList()); } public List<Object> withErasure(List<Object> list) { return list.stream().collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\generics\Generics.java
1
请完成以下Java代码
public int getA_Asset_Retirement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Retirement_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(getA_Asset_Retirement_ID())); } /** Set Market value Amount. @param AssetMarketValueAmt Market value of the asset */ public void setAssetMarketValueAmt (BigDecimal AssetMarketValueAmt) { set_Value (COLUMNNAME_AssetMarketValueAmt, AssetMarketValueAmt); } /** Get Market value Amount. @return Market value of the asset */ public BigDecimal getAssetMarketValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetMarketValueAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Asset value. @param AssetValueAmt Book Value of the asset */ public void setAssetValueAmt (BigDecimal AssetValueAmt) { set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt); } /** Get Asset value. @return Book Value of the asset */ public BigDecimal getAssetValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt); if (bd == null) return Env.ZERO; return bd;
} public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException { return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name) .getPO(getC_InvoiceLine_ID(), get_TrxName()); } /** Set Invoice Line. @param C_InvoiceLine_ID Invoice Detail Line */ public void setC_InvoiceLine_ID (int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_Value (COLUMNNAME_C_InvoiceLine_ID, null); else set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID)); } /** Get Invoice Line. @return Invoice Detail Line */ public int getC_InvoiceLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_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_A_Asset_Retirement.java
1
请在Spring Boot框架中完成以下Java代码
public class TrolleyService { @NonNull private final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); @NonNull private final LocatorScannedCodeResolverService locatorScannedCodeResolver; private final HashBiMap<UserId, LocatorQRCode> userId2locator = HashBiMap.create(); public LocatorQRCode setCurrent(@NonNull final UserId userId, @NonNull final ScannedCode scannedCode) { final LocatorQRCode locatorQRCode = locatorScannedCodeResolver.resolve(scannedCode).getLocatorQRCode(); final LocatorId locatorId = locatorQRCode.getLocatorId(); final I_M_Warehouse warehouse = warehouseDAO.getById(locatorId.getWarehouseId()); if (!warehouse.isInTransit()) { throw new AdempiereException("Warehouse is not in transit"); // TODO trl }
synchronized (userId2locator) { userId2locator.forcePut(userId, locatorQRCode); } return locatorQRCode; } public Optional<LocatorQRCode> getCurrent(@NonNull final UserId userId) { synchronized (userId2locator) { return Optional.ofNullable(userId2locator.get(userId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\service\TrolleyService.java
2
请完成以下Java代码
public String getOperationRef() { return operationRef; } public void setOperationRef(String operationRef) { this.operationRef = operationRef; } public String getExtensionId() { return extensionId; } public void setExtensionId(String extensionId) { this.extensionId = extensionId; } public boolean isExtended() { return extensionId != null && !extensionId.isEmpty(); } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public boolean hasBoundaryErrorEvents() { if (this.boundaryEvents != null && !this.boundaryEvents.isEmpty()) { return this.boundaryEvents.stream().anyMatch(boundaryEvent -> boundaryEvent.hasErrorEventDefinition()); } return false; } public ServiceTask clone() { ServiceTask clone = new ServiceTask(); clone.setValues(this); return clone; }
public void setValues(ServiceTask otherElement) { super.setValues(otherElement); setImplementation(otherElement.getImplementation()); setImplementationType(otherElement.getImplementationType()); setResultVariableName(otherElement.getResultVariableName()); setType(otherElement.getType()); setOperationRef(otherElement.getOperationRef()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); fieldExtensions = new ArrayList<FieldExtension>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } customProperties = new ArrayList<CustomProperty>(); if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) { for (CustomProperty property : otherElement.getCustomProperties()) { customProperties.add(property.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java
1
请完成以下Java代码
public DbOperation addRemovalTimeToVariableInstancesByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricVariableInstanceEntity.class, "updateHistoricVariableInstancesByProcessInstanceId", parameters); } @SuppressWarnings("unchecked") public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return getDbEntityManager().selectListWithRawParameter("selectHistoricVariableInstanceByNativeQuery", parameterMap, firstResult, maxResults); } public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbEntityManager().selectOne("selectHistoricVariableInstanceCountByNativeQuery", parameterMap); }
protected void configureQuery(HistoricVariableInstanceQueryImpl query) { getAuthorizationManager().configureHistoricVariableInstanceQuery(query); getTenantManager().configureQuery(query); } public DbOperation deleteHistoricVariableInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricVariableInstanceEntity.class, "deleteHistoricVariableInstancesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceManager.java
1
请完成以下Java代码
public void disconnected(ExecutorDriver driver) { } @Override public void launchTask(ExecutorDriver driver, TaskInfo task) { Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) .setState(Protos.TaskState.TASK_RUNNING).build(); driver.sendStatusUpdate(status); String myStatus = "Hello Framework"; driver.sendFrameworkMessage(myStatus.getBytes()); System.out.println("Hello World!!!"); status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) .setState(Protos.TaskState.TASK_FINISHED).build(); driver.sendStatusUpdate(status); }
@Override public void killTask(ExecutorDriver driver, Protos.TaskID taskId) { } @Override public void frameworkMessage(ExecutorDriver driver, byte[] data) { } @Override public void shutdown(ExecutorDriver driver) { } @Override public void error(ExecutorDriver driver, String message) { } public static void main(String[] args) { MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor()); System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); } }
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\mesos\executors\HelloWorldExecutor.java
1
请完成以下Java代码
public String getCamundaDecisionTenantId() { return camundaDecisionTenantIdAttribute.getValue(this); } public void setCamundaDecisionTenantId(String camundaDecisionTenantId) { camundaDecisionTenantIdAttribute.setValue(this, camundaDecisionTenantId); } @Override public String getCamundaMapDecisionResult() { return camundaMapDecisionResultAttribute.getValue(this); } @Override public void setCamundaMapDecisionResult(String camundaMapDecisionResult) { camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTask.class, CMMN_ELEMENT_DECISION_TASK) .namespaceUri(CMMN11_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<DecisionTask>() { public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionTaskImpl(instanceContext); } }); decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF) .build(); /** Camunda extensions */ camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE) .namespace(CAMUNDA_NS) .build(); camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING) .namespace(CAMUNDA_NS) .build(); camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION)
.namespace(CAMUNDA_NS) .build(); camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID) .namespace(CAMUNDA_NS) .build(); camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java
1
请完成以下Java代码
public class BinaryFileWriter implements AutoCloseable { private static final int CHUNK_SIZE = 1024; private final OutputStream outputStream; private final ProgressCallback progressCallback; public BinaryFileWriter(OutputStream outputStream, ProgressCallback progressCallback) { this.outputStream = outputStream; this.progressCallback = progressCallback; } public long write(InputStream inputStream, double length) throws IOException { try (BufferedInputStream input = new BufferedInputStream(inputStream)) { byte[] dataBuffer = new byte[CHUNK_SIZE]; int readBytes;
long totalBytes = 0; while ((readBytes = input.read(dataBuffer)) != -1) { totalBytes += readBytes; outputStream.write(dataBuffer, 0, readBytes); progressCallback.onProgress(totalBytes / length * 100.0); } return totalBytes; } } @Override public void close() throws IOException { outputStream.close(); } }
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\download\BinaryFileWriter.java
1
请完成以下Java代码
protected String doIt() throws Exception { final BPartnerId bpartnerId = BPartnerId.ofRepoId(getProcessInfo().getRecord_ID()); final I_C_BPartner bpartnerRecord = bpartnerBL.getById(bpartnerId); final OrgChangeRequest orgChangeRequest = OrgChangeRequest.builder() .bpartnerId(bpartnerId) .startDate(p_startDate) .groupCategoryId(p_groupCategoryId) .orgFromId(OrgId.ofRepoId(bpartnerRecord.getAD_Org_ID())) .orgToId(p_orgTargetId) .isCloseInvoiceCandidate(isCloseInvoiceCandidate) .build(); service.moveToNewOrg(orgChangeRequest); return MSG_OK; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept();
} @Override public void onParameterChanged(final String parameterName) { if (PARAM_AD_ORG_TARGET_ID.equals(parameterName) || PARAM_DATE_ORG_CHANGE.equals(parameterName)) { if (p_orgTargetId == null) { return; } final BPartnerId partnerId = BPartnerId.ofRepoId(getRecord_ID()); final Instant orgChangeDate = CoalesceUtil.coalesce(p_startDate, SystemTime.asInstant()); final OrgChangeBPartnerComposite orgChangePartnerComposite = service.getByIdAndOrgChangeDate(partnerId, orgChangeDate); isShowMembershipParameter = orgChangePartnerComposite.hasMembershipSubscriptions() && service.hasAnyMembershipProduct(p_orgTargetId); final GroupCategoryId groupCategoryId = orgChangePartnerComposite.getGroupCategoryId(); if (groupCategoryId != null && service.isGroupCategoryContainsProductsInTargetOrg(groupCategoryId, p_orgTargetId)) { p_groupCategoryId = groupCategoryId; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_MoveToAnotherOrg_ProcessHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class Animal { @Id private long animalId; private String species; public Animal() {} public Animal(long animalId, String species) { this.animalId = animalId; this.species = species; } public long getAnimalId() { return animalId;
} public void setAnimalId(long animalId) { this.animalId = animalId; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\inheritance\Animal.java
2
请完成以下Java代码
public AdditionalRequiredFactorsBuilder<T> requireFactors(String... additionalAuthorities) { requireFactors((factors) -> { for (String authority : additionalAuthorities) { factors.requireFactor((factor) -> factor.authority(authority)); } }); return this; } public AdditionalRequiredFactorsBuilder<T> requireFactors( Consumer<AllRequiredFactorsAuthorizationManager.Builder<T>> factors) { factors.accept(this.factors); return this; } public AdditionalRequiredFactorsBuilder<T> requireFactor(Consumer<RequiredFactor.Builder> factor) { this.factors.requireFactor(factor); return this; } /** * Builds a {@link DefaultAuthorizationManagerFactory} that has the * {@link DefaultAuthorizationManagerFactory#setAdditionalAuthorization(AuthorizationManager)}
* set. * @return the {@link DefaultAuthorizationManagerFactory}. */ public DefaultAuthorizationManagerFactory<T> build() { DefaultAuthorizationManagerFactory<T> result = new DefaultAuthorizationManagerFactory<>(); AllRequiredFactorsAuthorizationManager<T> additionalChecks = this.factors.build(); result.setAdditionalAuthorization(additionalChecks); return result; } private AdditionalRequiredFactorsBuilder() { } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationManagerFactories.java
1
请完成以下Java代码
public static ElementPermission none(final ElementResource resource) { return new ElementPermission(resource, ImmutableSet.of()); } @NonNull ElementResource resource; @Getter(AccessLevel.PRIVATE) @NonNull ImmutableSet<Access> accesses; private ElementPermission( @NonNull final ElementResource resource, @NonNull final ImmutableSet<Access> accesses) { this.resource = resource; this.accesses = accesses; } public int getElementId() { return resource.getElementId(); } @Override public boolean hasAccess(final Access access) { return accesses.contains(access); } public boolean hasReadAccess() { return accesses.contains(Access.READ); } public boolean hasWriteAccess() { return accesses.contains(Access.WRITE); } @Nullable public Boolean getReadWriteBoolean() { if (hasAccess(Access.WRITE)) {
return Boolean.TRUE; } else if (hasAccess(Access.READ)) { return Boolean.FALSE; } else { return null; } } @Override public ElementPermission mergeWith(final Permission permissionFrom) { final ElementPermission elementPermissionFrom = PermissionInternalUtils.checkCompatibleAndCastToTarget(this, permissionFrom); return withAccesses(ImmutableSet.<Access>builder() .addAll(this.accesses) .addAll(elementPermissionFrom.accesses) .build()); } private ElementPermission withAccesses(@NonNull final ImmutableSet<Access> accesses) { return !Objects.equals(this.accesses, accesses) ? new ElementPermission(this.resource, accesses) : this; } public ElementPermission withResource(@NonNull final ElementResource resource) { return !Objects.equals(this.resource, resource) ? new ElementPermission(resource, this.accesses) : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermission.java
1
请完成以下Java代码
private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql(); } else {
sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public DataSize getMaxDiskUsagePerPart() { return this.maxDiskUsagePerPart; } public void setMaxDiskUsagePerPart(DataSize maxDiskUsagePerPart) { this.maxDiskUsagePerPart = maxDiskUsagePerPart; } public Integer getMaxParts() { return this.maxParts; } public void setMaxParts(Integer maxParts) { this.maxParts = maxParts; } public @Nullable String getFileStorageDirectory() {
return this.fileStorageDirectory; } public void setFileStorageDirectory(@Nullable String fileStorageDirectory) { this.fileStorageDirectory = fileStorageDirectory; } public Charset getHeadersCharset() { return this.headersCharset; } public void setHeadersCharset(Charset headersCharset) { this.headersCharset = headersCharset; } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\ReactiveMultipartProperties.java
2
请完成以下Java代码
public static InputStream createInternetShortcut(String name, String url, String icon) { StringWriter sw = new StringWriter(); try { // 按照Windows快捷方式格式写入内容 sw.write("[InternetShortcut]\n"); sw.write("URL=" + url + "\n"); if (oConvertUtils.isNotEmpty(icon)) { sw.write("IconFile=" + icon + "\n"); } // 将字符串内容转换为输入流 return new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8)); } finally { IoUtil.close(sw); } } /** * 从URL中提取文件名 * 功能:从HTTP URL或本地路径中提取纯文件名 * @param fileUrl 文件URL * @return 文件名(不含路径) */ public static String getFileNameFromUrl(String fileUrl) { try { // 处理HTTP URL:从路径部分提取文件名 if (fileUrl.startsWith(CommonConstant.STR_HTTP)) { URL url = new URL(fileUrl); String path = url.getPath(); return path.substring(path.lastIndexOf('/') + 1); }
// 处理本地文件路径:从文件路径提取文件名 return fileUrl.substring(fileUrl.lastIndexOf(File.separator) + 1); } catch (Exception e) { // 如果解析失败,使用时间戳作为文件名 return "file_" + System.currentTimeMillis(); } } /** * 生成ZIP中的文件名 * 功能:避免文件名冲突,为多个文件添加序号 * @param fileUrl 文件URL(用于提取原始文件名) * @param index 文件序号(从0开始) * @param total 文件总数 * @return 处理后的文件名(带序号) */ public static String generateFileName(String fileUrl, int index, int total) { // 从URL中提取原始文件名 String originalFileName = getFileNameFromUrl(fileUrl); // 如果只有一个文件,直接使用原始文件名 if (total == 1) { return originalFileName; } // 多个文件时,使用序号+原始文件名 String extension = getFileExtension(originalFileName); String nameWithoutExtension = originalFileName.replace("." + extension, ""); return String.format("%s_%d.%s", nameWithoutExtension, index + 1, extension); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\FileDownloadUtils.java
1
请完成以下Java代码
public ResourceId getRawMaterialsPlantId() { loadIfNeeded(); return rawMaterialsPlantId; } public I_M_Warehouse getRawMaterialsWarehouse() { loadIfNeeded(); return rawMaterialsWarehouse; } public I_M_Locator getRawMaterialsLocator() { loadIfNeeded(); return rawMaterialsLocator; } public OrgId getOrgId() { loadIfNeeded(); return orgId; }
public BPartnerLocationId getOrgBPLocationId() { loadIfNeeded(); return orgBPLocationId; } public UserId getPlannerId() { loadIfNeeded(); return productPlanning == null ? null : productPlanning.getPlannerId(); } public WarehouseId getInTransitWarehouseId() { loadIfNeeded(); return inTransitWarehouseId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\RawMaterialsReturnDDOrderLineCandidate.java
1
请完成以下Java代码
private static SqlViewGroupingBinding createSqlViewGroupingBinding() { return SqlViewGroupingBinding.builder() .groupBy(I_M_Packageable_V.COLUMNNAME_C_OrderSO_ID) .groupBy(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID) .groupBy(I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID) .columnSql(I_M_Packageable_V.COLUMNNAME_DeliveryDate, SqlSelectValue.builder() .virtualColumnSql(ColumnSql.ofSql("MIN(DeliveryDate)")) .columnNameAlias(I_M_Packageable_V.COLUMNNAME_DeliveryDate) .build()) .columnSql(I_M_Packageable_V.COLUMNNAME_PreparationDate, SqlSelectValue.builder() .virtualColumnSql(ColumnSql.ofSql("IF_MIN(DeliveryDate, PreparationDate)")) .columnNameAlias(I_M_Packageable_V.COLUMNNAME_PreparationDate) .build()) .rowIdsConverter(SqlViewRowIdsConverters.TO_INT_EXCLUDING_STRINGS) .build(); } @Override public void customizeViewLayout(final ViewLayout.ChangeBuilder viewLayoutBuilder) { viewLayoutBuilder.element(DocumentLayoutElementDescriptor.builder() .setWidgetType(DocumentFieldWidgetType.Lookup) .addField(DocumentLayoutElementFieldDescriptor.builder(FIELDNAME_OrderOrBPLocation) .setPublicField(true)) .build()); viewLayoutBuilder.elementsOrder( FIELDNAME_OrderOrBPLocation, I_M_Packageable_V.COLUMNNAME_M_Product_ID, I_M_Packageable_V.COLUMNNAME_QtyOrdered, I_M_Packageable_V.COLUMNNAME_QtyPickedOrDelivered, I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID, I_M_Packageable_V.COLUMNNAME_PreparationDate); }
@Override public void customizeViewRow(final ViewRow.Builder rowBuilder) { final LookupValue orderOrBPLocationLV = createOrderOrBPLocation(rowBuilder); rowBuilder.putFieldValue(FIELDNAME_OrderOrBPLocation, orderOrBPLocationLV); } private LookupValue createOrderOrBPLocation(final ViewRow.Builder rowBuilder) { // Grouping row if (rowBuilder.isRootRow()) { final LookupValue orderLV = rowBuilder.getFieldValueAsLookupValue(I_M_Packageable_V.COLUMNNAME_C_OrderSO_ID); final LookupValue bpartnerLV = rowBuilder.getFieldValueAsLookupValue(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID); return LookupValue.concat(orderLV, bpartnerLV); } // Detail/included row else { return rowBuilder.getFieldValueAsLookupValue(I_M_Packageable_V.COLUMNNAME_C_BPartner_Location_ID); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\PickingTerminalByOrderViewCustomizer.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class); } @Override public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse) { set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse); } /** Set Lager. @param M_Warehouse_ID Lager oder Ort für Dienstleistung */ @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); }
/** Get Lager. @return Lager oder Ort für Dienstleistung */ @Override public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ResetBufferInterval. @param ResetBufferInterval ResetBufferInterval */ @Override public void setResetBufferInterval (java.math.BigDecimal ResetBufferInterval) { set_Value (COLUMNNAME_ResetBufferInterval, ResetBufferInterval); } /** Get ResetBufferInterval. @return ResetBufferInterval */ @Override public java.math.BigDecimal getResetBufferInterval () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ResetBufferInterval); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_Material_Balance_Config.java
1
请完成以下Java代码
public class MDAGSet extends MDAG implements Set<String> { public MDAGSet(File dataFile) throws IOException { super(dataFile); } public MDAGSet(Collection<String> strCollection) { super(strCollection); } public MDAGSet() { } public MDAGSet(String dictionaryPath) throws IOException { super(dictionaryPath); } @Override public int size() { return getAllStrings().size(); } @Override public boolean isEmpty() { return this.equivalenceClassMDAGNodeHashMap.size() != 0; } @Override public boolean contains(Object o) { if (o.getClass() != String.class) return false; return contains((String) o); } @Override public Iterator<String> iterator() { return getAllStrings().iterator(); } @Override public Object[] toArray() { return getAllStrings().toArray(); } @Override public <T> T[] toArray(T[] a) { return getAllStrings().toArray(a); } @Override public boolean add(String s) { addString(s); return true; } @Override public boolean remove(Object o) { if (o.getClass() == String.class) { removeString((String) o); } else { removeString(o.toString()); } return true; }
@Override public boolean containsAll(Collection<?> c) { for (Object e : c) if (!contains(e)) return false; return true; } @Override public boolean addAll(Collection<? extends String> c) { boolean modified = false; for (String e : c) if (add(e)) modified = true; return modified; } @Override public boolean retainAll(Collection<?> c) { boolean modified = false; Iterator<String> it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; } @Override public boolean removeAll(Collection<?> c) { boolean modified = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (c.contains(it.next())) { it.remove(); modified = true; } } return modified; } @Override public void clear() { sourceNode = new MDAGNode(false); simplifiedSourceNode = null; if (equivalenceClassMDAGNodeHashMap != null) equivalenceClassMDAGNodeHashMap.clear(); mdagDataArray = null; charTreeSet.clear(); transitionCount = 0; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGSet.java
1
请完成以下Java代码
public final boolean isChecked() { return this.isSelected(); } private final void setChecked(final boolean checked) { this.setSelected(checked); } protected void onActionPerformed() { if (!isEnabled()) { return; } setEnabled(false);
try { action.setToggled(isChecked()); action.execute(); } catch (Exception e) { final int windowNo = Env.getWindowNo(this); Services.get(IClientUI.class).error(windowNo, e); } finally { setEnabled(true); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\CheckableSideActionComponent.java
1
请完成以下Java代码
public java.math.BigDecimal getDK_ParcelHeight () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelHeight); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Paketlänge. @param DK_ParcelLength Paketlänge */ @Override public void setDK_ParcelLength (java.math.BigDecimal DK_ParcelLength) { set_Value (COLUMNNAME_DK_ParcelLength, DK_ParcelLength); } /** Get Paketlänge. @return Paketlänge */ @Override public java.math.BigDecimal getDK_ParcelLength () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelLength); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Sendungsnummer. @param DK_ParcelNumber Sendungsnummer */ @Override public void setDK_ParcelNumber (java.lang.String DK_ParcelNumber) { set_Value (COLUMNNAME_DK_ParcelNumber, DK_ParcelNumber); } /** Get Sendungsnummer. @return Sendungsnummer */ @Override public java.lang.String getDK_ParcelNumber () { return (java.lang.String)get_Value(COLUMNNAME_DK_ParcelNumber); } /** Set Paketgewicht. @param DK_ParcelWeight Paketgewicht */ @Override public void setDK_ParcelWeight (java.math.BigDecimal DK_ParcelWeight) { set_Value (COLUMNNAME_DK_ParcelWeight, DK_ParcelWeight); } /** Get Paketgewicht. @return Paketgewicht */ @Override public java.math.BigDecimal getDK_ParcelWeight () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWeight); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Paketbreite. @param DK_ParcelWidth Paketbreite */ @Override public void setDK_ParcelWidth (java.math.BigDecimal DK_ParcelWidth) {
set_Value (COLUMNNAME_DK_ParcelWidth, DK_ParcelWidth); } /** Get Paketbreite. @return Paketbreite */ @Override public java.math.BigDecimal getDK_ParcelWidth () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWidth); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Referenz. @param DK_Reference Referenz */ @Override public void setDK_Reference (java.lang.String DK_Reference) { set_Value (COLUMNNAME_DK_Reference, DK_Reference); } /** Get Referenz. @return Referenz */ @Override public java.lang.String getDK_Reference () { return (java.lang.String)get_Value(COLUMNNAME_DK_Reference); } /** Set Zeile Nr.. @param Line Einzelne Zeile in dem Dokument */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Einzelne Zeile in dem Dokument */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine.java
1
请完成以下Java代码
public BigDecimal getQtyAllocated() { return storage.getQtyFree(); } @Override public BigDecimal getQtyToAllocate() { return storage.getQty().toBigDecimal(); } @Override public Object getTrxReferencedModel() { return referenceModel; } protected IProductStorage getStorage() { return storage; } @Override public IAllocationSource createAllocationSource(final I_M_HU hu) {
return HUListAllocationSourceDestination.of(hu); } @Override public boolean isReadOnly() { return readonly; } @Override public void setReadOnly(final boolean readonly) { this.readonly = readonly; } @Override public I_M_HU_Item getInnerHUItem() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
1
请完成以下Java代码
public DataFetcherResult<ArticlePayload> favoriteArticle(@InputArgument("slug") String slug) { User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new); Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); ArticleFavorite articleFavorite = new ArticleFavorite(article.getId(), user.getId()); articleFavoriteRepository.save(articleFavorite); return DataFetcherResult.<ArticlePayload>newResult() .data(ArticlePayload.newBuilder().build()) .localContext(article) .build(); } @DgsMutation(field = MUTATION.UnfavoriteArticle) public DataFetcherResult<ArticlePayload> unfavoriteArticle(@InputArgument("slug") String slug) { User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new); Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); articleFavoriteRepository .find(article.getId(), user.getId()) .ifPresent( favorite -> { articleFavoriteRepository.remove(favorite); });
return DataFetcherResult.<ArticlePayload>newResult() .data(ArticlePayload.newBuilder().build()) .localContext(article) .build(); } @DgsMutation(field = MUTATION.DeleteArticle) public DeletionStatus deleteArticle(@InputArgument("slug") String slug) { User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new); Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); if (!AuthorizationService.canWriteArticle(user, article)) { throw new NoAuthorizationException(); } articleRepository.remove(article); return DeletionStatus.newBuilder().success(true).build(); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\ArticleMutation.java
1
请完成以下Java代码
private class FirewalledRequestAwareRequestDispatcher implements RequestDispatcher { private final String path; /** * @param path the {@code path} that will be used to obtain the delegate * {@link RequestDispatcher} from the original {@link HttpServletRequest}. */ FirewalledRequestAwareRequestDispatcher(String path) { this.path = path; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { reset();
getDelegateDispatcher().forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { getDelegateDispatcher().include(request, response); } private RequestDispatcher getDelegateDispatcher() { return RequestWrapper.super.getRequestDispatcher(this.path); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\RequestWrapper.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get 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 M_Product_LotNumber_Quarantine. @param M_Product_LotNumber_Quarantine_ID M_Product_LotNumber_Quarantine */ @Override public void setM_Product_LotNumber_Quarantine_ID (int M_Product_LotNumber_Quarantine_ID) { if (M_Product_LotNumber_Quarantine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, Integer.valueOf(M_Product_LotNumber_Quarantine_ID)); } /** Get M_Product_LotNumber_Quarantine. @return M_Product_LotNumber_Quarantine */ @Override public int getM_Product_LotNumber_Quarantine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_LotNumber_Quarantine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\product\model\X_M_Product_LotNumber_Quarantine.java
1
请完成以下Java代码
public final class RestPreconditions { private RestPreconditions() { throw new AssertionError(); } // API /** * Check if some value was found, otherwise throw exception. * * @param expression * has value true if found, otherwise false * @throws MyResourceNotFoundException * if expression is false, means value not found. */ public static void checkFound(final boolean expression) { if (!expression) { throw new MyResourceNotFoundException(); } } /**
* Check if some value was found, otherwise throw exception. * * @param expression * has value true if found, otherwise false * @throws MyResourceNotFoundException * if expression is false, means value not found. */ public static <T> T checkFound(final T resource) { if (resource == null) { throw new MyResourceNotFoundException(); } return resource; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\util\RestPreconditions.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public int getVersion() { return version; } public String getResource() { return resource; } public String getDeploymentId() { return deploymentId; } public String getTenantId() { return tenantId; } public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public Integer getHistoryTimeToLive() {
return historyTimeToLive; } public String getVersionTag(){ return versionTag; } public static DecisionDefinitionDto fromDecisionDefinition(DecisionDefinition definition) { DecisionDefinitionDto dto = new DecisionDefinitionDto(); dto.id = definition.getId(); dto.key = definition.getKey(); dto.category = definition.getCategory(); dto.name = definition.getName(); dto.version = definition.getVersion(); dto.resource = definition.getResourceName(); dto.deploymentId = definition.getDeploymentId(); dto.decisionRequirementsDefinitionId = definition.getDecisionRequirementsDefinitionId(); dto.decisionRequirementsDefinitionKey = definition.getDecisionRequirementsDefinitionKey(); dto.tenantId = definition.getTenantId(); dto.historyTimeToLive = definition.getHistoryTimeToLive(); dto.versionTag = definition.getVersionTag(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DecisionDefinitionDto.java
2
请完成以下Java代码
public int seekMovement() { if(fieldConcept.getValue() == null ) return 0; int HR_Movement_ID = 0; String date = DB.TO_DATE(fieldValidFrom.getValue()); int Process_ID = 0; KeyNamePair ppp = (KeyNamePair)fieldProcess.getSelectedItem(); int Employee_ID = 0; KeyNamePair ppe = (KeyNamePair)fieldEmployee.getSelectedItem(); int Concept_ID = 0; KeyNamePair ppc = (KeyNamePair)fieldConcept.getSelectedItem(); // Process_ID = ppp != null ? ppp.getKey(): null; Employee_ID = ppe != null ? ppe.getKey(): null; Concept_ID = ppc != null ? ppc.getKey(): null; MHRConcept concept = MHRConcept.get(Env.getCtx(),Concept_ID); // if ( (Process_ID+Employee_ID+Concept_ID) > 0 ){ HR_Movement_ID = DB.getSQLValue(null,"SELECT HR_Movement_ID " +" FROM HR_Movement WHERE HR_Process_ID = "+Process_ID +" AND C_BPartner_ID =" +Employee_ID+ " AND HR_Concept_ID = "+Concept_ID +" AND TRUNC(ValidFrom) = TRUNC(" + date +")"); if (HR_Movement_ID > 0){ // exist record in Movement Payroll sHR_Movement_ID = HR_Movement_ID; MHRMovement movementFound = new MHRMovement(Env.getCtx(),sHR_Movement_ID,null); // fieldDescription.setValue(movementFound.getDescription()); // clear fields fieldText.setValue(""); fieldDate.setValue(null); fieldQty.setValue(Env.ZERO); fieldAmount.setValue(Env.ZERO); // assign just corresponding field if ( concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity) ) // Quantity fieldQty.setValue(movementFound.getQty()); else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount) ) // Amount fieldAmount.setValue(movementFound.getAmount()); else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text) ) // Text fieldText.setValue(movementFound.getTextMsg()); else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date) ) // Date fieldDate.setValue(movementFound.getServiceDate()); } } return HR_Movement_ID;
} //seekMovement /** * Get SQL Code of ColumnType for given sqlValue * @param sqlValue * @return sql select code */ private String getSQL_ColumnType(String sqlValue) { int columnType_Ref_ID = MTable.get(Env.getCtx(), MHRConcept.Table_ID) .getColumn(MHRConcept.COLUMNNAME_ColumnType) .getAD_Reference_Value_ID(); String sql; if (Env.isBaseLanguage(Env.getCtx(), MRefList.Table_Name)) { sql = "SELECT zz.Name FROM AD_Ref_List zz WHERE zz.AD_Reference_ID="+columnType_Ref_ID; } else { sql = "SELECT zz.Name FROM AD_Ref_List zz, AD_Ref_List_Trl zzt" +" WHERE zz.AD_Reference_ID="+columnType_Ref_ID +" AND zzt.AD_Ref_List_ID=zz.AD_Ref_List_ID" +" AND zzt.AD_Language="+DB.TO_STRING(Env.getAD_Language(Env.getCtx())); } sql += " AND zz.Value = "+sqlValue; return sql; } // getSQL_ColumnType } // VHRActionNotice
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\form\VHRActionNotice.java
1
请在Spring Boot框架中完成以下Java代码
private <K, V> void add(Map<K, List<V>> map, K key, V value, boolean ifMissing) { List<V> values = map.computeIfAbsent(key, (k) -> new ArrayList<>()); if (!ifMissing || values.isEmpty()) { values.add(value); } } private ItemMetadata findMatchingItemMetadata(ItemMetadata metadata) { List<ItemMetadata> candidates = this.items.get(metadata.getName()); if (candidates == null || candidates.isEmpty()) { return null; } candidates = new ArrayList<>(candidates); candidates.removeIf((itemMetadata) -> !itemMetadata.hasSameType(metadata)); if (candidates.size() > 1 && metadata.getType() != null) { candidates.removeIf((itemMetadata) -> !metadata.getType().equals(itemMetadata.getType())); } if (candidates.size() == 1) { return candidates.get(0); } for (ItemMetadata candidate : candidates) { if (nullSafeEquals(candidate.getSourceType(), metadata.getSourceType())) { return candidate; } } return null; } private boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } return o1 != null && o1.equals(o2);
} public static String nestedPrefix(String prefix, String name) { String nestedPrefix = (prefix != null) ? prefix : ""; String dashedName = ConventionUtils.toDashedCase(name); nestedPrefix += nestedPrefix.isEmpty() ? dashedName : "." + dashedName; return nestedPrefix; } private static <T extends Comparable<T>> List<T> flattenValues(Map<?, List<T>> map) { List<T> content = new ArrayList<>(); for (List<T> values : map.values()) { content.addAll(values); } Collections.sort(content); return content; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(String.format("items: %n")); this.items.values().forEach((itemMetadata) -> result.append("\t").append(String.format("%s%n", itemMetadata))); return result.toString(); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ConfigurationMetadata.java
2
请完成以下Java代码
public List<Map<String, String>> parseTable(Document doc, int tableOrder) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements dataRows = tbody.select("tr"); Elements headerRow = table.select("tr") .get(0) .select("th,td"); List<String> headers = new ArrayList<String>(); for (Element header : headerRow) { headers.add(header.text()); } List<Map<String, String>> parsedDataRows = new ArrayList<Map<String, String>>(); for (int row = 0; row < dataRows.size(); row++) { Elements colVals = dataRows.get(row) .select("th,td"); int colCount = 0; Map<String, String> dataRow = new HashMap<String, String>(); for (Element colVal : colVals) { dataRow.put(headers.get(colCount++), colVal.text()); } parsedDataRows.add(dataRow); } return parsedDataRows; } public void updateTableData(Document doc, int tableOrder, String updateValue) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements dataRows = tbody.select("tr"); for (int row = 0; row < dataRows.size(); row++) { Elements colVals = dataRows.get(row) .select("th,td"); for (int colCount = 0; colCount < colVals.size(); colCount++) {
colVals.get(colCount) .text(updateValue); } } } public void addRowToTable(Document doc, int tableOrder) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements rows = table.select("tr"); Elements headerCols = rows.get(0) .select("th,td"); int numCols = headerCols.size(); Elements colVals = new Elements(numCols); for (int colCount = 0; colCount < numCols; colCount++) { Element colVal = new Element("td"); colVal.text("11"); colVals.add(colVal); } Elements dataRows = tbody.select("tr"); Element newDataRow = new Element("tr"); newDataRow.appendChildren(colVals); dataRows.add(newDataRow); tbody.html(dataRows.toString()); } public void deleteRowFromTable(Document doc, int tableOrder, int rowNumber) { Element table = doc.select("table") .get(tableOrder); Element tbody = table.select("tbody") .get(0); Elements dataRows = tbody.select("tr"); if (rowNumber < dataRows.size()) { dataRows.remove(rowNumber); } } }
repos\tutorials-master\jsoup\src\main\java\com\baeldung\jsoup\JsoupTableParser.java
1
请完成以下Java代码
private static long hash(String key) { // md5 byte MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported", e); } md5.reset(); byte[] keyBytes = null; try { keyBytes = key.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unknown string :" + key, e); } md5.update(keyBytes); byte[] digest = md5.digest(); // hash code, Truncate to 32-bits long hashCode = ((long) (digest[3] & 0xFF) << 24) | ((long) (digest[2] & 0xFF) << 16) | ((long) (digest[1] & 0xFF) << 8) | (digest[0] & 0xFF); long truncateHashCode = hashCode & 0xffffffffL; return truncateHashCode; } public String hashJob(int jobId, List<String> addressList) { // ------A1------A2-------A3------ // -----------J1------------------ TreeMap<Long, String> addressRing = new TreeMap<Long, String>();
for (String address: addressList) { for (int i = 0; i < VIRTUAL_NODE_NUM; i++) { long addressHash = hash("SHARD-" + address + "-NODE-" + i); addressRing.put(addressHash, address); } } long jobHash = hash(String.valueOf(jobId)); SortedMap<Long, String> lastRing = addressRing.tailMap(jobHash); if (!lastRing.isEmpty()) { return lastRing.get(lastRing.firstKey()); } return addressRing.firstEntry().getValue(); } @Override public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { String address = hashJob(triggerParam.getJobId(), addressList); return new ReturnT<String>(address); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteConsistentHash.java
1
请完成以下Java代码
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { // get token from http header String token = httpServletRequest.getHeader("token"); if(!(object instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod=(HandlerMethod)object; Method method=handlerMethod.getMethod(); //check is included @passtoken annotation? jump if have if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //check is included @UserLoginToken ? if (method.isAnnotationPresent(UserLoginToken.class)) { UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class); if (userLoginToken.required()) { // excute verify if (token == null) { throw new RuntimeException("token invalid,please login again"); } // get user id from token String userId; try { userId = JWT.decode(token).getAudience().get(0); } catch (JWTDecodeException j) { throw new RuntimeException("401"); } User user = userService.findUserById(userId); if (user == null) { throw new RuntimeException("user is not exist,please login again"); } // verify token JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); try {
jwtVerifier.verify(token); if (JWT.decode(token).getExpiresAt().before(new Date())) { throw new RuntimeException("token Expires"); } } catch (JWTVerificationException e) { throw new RuntimeException("401"); } return true; } } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
repos\springboot-demo-master\jwt\src\main\java\com\et\jwt\interceptor\AuthenticationInterceptor.java
1
请完成以下Java代码
private static ViewId createPackingHUsViewIdFromParts( @NonNull final String pickingSlotsClearingViewIdPart, final int bpartnerId, final int bpartnerLocationId, final int version) { return ViewId.ofParts( PackingHUsViewFactory.WINDOW_ID, // part 0 pickingSlotsClearingViewIdPart, // part 1 String.valueOf(Math.max(bpartnerId, 0)), // part 2 String.valueOf(Math.max(bpartnerLocationId, 0)), // part 3 String.valueOf(Math.max(version, 0)) // part 4 ); } int bpartnerId; int bpartnerLocationId; ViewId packingHUsViewId; @lombok.Builder private PackingHUsViewKey( @NonNull final String pickingSlotsClearingViewIdPart, final int bpartnerId, final int bpartnerLocationId) { this.bpartnerId = Math.max(bpartnerId, 0); this.bpartnerLocationId = Math.max(bpartnerLocationId, 0); this.packingHUsViewId = createPackingHUsViewIdFromParts( pickingSlotsClearingViewIdPart, this.bpartnerId, this.bpartnerLocationId, 0);
} private PackingHUsViewKey(@NonNull final ViewId packingHUsViewId) { Check.assumeEquals(packingHUsViewId.getWindowId(), PackingHUsViewFactory.WINDOW_ID, "Invalid packingHUsViewId: {}", packingHUsViewId); this.bpartnerId = packingHUsViewId.getPartAsInt(2); this.bpartnerLocationId = packingHUsViewId.getPartAsInt(3); this.packingHUsViewId = packingHUsViewId; } public ViewId getPickingSlotsClearingViewId() { return extractPickingSlotClearingViewId(packingHUsViewId); } public boolean isBPartnerIdMatching(final int bpartnerIdToMatch) { return (bpartnerIdToMatch <= 0 && bpartnerId <= 0) || bpartnerIdToMatch == bpartnerId; } public boolean isBPartnerLocationIdMatching(final int bpartnerLocationIdToMatch) { return (bpartnerLocationIdToMatch <= 0 && bpartnerLocationId <= 0) || bpartnerLocationIdToMatch == bpartnerLocationId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewKey.java
1
请完成以下Java代码
public Workbook createWorkbook(final boolean useStreamingImplementation) { if (useStreamingImplementation) { return new SXSSFWorkbook(); } else { return new XSSFWorkbook(); } } @Override public String getCurrentPageMarkupTag() { // see XSSFHeaderFooter javadoc return "&P"; }
@Override public String getTotalPagesMarkupTag() { // see XSSFHeaderFooter javadoc return "&N"; } @Override public int getLastRowIndex() { return SpreadsheetVersion.EXCEL2007.getLastRowIndex(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelOpenXMLFormat.java
1
请完成以下Java代码
public ErrorItemBuilder createErrorItem() { return new ErrorItemBuilder(this); } public static final class OrderItemBuilder { private final PurchaseCandidate parent; private final PurchaseOrderItemBuilder innerBuilder; private OrderItemBuilder(@NonNull final PurchaseCandidate parent) { this.parent = parent; innerBuilder = PurchaseOrderItem.builder().purchaseCandidate(parent); } public OrderItemBuilder datePromised(@NonNull final ZonedDateTime datePromised) { innerBuilder.datePromised(datePromised); return this; } public OrderItemBuilder dateOrdered(@Nullable final ZonedDateTime dateOrdered) { innerBuilder.dateOrdered(dateOrdered); return this; } public OrderItemBuilder purchasedQty(@NonNull final Quantity purchasedQty) { innerBuilder.purchasedQty(purchasedQty); return this; } public OrderItemBuilder remotePurchaseOrderId(final String remotePurchaseOrderId) { innerBuilder.remotePurchaseOrderId(remotePurchaseOrderId); return this; } public OrderItemBuilder transactionReference(final ITableRecordReference transactionReference) { innerBuilder.transactionReference(transactionReference); return this; } public OrderItemBuilder dimension(final Dimension dimension) { innerBuilder.dimension(dimension);
return this; } public PurchaseOrderItem buildAndAddToParent() { final PurchaseOrderItem newItem = innerBuilder.build(); parent.purchaseOrderItems.add(newItem); return newItem; } } public OrderItemBuilder createOrderItem() { return new OrderItemBuilder(this); } /** * Intended to be used by the persistence layer */ public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem) { final PurchaseCandidateId id = getId(); Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this); Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(), "The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}", purchaseOrderItem, this); purchaseOrderItems.add(purchaseOrderItem); } public Quantity getPurchasedQty() { return purchaseOrderItems.stream() .map(PurchaseOrderItem::getPurchasedQty) .reduce(Quantity::add) .orElseGet(() -> getQtyToPurchase().toZero()); } public List<PurchaseOrderItem> getPurchaseOrderItems() { return ImmutableList.copyOf(purchaseOrderItems); } public List<PurchaseErrorItem> getPurchaseErrorItems() { return ImmutableList.copyOf(purchaseErrorItems); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java
1
请完成以下Java代码
public void setAttribute (final java.lang.String Attribute) { set_Value (COLUMNNAME_Attribute, Attribute); } @Override public java.lang.String getAttribute() { return get_ValueAsString(COLUMNNAME_Attribute); } @Override public void setC_BPartner_Contact_QuickInput_Attributes_ID (final int C_BPartner_Contact_QuickInput_Attributes_ID) { if (C_BPartner_Contact_QuickInput_Attributes_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public int getC_BPartner_Contact_QuickInput_Attributes_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public org.compiere.model.I_C_BPartner_Contact_QuickInput getC_BPartner_Contact_QuickInput() { return get_ValueAsPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class); } @Override public void setC_BPartner_Contact_QuickInput(final org.compiere.model.I_C_BPartner_Contact_QuickInput C_BPartner_Contact_QuickInput)
{ set_ValueFromPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class, C_BPartner_Contact_QuickInput); } @Override public void setC_BPartner_Contact_QuickInput_ID (final int C_BPartner_Contact_QuickInput_ID) { if (C_BPartner_Contact_QuickInput_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, C_BPartner_Contact_QuickInput_ID); } @Override public int getC_BPartner_Contact_QuickInput_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput_Attributes.java
1
请完成以下Java代码
public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** RewardMode AD_Reference_ID=53389 */ public static final int REWARDMODE_AD_Reference_ID=53389; /** Charge = CH */ public static final String REWARDMODE_Charge = "CH"; /** Split Quantity = SQ */ public static final String REWARDMODE_SplitQuantity = "SQ"; /** Set Reward Mode. @param RewardMode Reward Mode */ public void setRewardMode (String RewardMode) { set_Value (COLUMNNAME_RewardMode, RewardMode); } /** Get Reward Mode. @return Reward Mode */ public String getRewardMode () { return (String)get_Value(COLUMNNAME_RewardMode); } /** RewardType AD_Reference_ID=53298 */ public static final int REWARDTYPE_AD_Reference_ID=53298; /** Percentage = P */ public static final String REWARDTYPE_Percentage = "P"; /** Flat Discount = F */ public static final String REWARDTYPE_FlatDiscount = "F"; /** Absolute Amount = A */ public static final String REWARDTYPE_AbsoluteAmount = "A"; /** Set Reward Type. @param RewardType Type of reward which consists of percentage discount, flat discount or absolute amount */ public void setRewardType (String RewardType) { set_Value (COLUMNNAME_RewardType, RewardType); } /** Get Reward Type. @return Type of reward which consists of percentage discount, flat discount or absolute amount
*/ public String getRewardType () { return (String)get_Value(COLUMNNAME_RewardType); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @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_M_PromotionReward.java
1