instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public Dependency addDependency(String id, Dependency dependency) {
return this.requestedDependencies.put(id, dependency);
}
/**
* Adds the given dependency.
* @param id the id
* @param builder the dependency builder
* @return the added dependency
*/
public Dependency addDependency(String id, Dependency.Builder<?> builder) {
return addDependency(id, builder.build());
}
/**
* Removes the dependency with the given id.
* @param id the id
* @return the removed dependency
*/
public Dependency removeDependency(String id) {
return this.requestedDependencies.remove(id);
}
@Override
public Map<String, Dependency> getRequestedDependencies() {
return Collections.unmodifiableMap(this.requestedDependencies);
}
@Override
public String getGroupId() {
return this.groupId;
}
/**
* Sets the group id.
* @param groupId the group id
*/
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Override
public String getArtifactId() {
return this.artifactId;
}
/**
* Sets the artifact id.
* @param artifactId the artifact id
*/
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
@Override
public String getVersion() {
return this.version;
}
/**
* Sets the version.
* @param version the version
*/
public void setVersion(String version) {
this.version = version;
}
@Override
public String getName() {
return this.name;
}
/**
* Sets the name.
* @param name the name
*/
|
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return this.description;
}
/**
* Sets the description.
* @param description the description
*/
public void setDescription(String description) {
this.description = description;
}
@Override
public String getApplicationName() {
return this.applicationName;
}
/**
* Sets the application name.
* @param applicationName the application name
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public String getPackageName() {
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return this.groupId + "." + this.artifactId;
}
return null;
}
/**
* Sets the package name.
* @param packageName the package name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
public String getBaseDirectory() {
return this.baseDirectory;
}
/**
* Sets the base directory.
* @param baseDirectory the base directory
*/
public void setBaseDirectory(String baseDirectory) {
this.baseDirectory = baseDirectory;
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java
| 1
|
请完成以下Java代码
|
public Set<GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
HashSet<GrantedAuthority> mapped = new HashSet<>(authorities.size());
for (GrantedAuthority authority : authorities) {
String authorityStr = authority.getAuthority();
if (authorityStr != null) {
mapped.add(mapAuthority(authorityStr));
}
}
if (this.defaultAuthority != null) {
mapped.add(this.defaultAuthority);
}
return mapped;
}
private GrantedAuthority mapAuthority(String name) {
if (this.convertToUpperCase) {
name = name.toUpperCase(Locale.ROOT);
}
else if (this.convertToLowerCase) {
name = name.toLowerCase(Locale.ROOT);
}
if (this.prefix.length() > 0 && !name.startsWith(this.prefix)) {
name = this.prefix + name;
}
return new SimpleGrantedAuthority(name);
}
/**
* Sets the prefix which should be added to the authority name (if it doesn't already
* exist)
* @param prefix the prefix, typically to satisfy the behaviour of an
* {@code AccessDecisionVoter}.
*/
public void setPrefix(String prefix) {
Assert.notNull(prefix, "prefix cannot be null");
this.prefix = prefix;
}
/**
* Whether to convert the authority value to upper case in the mapping.
|
* @param convertToUpperCase defaults to {@code false}
*/
public void setConvertToUpperCase(boolean convertToUpperCase) {
this.convertToUpperCase = convertToUpperCase;
}
/**
* Whether to convert the authority value to lower case in the mapping.
* @param convertToLowerCase defaults to {@code false}
*/
public void setConvertToLowerCase(boolean convertToLowerCase) {
this.convertToLowerCase = convertToLowerCase;
}
/**
* Sets a default authority to be assigned to all users
* @param authority the name of the authority to be assigned to all users.
*/
public void setDefaultAuthority(String authority) {
Assert.hasText(authority, "The authority name cannot be set to an empty value");
this.defaultAuthority = new SimpleGrantedAuthority(authority);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAuthorityMapper.java
| 1
|
请完成以下Java代码
|
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Warehouse_Dest_ID (final int M_Warehouse_Dest_ID)
{
if (M_Warehouse_Dest_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, M_Warehouse_Dest_ID);
}
@Override
public int getM_Warehouse_Dest_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_Dest_ID);
}
@Override
public void setPackageNetTotal (final @Nullable BigDecimal PackageNetTotal)
{
set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal);
}
@Override
public BigDecimal getPackageNetTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPackageWeight (final @Nullable BigDecimal PackageWeight)
{
set_Value (COLUMNNAME_PackageWeight, PackageWeight);
}
@Override
public BigDecimal getPackageWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setReceivedInfo (final @Nullable java.lang.String ReceivedInfo)
{
set_Value (COLUMNNAME_ReceivedInfo, ReceivedInfo);
}
@Override
public java.lang.String getReceivedInfo()
{
return get_ValueAsString(COLUMNNAME_ReceivedInfo);
}
@Override
public void setShipDate (final @Nullable java.sql.Timestamp ShipDate)
{
set_Value (COLUMNNAME_ShipDate, ShipDate);
}
@Override
public java.sql.Timestamp getShipDate()
|
{
return get_ValueAsTimestamp(COLUMNNAME_ShipDate);
}
@Override
public void setTrackingInfo (final @Nullable java.lang.String TrackingInfo)
{
set_Value (COLUMNNAME_TrackingInfo, TrackingInfo);
}
@Override
public java.lang.String getTrackingInfo()
{
return get_ValueAsString(COLUMNNAME_TrackingInfo);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Package.java
| 1
|
请完成以下Java代码
|
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
@Override
|
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getBehaviorClass() {
return behaviorClass;
}
public void setBehaviorClass(String behaviorClass) {
this.behaviorClass = behaviorClass;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiActivityEventImpl.java
| 1
|
请完成以下Spring Boot application配置
|
## Dubbo 服务提供者配置
spring.dubbo.application.name=provider
spring.dubbo.registry.address=zookeeper://127.0.0.1:2181
spring.dubbo.protocol.name=dubbo
spring.dub
|
bo.protocol.port=20880
spring.dubbo.scan=org.spring.springboot.dubbo
|
repos\springboot-learning-example-master\springboot-dubbo-server\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(fileItemReader())
.writer(list -> list.forEach(System.out::println))
.build();
}
private ItemReader<TestData> fileItemReader() {
FlatFileItemReader<TestData> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("file")); // 设置文件资源地址
reader.setLinesToSkip(1); // 忽略第一行
// AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取,
// 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
// 设置属性名,类似于表头
tokenizer.setNames("id", "field1", "field2", "field3");
|
// 将每行数据转换为TestData对象
DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>();
mapper.setLineTokenizer(tokenizer);
// 设置映射方式
mapper.setFieldSetMapper(fieldSet -> {
TestData data = new TestData();
data.setId(fieldSet.readInt("id"));
data.setField1(fieldSet.readString("field1"));
data.setField2(fieldSet.readString("field2"));
data.setField3(fieldSet.readString("field3"));
return data;
});
reader.setLineMapper(mapper);
return reader;
}
}
|
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\FileItemReaderDemo.java
| 1
|
请完成以下Java代码
|
public void setValidationType (java.lang.String ValidationType)
{
set_Value (COLUMNNAME_ValidationType, ValidationType);
}
/** Get Validation type.
@return Different method of validating data
*/
@Override
public java.lang.String getValidationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValidationType);
}
/** Set Value Format.
@param VFormat
Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
|
@Override
public void setVFormat (java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public java.lang.String getVFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_VFormat);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java
| 1
|
请完成以下Java代码
|
public Optional<I_AD_Archive> getLastArchiveRecord(
@NonNull final TableRecordReference reference)
{
final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class);
final List<I_AD_Archive> lastArchives = archiveDAO.retrieveLastArchives(Env.getCtx(), reference, QueryLimit.ONE);
if (lastArchives.isEmpty())
{
return Optional.empty();
}
else
{
return Optional.of(lastArchives.get(0));
}
}
@Override
public Optional<Resource> getLastArchiveBinaryData(
@NonNull final TableRecordReference reference)
{
return getLastArchive(reference).map(AdArchive::getArchiveDataAsResource);
|
}
@Override
public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId)
{
archiveDAO.updatePrintedRecords(ids, userId);
}
private AdArchive toAdArchive(final I_AD_Archive record)
{
return AdArchive.builder()
.id(ArchiveId.ofRepoId(record.getAD_Archive_ID()))
.archiveData(getBinaryData(record))
.contentType(getContentType(record))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveBL.java
| 1
|
请完成以下Java代码
|
public class X_DIM_Dimension_Type extends org.compiere.model.PO implements I_DIM_Dimension_Type, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1963103620L;
/** Standard Constructor */
public X_DIM_Dimension_Type (Properties ctx, int DIM_Dimension_Type_ID, String trxName)
{
super (ctx, DIM_Dimension_Type_ID, trxName);
/** if (DIM_Dimension_Type_ID == 0)
{
setDIM_Dimension_Type_ID (0);
setInternalName (null);
} */
}
/** Load Constructor */
public X_DIM_Dimension_Type (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
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);
}
/** Set Dimensionstyp.
@param DIM_Dimension_Type_ID Dimensionstyp */
@Override
public void setDIM_Dimension_Type_ID (int DIM_Dimension_Type_ID)
{
if (DIM_Dimension_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, Integer.valueOf(DIM_Dimension_Type_ID));
}
/** Get Dimensionstyp.
@return Dimensionstyp */
@Override
public int getDIM_Dimension_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Type_ID);
if (ii == null)
|
return 0;
return ii.intValue();
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Type.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractMetadataController {
protected final InitializrMetadataProvider metadataProvider;
private Boolean forceSsl;
protected AbstractMetadataController(InitializrMetadataProvider metadataProvider) {
this.metadataProvider = metadataProvider;
}
/**
* Generate a full URL of the service, mostly for use in templates.
* @return the app URL
* @see io.spring.initializr.metadata.InitializrConfiguration.Env#isForceSsl()
*/
protected String generateAppUrl() {
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping();
if (isForceSsl()) {
|
builder.scheme("https");
}
return builder.build().toString();
}
protected String createUniqueId(String content) {
StringBuilder builder = new StringBuilder();
DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8), builder);
return builder.toString();
}
private boolean isForceSsl() {
if (this.forceSsl == null) {
this.forceSsl = this.metadataProvider.get().getConfiguration().getEnv().isForceSsl();
}
return this.forceSsl;
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\controller\AbstractMetadataController.java
| 2
|
请完成以下Java代码
|
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShelfLifeMinDays (final int ShelfLifeMinDays)
{
set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays);
}
@Override
public int getShelfLifeMinDays()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays);
}
@Override
public void setShelfLifeMinPct (final int ShelfLifeMinPct)
{
set_Value (COLUMNNAME_ShelfLifeMinPct, ShelfLifeMinPct);
}
@Override
public int getShelfLifeMinPct()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setUsedForCustomer (final boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer);
}
@Override
public boolean isUsedForCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer);
}
@Override
public void setUsedForVendor (final boolean UsedForVendor)
{
|
set_Value (COLUMNNAME_UsedForVendor, UsedForVendor);
}
@Override
public boolean isUsedForVendor()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForVendor);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java
| 1
|
请完成以下Java代码
|
public static class ResponseResult {
private int resultCode;
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
}
private Fonts fonts;
private Background background;
@JsonProperty("RequestResult")
private RequestResult requestResult;
@JsonProperty("ResponseResult")
private ResponseResult responseResult;
public Fonts getFonts() {
return fonts;
}
public void setFonts(Fonts fonts) {
this.fonts = fonts;
|
}
public Background getBackground() {
return background;
}
public void setBackground(Background background) {
this.background = background;
}
public RequestResult getRequestResult() {
return requestResult;
}
public void setRequestResult(RequestResult requestResult) {
this.requestResult = requestResult;
}
public ResponseResult getResponseResult() {
return responseResult;
}
public void setResponseResult(ResponseResult responseResult) {
this.responseResult = responseResult;
}
}
|
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\ini\MyConfiguration.java
| 1
|
请完成以下Java代码
|
public MobileAppBundleInfo findMobileAppBundleInfoById(TenantId tenantId, MobileAppBundleId mobileAppIdBundle) {
log.trace("Executing findMobileAppBundleInfoById [{}] [{}]", tenantId, mobileAppIdBundle);
MobileAppBundleInfo mobileAppBundleInfo = mobileAppBundleDao.findInfoById(tenantId, mobileAppIdBundle);
if (mobileAppBundleInfo != null) {
fetchOauth2Clients(mobileAppBundleInfo);
}
return mobileAppBundleInfo;
}
@Override
public MobileAppBundle findMobileAppBundleByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) {
log.trace("Executing findMobileAppBundleByPkgNameAndPlatform, tenantId [{}], pkgName [{}], platform [{}]", tenantId, pkgName, platform);
checkNotNull(platform, PLATFORM_TYPE_IS_REQUIRED);
return mobileAppBundleDao.findByPkgNameAndPlatform(tenantId, pkgName, platform);
}
@Override
public void deleteMobileAppBundleById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) {
log.trace("Executing deleteMobileAppBundleById [{}]", mobileAppBundleId.getId());
mobileAppBundleDao.removeById(tenantId, mobileAppBundleId.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(mobileAppBundleId).build());
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteMobileAppsByTenantId, tenantId [{}]", tenantId);
mobileAppBundleDao.deleteByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findMobileAppBundleById(tenantId, new MobileAppBundleId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(mobileAppBundleDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
|
@Override
@Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteMobileAppBundleById(tenantId, (MobileAppBundleId) id);
}
@Override
public EntityType getEntityType() {
return EntityType.MOBILE_APP_BUNDLE;
}
private void fetchOauth2Clients(MobileAppBundleInfo mobileAppBundleInfo) {
List<OAuth2ClientInfo> clients = oauth2ClientDao.findByMobileAppBundleId(mobileAppBundleInfo.getUuidId()).stream()
.map(OAuth2ClientInfo::new)
.sorted(Comparator.comparing(OAuth2ClientInfo::getTitle))
.collect(Collectors.toList());
mobileAppBundleInfo.setOauth2ClientInfos(clients);
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppBundleServiceImpl.java
| 1
|
请完成以下Java代码
|
private static OrgId extractOrgId(final List<I_C_Invoice_Acct> records)
{
return records.stream()
.map(record -> OrgId.ofRepoId(record.getAD_Org_ID()))
.collect(GuavaCollectors.uniqueElementOrThrow(orgIds -> new AdempiereException("Unique org expected but got " + orgIds)));
}
private static InvoiceAcctRule toRule(final I_C_Invoice_Acct record)
{
return InvoiceAcctRule.builder()
.matcher(toRuleMatcher(record))
.elementValueId(ElementValueId.ofRepoId(record.getC_ElementValue_ID()))
.build();
}
private static InvoiceAcctRuleMatcher toRuleMatcher(final I_C_Invoice_Acct record)
{
return InvoiceAcctRuleMatcher.builder()
.invoiceAndLineId(InvoiceAndLineId.ofRepoIdOrNull(record.getC_Invoice_ID(), record.getC_InvoiceLine_ID()))
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.accountConceptualName(AccountConceptualName.ofNullableString(record.getAccountName()))
.build();
}
public void save(@NonNull final InvoiceAcct invoiceAcct)
{
//
// Delete previous records
queryBL.createQueryBuilder(I_C_Invoice_Acct.class)
.addEqualsFilter(I_C_Invoice_Acct.COLUMNNAME_C_Invoice_ID, invoiceAcct.getInvoiceId())
.create()
.delete();
//
// Save new
for (final InvoiceAcctRule rule : invoiceAcct.getRulesOrdered())
{
final I_C_Invoice_Acct record = InterfaceWrapperHelper.newInstance(I_C_Invoice_Acct.class);
record.setC_Invoice_ID(invoiceAcct.getInvoiceId().getRepoId());
record.setAD_Org_ID(invoiceAcct.getOrgId().getRepoId());
|
updateRecordFromRule(record, rule);
InterfaceWrapperHelper.save(record);
}
}
private void updateRecordFromRule(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRule from)
{
updateRecordFromRuleMatcher(record, from.getMatcher());
record.setC_ElementValue_ID(from.getElementValueId().getRepoId());
}
private void updateRecordFromRuleMatcher(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRuleMatcher from)
{
record.setC_AcctSchema_ID(from.getAcctSchemaId().getRepoId());
record.setC_InvoiceLine_ID(InvoiceAndLineId.toRepoId(from.getInvoiceAndLineId()));
record.setAccountName(from.getAccountConceptualName() != null ? from.getAccountConceptualName().getAsString() : null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\acct\InvoiceAcctRepository.java
| 1
|
请完成以下Java代码
|
private boolean updateTopLevelHU(@NonNull final HuId topLevelHUId)
{
final ClientAndOrgId clientAndOrgId = handlingUnitsDAO.getClientAndOrgId(topLevelHUId);
final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(Env.getCtx(), clientAndOrgId);
final IAttributeStorage huAttributes = getHUAttributes(topLevelHUId, huContext);
return updateRecursive(huAttributes);
}
private boolean updateRecursive(@NonNull final IAttributeStorage huAttributes)
{
boolean updated = update(huAttributes);
for (final IAttributeStorage childHUAttributes : huAttributes.getChildAttributeStorages(true))
{
if (updateRecursive(childHUAttributes))
{
updated = true;
}
}
return updated;
}
private boolean update(@NonNull final IAttributeStorage huAttributes)
{
if (!huAttributes.hasAttribute(AttributeConstants.ATTR_MonthsUntilExpiry))
{
return false;
}
final OptionalInt monthsUntilExpiry = computeMonthsUntilExpiry(huAttributes, today);
final int monthsUntilExpiryOld = huAttributes.getValueAsInt(AttributeConstants.ATTR_MonthsUntilExpiry);
if (monthsUntilExpiry.orElse(0) == monthsUntilExpiryOld)
{
return false;
}
huAttributes.setSaveOnChange(true);
if (monthsUntilExpiry.isPresent())
{
huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, monthsUntilExpiry.getAsInt());
}
|
else
{
huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, null);
}
huAttributes.saveChangesIfNeeded();
return true;
}
static OptionalInt computeMonthsUntilExpiry(@NonNull final IAttributeStorage huAttributes, @NonNull final LocalDate today)
{
final LocalDate bestBeforeDate = huAttributes.getValueAsLocalDate(AttributeConstants.ATTR_BestBeforeDate);
if (bestBeforeDate == null)
{
return OptionalInt.empty();
}
final int monthsUntilExpiry = (int)ChronoUnit.MONTHS.between(today, bestBeforeDate);
return OptionalInt.of(monthsUntilExpiry);
}
private IAttributeStorage getHUAttributes(@NonNull final HuId huId, @NonNull final IHUContext huContext)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
return huContext
.getHUAttributeStorageFactory()
.getAttributeStorage(hu);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\UpdateMonthsUntilExpiryCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long getReadCountByUserId(String id) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
return sysAnnouncementSendMapper.getReadCountByUserId(id, sysUser.getId());
}
/**
* 根据多个id批量删除已阅读的数量
*
* @param ids
*/
@Override
public void deleteBatchByIds(String ids) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//根据用户id和阅读表的id获取所有阅读的数据
List<String> sendIds = sysAnnouncementSendMapper.getReadAnnSendByUserId(Arrays.asList(ids.split(SymbolConstant.COMMA)),sysUser.getId());
if(CollectionUtil.isNotEmpty(sendIds)){
this.removeByIds(sendIds);
}
}
/**
|
* 根据busId更新阅读状态
* @param busId
* @param busType
*/
@Override
public void updateReadFlagByBusId(String busId, String busType) {
SysAnnouncement announcement = sysAnnouncementMapper.selectOne(new QueryWrapper<SysAnnouncement>().eq("bus_type",busType).eq("bus_id",busId));
if(oConvertUtils.isNotEmpty(announcement)){
LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
String userId = sysUser.getId();
LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
updateWrapper.eq(SysAnnouncementSend::getAnntId,announcement.getId());
updateWrapper.eq(SysAnnouncementSend::getUserId,userId);
SysAnnouncementSend announcementSend = new SysAnnouncementSend();
sysAnnouncementSendMapper.update(announcementSend, updateWrapper);
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysAnnouncementSendServiceImpl.java
| 2
|
请完成以下Java代码
|
protected List<String> getTenantsOfUser(ProcessEngine engine, String userId) {
List<Tenant> tenants = engine.getIdentityService().createTenantQuery()
.userMember(userId)
.includingGroupsOfUser(true)
.list();
List<String> tenantIds = new ArrayList<String>();
for(Tenant tenant : tenants) {
tenantIds.add(tenant.getId());
}
return tenantIds;
}
protected void clearAuthentication(ProcessEngine engine) {
engine.getIdentityService().clearAuthentication();
}
protected boolean requiresEngineAuthentication(String requestUrl) {
for (Pattern whiteListedUrlPattern : WHITE_LISTED_URL_PATTERNS) {
Matcher matcher = whiteListedUrlPattern.matcher(requestUrl);
if (matcher.matches()) {
return false;
}
}
return true;
}
|
/**
* May not return null
*/
protected String extractEngineName(String requestUrl) {
Matcher matcher = ENGINE_REQUEST_URL_PATTERN.matcher(requestUrl);
if (matcher.find()) {
return matcher.group(1);
} else {
// any request that does not match a specific engine and is not an /engine request
// is mapped to the default engine
return DEFAULT_ENGINE_NAME;
}
}
protected ProcessEngine getAddressedEngine(String engineName) {
return EngineUtil.lookupProcessEngine(engineName);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\security\auth\ProcessEngineAuthenticationFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PPOrderCandidateCreatedEventHandler extends PPOrderCandidateEventHandler implements MaterialEventHandler<PPOrderCandidateCreatedEvent>
{
public PPOrderCandidateCreatedEventHandler(
@NonNull final CandidateChangeService candidateChangeService,
@NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval)
{
super(candidateChangeService, candidateRepositoryRetrieval);
}
@Override
public Collection<Class<? extends PPOrderCandidateCreatedEvent>> getHandledEventType()
{
return ImmutableList.of(PPOrderCandidateCreatedEvent.class);
}
@Override
public void handleEvent(@NonNull final PPOrderCandidateCreatedEvent event)
{
handleMaterialDispoProductionDetail(event);
}
private void handleMaterialDispoProductionDetail(@NonNull final PPOrderCandidateCreatedEvent event)
{
final MaterialDispoGroupId groupId = event.getPpOrderCandidate().getPpOrderData().getMaterialDispoGroupId();
final SimulatedQueryQualifier simulatedQueryQualifier = event.getPpOrderCandidate().isSimulated()
? SimulatedQueryQualifier.ONLY_SIMULATED
: SimulatedQueryQualifier.EXCLUDE_SIMULATED;
final CandidatesQuery query = CandidatesQuery.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PRODUCTION)
|
.groupId(groupId)
.materialDescriptorQuery(PPOrderHandlerUtils.createMaterialDescriptorQuery(event.getPpOrderCandidate().getPpOrderData().getProductDescriptor()))
.simulatedQueryQualifier(simulatedQueryQualifier)
.build();
final Candidate headerCandidate = createHeaderCandidate(event, query);
createLineCandidates(event, groupId, headerCandidate);
}
@Override
protected boolean isMaterialTrackingDeferredForThisEventType()
{
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ppordercandidate\PPOrderCandidateCreatedEventHandler.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setCancelRequestId(String cancelRequestId)
{
this.cancelRequestId = cancelRequestId;
}
public CancelRequest cancelRequestState(String cancelRequestState)
{
this.cancelRequestState = cancelRequestState;
return this;
}
/**
* The current stage or condition of the cancellation request. This field is returned for each cancellation request. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:CancelRequestStateEnum'>eBay API documentation</a>
*
* @return cancelRequestState
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The current stage or condition of the cancellation request. This field is returned for each cancellation request. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:CancelRequestStateEnum'>eBay API documentation</a>")
public String getCancelRequestState()
{
return cancelRequestState;
}
public void setCancelRequestState(String cancelRequestState)
{
this.cancelRequestState = cancelRequestState;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
CancelRequest cancelRequest = (CancelRequest)o;
return Objects.equals(this.cancelCompletedDate, cancelRequest.cancelCompletedDate) &&
Objects.equals(this.cancelInitiator, cancelRequest.cancelInitiator) &&
Objects.equals(this.cancelReason, cancelRequest.cancelReason) &&
|
Objects.equals(this.cancelRequestedDate, cancelRequest.cancelRequestedDate) &&
Objects.equals(this.cancelRequestId, cancelRequest.cancelRequestId) &&
Objects.equals(this.cancelRequestState, cancelRequest.cancelRequestState);
}
@Override
public int hashCode()
{
return Objects.hash(cancelCompletedDate, cancelInitiator, cancelReason, cancelRequestedDate, cancelRequestId, cancelRequestState);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class CancelRequest {\n");
sb.append(" cancelCompletedDate: ").append(toIndentedString(cancelCompletedDate)).append("\n");
sb.append(" cancelInitiator: ").append(toIndentedString(cancelInitiator)).append("\n");
sb.append(" cancelReason: ").append(toIndentedString(cancelReason)).append("\n");
sb.append(" cancelRequestedDate: ").append(toIndentedString(cancelRequestedDate)).append("\n");
sb.append(" cancelRequestId: ").append(toIndentedString(cancelRequestId)).append("\n");
sb.append(" cancelRequestState: ").append(toIndentedString(cancelRequestState)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\CancelRequest.java
| 2
|
请完成以下Java代码
|
public ImmutableRowsIndex<T> removingRowId(@NonNull final DocumentId rowIdToRemove)
{
if (!rowsById.containsKey(rowIdToRemove))
{
return this;
}
final ArrayList<T> resultRows = new ArrayList<>(rowIds.size());
for (final DocumentId rowId : this.rowIds)
{
if (!rowId.equals(rowIdToRemove))
{
resultRows.add(rowsById.get(rowId));
}
}
return new ImmutableRowsIndex<>(this.initialRowIds, resultRows);
}
public ImmutableRowsIndex<T> removingRowIds(@NonNull final DocumentIdsSelection rowIdsToRemove)
{
if (rowIdsToRemove.isEmpty())
{
return this;
}
else if (rowIdsToRemove.isAll())
{
if (rowIds.isEmpty())
{
return this; // already empty, nothing to remove
}
return new ImmutableRowsIndex<>(this.initialRowIds, ImmutableList.of());
}
else
{
final int sizeBeforeRemove = rowIds.size();
final ArrayList<T> rowsAfterRemove = new ArrayList<>(sizeBeforeRemove);
for (final DocumentId rowId : this.rowIds)
{
if (!rowIdsToRemove.contains(rowId))
{
rowsAfterRemove.add(rowsById.get(rowId));
}
}
if (rowsAfterRemove.size() == sizeBeforeRemove)
{
return this; // nothing was deleted
}
return new ImmutableRowsIndex<>(this.initialRowIds, rowsAfterRemove);
}
}
public ImmutableRowsIndex<T> removingIf(@NonNull final Predicate<T> predicate)
{
final int sizeBeforeRemove = rowIds.size();
final ArrayList<T> rowsAfterRemove = new ArrayList<>(sizeBeforeRemove);
for (final DocumentId rowId : this.rowIds)
{
final T row = rowsById.get(rowId);
final boolean remove = predicate.test(row);
if (!remove)
{
|
rowsAfterRemove.add(row);
}
}
if (rowsAfterRemove.size() == sizeBeforeRemove)
{
return this; // nothing was deleted
}
return new ImmutableRowsIndex<>(this.initialRowIds, rowsAfterRemove);
}
public <ID extends RepoIdAware> ImmutableSet<ID> getRecordIdsToRefresh(
@NonNull final DocumentIdsSelection rowIds,
@NonNull final Function<DocumentId, ID> idMapper)
{
if (rowIds.isEmpty())
{
return ImmutableSet.of();
}
else if (rowIds.isAll())
{
return Stream.concat(this.rowIds.stream(), this.initialRowIds.stream())
.map(idMapper)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return rowIds.stream()
.filter(this::isRelevantForRefreshing)
.map(idMapper)
.collect(ImmutableSet.toImmutableSet());
}
}
public Stream<T> stream() {return rowsById.values().stream();}
public Stream<T> stream(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate);}
public long count(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate).count();}
public boolean anyMatch(final Predicate<T> predicate) {return rowsById.values().stream().anyMatch(predicate);}
public List<T> list() {return rowIds.stream().map(rowsById::get).collect(ImmutableList.toImmutableList());}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\ImmutableRowsIndex.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
|
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\inheritancevscomposition\composition\Address.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WEBUI_KPI_TestQuery extends JavaProcess implements IProcessPrecondition
{
private final IESSystem esSystem = Services.get(IESSystem.class);
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
private final KPIRepository kpisRepo = SpringContextHolder.instance.getBean(KPIRepository.class);
private final IUserRolePermissionsDAO userRolePermissionsDAO = Services.get(IUserRolePermissionsDAO.class);
private final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
@Param(parameterName = "DateFrom")
private Instant p_DateFrom;
@Param(parameterName = "DateTo")
private Instant p_DateTo;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws JsonProcessingException
{
final KPIId kpiId = KPIId.ofRepoId(getRecord_ID());
kpisRepo.invalidateCache();
final KPI kpi = kpisRepo.getKPI(kpiId);
final KPIDataResult kpiData = KPIDataProvider.builder()
|
.kpiRepository(kpisRepo)
.esSystem(esSystem)
.sysConfigBL(sysConfigBL)
.kpiPermissionsProvider(new KPIPermissionsProvider(userRolePermissionsDAO))
.build()
.getKPIData(KPIDataRequest.builder()
.kpiId(kpiId)
.timeRangeDefaults(kpi.getTimeRangeDefaults())
.context(KPIDataContext.ofEnvProperties(getCtx())
.toBuilder()
.from(p_DateFrom)
.to(p_DateTo)
.build())
.build());
final String jsonData = jsonObjectMapper.writeValueAsString(kpiData);
log.info("jsonData:\n {}", jsonData);
return jsonData;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\process\WEBUI_KPI_TestQuery.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private boolean isMaterialReturns()
{
if (_materialReturns == null)
{
final I_M_InOut inout = getInOut();
_materialReturns = MovementType.isMaterialReturn(inout.getMovementType());
}
return _materialReturns;
}
private ProductId getProductId()
{
final I_M_InOutLine inoutLine = getInOutLine();
final ProductId inoutLineProductId = ProductId.ofRepoId(inoutLine.getM_Product_ID());
//
// Make sure M_Product_ID matches
if (getType().isMaterial())
{
final I_C_InvoiceLine invoiceLine = getInvoiceLine();
final ProductId invoiceLineProductId = ProductId.ofRepoId(invoiceLine.getM_Product_ID());
if (!ProductId.equals(invoiceLineProductId, inoutLineProductId))
{
final String invoiceProductName = productBL.getProductValueAndName(invoiceLineProductId);
final String inoutProductName = productBL.getProductValueAndName(inoutLineProductId);
throw new AdempiereException("@Invalid@ @M_Product_ID@"
+ "\n @C_InvoiceLine_ID@: " + invoiceLine + ", @M_Product_ID@=" + invoiceProductName
+ "\n @M_InOutLine_ID@: " + inoutLine + ", @M_Product_ID@=" + inoutProductName);
}
|
}
return inoutLineProductId;
}
private boolean isSOTrx()
{
final I_C_Invoice invoice = getInvoice();
final I_M_InOut inout = getInOut();
final boolean invoiceIsSOTrx = invoice.isSOTrx();
final boolean inoutIsSOTrx = inout.isSOTrx();
//
// Make sure IsSOTrx matches
if (invoiceIsSOTrx != inoutIsSOTrx)
{
throw new AdempiereException("@Invalid @IsSOTrx@"
+ "\n @C_Invoice_ID@: " + invoice + ", @IsSOTrx@=" + invoiceIsSOTrx
+ "\n @M_InOut_ID@: " + inout + ", @IsSOTrx@=" + inoutIsSOTrx);
}
return inoutIsSOTrx;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvBuilder.java
| 2
|
请完成以下Java代码
|
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
|
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Expense Report.
@param S_TimeExpense_ID
Time and Expense Report
*/
public void setS_TimeExpense_ID (int S_TimeExpense_ID)
{
if (S_TimeExpense_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, Integer.valueOf(S_TimeExpense_ID));
}
/** Get Expense Report.
@return Time and Expense Report
*/
public int getS_TimeExpense_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpense_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeExpense.java
| 1
|
请完成以下Java代码
|
public void setQty(@NonNull final BigDecimal qtyInHUsUOM)
{
invoiceLine.setQtyEntered(qtyInHUsUOM);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyInvoiced = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qtyInHUsUOM);
invoiceLine.setQtyInvoiced(qtyInvoiced);
}
@Override
public BigDecimal getQty()
{
return invoiceLine.getQtyEntered();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
//
// Check the invoice line first
final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID();
if (invoiceLine_PIItemProductId > 0)
{
return invoiceLine_PIItemProductId;
}
//
// Check order line
final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class);
if (orderline == null)
{
//
// C_OrderLine not found (i.e Manual Invoice)
return -1;
}
return orderline.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
|
@Override
public BigDecimal getQtyTU()
{
return invoiceLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
invoiceLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ListenableFuture<Void> deleteLatestFromEntityView(EntityView entityView, List<String> keys, User user) {
EntityViewId entityId = entityView.getId();
SettableFuture<Void> resultFuture = SettableFuture.create();
tsSubService.deleteTimeseries(TimeseriesDeleteRequest.builder()
.tenantId(entityView.getTenantId())
.entityId(entityId)
.keys(keys)
.callback(new FutureCallback<>() {
@Override
public void onSuccess(@Nullable List<String> result) {
try {
logTimeseriesDeleted(entityView.getTenantId(), user, entityId, result, null);
} catch (ThingsboardException e) {
log.error("Failed to log timeseries delete", e);
}
resultFuture.set(null);
}
@Override
public void onFailure(Throwable t) {
try {
logTimeseriesDeleted(entityView.getTenantId(), user, entityId, Optional.ofNullable(keys).orElse(Collections.emptyList()), t);
} catch (ThingsboardException e) {
log.error("Failed to log timeseries delete", e);
}
resultFuture.setException(t);
}
})
.build());
return resultFuture;
}
|
private void logAttributesUpdated(TenantId tenantId, User user, EntityId entityId, AttributeScope scope, List<AttributeKvEntry> attributes, Throwable e) throws ThingsboardException {
logEntityActionService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_UPDATED, user, toException(e), scope, attributes);
}
private void logAttributesDeleted(TenantId tenantId, User user, EntityId entityId, AttributeScope scope, List<String> keys, Throwable e) throws ThingsboardException {
logEntityActionService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys);
}
private void logTimeseriesDeleted(TenantId tenantId, User user, EntityId entityId, List<String> keys, Throwable e) throws ThingsboardException {
logEntityActionService.logEntityAction(tenantId, entityId, ActionType.TIMESERIES_DELETED, user, toException(e), keys);
}
public static Exception toException(Throwable error) {
return error != null ? (Exception.class.isInstance(error) ? (Exception) error : new Exception(error)) : null;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\entityview\DefaultTbEntityViewService.java
| 2
|
请完成以下Java代码
|
public void syncTriggerDocumentToCommissionInstance(
@NonNull final CommissionTriggerDocument commissionTriggerDocument,
final boolean candidateDeleted)
{
final Optional<CommissionInstance> instance = commissionInstanceRepository.getByDocumentId(commissionTriggerDocument.getId());
if (!instance.isPresent())
{
createNewInstance(commissionTriggerDocument, candidateDeleted);
return;
}
updateInstance(commissionTriggerDocument, candidateDeleted, instance.get());
}
private void createNewInstance(
@NonNull final CommissionTriggerDocument commissionTriggerDocument,
final boolean candidateDeleted)
{
final int repoId = commissionTriggerDocument.getId().getRepoIdAware().getRepoId(); // will be used in logging
if (candidateDeleted)
{
logger.debug("commissionTriggerDocument with id={} has no instances and candidateDeleted=true; -> doing nothing", repoId);
return; // nothing to do
}
// initially create commission data for the given trigger document
// createdInstance might be not present, if there are no matching contracts and/or settings
final Optional<CommissionInstance> createdInstance = commissionInstanceService.createCommissionInstance(commissionTriggerDocument);
if (createdInstance.isPresent())
{
commissionInstanceRepository.save(createdInstance.get());
}
else
{
logger.debug("No existing or newly-created instances for the commissionTriggerDocument with id={}; -> doing nothing", repoId);
}
}
private void updateInstance(
|
@NonNull final CommissionTriggerDocument commissionTriggerDocument,
final boolean candidateDeleted,
@NonNull final CommissionInstance instance)
{
try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_Commission_Instance.Table_Name, instance.getId()))
{
final int repoId = commissionTriggerDocument.getId().getRepoIdAware().getRepoId(); // will be used in logging
// update existing commission data
logger.debug("commissionTriggerDocument with id={} has an instance (candidateDeleted={}); -> updating its commission shares;",
repoId, candidateDeleted);
final CommissionTrigger trigger = commissionTriggerFactory.createForDocument(commissionTriggerDocument, candidateDeleted);
final CommissionTriggerData newTriggerData = trigger.getCommissionTriggerData();
final CommissionTriggerChange change = CommissionTriggerChange.builder()
.instanceToUpdate(instance)
.newCommissionTriggerData(newTriggerData)
.build();
commissionAlgorithmInvoker.updateCommissionShares(change);
instance.setCurrentTriggerData(newTriggerData);
if (candidateDeleted)
{
commissionInstanceRepository.save(instance);
return; // we are done
}
logger.debug("creating missing commission shares as needed;", repoId, candidateDeleted);
commissionInstanceService.createAndAddMissingShares(instance, commissionTriggerDocument);
commissionInstanceRepository.save(instance);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\commissiontrigger\CommissionTriggerDocumentService.java
| 1
|
请完成以下Java代码
|
public int getMounted() {
return this.mounted;
}
public long getQueued() {
return this.queued;
}
public int getParallelism() {
return this.parallelism;
}
public int getPoolSize() {
return this.poolSize;
}
}
/**
* Memory information.
*
* @since 3.4.0
*/
public static class MemoryInfo {
private static final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
private static final List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory
.getGarbageCollectorMXBeans();
private final MemoryUsageInfo heap;
private final MemoryUsageInfo nonHeap;
private final List<GarbageCollectorInfo> garbageCollectors;
MemoryInfo() {
this.heap = new MemoryUsageInfo(memoryMXBean.getHeapMemoryUsage());
this.nonHeap = new MemoryUsageInfo(memoryMXBean.getNonHeapMemoryUsage());
this.garbageCollectors = garbageCollectorMXBeans.stream().map(GarbageCollectorInfo::new).toList();
}
public MemoryUsageInfo getHeap() {
return this.heap;
}
public MemoryUsageInfo getNonHeap() {
return this.nonHeap;
}
/**
* Garbage Collector information for the process. This list provides details about
* the currently used GC algorithms selected by the user or JVM ergonomics. It
* might not be trivial to know the used GC algorithms since that usually depends
* on the {@link Runtime#availableProcessors()} (see:
* {@link ProcessInfo#getCpus()}) and the available memory (see:
* {@link MemoryUsageInfo}).
* @return {@link List} of {@link GarbageCollectorInfo}.
* @since 3.5.0
|
*/
public List<GarbageCollectorInfo> getGarbageCollectors() {
return this.garbageCollectors;
}
public static class MemoryUsageInfo {
private final MemoryUsage memoryUsage;
MemoryUsageInfo(MemoryUsage memoryUsage) {
this.memoryUsage = memoryUsage;
}
public long getInit() {
return this.memoryUsage.getInit();
}
public long getUsed() {
return this.memoryUsage.getUsed();
}
public long getCommitted() {
return this.memoryUsage.getCommitted();
}
public long getMax() {
return this.memoryUsage.getMax();
}
}
/**
* Garbage collection information.
*
* @since 3.5.0
*/
public static class GarbageCollectorInfo {
private final String name;
private final long collectionCount;
GarbageCollectorInfo(GarbageCollectorMXBean garbageCollectorMXBean) {
this.name = garbageCollectorMXBean.getName();
this.collectionCount = garbageCollectorMXBean.getCollectionCount();
}
public String getName() {
return this.name;
}
public long getCollectionCount() {
return this.collectionCount;
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\ProcessInfo.java
| 1
|
请完成以下Java代码
|
public I_C_AcctSchema getC_AcctSchema() throws RuntimeException
{
return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name)
.getPO(getC_AcctSchema_ID(), get_TrxName()); }
/** Set Accounting Schema.
@param C_AcctSchema_ID
Rules for accounting
*/
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_Value (COLUMNNAME_C_AcctSchema_ID, null);
else
set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
|
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Acct.java
| 1
|
请完成以下Java代码
|
public void setUserLevel (java.lang.String UserLevel)
{
set_Value (COLUMNNAME_UserLevel, UserLevel);
}
/** Get Nutzer-Ebene.
@return System Client Organization
*/
@Override
public java.lang.String getUserLevel ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserLevel);
}
/** Set Is webui role.
@param WEBUI_Role Is webui role */
@Override
public void setWEBUI_Role (boolean WEBUI_Role)
{
set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role));
}
/** Get Is webui role.
@return Is webui role */
@Override
public boolean isWEBUI_Role ()
{
|
Object oo = get_Value(COLUMNNAME_WEBUI_Role);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers)
{
set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers);
}
@Override
public boolean isAllowPasswordChangeForOthers()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SimpleBook {
@Id
@GeneratedValue
private Long id;
private String title;
public SimpleBook() {
}
public SimpleBook(String title) {
this.title = title;
}
public void setId(Long id) {
|
this.id = id;
}
public Long getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\insertableonly\simple\SimpleBook.java
| 2
|
请完成以下Java代码
|
public int getKPI_AllowedStaledTimeInSec()
{
return get_ValueAsInt(COLUMNNAME_KPI_AllowedStaledTimeInSec);
}
/**
* KPI_DataSource_Type AD_Reference_ID=541339
* Reference name: KPI_DataSource_Type
*/
public static final int KPI_DATASOURCE_TYPE_AD_Reference_ID=541339;
/** Elasticsearch = E */
public static final String KPI_DATASOURCE_TYPE_Elasticsearch = "E";
/** SQL = S */
public static final String KPI_DATASOURCE_TYPE_SQL = "S";
@Override
public void setKPI_DataSource_Type (final java.lang.String KPI_DataSource_Type)
{
set_Value (COLUMNNAME_KPI_DataSource_Type, KPI_DataSource_Type);
}
@Override
public java.lang.String getKPI_DataSource_Type()
{
return get_ValueAsString(COLUMNNAME_KPI_DataSource_Type);
}
@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 setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setSQL_Details_WhereClause (final @Nullable java.lang.String SQL_Details_WhereClause)
{
set_Value (COLUMNNAME_SQL_Details_WhereClause, SQL_Details_WhereClause);
}
|
@Override
public java.lang.String getSQL_Details_WhereClause()
{
return get_ValueAsString(COLUMNNAME_SQL_Details_WhereClause);
}
@Override
public void setSQL_From (final @Nullable java.lang.String SQL_From)
{
set_Value (COLUMNNAME_SQL_From, SQL_From);
}
@Override
public java.lang.String getSQL_From()
{
return get_ValueAsString(COLUMNNAME_SQL_From);
}
@Override
public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy)
{
set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy);
}
@Override
public java.lang.String getSQL_GroupAndOrderBy()
{
return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy);
}
@Override
public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause)
{
set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause);
}
@Override
public java.lang.String getSQL_WhereClause()
{
return get_ValueAsString(COLUMNNAME_SQL_WhereClause);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java
| 1
|
请完成以下Java代码
|
public synchronized static void setCursorsFromParent(Container parent, boolean waiting) {
Container con = parent;
for(int i = 0; i < con.getComponentCount(); i++) {
setCursor(con.getComponent(i), waiting);
if(con.getComponent(i) instanceof Container) {
setCursorsFromParent((Container)con.getComponent(i), waiting);
}
}
}
public static Component searchComponent(Container parent, Class<?> clazz, boolean remove) {
Container con = parent;
Component retVal = null;
Component c = null;
for(int i = 0; i < con.getComponentCount(); i++) {
c = con.getComponent(i);
//Found the given class and breaks the loop
if(clazz.isInstance(c)) {
if(remove) {
con.remove(c);
}
return c;
}
//Recursively calling this method to search in deep
if(c instanceof Container) {
c = searchComponent((Container)c , clazz, remove);
if(clazz.isInstance(c)) {
if(remove) {
con.remove(retVal);
}
return c;
}
}
}
return null;
}
public static void addOpaque(JComponent c, final boolean opaque) {
ContainerAdapter ca = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
setOpaque(e.getChild());
}
private void setOpaque(Component c) {
//ignores all selectable items, like buttons
if(c instanceof ItemSelectable) {
return;
}
// sets transparent
else if(c instanceof JComponent) {
((JComponent)c).setOpaque(opaque);
}
// recursively calls this method for all container components
else if(c instanceof Container) {
for(int i = 0; i > ((Container)c).getComponentCount(); i++) {
setOpaque(((Container)c).getComponent(i));
}
}
}
};
c.addContainerListener(ca);
|
}
public static KeyStroke getKeyStrokeFor(String name, List<KeyStroke> usedStrokes) {
return (name == null) ? null : getKeyStrokeFor(name.charAt(0), usedStrokes);
}
public static KeyStroke getKeyStrokeFor(char c, List<KeyStroke> usedStrokes) {
int m = Event.CTRL_MASK;
KeyStroke o = null;
for(Iterator<?> i = usedStrokes.iterator(); i.hasNext();) {
o = (KeyStroke)i.next();
if(c == o.getKeyChar()) {
if(c == o.getKeyChar()) {
if(o.getModifiers() != Event.SHIFT_MASK+Event.CTRL_MASK) {
m = Event.SHIFT_MASK+Event.CTRL_MASK;
}
else if(o.getModifiers() != Event.SHIFT_MASK+Event.ALT_MASK) {
m = Event.SHIFT_MASK+Event.ALT_MASK;
}
else {
m = -1;
}
}
}
}
KeyStroke s = null;
if(m != -1) {
s = KeyStroke.getKeyStroke(c, m);
usedStrokes.add(s);
}
return s;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\tools\swing\SwingTool.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String resolveCallbackUri(ClientRegistration registration) {
var path = UriComponentsBuilder.fromUriString(registration.getRedirectUri())
.build(Map.of(
"baseUrl", "",
"action", "login",
"registrationId", registration.getRegistrationId()))
.toString();
return "http://localhost:8090" + path;
}
private ClientRegistration createClientRegistration(ClientRegistration staticRegistration, ObjectNode body) {
var clientId = body.get("client_id").asText();
var clientSecret = body.get("client_secret").asText();
log.info("creating ClientRegistration: registrationId={}, client_id={}", staticRegistration.getRegistrationId(),clientId);
return ClientRegistration.withClientRegistration(staticRegistration)
.clientId(body.get("client_id").asText())
.clientSecret(body.get("client_secret").asText())
.build();
}
private String createRegistrationToken() {
var body = new LinkedMultiValueMap<String,String>();
body.put( "grant_type", List.of("client_credentials"));
body.put( "scope", registrationDetails.registrationScopes());
var headers = new HttpHeaders();
headers.setBasicAuth(registrationDetails.registrationUsername(), registrationDetails.registrationPassword());
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
var request = new RequestEntity<>(
body,
headers,
HttpMethod.POST,
registrationDetails.tokenEndpoint());
var result = registrationClient.exchange(request, ObjectNode.class);
if ( !result.getStatusCode().is2xxSuccessful()) {
|
throw new RuntimeException("Failed to create registration token: code=" + result.getStatusCode());
}
return result.getBody().get("access_token").asText();
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<ClientRegistration> iterator() {
return registrations
.values()
.iterator();
}
public void doRegistrations() {
staticClients.forEach((key, value) -> findByRegistrationId(key));
}
public record RegistrationDetails(
URI registrationEndpoint,
String registrationUsername,
String registrationPassword,
List<String> registrationScopes,
List<String> grantTypes,
List<String> redirectUris,
URI tokenEndpoint
) {
}
// Type-safe RestTemplate
public static class RegistrationRestTemplate extends RestTemplate {
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\service\DynamicClientRegistrationRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ItemWriter<BudgetVtoll> writer(DruidDataSource dataSource) {
JdbcBatchItemWriter<BudgetVtoll> writer = new JdbcBatchItemWriter<>();
//我们使用JDBC批处理的JdbcBatchItemWriter来写数据到数据库
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>());
String sql = "insert into nt_bsc_BudgetVtoll " + " (f_id,f_year,f_tollid,f_budgetid,f_cbudgetid,f_version,f_auditmsg,f_trialstatus,f_firauditer,f_firaudittime,f_finauditer,f_finaudittime,f_edittime,f_startdate,f_enddate) "
+ " values(:id,:year,:tollid,:budgetid,:cbudgetid,:version,:auditmsg,:trialstatus,:firauditer,:firaudittime,:finauditer,:finaudittime,:edittime,:startdate,:enddate)";
//在此设置要执行批处理的SQL语句
writer.setSql(sql);
writer.setDataSource(dataSource);
return writer;
}
/**
* Job定义,我们要实际执行的任务,包含一个或多个Step
*
* @param jobBuilderFactory
* @param s1
* @return
*/
@Bean(name = "vtollJob")
public Job vtollJob(JobBuilderFactory jobBuilderFactory, @Qualifier("vtollStep1") Step s1) {
return jobBuilderFactory.get("vtollJob")
.incrementer(new RunIdIncrementer())
.flow(s1)//为Job指定Step
.end()
.listener(new MyJobListener())//绑定监听器csvJobListener
.build();
}
/**
* step步骤,包含ItemReader,ItemProcessor和ItemWriter
*
* @param stepBuilderFactory
* @param reader
* @param writer
* @param processor
* @return
*/
@Bean(name = "vtollStep1")
public Step vtollStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("vtollReader") ItemReader<BudgetVtoll> reader,
@Qualifier("vtollWriter") ItemWriter<BudgetVtoll> writer,
|
@Qualifier("vtollProcessor") ItemProcessor<BudgetVtoll, BudgetVtoll> processor) {
return stepBuilderFactory
.get("vtollStep1")
.<BudgetVtoll, BudgetVtoll>chunk(5000)//批处理每次提交5000条数据
.reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次
.skip(Exception.class)
.skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<BudgetVtoll> csvBeanValidator() {
return new MyBeanValidator<>();
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtollConfig.java
| 2
|
请完成以下Java代码
|
public void sendAttachmentAsEmail(final int shipperId, @NonNull final AttachmentEntry attachmentEntry)
{
Check.assumeGreaterThanZero(shipperId, "shipperId");
final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository
.retrieveConfigForShipperId(shipperId);
final EMailAddress emailAddress = shipperConfig.getDeliveryOrderRecipientEmailOrNull();
if (emailAddress == null)
{
return;
}
final Mailbox deliveryOrderMailBox = shipperConfig.getDeliveryOrderMailBoxId()
.map(mailService::getMailboxById)
.orElseThrow(() -> new AdempiereException("No mailbox defined: " + shipperConfig));
sendAttachmentAsEmail(deliveryOrderMailBox, emailAddress, attachmentEntry);
}
@VisibleForTesting
void sendAttachmentAsEmail(
@NonNull final Mailbox mailBox,
@NonNull final EMailAddress mailTo,
@NonNull final AttachmentEntry attachmentEntry)
{
final byte[] data = attachmentEntryService.retrieveData(attachmentEntry.getId());
final String csvDataString = new String(data, DerKurierConstants.CSV_DATA_CHARSET);
final String subject = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailSubject);
final String message = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailMessage, new Object[] { csvDataString });
|
mailService.sendEMail(EMailRequest.builder()
.mailbox(mailBox)
.to(mailTo)
.subject(subject)
.message(message)
.html(false)
.build());
// we don't have an AD_Archive..
// final I_AD_User user = loadOutOfTrx(Env.getAD_User_ID(), I_AD_User.class);
// final IArchiveEventManager archiveEventManager = Services.get(IArchiveEventManager.class);
// archiveEventManager.fireEmailSent(
// null,
// X_C_Doc_Outbound_Log_Line.ACTION_EMail,
// user,
// null/* from */,
// mailTo,
// null /* cc */,
// null /* bcc */,
// IArchiveEventManager.STATUS_MESSAGE_SENT);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\DerKurierDeliveryOrderEmailer.java
| 1
|
请完成以下Java代码
|
protected ELResolver createElResolver() {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver());
elResolver.add(new VariableContextElResolver());
elResolver.add(new MockElResolver());
if (beans != null) {
// ACT-1102: Also expose all beans in configuration when using standalone
// engine, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
elResolver.add(new ProcessApplicationElResolverDelegate());
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new ProcessApplicationBeanElResolverDelegate());
return elResolver;
}
protected FunctionMapper createFunctionMapper() {
FunctionMapper functionMapper = new FunctionMapper() {
@Override
public Method resolveFunction(String prefix, String localName) {
String fullName = localName;
if (prefix != null && !prefix.trim().isEmpty()) {
fullName = prefix + ":" + localName;
|
}
return functions.get(fullName);
}
};
return functionMapper;
}
@Override
public ElProvider toElProvider() {
if (elProvider == null) {
synchronized (this) {
if (elProvider == null) {
elProvider = createElProvider();
}
}
}
return elProvider;
}
protected ElProvider createElProvider() {
return new ProcessEngineJuelElProvider(this);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\JuelExpressionManager.java
| 1
|
请完成以下Java代码
|
private static Set<PaymentId> extractPaymentIds(final List<I_C_AllocationLine> lines)
{
return lines.stream()
.map(line -> PaymentId.ofRepoIdOrNull(line.getC_Payment_ID()))
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
private static Set<InvoiceId> extractInvoiceIds(final List<I_C_AllocationLine> lines)
{
return lines.stream()
.map(line -> InvoiceId.ofRepoIdOrNull(line.getC_Invoice_ID()))
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
public void updateDraftedPaySelectionLinesForInvoiceIds(final Set<InvoiceId> invoiceIds)
{
if (invoiceIds.isEmpty())
{
return;
}
//
// Retrieve all C_PaySelectionLines which are about invoices from our allocation and which are not already processed.
// The C_PaySelectionLines will be grouped by C_PaySelection_ID.
//@formatter:off
final Collection<List<I_C_PaySelectionLine>> paySelectionLinesGroups =
Services.get(IPaySelectionDAO.class)
.queryActivePaySelectionLinesByInvoiceId(invoiceIds)
.listAndSplit(I_C_PaySelectionLine.class, I_C_PaySelectionLine::getC_PaySelection_ID);
//@formatter:on
//
// Update each C_PaySelectionLines group
for (final Collection<I_C_PaySelectionLine> paySelectionLines : paySelectionLinesGroups)
{
updatePaySelectionLines(paySelectionLines);
}
}
/**
* Update all given pay selection lines.
* <p>
* NOTE: pay selection lines shall ALL be part of the same {@link I_C_PaySelection}.
|
*/
private void updatePaySelectionLines(final Collection<I_C_PaySelectionLine> paySelectionLines)
{
// shall not happen
if (paySelectionLines.isEmpty())
{
return;
}
// Make sure the C_PaySelection was not already processed.
// Shall not happen.
final I_C_PaySelection paySelection = paySelectionLines.iterator().next().getC_PaySelection();
if (paySelection.isProcessed())
{
logger.debug("Skip updating lines because pay selection was already processed: {}", paySelection);
return;
}
//
// Update all pay selection lines
final IPaySelectionBL paySelectionBL = Services.get(IPaySelectionBL.class);
final IPaySelectionUpdater paySelectionUpdater = paySelectionBL.newPaySelectionUpdater();
paySelectionUpdater
.setC_PaySelection(paySelection)
.addPaySelectionLinesToUpdate(paySelectionLines)
.update();
logger.debug("Updated {}", paySelectionUpdater.getSummary());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_AllocationHdr.java
| 1
|
请完成以下Java代码
|
public String getDBAddress ()
{
return (String)get_Value(COLUMNNAME_DBAddress);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getDBAddress());
}
/** Set Profile.
@param ProfileInfo
Information to help profiling the system for solving support issues
*/
public void setProfileInfo (String ProfileInfo)
{
set_ValueNoCheck (COLUMNNAME_ProfileInfo, ProfileInfo);
}
/** Get Profile.
@return Information to help profiling the system for solving support issues
*/
public String getProfileInfo ()
{
return (String)get_Value(COLUMNNAME_ProfileInfo);
}
/** Set Issue System.
@param R_IssueSystem_ID
System creating the issue
*/
public void setR_IssueSystem_ID (int R_IssueSystem_ID)
{
if (R_IssueSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, Integer.valueOf(R_IssueSystem_ID));
}
/** Get Issue System.
@return System creating the issue
*/
public int getR_IssueSystem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueSystem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistics.
@param StatisticsInfo
|
Information to help profiling the system for solving support issues
*/
public void setStatisticsInfo (String StatisticsInfo)
{
set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo);
}
/** Get Statistics.
@return Information to help profiling the system for solving support issues
*/
public String getStatisticsInfo ()
{
return (String)get_Value(COLUMNNAME_StatisticsInfo);
}
/** SystemStatus AD_Reference_ID=374 */
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
public void setSystemStatus (String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
public String getSystemStatus ()
{
return (String)get_Value(COLUMNNAME_SystemStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueSystem.java
| 1
|
请完成以下Java代码
|
public class BscOfficeExeItem {
private String F_ID;
private String F_CANTONID;
private String F_OFFICEID;
private String F_TOLLID;
private String F_TOLLCODE;
private String F_START;
private String F_END;
private String F_STATUS;
private String F_VERSION;
public String getF_ID() {
return F_ID;
}
public void setF_ID(String f_ID) {
F_ID = f_ID;
}
public String getF_CANTONID() {
return F_CANTONID;
}
public void setF_CANTONID(String f_CANTONID) {
F_CANTONID = f_CANTONID;
}
public String getF_OFFICEID() {
return F_OFFICEID;
}
public void setF_OFFICEID(String f_OFFICEID) {
F_OFFICEID = f_OFFICEID;
}
public String getF_TOLLID() {
return F_TOLLID;
}
public void setF_TOLLID(String f_TOLLID) {
F_TOLLID = f_TOLLID;
}
public String getF_TOLLCODE() {
return F_TOLLCODE;
}
public void setF_TOLLCODE(String f_TOLLCODE) {
F_TOLLCODE = f_TOLLCODE;
}
public String getF_START() {
|
return F_START;
}
public void setF_START(String f_START) {
F_START = f_START;
}
public String getF_END() {
return F_END;
}
public void setF_END(String f_END) {
F_END = f_END;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_VERSION() {
return F_VERSION;
}
public void setF_VERSION(String f_VERSION) {
F_VERSION = f_VERSION;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscOfficeExeItem.java
| 1
|
请完成以下Java代码
|
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
}
|
@Override
public int getUpdatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions);
}
@Override
public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getUpdated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java
| 1
|
请完成以下Java代码
|
public void setDefaultMaxInactiveInterval(Duration defaultMaxInactiveInterval) {
Assert.notNull(defaultMaxInactiveInterval, "defaultMaxInactiveInterval must not be null");
this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
}
@Override
public void save(MapSession session) {
if (!session.getId().equals(session.getOriginalId())) {
this.sessions.remove(session.getOriginalId());
}
MapSession saved = new MapSession(session);
saved.setSessionIdGenerator(this.sessionIdGenerator);
this.sessions.put(session.getId(), saved);
}
@Override
public MapSession findById(String id) {
Session saved = this.sessions.get(id);
if (saved == null) {
return null;
}
if (saved.isExpired()) {
deleteById(saved.getId());
return null;
}
MapSession result = new MapSession(saved);
|
result.setSessionIdGenerator(this.sessionIdGenerator);
return result;
}
@Override
public void deleteById(String id) {
this.sessions.remove(id);
}
@Override
public MapSession createSession() {
MapSession result = new MapSession(this.sessionIdGenerator);
result.setMaxInactiveInterval(this.defaultMaxInactiveInterval);
return result;
}
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null");
this.sessionIdGenerator = sessionIdGenerator;
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSessionRepository.java
| 1
|
请完成以下Java代码
|
public I_M_Product getM_Product()
{
return loadOutOfTrx(rs.getM_Product_ID(), I_M_Product.class);
}
@Override
public int getM_Product_ID()
{
return rs.getM_Product_ID();
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return Services.get(IReceiptScheduleBL.class).getM_AttributeSetInstance_Effective(rs);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return Services.get(IReceiptScheduleBL.class).getM_AttributeSetInstance_Effective_ID(rs);
}
@Override
|
public void setM_AttributeSetInstance(@Nullable final I_M_AttributeSetInstance asi)
{
AttributeSetInstanceId asiId = asi == null
? AttributeSetInstanceId.NONE
: AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID());
receiptScheduleBL.setM_AttributeSetInstance_Effective(rs, asiId);
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(M_AttributeSetInstance_ID);
receiptScheduleBL.setM_AttributeSetInstance_Effective(rs, asiId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleASIAware.java
| 1
|
请完成以下Java代码
|
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldString
* @return
*/
public boolean existSameField(String fieldString) {
String[] controlFields = fieldString.split(",");
for (String sqlField : fields) {
for (String controlField : controlFields) {
if (sqlField.equals(controlField)) {
// 非常明确的列直接比较
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
} else {
// 使用表达式的列 只能判读字符串包含了
String aliasColumn = controlField;
if (StringUtils.isNotBlank(alias)) {
aliasColumn = alias + "." + controlField;
}
if (sqlField.indexOf(aliasColumn) != -1) {
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
}
}
}
}
return false;
|
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
public String getError(){
// TODO
return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!";
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\AbstractQueryBlackListHandler.java
| 1
|
请完成以下Java代码
|
public void setPriceLimit (BigDecimal PriceLimit)
{
set_Value (COLUMNNAME_PriceLimit, PriceLimit);
}
/** Get Limit Price.
@return Lowest price for a product
*/
public BigDecimal getPriceLimit ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set List Price.
@param PriceList
List Price
*/
public void setPriceList (BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get List Price.
@return List Price
*/
public BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standard Price.
|
@param PriceStd
Standard Price
*/
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPriceVendorBreak.java
| 1
|
请完成以下Java代码
|
public MessageExecutionContext createMessageExecutionContext(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition
) {
MessagePayloadMappingProvider mappingProvider = createMessagePayloadMappingProvider(
bpmnEvent,
messageEventDefinition
);
return getMessageExecutionContextFactory().create(messageEventDefinition, mappingProvider, expressionManager);
}
public ThrowMessageDelegate createThrowMessageJavaDelegate(String className) {
Class<? extends ThrowMessageDelegate> clazz = ReflectUtil.loadClass(className).asSubclass(
ThrowMessageDelegate.class
);
return new ThrowMessageJavaDelegate(clazz, emptyList());
}
public ThrowMessageDelegate createThrowMessageDelegateExpression(String delegateExpression) {
Expression expression = expressionManager.createExpression(delegateExpression);
return new ThrowMessageDelegateExpression(expression, emptyList());
}
public ThrowMessageDelegate createDefaultThrowMessageDelegate() {
return getThrowMessageDelegateFactory().create();
}
public MessagePayloadMappingProvider createMessagePayloadMappingProvider(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition
) {
return getMessagePayloadMappingProviderFactory().create(
bpmnEvent,
messageEventDefinition,
getExpressionManager()
);
}
|
protected Optional<String> checkClassDelegate(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "class");
}
protected Optional<String> checkDelegateExpression(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "delegateExpression");
}
protected Optional<String> getAttributeValue(Map<String, List<ExtensionAttribute>> attributes, String name) {
return Optional.ofNullable(attributes)
.filter(it -> it.containsKey("activiti"))
.map(it -> it.get("activiti"))
.flatMap(it ->
it
.stream()
.filter(el -> name.equals(el.getName()))
.findAny()
)
.map(ExtensionAttribute::getValue);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
| 1
|
请完成以下Java代码
|
public void setTask(TaskEntity task) {
this.task = task;
this.taskId = task.getId();
}
public ProcessDefinitionEntity getProcessDef() {
if ((processDef == null) && (processDefId != null)) {
this.processDef = Context
.getCommandContext()
.getProcessDefinitionManager()
.findLatestProcessDefinitionById(processDefId);
}
return processDef;
}
public void setProcessDef(ProcessDefinitionEntity processDef) {
this.processDef = processDef;
this.processDefId = processDef.getId();
}
public void fireHistoricIdentityLinkEvent(final HistoryEventType eventType) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = processEngineConfiguration.getHistoryLevel();
if(historyLevel.isHistoryEventProduced(eventType, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
HistoryEvent event = null;
if (HistoryEvent.IDENTITY_LINK_ADD.equals(eventType.getEventName())) {
event = producer.createHistoricIdentityLinkAddEvent(IdentityLinkEntity.this);
} else if (HistoryEvent.IDENTITY_LINK_DELETE.equals(eventType.getEventName())) {
event = producer.createHistoricIdentityLinkDeleteEvent(IdentityLinkEntity.this);
}
return event;
}
});
}
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
|
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (processDefId != null) {
referenceIdAndClass.put(processDefId, ProcessDefinitionEntity.class);
}
if (taskId != null) {
referenceIdAndClass.put(taskId, TaskEntity.class);
}
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", taskId=" + taskId
+ ", processDefId=" + processDefId
+ ", task=" + task
+ ", processDef=" + processDef
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityLinkEntity.java
| 1
|
请完成以下Java代码
|
public void approveIt(final DocumentTableFields docFields)
{
}
@Override
public void rejectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void voidIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void closeIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeClose(rfq);
//
// Mark as closed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Closed);
rfq.setDocAction(X_C_RfQ.DOCACTION_None);
rfq.setProcessed(true);
rfq.setIsRfQResponseAccepted(false);
InterfaceWrapperHelper.save(rfq);
//
// Close RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isDraft(rfqResponse))
{
continue;
}
rfqBL.complete(rfqResponse);
}
//
rfqEventDispacher.fireAfterClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeUnClose(rfq);
//
// Mark as completed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Completed);
rfq.setDocAction(X_C_RfQ.DOCACTION_Close);
InterfaceWrapperHelper.save(rfq);
//
// UnClose RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isClosed(rfqResponse))
{
continue;
}
rfqBL.unclose(rfqResponse);
}
//
rfqEventDispacher.fireAfterUnClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
|
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
// Void and delete all responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
voidAndDelete(rfqResponse);
}
rfq.setIsRfQResponseAccepted(false);
rfq.setDocAction(IDocument.ACTION_Complete);
rfq.setProcessed(false);
}
private void voidAndDelete(final I_C_RfQResponse rfqResponse)
{
// Prevent deleting/voiding an already closed RfQ response
if (rfqBL.isClosed(rfqResponse))
{
throw new RfQDocumentClosedException(rfqBL.getSummary(rfqResponse));
}
// TODO: FRESH-402 shall we throw exception if the rfqResponse was published?
rfqResponse.setProcessed(false);
InterfaceWrapperHelper.delete(rfqResponse);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQDocumentHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RecordChangeLog
{
String tableName;
ComposedRecordId recordId;
UserId createdByUserId;
Instant createdTimestamp;
UserId lastChangedByUserId;
Instant lastChangedTimestamp;
ImmutableList<RecordChangeLogEntry> entries;
public boolean hasChanges()
{
return !Objects.equals(createdByUserId, lastChangedByUserId)
|| !Objects.equals(createdTimestamp, lastChangedTimestamp)
|| !entries.isEmpty();
}
/**
* Both {@code createdByUserId} and {@code lastChangedByUserId} can be {@code null} if the respective DB columns have a value less than zero.
|
* This happens if there is no user-id in the context while a DB record is saved.
*/
@Builder
private RecordChangeLog(
@NonNull String tableName,
@NonNull ComposedRecordId recordId,
@Nullable UserId createdByUserId,
@NonNull Instant createdTimestamp,
@Nullable UserId lastChangedByUserId,
@NonNull Instant lastChangedTimestamp,
@NonNull @Singular ImmutableList<RecordChangeLogEntry> entries)
{
this.tableName = tableName;
this.recordId = recordId;
this.createdByUserId = createdByUserId;
this.createdTimestamp = createdTimestamp;
this.lastChangedByUserId = lastChangedByUserId;
this.lastChangedTimestamp = lastChangedTimestamp;
this.entries = entries;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLog.java
| 2
|
请完成以下Java代码
|
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Image URL.
@param ImageURL
URL of image
*/
public void setImageURL (String ImageURL)
{
set_Value (COLUMNNAME_ImageURL, ImageURL);
}
/** Get Image URL.
@return URL of image
*/
public String getImageURL ()
{
return (String)get_Value(COLUMNNAME_ImageURL);
}
/** 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_Image.java
| 1
|
请完成以下Java代码
|
public String getReferenceId() {
return referenceId;
}
public String getReferenceType() {
return referenceType;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public IdentityLinkQueryObject getInvolvedUserIdentityLink() {
return involvedUserIdentityLink;
}
public IdentityLinkQueryObject getInvolvedGroupIdentityLink() {
return involvedGroupIdentityLink;
}
public boolean isWithJobException() {
return withJobException;
}
public String getLocale() {
return locale;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
}
public boolean isNeedsProcessDefinitionOuterJoin() {
if (isNeedsPaging()) {
if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) {
// When using oracle, db2 or mssql we don't need outer join for the process definition join.
// It is not needed because the outer join order by is done by the row number instead
return false;
}
}
return hasOrderByForColumn(HistoricProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName());
|
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public String getRootScopeId() {
return rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public void onOpen(Session session, @PathParam("username") String username) {
this.session = session;
chatEndpoints.add(this);
users.put(session.getId(), username);
Message message = new Message();
message.setFrom(username);
message.setContent("Connected!");
broadcast(message);
}
@OnMessage
public void onMessage(Session session, Message message) {
message.setFrom(users.get(session.getId()));
broadcast(message);
}
@OnClose
public void onClose(Session session) {
chatEndpoints.remove(this);
Message message = new Message();
message.setFrom(users.get(session.getId()));
message.setContent("Disconnected!");
broadcast(message);
}
|
@OnError
public void onError(Session session, Throwable throwable) {
// Do error handling here
}
private static void broadcast(Message message) {
chatEndpoints.forEach(endpoint -> {
synchronized (endpoint) {
try {
endpoint.session.getBasicRemote()
.sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
|
repos\tutorials-master\core-java-modules\java-websocket\src\main\java\com\baeldung\websocket\ChatEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<InvoicePayScheduleCreateRequest> newInvoicePayScheduleCreateRequest_fromPaymentTerm()
{
final PaymentTermId paymentTermId = PaymentTermId.ofRepoIdOrNull(invoiceRecord.getC_PaymentTerm_ID());
if (paymentTermId == null)
{
return Optional.empty();
}
final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId);
if (!paymentTerm.isValid() || paymentTerm.getPaySchedules().isEmpty())
{
return Optional.empty();
}
final Money grandTotal = invoiceBL.extractGrandTotal(invoiceRecord).toMoney();
final CurrencyPrecision currencyPrecision = currencyDAO.getStdPrecision(grandTotal.getCurrencyId());
final LocalDate dateInvoiced = invoiceRecord.getDateInvoiced().toLocalDateTime().toLocalDate();
final ArrayList<InvoicePayScheduleCreateRequest.Line> lines = new ArrayList<>();
Money dueAmtRemaining = grandTotal;
final ImmutableList<PaySchedule> paySchedules = paymentTerm.getPaySchedules();
for (int i = 0, paySchedulesCount = paySchedules.size(); i < paySchedulesCount; i++)
{
final PaySchedule paySchedule = paySchedules.get(i);
final boolean isLast = i == paySchedulesCount - 1;
final Money dueAmt = isLast
? dueAmtRemaining
: paySchedule.calculateDueAmt(grandTotal, currencyPrecision);
lines.add(InvoicePayScheduleCreateRequest.Line.builder()
.valid(true)
.dueDate(paySchedule.calculateDueDate(dateInvoiced))
|
.dueAmount(dueAmt)
.discountDate(paySchedule.calculateDiscountDate(dateInvoiced))
.discountAmount(paySchedule.calculateDiscountAmt(dueAmt, currencyPrecision))
.paymentTermScheduleId(paySchedule.getId())
.build());
dueAmtRemaining = dueAmtRemaining.subtract(dueAmt);
}
return Optional.of(
InvoicePayScheduleCreateRequest.builder()
.invoiceId(InvoiceId.ofRepoId(invoiceRecord.getC_Invoice_ID()))
.lines(lines)
.build()
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\service\InvoicePayScheduleCreateCommand.java
| 2
|
请完成以下Java代码
|
public String getUhrzeitVon() {
return uhrzeitVon;
}
/**
* Sets the value of the uhrzeitVon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUhrzeitVon(String value) {
this.uhrzeitVon = value;
}
/**
* Gets the value of the uhrzeitBis property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getUhrzeitBis() {
return uhrzeitBis;
}
/**
* Sets the value of the uhrzeitBis property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUhrzeitBis(String value) {
this.uhrzeitBis = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Sendung.java
| 1
|
请完成以下Java代码
|
public class PageListVO {
/** 总数量 **/
private long total ;
/** 页码 **/
private int page;
/** 每页条数 **/
private int pageSize;
/** 分页数据 **/
private List pageData = new ArrayList();
/**
* 汇总数据
*/
private Object summary;
public PageListVO(long total , int page , int pageSize , List pageData){
this.total = total;
this.page = page;
this.pageSize = pageSize;
if (pageData != null){
this.pageData = pageData;
}
}
public PageListVO(long total , int page , int pageSize , List pageData, Object summary){
this.total = total;
this.page = page;
this.pageSize = pageSize;
this.summary = summary;
if (pageData != null){
this.pageData = pageData;
}
}
public Object getSummary() {
return summary;
}
public void setSummary(Object summary) {
this.summary = summary;
}
public void setTotal(int total) {
this.total = total;
}
public void setPage(int page) {
this.page = page;
}
|
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setPageData(List pageData) {
this.pageData = pageData;
}
public long getTotal() {
return total;
}
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
public List getPageData() {
return pageData;
}
}
|
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\entity\PageListVO.java
| 1
|
请完成以下Java代码
|
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理缓存
*
* @param redisTemplate
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager CacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置cache过期时间,时间单位是秒
rcm.setDefaultExpiration(60);
Map<String, Long> map = new HashMap<String, Long>();
map.put("test", 60L);
rcm.setExpires(map);
return rcm;
}
/**
* redis 数据库连接池
* @return
*/
@Bean
public JedisConnectionFactory redisConnectionFactory() {
|
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisConn.getHost());
factory.setPort(redisConn.getPort());
factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
return factory;
}
/**
* redisTemplate配置
*
* @param factory
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\redis\CacheService.java
| 1
|
请完成以下Java代码
|
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) throws IOException {
FastAutoGenerator.create(dataSourceGenerate())
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author(scanner.apply("请输入作者")).fileOverride();
builder.outputDir(OUT_DIR);
})
// 包配置
.packageConfig((scanner, builder) -> {
builder
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "/src/main/resources/mapper"))
.parent(scanner.apply("请输入包名?"));
})
// 策略配置
.strategyConfig((scanner, builder) -> {
builder.addInclude(MyBatisPlusGenerator.getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.build();
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
//entity的策略配置
builder.entityBuilder()
.enableLombok()
.enableTableFieldAnnotation()
|
.versionColumnName("version")
.logicDeleteColumnName("is_delete")
.columnNaming(NamingStrategy.underline_to_camel)
// .idType(IdType.AUTO)
.formatFileName("%sEntity")
.build();
// mapper xml配置
builder.mapperBuilder()
.formatMapperFileName("%sMapper")
.enableBaseColumnList()
.enableBaseResultMap()
.build();
})
.execute();
}
}
|
repos\spring-boot-quick-master\quick-sample-server\sample-server\src\main\java\com\quick\utils\MyBatisPlusGenerator.java
| 1
|
请完成以下Java代码
|
private boolean isResolvable(Object base) {
return base == null;
}
private boolean resolve(ELContext context, Object base, Object property) {
context.setPropertyResolved(isResolvable(base) && property instanceof String);
return context.isPropertyResolved();
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return isResolvable(context) ? String.class : null;
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? Object.class : null;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (resolve(context, base, property)) {
if (!isProperty((String) property)) {
throw new PropertyNotFoundException("Cannot find property " + property);
}
return getProperty((String) property);
}
return null;
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? readOnly : false;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value)
throws PropertyNotWritableException {
if (resolve(context, base, property)) {
if (readOnly) {
throw new PropertyNotWritableException("Resolver is read only!");
}
setProperty((String) property, value);
}
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
|
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
return null;
}
/**
* Get property value
*
* @param property
* property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\util\RootPropertyResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Coupon retrieveCoupon(String code) {
try {
Stripe.apiKey = API_SECRET_KEY;
return Coupon.retrieve(code);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public String createCharge(String email, String token, int amount) {
String id = null;
try {
Stripe.apiKey = API_SECRET_KEY;
Map<String, Object> chargeParams = new HashMap<>();
|
chargeParams.put("amount", amount);
chargeParams.put("currency", "usd");
chargeParams.put("description", "Charge for " + email);
chargeParams.put("source", token); // ^ obtained with Stripe.js
//create a charge
Charge charge = Charge.create(chargeParams);
id = charge.getId();
} catch (Exception ex) {
ex.printStackTrace();
}
return id;
}
}
|
repos\springboot-demo-master\stripe\src\main\java\com\et\stripe\service\StripeService.java
| 2
|
请完成以下Java代码
|
public MigratingInstanceParseHandler<ActivityInstance> getActivityInstanceHandler() {
return activityInstanceHandler;
}
public MigratingInstanceParseHandler<TransitionInstance> getTransitionInstanceHandler() {
return transitionInstanceHandler;
}
public MigratingDependentInstanceParseHandler<MigratingActivityInstance, List<EventSubscriptionEntity>> getDependentEventSubscriptionHandler() {
return dependentEventSubscriptionHandler;
}
public MigratingDependentInstanceParseHandler<MigratingActivityInstance, List<JobEntity>> getDependentActivityInstanceJobHandler() {
return dependentActivityInstanceJobHandler;
}
public MigratingDependentInstanceParseHandler<MigratingTransitionInstance, List<JobEntity>> getDependentTransitionInstanceJobHandler() {
return dependentTransitionInstanceJobHandler;
}
public MigratingInstanceParseHandler<IncidentEntity> getIncidentHandler() {
return incidentHandler;
}
public MigratingDependentInstanceParseHandler<MigratingProcessElementInstance, List<VariableInstanceEntity>> getDependentVariablesHandler() {
return dependentVariableHandler;
}
protected List<ExecutionEntity> fetchExecutions(CommandContext commandContext, String processInstanceId) {
return commandContext.getExecutionManager().findExecutionsByProcessInstanceId(processInstanceId);
}
protected List<EventSubscriptionEntity> fetchEventSubscriptions(CommandContext commandContext, String processInstanceId) {
return commandContext.getEventSubscriptionManager().findEventSubscriptionsByProcessInstanceId(processInstanceId);
}
protected List<ExternalTaskEntity> fetchExternalTasks(CommandContext commandContext, String processInstanceId) {
return commandContext.getExternalTaskManager().findExternalTasksByProcessInstanceId(processInstanceId);
|
}
protected List<JobEntity> fetchJobs(CommandContext commandContext, String processInstanceId) {
return commandContext.getJobManager().findJobsByProcessInstanceId(processInstanceId);
}
protected List<IncidentEntity> fetchIncidents(CommandContext commandContext, String processInstanceId) {
return commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId);
}
protected List<TaskEntity> fetchTasks(CommandContext commandContext, String processInstanceId) {
return commandContext.getTaskManager().findTasksByProcessInstanceId(processInstanceId);
}
protected List<JobDefinitionEntity> fetchJobDefinitions(CommandContext commandContext, String processDefinitionId) {
return commandContext.getJobDefinitionManager().findByProcessDefinitionId(processDefinitionId);
}
protected List<VariableInstanceEntity> fetchVariables(CommandContext commandContext, String processInstanceId) {
return commandContext.getVariableInstanceManager().findVariableInstancesByProcessInstanceId(processInstanceId);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\MigratingInstanceParser.java
| 1
|
请完成以下Java代码
|
private List<JmxOperationParameter> mergeParameters(OperationParameters operationParameters,
@Nullable ManagedOperationParameter[] managedParameters) {
List<JmxOperationParameter> merged = new ArrayList<>(managedParameters.length);
for (int i = 0; i < managedParameters.length; i++) {
ManagedOperationParameter managedParameter = managedParameters[i];
Assert.state(managedParameter != null, "'managedParameter' must not be null");
merged.add(new DiscoveredJmxOperationParameter(managedParameter, operationParameters.get(i)));
}
return Collections.unmodifiableList(merged);
}
@Override
public String getName() {
return this.name;
}
@Override
public Class<?> getOutputType() {
return this.outputType;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public List<JmxOperationParameter> getParameters() {
return this.parameters;
}
@Override
protected void appendFields(ToStringCreator creator) {
creator.append("name", this.name)
.append("outputType", this.outputType)
.append("description", this.description)
.append("parameters", this.parameters);
}
/**
* A discovered {@link JmxOperationParameter}.
*/
private static class DiscoveredJmxOperationParameter implements JmxOperationParameter {
private final String name;
private final Class<?> type;
private final @Nullable String description;
DiscoveredJmxOperationParameter(OperationParameter operationParameter) {
this.name = operationParameter.getName();
this.type = JmxType.get(operationParameter.getType());
this.description = null;
}
DiscoveredJmxOperationParameter(ManagedOperationParameter managedParameter,
OperationParameter operationParameter) {
this.name = managedParameter.getName();
this.type = JmxType.get(operationParameter.getType());
this.description = managedParameter.getDescription();
}
|
@Override
public String getName() {
return this.name;
}
@Override
public Class<?> getType() {
return this.type;
}
@Override
public @Nullable String getDescription() {
return this.description;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(this.name);
if (this.description != null) {
result.append(" (").append(this.description).append(")");
}
result.append(":").append(this.type);
return result.toString();
}
}
/**
* Utility to convert to JMX supported types.
*/
private static final class JmxType {
static Class<?> get(Class<?> source) {
if (source.isEnum()) {
return String.class;
}
if (Date.class.isAssignableFrom(source) || Instant.class.isAssignableFrom(source)) {
return String.class;
}
if (source.getName().startsWith("java.")) {
return source;
}
if (source.equals(Void.TYPE)) {
return source;
}
return Object.class;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\annotation\DiscoveredJmxOperation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class CustomGlobalExceptionHandler extends AbstractErrorWebExceptionHandler {
public CustomGlobalExceptionHandler(final ErrorAttributes errorAttributes,
final WebProperties.Resources resources,
final ApplicationContext applicationContext,
final ServerCodecConfigurer configurer) {
super(errorAttributes, resources, applicationContext);
setMessageReaders(configurer.getReaders());
setMessageWriters(configurer.getWriters());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
ErrorAttributeOptions options = ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE);
Map<String, Object> errorPropertiesMap = getErrorAttributes(request, options);
Throwable throwable = getError(request);
HttpStatusCode httpStatus = determineHttpStatus(throwable);
errorPropertiesMap.put("status", httpStatus.value());
errorPropertiesMap.remove("error");
return ServerResponse.status(httpStatus)
.contentType(MediaType.APPLICATION_JSON_UTF8)
|
.body(BodyInserters.fromObject(errorPropertiesMap));
}
private HttpStatusCode determineHttpStatus(Throwable throwable) {
if (throwable instanceof ResponseStatusException) {
return ((ResponseStatusException) throwable).getStatusCode();
} else if (throwable instanceof CustomRequestAuthException) {
return HttpStatus.UNAUTHORIZED;
} else if (throwable instanceof RateLimitRequestException) {
return HttpStatus.TOO_MANY_REQUESTS;
} else {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}
|
repos\tutorials-master\spring-cloud-modules\gateway-exception-management\src\main\java\com\baeldung\errorhandling\CustomGlobalExceptionHandler.java
| 2
|
请完成以下Java代码
|
public String getConfigSummary()
{
return config != null ? config.toString() : "";
}
public String getRequestAsString()
{
return toString(requestElement);
}
public String getResponseAsString()
{
return toString(responseElement);
}
private String toString(final JAXBElement<?> jaxbElement)
{
if (jaxbElement == null)
|
{
return null;
}
try
{
final StringResult result = new StringResult();
jaxbMarshaller.marshal(jaxbElement, result);
return result.toString();
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting " + jaxbElement + " to String", ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GOClientLogEvent.java
| 1
|
请完成以下Java代码
|
public Builder setId(final String id)
{
this.id = id;
return this;
}
private String getId()
{
if (id != null)
{
return id;
}
if (record != null)
{
return record.getTableName() + "#" + record.getRecord_ID();
}
throw new IllegalStateException("id is null");
}
public Builder setName(final String name)
{
this.name = name;
return this;
}
private String getName()
{
if (name != null)
{
return name;
}
if (record != null)
{
return Services.get(IMsgBL.class).translate(Env.getCtx(), record.getTableName()) + " #" + record.getRecord_ID();
}
return "";
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
}
|
private Date getDate()
{
if (date == null)
{
return null;
}
return (Date)date.clone();
}
public Builder setRecord(final Object record)
{
this.record = TableRecordReference.of(record);
return this;
}
private ITableRecordReference getRecord()
{
return record;
}
public Builder setPaymentBatchProvider(IPaymentBatchProvider paymentBatchProvider)
{
this.paymentBatchProvider = paymentBatchProvider;
return this;
}
private IPaymentBatchProvider getPaymentBatchProvider()
{
return paymentBatchProvider;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\bankstatement\match\spi\PaymentBatch.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
PropertyDescriptor createPropertyDescriptor(String name,
Function<String, PropertyDescriptor> regularDescriptor) {
return createPropertyDescriptor(name, regularDescriptor.apply(name));
}
}
/**
* A {@link PropertyDescriptor} that applies source metadata.
*/
static class SourcePropertyDescriptor extends PropertyDescriptor {
private final PropertyDescriptor delegate;
private final ItemMetadata sourceItemMetadata;
private final ItemHint sourceItemHint;
SourcePropertyDescriptor(PropertyDescriptor delegate, ItemMetadata sourceItemMetadata,
ItemHint sourceItemHint) {
super(delegate.getName(), delegate.getType(), delegate.getDeclaringElement(), delegate.getGetter());
this.delegate = delegate;
this.sourceItemMetadata = sourceItemMetadata;
this.sourceItemHint = sourceItemHint;
}
@Override
protected ItemHint resolveItemHint(String prefix, MetadataGenerationEnvironment environment) {
return (this.sourceItemHint != null) ? this.sourceItemHint.applyPrefix(prefix)
: super.resolveItemHint(prefix, environment);
}
@Override
protected boolean isMarkedAsNested(MetadataGenerationEnvironment environment) {
return this.delegate.isMarkedAsNested(environment);
}
|
@Override
protected String resolveDescription(MetadataGenerationEnvironment environment) {
String description = this.delegate.resolveDescription(environment);
return (description != null) ? description : this.sourceItemMetadata.getDescription();
}
@Override
protected Object resolveDefaultValue(MetadataGenerationEnvironment environment) {
Object defaultValue = this.delegate.resolveDefaultValue(environment);
return (defaultValue != null) ? defaultValue : this.sourceItemMetadata.getDefaultValue();
}
@Override
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
ItemDeprecation itemDeprecation = this.delegate.resolveItemDeprecation(environment);
return (itemDeprecation != null) ? itemDeprecation : this.sourceItemMetadata.getDeprecation();
}
@Override
boolean isProperty(MetadataGenerationEnvironment environment) {
return this.delegate.isProperty(environment);
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ConfigurationPropertiesSourceResolver.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getElementId() {
return elementId;
}
public String getElementName() {
return elementName;
}
public String getScopeId() {
return scopeId;
}
public boolean isWithoutScopeId() {
return withoutScopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCorrelationId() {
return correlationId;
}
public boolean isOnlyTimers() {
return onlyTimers;
|
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public boolean isExecutable() {
return executable;
}
public boolean isOnlyExternalWorkers() {
return onlyExternalWorkers;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\DeadLetterJobQueryImpl.java
| 2
|
请完成以下Java代码
|
protected Properties getDelegate()
{
return getActualContext();
}
private static final long serialVersionUID = 0;
};
@Override
public void init()
{
// nothing to do here
}
@Override
public Properties getContext()
{
return ctxProxy;
}
private final Properties getActualContext()
{
final Properties temporaryCtx = temporaryCtxHolder.get();
if (temporaryCtx != null)
{
return temporaryCtx;
}
return rootCtx;
}
@Override
public IAutoCloseable switchContext(final Properties ctx)
{
Check.assumeNotNull(ctx, "ctx not null");
// If we were asked to set the context proxy (the one which we are returning everytime),
// then it's better to do nothing because this could end in a StackOverflowException.
if (ctx == ctxProxy)
{
return NullAutoCloseable.instance;
}
final Properties previousTempCtx = temporaryCtxHolder.get();
temporaryCtxHolder.set(ctx);
|
return new IAutoCloseable()
{
private boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
if (previousTempCtx != null)
{
temporaryCtxHolder.set(previousTempCtx);
}
else
{
temporaryCtxHolder.remove();
}
closed = true;
}
};
}
@Override
public void reset()
{
temporaryCtxHolder.remove();
rootCtx.clear();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\SwingContextProvider.java
| 1
|
请完成以下Java代码
|
public class Message implements Serializable {
private String messageText;
private String contentType;
public Message() {
}
public Message(String messageText, String contentType) {
this.messageText = messageText;
this.contentType = contentType;
}
public String getMessageText() {
return messageText;
|
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
repos\tutorials-master\core-java-modules\java-rmi\src\main\java\com\baeldung\rmi\Message.java
| 1
|
请完成以下Java代码
|
public class LocalTaskVariablesResource extends AbstractVariablesResource {
public LocalTaskVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) {
super(engine, resourceId, objectMapper);
}
protected String getResourceTypeName() {
return "task";
}
protected void removeVariableEntity(String variableKey) {
engine.getTaskService().removeVariableLocal(resourceId, variableKey);
}
protected VariableMap getVariableEntities(boolean deserializeValues) {
return engine.getTaskService().getVariablesLocalTyped(resourceId, deserializeValues);
}
|
protected void updateVariableEntities(VariableMap modifications, List<String> deletions) {
TaskServiceImpl taskService = (TaskServiceImpl) engine.getTaskService();
taskService.updateVariablesLocal(resourceId, modifications, deletions);
}
protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) {
return engine.getTaskService().getVariableLocalTyped(resourceId, variableKey, deserializeValue);
}
protected void setVariableEntity(String variableKey, TypedValue variableValue) {
engine.getTaskService().setVariableLocal(resourceId, variableKey, variableValue);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\LocalTaskVariablesResource.java
| 1
|
请完成以下Java代码
|
public int getC_Queue_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_WorkPackage_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
|
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setWP_IsError (boolean WP_IsError)
{
set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError));
}
@Override
public boolean isWP_IsError()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsError);
}
@Override
public void setWP_IsProcessed (boolean WP_IsProcessed)
{
set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed));
}
@Override
public boolean isWP_IsProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java
| 1
|
请完成以下Java代码
|
public boolean isSequential() {
return sequential;
}
public void setSequential(boolean sequential) {
this.sequential = sequential;
}
public String getLoopDataOutputRef() {
return loopDataOutputRef;
}
public void setLoopDataOutputRef(String loopDataOutputRef) {
this.loopDataOutputRef = loopDataOutputRef;
}
public String getOutputDataItem() {
return outputDataItem;
}
public void setOutputDataItem(String outputDataItem) {
this.outputDataItem = outputDataItem;
|
}
public MultiInstanceLoopCharacteristics clone() {
MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics();
clone.setValues(this);
return clone;
}
public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) {
setInputDataItem(otherLoopCharacteristics.getInputDataItem());
setLoopCardinality(otherLoopCharacteristics.getLoopCardinality());
setCompletionCondition(otherLoopCharacteristics.getCompletionCondition());
setElementVariable(otherLoopCharacteristics.getElementVariable());
setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable());
setSequential(otherLoopCharacteristics.isSequential());
setLoopDataOutputRef(otherLoopCharacteristics.getLoopDataOutputRef());
setOutputDataItem(otherLoopCharacteristics.getOutputDataItem());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MultiInstanceLoopCharacteristics.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getSalesId() {
return salesId;
}
public void setSalesId(String salesId) {
this.salesId = salesId;
}
public OrderStatus status(BigDecimal status) {
this.status = status;
return this;
}
/**
* -3 = Ausstehend, 0 = Angelegt, 1 = Übermittelt, 2 = Übermittlung fehlgeschlagen, 3 = Verarbeitet, 4 = Versandt, 5 = Ausgeliefert, 6 = Gelöscht, 7 = Storniert, 8 = Gestoppte Serienbestellung
* @return status
**/
@Schema(example = "3", required = true, description = "-3 = Ausstehend, 0 = Angelegt, 1 = Übermittelt, 2 = Übermittlung fehlgeschlagen, 3 = Verarbeitet, 4 = Versandt, 5 = Ausgeliefert, 6 = Gelöscht, 7 = Storniert, 8 = Gestoppte Serienbestellung")
public BigDecimal getStatus() {
return status;
}
public void setStatus(BigDecimal status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderStatus orderStatus = (OrderStatus) o;
return Objects.equals(this._id, orderStatus._id) &&
Objects.equals(this.salesId, orderStatus.salesId) &&
Objects.equals(this.status, orderStatus.status);
}
|
@Override
public int hashCode() {
return Objects.hash(_id, salesId, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderStatus {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" salesId: ").append(toIndentedString(salesId)).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(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderStatus.java
| 2
|
请完成以下Java代码
|
public class ExceptionResponseDto {
protected String type;
protected String message;
protected Integer code;
public String getType() {
return type;
}
public String getMessage() {
return message;
}
public void setType(String type) {
this.type = type;
|
}
public void setMessage(String message) {
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\dto\ExceptionResponseDto.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_Depreciation_Method[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Depreciation Calculation Type.
@param A_Depreciation_Method_ID Depreciation Calculation Type */
public void setA_Depreciation_Method_ID (int A_Depreciation_Method_ID)
{
if (A_Depreciation_Method_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Method_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Method_ID, Integer.valueOf(A_Depreciation_Method_ID));
}
/** Get Depreciation Calculation Type.
@return Depreciation Calculation Type */
public int getA_Depreciation_Method_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Method_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_Depreciation_Method_ID()));
}
/** Set DepreciationType.
@param DepreciationType DepreciationType */
public void setDepreciationType (String DepreciationType)
{
set_Value (COLUMNNAME_DepreciationType, DepreciationType);
}
/** Get DepreciationType.
@return DepreciationType */
public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
|
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Method.java
| 1
|
请完成以下Java代码
|
public void destroy() {
}
/**
* Determine if the request a non-modifying request. A non-modifying
* request is one that is either a 'HTTP GET/OPTIONS/HEAD' request, or
* is allowed explicitly through the 'entryPoints' parameter in the web.xml
*
* @return true if the request is a non-modifying request
* */
protected boolean isNonModifyingRequest(HttpServletRequest request) {
return CsrfConstants.CSRF_NON_MODIFYING_METHODS_PATTERN.matcher(request.getMethod()).matches()
|| entryPoints.contains(getRequestedPath(request));
}
/**
* Generate a one-time token for authenticating subsequent
* requests.
*
* @return the generated token
*/
protected String generateCSRFToken() {
byte random[] = new byte[16];
// Render the result as a String of hexadecimal digits
StringBuilder buffer = new StringBuilder();
randomSource.nextBytes(random);
for (int j = 0; j < random.length; j++) {
byte b1 = (byte) ((random[j] & 0xf0) >> 4);
byte b2 = (byte) (random[j] & 0x0f);
if (b1 < 10) {
buffer.append((char) ('0' + b1));
} else {
buffer.append((char) ('A' + (b1 - 10)));
}
if (b2 < 10) {
buffer.append((char) ('0' + b2));
} else {
buffer.append((char) ('A' + (b2 - 10)));
}
}
return buffer.toString();
}
private Object getCSRFTokenSession(HttpSession session) {
return session.getAttribute(CsrfConstants.CSRF_TOKEN_SESSION_ATTR_NAME);
}
private String getCSRFTokenHeader(HttpServletRequest request) {
return request.getHeader(CsrfConstants.CSRF_TOKEN_HEADER_NAME);
}
|
private Object getSessionMutex(HttpSession session) {
if (session == null) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "HttpSession is missing");
}
Object mutex = session.getAttribute(CsrfConstants.CSRF_SESSION_MUTEX);
if (mutex == null) {
mutex = session;
}
return mutex;
}
private boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private String getRequestedPath(HttpServletRequest request) {
String path = request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
return path;
}
private Set<String> parseURLs(String urlString) {
Set<String> urlSet = new HashSet<>();
if (urlString != null && !urlString.isEmpty()) {
String values[] = urlString.split(",");
for (String value : values) {
urlSet.add(value.trim());
}
}
return urlSet;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\CsrfPreventionFilter.java
| 1
|
请完成以下Java代码
|
protected boolean isDaysBetweenDunningsRespected(final Date dunningDate, final int requiredDaysBetweenDunnings, final List<I_C_Dunning_Candidate> candidates)
{
if (candidates.isEmpty())
{
// no previous candidates => of course is respected
return true;
}
final int daysAfterLast = getDaysAfterLastDunningEffective(dunningDate, candidates);
if (daysAfterLast == DAYS_NotAvailable)
{
// TODO if days after last dunning could not be calculated (e.g. all candidates are not processed) then consider it "Respected")
// NOTE: Discussion with Mark: if sequentially (see there) this case cannot happen => internal error
throw new InconsistentDunningCandidateStateException("Inconsistent state: DaysAfterLast is not available for (DunningDate=" + dunningDate + ", candidates=" + candidates + ")");
}
else if (daysAfterLast < 0)
{
// We have future dunning candidates (relatively to dunningDate) => rule not respected
// metas-mo: don't create candidates!
logger.info("Negative DaysAfterLast={}. Consider rule not respected", daysAfterLast);
return false;
}
else if (daysAfterLast >= requiredDaysBetweenDunnings)
{
// it passed more days after last dunning then required, defenetelly we can dun again
return true;
}
return false;
}
protected Date getLastDunningDateEffective(final List<I_C_Dunning_Candidate> candidates)
{
Date lastDunningDateEffective = null;
for (final I_C_Dunning_Candidate candidate : candidates)
{
// When we are calculating the effective date, we consider only candidates that have processed dunning docs
if (!candidate.isDunningDocProcessed())
{
continue;
}
final Date dunningDateEffective = candidate.getDunningDateEffective();
Check.assumeNotNull(dunningDateEffective, "DunningDateEffective shall be available for candidate with dunning docs processed: {}", candidate);
|
if (lastDunningDateEffective == null)
{
lastDunningDateEffective = dunningDateEffective;
}
else if (lastDunningDateEffective.before(dunningDateEffective))
{
lastDunningDateEffective = dunningDateEffective;
}
}
return lastDunningDateEffective;
}
/**
* Gets Days after last DunningDateEffective
*
* @param dunningDate
* @param candidates
* @return days after DunningDateEffective or {@link #DAYS_NotAvailable} if not available
*/
protected int getDaysAfterLastDunningEffective(final Date dunningDate, final List<I_C_Dunning_Candidate> candidates)
{
final Date lastDunningDate = getLastDunningDateEffective(candidates);
if (lastDunningDate == null)
{
return DAYS_NotAvailable;
}
final int daysAfterLast = TimeUtil.getDaysBetween(lastDunningDate, dunningDate);
return daysAfterLast;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunningCandidateProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<List<RoleVO>> tree(String tenantId, BladeUser bladeUser) {
List<RoleVO> tree = roleService.tree(Func.toStr(tenantId, bladeUser.getTenantId()));
return R.data(tree);
}
/**
* 获取指定角色树形结构
*/
@GetMapping("/tree-by-id")
@ApiOperationSupport(order = 4)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<RoleVO>> treeById(Long roleId, BladeUser bladeUser) {
Role role = roleService.getById(roleId);
List<RoleVO> tree = roleService.tree(Func.notNull(role) ? role.getTenantId() : bladeUser.getTenantId());
return R.data(tree);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 5)
@Operation(summary = "新增或修改", description = "传入role")
public R submit(@Valid @RequestBody Role role, BladeUser user) {
CacheUtil.clear(SYS_CACHE);
if (Func.isEmpty(role.getId())) {
role.setTenantId(user.getTenantId());
}
return R.status(roleService.saveOrUpdate(role));
}
/**
* 删除
*/
@PostMapping("/remove")
|
@ApiOperationSupport(order = 6)
@Operation(summary = "删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
CacheUtil.clear(SYS_CACHE);
return R.status(roleService.removeByIds(Func.toLongList(ids)));
}
/**
* 设置菜单权限
*/
@PostMapping("/grant")
@ApiOperationSupport(order = 7)
@Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合")
public R grant(@RequestBody GrantVO grantVO) {
CacheUtil.clear(SYS_CACHE);
boolean temp = roleService.grant(grantVO.getRoleIds(), grantVO.getMenuIds(), grantVO.getDataScopeIds());
return R.status(temp);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RoleController.java
| 2
|
请完成以下Java代码
|
public class Role {
private Long rid; // 角色id
private String rname; // 角色名,用于显示
private String rdesc; // 角色描述
private String rval; // 角色值,用于权限判断
private Date created; // 创建时间
private Date updated; // 修改时间
public Long getRid() {
return rid;
}
public void setRid(Long rid) {
this.rid = rid;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public String getRdesc() {
return rdesc;
}
public void setRdesc(String rdesc) {
this.rdesc = rdesc;
}
public String getRval() {
return rval;
}
|
public void setRval(String rval) {
this.rval = rval;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
|
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Role.java
| 1
|
请完成以下Java代码
|
public List<HistoricVariableInstanceDto> getHistoricVariableInstances(UriInfo uriInfo, Integer firstResult,
Integer maxResults, boolean deserializeObjectValues) {
HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues);
}
@Override
public List<HistoricVariableInstanceDto> queryHistoricVariableInstances(HistoricVariableInstanceQueryDto queryDto,
Integer firstResult, Integer maxResults, boolean deserializeObjectValues) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
query.disableBinaryFetching();
if (!deserializeObjectValues) {
query.disableCustomObjectDeserialization();
}
List<HistoricVariableInstance> matchingHistoricVariableInstances = QueryUtil.list(query, firstResult, maxResults);
List<HistoricVariableInstanceDto> historicVariableInstanceDtoResults = new ArrayList<HistoricVariableInstanceDto>();
for (HistoricVariableInstance historicVariableInstance : matchingHistoricVariableInstances) {
HistoricVariableInstanceDto resultHistoricVariableInstance = HistoricVariableInstanceDto.fromHistoricVariableInstance(historicVariableInstance);
historicVariableInstanceDtoResults.add(resultHistoricVariableInstance);
}
return historicVariableInstanceDtoResults;
}
|
@Override
public CountResultDto getHistoricVariableInstancesCount(UriInfo uriInfo) {
HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricVariableInstancesCount(queryDto);
}
@Override
public CountResultDto queryHistoricVariableInstancesCount(HistoricVariableInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricVariableInstanceRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitaets-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitaets-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** 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());
}
/** Type AD_Reference_ID=101 */
public static final int TYPE_AD_Reference_ID=101;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Java = J */
public static final String TYPE_Java = "J";
/** Java-Script = E */
public static final String TYPE_Java_Script = "E";
/** Composite = C */
public static final String TYPE_Composite = "C";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule.java
| 1
|
请完成以下Java代码
|
public DeploymentCache<Object> getAppResourceCache() {
return appResourceCache;
}
public void setAppResourceCache(DeploymentCache<Object> appResourceCache) {
this.appResourceCache = appResourceCache;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
public ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
|
return processDefinitionEntityManager;
}
public void setProcessDefinitionEntityManager(ProcessDefinitionEntityManager processDefinitionEntityManager) {
this.processDefinitionEntityManager = processDefinitionEntityManager;
}
public DeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(DeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\deploy\DeploymentManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static final class JacksonClusterEnvironmentBuilderCustomizer
implements ClusterEnvironmentBuilderCustomizer, Ordered {
private final ObjectMapper objectMapper;
private JacksonClusterEnvironmentBuilderCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(Builder builder) {
builder.jsonSerializer(JacksonJsonSerializer.create(this.objectMapper));
}
@Override
public int getOrder() {
return 0;
}
}
/**
* Condition that matches when {@code spring.couchbase.connection-string} has been
* configured or there is a {@link CouchbaseConnectionDetails} bean.
*/
static final class CouchbaseCondition extends AnyNestedCondition {
CouchbaseCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.couchbase.connection-string")
private static final class CouchbaseUrlCondition {
}
@ConditionalOnBean(CouchbaseConnectionDetails.class)
private static final class CouchbaseConnectionDetailsCondition {
}
}
/**
* Adapts {@link CouchbaseProperties} to {@link CouchbaseConnectionDetails}.
*/
static final class PropertiesCouchbaseConnectionDetails implements CouchbaseConnectionDetails {
private final CouchbaseProperties properties;
private final @Nullable SslBundles sslBundles;
PropertiesCouchbaseConnectionDetails(CouchbaseProperties properties, @Nullable SslBundles sslBundles) {
this.properties = properties;
this.sslBundles = sslBundles;
}
@Override
|
public String getConnectionString() {
String connectionString = this.properties.getConnectionString();
Assert.state(connectionString != null, "'connectionString' must not be null");
return connectionString;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getEnv().getSsl();
if (!ssl.getEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public static Instant asInstant()
{
return Instant.ofEpochMilli(millis());
}
public static LocalDateTime asLocalDateTime()
{
return asZonedDateTime().toLocalDateTime();
}
@NonNull
public static LocalDate asLocalDate()
{
return asLocalDate(zoneId());
}
@NonNull
public static LocalDate asLocalDate(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId).toLocalDate();
}
public static ZonedDateTime asZonedDateTime()
{
return asZonedDateTime(zoneId());
}
|
public static ZonedDateTime asZonedDateTimeAtStartOfDay()
{
return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS);
}
public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId)
.toLocalDate()
.atTime(LocalTime.MAX)
.atZone(zoneId);
}
public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId)
{
return asInstant().atZone(zoneId);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
| 1
|
请完成以下Java代码
|
public void setCM_WikiToken_ID (int CM_WikiToken_ID)
{
if (CM_WikiToken_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_WikiToken_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_WikiToken_ID, Integer.valueOf(CM_WikiToken_ID));
}
/** Get Wiki Token.
@return Wiki Token
*/
public int getCM_WikiToken_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_WikiToken_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 Macro.
@param Macro
Macro
*/
public void setMacro (String Macro)
{
set_Value (COLUMNNAME_Macro, Macro);
}
/** Get Macro.
@return Macro
*/
public String getMacro ()
{
return (String)get_Value(COLUMNNAME_Macro);
}
/** 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 Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
|
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** TokenType AD_Reference_ID=397 */
public static final int TOKENTYPE_AD_Reference_ID=397;
/** SQL Command = Q */
public static final String TOKENTYPE_SQLCommand = "Q";
/** Internal Link = I */
public static final String TOKENTYPE_InternalLink = "I";
/** External Link = E */
public static final String TOKENTYPE_ExternalLink = "E";
/** Style = S */
public static final String TOKENTYPE_Style = "S";
/** Set TokenType.
@param TokenType
Wiki Token Type
*/
public void setTokenType (String TokenType)
{
set_Value (COLUMNNAME_TokenType, TokenType);
}
/** Get TokenType.
@return Wiki Token Type
*/
public String getTokenType ()
{
return (String)get_Value(COLUMNNAME_TokenType);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java
| 1
|
请完成以下Java代码
|
public static MCharge get (Properties ctx, int C_Charge_ID)
{
Integer key = new Integer (C_Charge_ID);
MCharge retValue = s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MCharge (ctx, C_Charge_ID, null);
if (retValue.get_ID() != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer, MCharge> s_cache
= new CCache<> ("C_Charge", 10);
/** Static Logger */
private static Logger s_log = LogManager.getLogger(MCharge.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param C_Charge_ID id
* @param trxName transaction
*/
public MCharge (Properties ctx, int C_Charge_ID, String trxName)
{
super (ctx, C_Charge_ID, trxName);
if (C_Charge_ID == 0)
{
setChargeAmt (Env.ZERO);
setIsSameCurrency (false);
setIsSameTax (false);
setIsTaxIncluded (false); // N
// setName (null);
// setC_TaxCategory_ID (0);
}
} // MCharge
/**
* Load Constructor
* @param ctx ctx
|
* @param rs result set
* @param trxName transaction
*/
public MCharge (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MCharge
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success)
insert_Accounting("C_Charge_Acct", "C_AcctSchema_Default", null);
return success;
} // afterSave
/**
* Before Delete
* @return true
*/
@Override
protected boolean beforeDelete ()
{
return delete_Accounting("C_Charge_Acct");
} // beforeDelete
} // MCharge
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCharge.java
| 1
|
请完成以下Java代码
|
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
|
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
}
|
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InfluxConsistency getConsistency() {
return this.consistency;
}
public void setConsistency(InfluxConsistency consistency) {
this.consistency = consistency;
}
public @Nullable String getUserName() {
return this.userName;
}
public void setUserName(@Nullable String userName) {
this.userName = userName;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getRetentionPolicy() {
return this.retentionPolicy;
}
public void setRetentionPolicy(@Nullable String retentionPolicy) {
this.retentionPolicy = retentionPolicy;
}
public @Nullable String getRetentionDuration() {
return this.retentionDuration;
}
public void setRetentionDuration(@Nullable String retentionDuration) {
this.retentionDuration = retentionDuration;
}
public @Nullable Integer getRetentionReplicationFactor() {
return this.retentionReplicationFactor;
}
public void setRetentionReplicationFactor(@Nullable Integer retentionReplicationFactor) {
this.retentionReplicationFactor = retentionReplicationFactor;
}
public @Nullable String getRetentionShardDuration() {
return this.retentionShardDuration;
}
public void setRetentionShardDuration(@Nullable String retentionShardDuration) {
this.retentionShardDuration = retentionShardDuration;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isCompressed() {
return this.compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public boolean isAutoCreateDb() {
return this.autoCreateDb;
}
public void setAutoCreateDb(boolean autoCreateDb) {
this.autoCreateDb = autoCreateDb;
|
}
public @Nullable InfluxApiVersion getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(@Nullable InfluxApiVersion apiVersion) {
this.apiVersion = apiVersion;
}
public @Nullable String getOrg() {
return this.org;
}
public void setOrg(@Nullable String org) {
this.org = org;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private HuId getHuIdToBePicked()
{
final PickingJobStep step = getStepIfExists().orElse(null);
if (step != null)
{
return getStep()
.getPickFrom(stepPickFromKey)
.assertNotPicked()
.getPickFromHUId();
}
else
{
return getPickFromHUIdAndQRCode().getId();
}
}
private ShipmentScheduleInfo getShipmentScheduleInfo()
{
return shipmentSchedulesCache.computeIfAbsent(getScheduleId().getShipmentScheduleId(), shipmentScheduleService::getById);
}
private HUInfo getSingleTUInfo(@NonNull final TU tu)
{
tu.assertSingleTU();
return getHUInfo(tu.getId());
}
private HUInfo getHUInfo(@NonNull final HuId huId)
{
return HUInfo.builder()
.id(huId)
.qrCode(huService.getQRCodeByHuId(huId))
.build();
}
public Quantity getStorageQty(@NonNull final TU tu, @NonNull final ProductId productId)
{
final IHUStorageFactory huStorageFactory = HUContextHolder.getCurrent().getHUStorageFactory();
return huStorageFactory.getStorage(tu.toHU()).getQuantity(productId).orElseThrow(() -> new AdempiereException(NO_QTY_ERROR_MSG, tu, productId));
}
private HUQRCode getQRCode(@NonNull final LU lu) {return huService.getQRCodeByHuId(lu.getId());}
private HUQRCode getQRCode(@NonNull final TU tu) {return huService.getQRCodeByHuId(tu.getId());}
private void addToPickingSlotQueue(final LUTUResult packedHUs)
{
final PickingSlotId pickingSlotId = getPickingSlotId().orElse(null);
|
if (pickingSlotId == null)
{
return;
}
final CurrentPickingTarget currentPickingTarget = getPickingJob().getCurrentPickingTarget();
final LinkedHashSet<HuId> huIdsToAdd = new LinkedHashSet<>();
for (final LU lu : packedHUs.getLus())
{
if (lu.isPreExistingLU())
{
continue;
}
// do not add it if is current picking target, we will add it when closing the picking target.
if (currentPickingTarget.matches(lu.getId()))
{
continue;
}
huIdsToAdd.add(lu.getId());
}
for (final TU tu : packedHUs.getTopLevelTUs())
{
// do not add it if is current picking target, we will add it when closing the picking target.
if (currentPickingTarget.matches(tu.getId()))
{
continue;
}
huIdsToAdd.add(tu.getId());
}
if (!huIdsToAdd.isEmpty())
{
pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIdsToAdd);
}
}
private Optional<PickingSlotId> getPickingSlotId()
{
return getPickingJob().getPickingSlotIdEffective(getLineId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\pick\PickingJobPickCommand.java
| 2
|
请完成以下Java代码
|
private static String getTransactionIsolationInfo(int transactionIsolation)
{
if (transactionIsolation == Connection.TRANSACTION_NONE)
{
return "NONE";
}
if (transactionIsolation == Connection.TRANSACTION_READ_COMMITTED)
{
return "READ_COMMITTED";
}
if (transactionIsolation == Connection.TRANSACTION_READ_UNCOMMITTED)
{
return "READ_UNCOMMITTED";
}
if (transactionIsolation == Connection.TRANSACTION_REPEATABLE_READ)
{
|
return "REPEATABLE_READ";
}
if (transactionIsolation == Connection.TRANSACTION_SERIALIZABLE)
{
return "SERIALIZABLE";
}
return "<?" + transactionIsolation + "?>";
} // getTransactionIsolationInfo
@Override
public Object clone() throws CloneNotSupportedException
{
CConnection c = (CConnection)super.clone();
return c;
}
} // CConnection
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnection.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);
}
/** Set Frequency.
@param Frequency
Frequency of events
*/
@Override
public void setFrequency (int Frequency)
{
set_Value (COLUMNNAME_Frequency, Integer.valueOf(Frequency));
}
/** Get Frequency.
@return Frequency of events
*/
@Override
public int getFrequency ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Frequency);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* FrequencyType AD_Reference_ID=540067
* Reference name: Recurrent Payment Frequency Type
*/
public static final int FREQUENCYTYPE_AD_Reference_ID=540067;
/** Day = D */
public static final String FREQUENCYTYPE_Day = "D";
/** Month = M */
public static final String FREQUENCYTYPE_Month = "M";
/** Set Frequency Type.
@param FrequencyType
Frequency of event
*/
@Override
public void setFrequencyType (java.lang.String FrequencyType)
{
set_Value (COLUMNNAME_FrequencyType, FrequencyType);
}
/** Get Frequency Type.
@return Frequency of event
*/
@Override
public java.lang.String getFrequencyType ()
{
return (java.lang.String)get_Value(COLUMNNAME_FrequencyType);
}
/** Set Next Payment Date.
@param NextPaymentDate Next Payment Date */
@Override
public void setNextPaymentDate (java.sql.Timestamp NextPaymentDate)
{
set_ValueNoCheck (COLUMNNAME_NextPaymentDate, NextPaymentDate);
}
/** Get Next Payment Date.
@return Next Payment Date */
@Override
public java.sql.Timestamp getNextPaymentDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_NextPaymentDate);
}
|
/** Set Payment amount.
@param PayAmt
Amount being paid
*/
@Override
public void setPayAmt (java.math.BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Payment amount.
@return Amount being paid
*/
@Override
public java.math.BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentLine.java
| 1
|
请完成以下Java代码
|
protected boolean shouldFetchValue(HistoricDetailVariableInstanceUpdateEntity entity) {
final ValueType entityType = entity.getSerializer().getType();
// do no fetch values for byte arrays/blob variables (e.g. files or bytes)
return !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entityType.getName())
// nor object values unless enabled
&& (!ValueType.OBJECT.equals(entityType) || !excludeObjectValues);
}
protected boolean isHistoricDetailVariableInstanceUpdateEntity(HistoricVariableUpdate variableUpdate) {
return variableUpdate instanceof HistoricDetailVariableInstanceUpdateEntity;
}
protected List<String> getByteArrayIds(List<HistoricVariableUpdate> variableUpdates) {
List<String> byteArrayIds = new ArrayList<>();
for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) {
HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
String byteArrayId = entity.getByteArrayValueId();
if (byteArrayId != null) {
byteArrayIds.add(byteArrayId);
}
}
}
}
return byteArrayIds;
}
protected void resolveTypedValues(List<HistoricVariableUpdate> variableUpdates) {
|
for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) {
HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
try {
entity.getTypedValue(false);
} catch (Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\optimize\OptimizeHistoricVariableUpdateQueryCmd.java
| 1
|
请完成以下Java代码
|
public class DecisionCacheEntry implements Serializable {
private static final long serialVersionUID = 1L;
protected DecisionEntity decisionEntity;
protected DmnDefinition dmnDefinition;
protected DecisionService decisionService;
protected Decision decision;
public DecisionCacheEntry(DecisionEntity decisionEntity, DmnDefinition dmnDefinition, DecisionService decisionService) {
this.decisionEntity = decisionEntity;
this.dmnDefinition = dmnDefinition;
this.decisionService = decisionService;
}
public DecisionCacheEntry(DecisionEntity decisionEntity, DmnDefinition dmnDefinition, Decision decision) {
this.decisionEntity = decisionEntity;
this.dmnDefinition = dmnDefinition;
this.decision = decision;
}
public DecisionEntity getDecisionEntity() {
return decisionEntity;
}
public void setDecisionEntity(DecisionEntity decisionEntity) {
|
this.decisionEntity = decisionEntity;
}
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
public DecisionService getDecisionService() {
return decisionService;
}
public void setDecisionService(DecisionService decisionService) {
this.decisionService = decisionService;
}
public Decision getDecision() {
return decision;
}
public void setDecision(Decision decision) {
this.decision = decision;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\deploy\DecisionCacheEntry.java
| 1
|
请完成以下Java代码
|
public boolean isReadWrite()
{
return super.isEnabled();
} // isReadWrite
/**
* Set Editor to value
* @param value value of the editor
*/
@Override
public void setValue (Object value)
{
if (value == null)
setText("");
else
setText(value.toString());
} // setValue
/**
* Return Editor value
* @return current value
*/
@Override
public Object getValue()
|
{
return getText();
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
return getText();
} // getDisplay
} // CToggleButton
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CToggleButton.java
| 1
|
请完成以下Java代码
|
public static Layout forFile(File file) {
Assert.notNull(file, "'file' must not be null");
String lowerCaseFileName = file.getName().toLowerCase(Locale.ENGLISH);
if (lowerCaseFileName.endsWith(".jar")) {
return new Jar();
}
if (lowerCaseFileName.endsWith(".war")) {
return new War();
}
if (file.isDirectory() || lowerCaseFileName.endsWith(".zip")) {
return new Expanded();
}
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
}
/**
* Executable JAR layout.
*/
public static class Jar implements RepackagingLayout {
@Override
public @Nullable String getLauncherClassName() {
return "org.springframework.boot.loader.launch.JarLauncher";
}
@Override
public String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return "BOOT-INF/lib/";
}
@Override
public String getClassesLocation() {
return "";
}
@Override
public String getRepackagedClassesLocation() {
return "BOOT-INF/classes/";
}
@Override
public String getClasspathIndexFileLocation() {
return "BOOT-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "BOOT-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
/**
* Executable expanded archive layout.
*/
public static class Expanded extends Jar {
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.PropertiesLauncher";
}
}
/**
* No layout.
*/
public static class None extends Jar {
|
@Override
public @Nullable String getLauncherClassName() {
return null;
}
@Override
public boolean isExecutable() {
return false;
}
}
/**
* Executable WAR layout.
*/
public static class War implements Layout {
private static final Map<LibraryScope, String> SCOPE_LOCATION;
static {
Map<LibraryScope, String> locations = new HashMap<>();
locations.put(LibraryScope.COMPILE, "WEB-INF/lib/");
locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/");
locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/");
locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_LOCATION = Collections.unmodifiableMap(locations);
}
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.WarLauncher";
}
@Override
public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return SCOPE_LOCATION.get(scope);
}
@Override
public String getClassesLocation() {
return "WEB-INF/classes/";
}
@Override
public String getClasspathIndexFileLocation() {
return "WEB-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "WEB-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java
| 1
|
请完成以下Java代码
|
public class HumanTaskActivityBehavior extends TaskActivityBehavior {
protected TaskDecorator taskDecorator;
protected void performStart(CmmnActivityExecution execution) {
execution.createTask(taskDecorator);
}
protected void performTerminate(CmmnActivityExecution execution) {
terminating(execution);
super.performTerminate(execution);
}
protected void performExit(CmmnActivityExecution execution) {
terminating(execution);
super.performExit(execution);
}
protected void terminating(CmmnActivityExecution execution) {
TaskEntity task = getTask(execution);
// it can happen that a there does not exist
// a task, because the given execution was never
// active.
if (task != null) {
task.delete("terminated", false);
}
}
protected void completing(CmmnActivityExecution execution) {
TaskEntity task = getTask(execution);
if (task != null) {
task.caseExecutionCompleted();
}
}
protected void manualCompleting(CmmnActivityExecution execution) {
completing(execution);
}
protected void suspending(CmmnActivityExecution execution) {
String id = execution.getId();
Context
.getCommandContext()
.getTaskManager()
.updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.SUSPENDED);
}
protected void resuming(CmmnActivityExecution execution) {
|
String id = execution.getId();
Context
.getCommandContext()
.getTaskManager()
.updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.ACTIVE);
}
protected TaskEntity getTask(CmmnActivityExecution execution) {
return Context
.getCommandContext()
.getTaskManager()
.findTaskByCaseExecutionId(execution.getId());
}
protected String getTypeName() {
return "human task";
}
// getters/setters /////////////////////////////////////////////////
public TaskDecorator getTaskDecorator() {
return taskDecorator;
}
public void setTaskDecorator(TaskDecorator taskDecorator) {
this.taskDecorator = taskDecorator;
}
public TaskDefinition getTaskDefinition() {
return taskDecorator.getTaskDefinition();
}
public ExpressionManager getExpressionManager() {
return taskDecorator.getExpressionManager();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\HumanTaskActivityBehavior.java
| 1
|
请完成以下Java代码
|
private static HardwarePrinter fromRecord(
@NonNull final I_AD_PrinterHW printerRecord,
@NonNull final ImmutableListMultimap<HardwarePrinterId, HardwareTray> traysByPrinterId)
{
final HardwarePrinterId id = HardwarePrinterId.ofRepoId(printerRecord.getAD_PrinterHW_ID());
return HardwarePrinter.builder()
.id(id)
.name(printerRecord.getName())
.outputType(OutputType.ofCode(printerRecord.getOutputType()))
.externalSystemParentConfigId(ExternalSystemParentConfigId.ofRepoIdOrNull(printerRecord.getExternalSystem_Config_ID()))
.ippUrl(extractIPPUrl(printerRecord))
.trays(traysByPrinterId.get(id))
.build();
}
@Nullable
private static URI extractIPPUrl(final @NonNull I_AD_PrinterHW printerRecord)
{
final String ippUrl = StringUtils.trimBlankToNull(printerRecord.getIPP_URL());
if (ippUrl == null)
{
return null;
}
return URI.create(ippUrl);
}
@NonNull
private static HardwareTray fromRecord(@NonNull final I_AD_PrinterHW_MediaTray trayRecord)
{
final HardwareTrayId trayId = HardwareTrayId.ofRepoId(trayRecord.getAD_PrinterHW_ID(), trayRecord.getAD_PrinterHW_MediaTray_ID());
return new HardwareTray(trayId, trayRecord.getName(), trayRecord.getTrayNumber());
}
public void deleteCalibrations(@NonNull final HardwarePrinterId printerId) {printingDAO.deleteCalibrations(printerId);}
public void deleteMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaTrays(hardwarePrinterId);}
public void deleteMediaSizes(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaSizes(hardwarePrinterId);}
//
//
//
//
//
|
private static class HardwarePrinterMap
{
private final ImmutableMap<HardwarePrinterId, HardwarePrinter> byId;
private HardwarePrinterMap(final List<HardwarePrinter> list)
{
this.byId = Maps.uniqueIndex(list, HardwarePrinter::getId);
}
public HardwarePrinter getById(@NonNull final HardwarePrinterId id)
{
final HardwarePrinter hardwarePrinter = byId.get(id);
if (hardwarePrinter == null)
{
throw new AdempiereException("No active hardware printer found for id " + id);
}
return hardwarePrinter;
}
public Collection<HardwarePrinter> getByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
return streamByIds(ids).collect(ImmutableList.toImmutableList());
}
public Stream<HardwarePrinter> streamByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
if (ids.isEmpty())
{
return Stream.empty();
}
return ids.stream()
.map(byId::get)
.filter(Objects::nonNull);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean tryCreateSignatureVerifier() {
long t = System.currentTimeMillis();
if (t - lastKeyFetchTimestamp < oAuth2Properties.getSignatureVerification().getPublicKeyRefreshRateLimit()) {
return false;
}
try {
SignatureVerifier verifier = signatureVerifierClient.getSignatureVerifier();
if (verifier != null) {
setVerifier(verifier);
lastKeyFetchTimestamp = t;
log.debug("Public key retrieved from OAuth2 server to create SignatureVerifier");
return true;
}
} catch (Throwable ex) {
log.error("could not get public key from OAuth2 server to create SignatureVerifier", ex);
}
return false;
}
/**
* Extract JWT claims and set it to OAuth2Authentication decoded details.
* Here is how to get details:
*
* <pre>
* <code>
* SecurityContext securityContext = SecurityContextHolder.getContext();
* Authentication authentication = securityContext.getAuthentication();
* if (authentication != null) {
* Object details = authentication.getDetails();
|
* if(details instanceof OAuth2AuthenticationDetails) {
* Object decodedDetails = ((OAuth2AuthenticationDetails) details).getDecodedDetails();
* if(decodedDetails != null && decodedDetails instanceof Map) {
* String detailFoo = ((Map) decodedDetails).get("foo");
* }
* }
* }
* </code>
* </pre>
* @param claims OAuth2JWTToken claims
* @return OAuth2Authentication
*/
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
OAuth2Authentication authentication = super.extractAuthentication(claims);
authentication.setDetails(claims);
return authentication;
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2JwtAccessTokenConverter.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Void call() throws Exception {
preUndeployMethod.invoke(processApplication.getRawObject(), getInjections(preUndeployMethod));
return null;
}
});
} catch(Exception e) {
throw new RuntimeException("Exception while invoking the @PreUndeploy method ", e);
}
}
}
}
protected Object[] getInjections(Method lifecycleMethod) {
final Type[] parameterTypes = lifecycleMethod.getGenericParameterTypes();
final List<Object> parameters = new ArrayList<>();
for (Type parameterType : parameterTypes) {
boolean injectionResolved = false;
if(parameterType instanceof Class) {
Class<?> parameterClass = (Class<?>)parameterType;
// support injection of the default process engine, if present
if(ProcessEngine.class.isAssignableFrom(parameterClass)) {
parameters.add(defaultProcessEngineSupplier.get());
injectionResolved = true;
}
// support injection of the ProcessApplicationInfo
else if(ProcessApplicationInfo.class.isAssignableFrom(parameterClass)) {
parameters.add(processApplicationInfo);
injectionResolved = true;
}
} else if(parameterType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) parameterType;
|
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// support injection of List<ProcessEngine>
if(actualTypeArguments.length==1 && ProcessEngine.class.isAssignableFrom((Class<?>) actualTypeArguments[0])) {
parameters.add(new ArrayList<>(referencedProcessEngines));
injectionResolved = true;
}
}
if(!injectionResolved) {
throw new ProcessEngineException("Unsupported parametertype "+parameterType);
}
}
return parameters.toArray();
}
protected Class<?> getPaClass(AnnotationInstance annotation) throws ClassNotFoundException {
String paClassName = ((MethodInfo)annotation.target()).declaringClass().name().toString();
Class<?> paClass = paModule.getClassLoader().loadClass(paClassName);
return paClass;
}
@SuppressWarnings("unchecked")
private ProcessApplicationDeploymentService getDeploymentService(StartContext context, ServiceName deploymentServiceName) {
final ServiceContainer serviceContainer = context.getController().getServiceContainer();
ServiceController<ProcessApplicationDeploymentService> deploymentService = (ServiceController<ProcessApplicationDeploymentService>) serviceContainer.getRequiredService(deploymentServiceName);
return deploymentService.getValue();
}
@Override
public ProcessApplicationStartService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationStartService.java
| 2
|
请完成以下Java代码
|
public VersionProperty getProperty() {
return this.property;
}
/**
* Return the version or {@code null} if this reference is backed by a property.
* @return the version or {@code null}
*/
public String getValue() {
return this.value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
|
if (o == null || getClass() != o.getClass()) {
return false;
}
VersionReference that = (VersionReference) o;
return Objects.equals(this.property, that.property) && Objects.equals(this.value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.value);
}
@Override
public String toString() {
return (this.property != null) ? "${" + this.property.toStandardFormat() + "}" : this.value;
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionReference.java
| 1
|
请完成以下Java代码
|
static ServerResponse.HeadersBuilder<?> notFound() {
return status(HttpStatus.NOT_FOUND);
}
/**
* Create a builder with a {@linkplain HttpStatus#UNPROCESSABLE_ENTITY 422
* Unprocessable Entity} status.
* @return the created builder
*/
static ServerResponse.BodyBuilder unprocessableEntity() {
return status(HttpStatus.UNPROCESSABLE_ENTITY);
}
/**
* Create a (built) response with the given asynchronous response. Parameter
* {@code asyncResponse} can be a {@link CompletableFuture
* CompletableFuture<ServerResponse>} or {@link Publisher
* Publisher<ServerResponse>} (or any asynchronous producer of a single
* {@code ServerResponse} that can be adapted via the
* {@link ReactiveAdapterRegistry}).
*
* <p>
* This method can be used to set the response status code, headers, and body based on
* an asynchronous result. If only the body is asynchronous,
* {@link ServerResponse.BodyBuilder#body(Object)} can be used instead.
* @param asyncResponse a {@code CompletableFuture<ServerResponse>} or
* {@code Publisher<ServerResponse>}
* @return the asynchronous response
* @since 5.3
|
*/
static ServerResponse async(Object asyncResponse) {
return GatewayAsyncServerResponse.create(asyncResponse, null);
}
/**
* Create a (built) response with the given asynchronous response. Parameter
* {@code asyncResponse} can be a {@link CompletableFuture
* CompletableFuture<ServerResponse>} or {@link Publisher
* Publisher<ServerResponse>} (or any asynchronous producer of a single
* {@code ServerResponse} that can be adapted via the
* {@link ReactiveAdapterRegistry}).
*
* <p>
* This method can be used to set the response status code, headers, and body based on
* an asynchronous result. If only the body is asynchronous,
* {@link ServerResponse.BodyBuilder#body(Object)} can be used instead.
* @param asyncResponse a {@code CompletableFuture<ServerResponse>} or
* {@code Publisher<ServerResponse>}
* @param timeout maximum time period to wait for before timing out
* @return the asynchronous response
* @since 5.3.2
*/
static ServerResponse async(Object asyncResponse, Duration timeout) {
return GatewayAsyncServerResponse.create(asyncResponse, timeout);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponse.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.