instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class SAPGLJournalLine
{
@Nullable private SAPGLJournalLineId id;
@Getter @Setter(AccessLevel.PACKAGE) private boolean processed;
@Nullable @Getter private final SAPGLJournalLineId parentId;
@NonNull @Getter @Setter(AccessLevel.PACKAGE) private SeqNo line;
@Nullable @Getter private final String description;
@NonNull @Getter private final Account account;
@NonNull @Getter private final PostingSign postingSign;
@NonNull @Getter @Setter private Money amount;
@NonNull @Getter @Setter(AccessLevel.PACKAGE) private Money amountAcct;
@Nullable @Getter private final TaxId taxId;
@NonNull @Getter private final OrgId orgId;
@Nullable @Getter private final BPartnerId bpartnerId;
@NonNull @Getter private final Dimension dimension;
@Getter private final boolean determineTaxBaseSAP;
@Getter private final boolean isExplodeToNetAndTaxLines;
@Getter @Setter private boolean isTaxIncluded;
@Nullable @Getter private final FAOpenItemTrxInfo openItemTrxInfo;
@Getter private final boolean isFieldsReadOnlyInUI;
public SAPGLJournalLineId getIdNotNull()
{
if (id == null)
{
throw new AdempiereException("Line ID not yet available: " + this);
}
return id;
}
@Nullable
public SAPGLJournalLineId getIdOrNull()
{
return id;
}
public void assignId(@NonNull final SAPGLJournalLineId id)
{
if (this.id != null && !SAPGLJournalLineId.equals(this.id, id))
{
throw new AdempiereException("Line has already assigned a different ID: " + this);
}
this.id = id;
}
public boolean isGeneratedTaxLine()
{
return parentId != null && taxId != null;
}
/**
* This logic expects, that tax lines always generated from an base account with tax set (included or not)
*/ | public boolean isTaxLine()
{
return taxId != null && (determineTaxBaseSAP || parentId != null);
}
public boolean isTaxLineGeneratedForBaseLine(@NonNull final SAPGLJournalLine taxBaseLine)
{
return isTaxLine()
&& parentId != null
&& SAPGLJournalLineId.equals(parentId, taxBaseLine.getIdOrNull());
}
public boolean isBaseTaxLine()
{
return parentId == null && taxId != null && !determineTaxBaseSAP;
}
@NonNull
public Optional<SAPGLJournalLine> getReverseChargeCounterPart(
@NonNull final SAPGLJournalTaxProvider taxProvider,
@NonNull final AcctSchemaId acctSchemaId)
{
return Optional.ofNullable(taxId)
.filter(taxProvider::isReverseCharge)
.map(reverseChargeTaxId -> toBuilder()
.postingSign(getPostingSign().reverse())
.account(taxProvider.getTaxAccount(reverseChargeTaxId, acctSchemaId, getPostingSign().reverse()))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\SAPGLJournalLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
public String getScopeType() {
return scopeType;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public String getTenantId() {
return tenantId;
}
public Collection<String> getTenantIds() {
return tenantIds;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
} | public String getConfiguration() {
return configuration;
}
public Collection<String> getConfigurations() {
return configurations;
}
public boolean isWithoutConfiguration() {
return withoutConfiguration;
}
public List<EventSubscriptionQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public EventSubscriptionQueryImpl getCurrentOrQueryObject() {
return currentOrQueryObject;
}
public boolean isInOrStatement() {
return inOrStatement;
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java | 2 |
请完成以下Java代码 | public Grid getGrid() {
return grid;
}
public void setGrid(Grid grid) {
this.grid = grid;
}
public Toolbox getToolbox() {
return toolbox;
}
public void setToolbox(Toolbox toolbox) {
this.toolbox = toolbox;
}
public XAxis getxAxis() {
return xAxis;
}
public void setxAxis(XAxis xAxis) {
this.xAxis = xAxis; | }
public YAxis getyAxis() {
return yAxis;
}
public void setyAxis(YAxis yAxis) {
this.yAxis = yAxis;
}
public List<Serie> getSeries() {
return series;
}
public void setSeries(List<Serie> series) {
this.series = series;
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\Option.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Whitelabel getWhitelabel() {
return this.whitelabel;
}
/**
* Include error attributes options.
*/
public enum IncludeAttribute {
/**
* Never add error attribute.
*/
NEVER,
/**
* Always add error attribute.
*/
ALWAYS,
/**
* Add error attribute when the appropriate request parameter is not "false".
*/
ON_PARAM
} | public static class Whitelabel {
/**
* Whether to enable the default error page displayed in browsers in case of a
* server error.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java | 2 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_BOMAlternative[")
.append(get_ID()).append("]");
return sb.toString();
}
/** 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 Alternative Group.
@param M_BOMAlternative_ID
Product BOM Alternative Group
*/
public void setM_BOMAlternative_ID (int M_BOMAlternative_ID)
{
if (M_BOMAlternative_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, Integer.valueOf(M_BOMAlternative_ID));
}
/** Get Alternative Group.
@return Product BOM Alternative Group
*/
public int getM_BOMAlternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID);
if (ii == null)
return 0; | return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set 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_M_BOMAlternative.java | 1 |
请完成以下Java代码 | public Builder setButtonActionDescriptor(@Nullable final ButtonFieldActionDescriptor buttonActionDescriptor)
{
this.buttonActionDescriptor = buttonActionDescriptor;
return this;
}
public boolean isSupportZoomInto()
{
// Allow zooming into key column. It shall open precisely this record in a new window
// (see https://github.com/metasfresh/metasfresh/issues/1687 to understand the use-case)
// In future we shall think to narrow it down only to included tabs and only for those tables which also have a window where they are the header document.
if (isKey())
{
return true;
}
final DocumentFieldWidgetType widgetType = getWidgetType();
if (!widgetType.isSupportZoomInto())
{
return false;
}
final Class<?> valueClass = getValueClass();
if (StringLookupValue.class.isAssignableFrom(valueClass))
{
return false;
}
final String lookupTableName = getLookupTableName().orElse(null);
return !WindowConstants.TABLENAME_AD_Ref_List.equals(lookupTableName);
}
public Builder setDefaultFilterInfo(@Nullable DocumentFieldDefaultFilterDescriptor defaultFilterInfo)
{
this.defaultFilterInfo = defaultFilterInfo;
return this;
}
/**
* Setting this to a non-{@code null} value means that this field is a tooltip field,
* i.e. it represents a tooltip that is attached to some other field.
*/
public Builder setTooltipIconName(@Nullable final String tooltipIconName)
{
this.tooltipIconName = tooltipIconName;
return this;
}
/**
* @return true if this field has ORDER BY instructions
*/
public boolean isDefaultOrderBy() | {
final DocumentFieldDataBindingDescriptor dataBinding = getDataBinding().orElse(null);
return dataBinding != null && dataBinding.isDefaultOrderBy();
}
public int getDefaultOrderByPriority()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().getDefaultOrderByPriority();
}
public boolean isDefaultOrderByAscending()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().isDefaultOrderByAscending();
}
public Builder deviceDescriptorsProvider(@NonNull final DeviceDescriptorsProvider deviceDescriptorsProvider)
{
this.deviceDescriptorsProvider = deviceDescriptorsProvider;
return this;
}
private DeviceDescriptorsProvider getDeviceDescriptorsProvider()
{
return deviceDescriptorsProvider;
}
public Builder mainAdFieldId(@Nullable final AdFieldId mainAdFieldId)
{
this.mainAdFieldId = mainAdFieldId;
return this;
}
@Nullable
public AdFieldId getMainAdFieldId() {return mainAdFieldId;}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShipperMappingConfigId implements RepoIdAware
{
int repoId;
@JsonCreator
public static ShipperMappingConfigId ofRepoId(final int repoId)
{
return new ShipperMappingConfigId(repoId);
}
@Nullable
public static ShipperMappingConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ShipperMappingConfigId(repoId) : null;
}
public static int toRepoId(final ShipperMappingConfigId productId)
{ | return productId != null ? productId.getRepoId() : -1;
}
private ShipperMappingConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Shipper_Mapping_Config_Id");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\mapping\ShipperMappingConfigId.java | 2 |
请完成以下Java代码 | public class LicenseConfig {
/**
* 证书 subject
*/
private String subject;
/**
* 公钥别称
*/
private String publicAlias;
/**
* 访问公钥库的密码
*/
private String storePass;
/**
* 证书生成路径
*/
private String licensePath;
/**
* 密钥库存储路径
*/
private String publicKeysStorePath; | /**
* <p>项目名称: true-license-demo </p>
* <p>文件名称: LicenseConfig.java </p>
* <p>方法描述: 把 LicenseVerify 类添加到 Spring 容器。在 LicenseVerify 从 Spring 容器添加或移除的时候调用证书安装或卸载 </p>
* <p>创建时间: 2020/10/10 16:07 </p>
*
* @return com.example.demo.licensegenerate.LicenseVerify
* @author 方瑞冬
* @version 1.0
*/
@Bean(initMethod = "installLicense", destroyMethod = "unInstallLicense")
public LicenseVerify licenseVerify() {
return new LicenseVerify(subject, publicAlias, storePass, licensePath, publicKeysStorePath);
}
} | repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\LicenseConfig.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Info_Lic_ID()));
}
/** Set Issuing Agency.
@param A_Issuing_Agency Issuing Agency */
public void setA_Issuing_Agency (String A_Issuing_Agency)
{
set_Value (COLUMNNAME_A_Issuing_Agency, A_Issuing_Agency);
}
/** Get Issuing Agency.
@return Issuing Agency */
public String getA_Issuing_Agency ()
{
return (String)get_Value(COLUMNNAME_A_Issuing_Agency);
}
/** Set License Fee.
@param A_License_Fee License Fee */
public void setA_License_Fee (BigDecimal A_License_Fee)
{
set_Value (COLUMNNAME_A_License_Fee, A_License_Fee);
}
/** Get License Fee.
@return License Fee */
public BigDecimal getA_License_Fee ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_License_Fee);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set License No.
@param A_License_No License No */
public void setA_License_No (String A_License_No)
{
set_Value (COLUMNNAME_A_License_No, A_License_No);
}
/** Get License No.
@return License No */
public String getA_License_No ()
{
return (String)get_Value(COLUMNNAME_A_License_No);
}
/** Set Policy Renewal Date.
@param A_Renewal_Date Policy Renewal Date */
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date);
}
/** Set Account State. | @param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
/** 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_Asset_Info_Lic.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class ChangelogGenerator {
private ChangelogGenerator() {
}
public static void main(String[] args) throws IOException {
generate(new File(args[0]), new File(args[1]), new File(args[2]));
}
private static void generate(File oldDir, File newDir, File out) throws IOException {
String oldVersionNumber = oldDir.getName();
ConfigurationMetadataRepository oldMetadata = buildRepository(oldDir);
String newVersionNumber = newDir.getName();
ConfigurationMetadataRepository newMetadata = buildRepository(newDir);
Changelog changelog = Changelog.of(oldVersionNumber, oldMetadata, newVersionNumber, newMetadata);
try (ChangelogWriter writer = new ChangelogWriter(out)) {
writer.write(changelog);
}
System.out.println("%nConfiguration metadata changelog written to '%s'".formatted(out));
}
static ConfigurationMetadataRepository buildRepository(File directory) {
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create(); | File[] files = directory.listFiles();
if (files == null) {
throw new IllegalStateException("'files' must not be null");
}
for (File file : files) {
try (JarFile jarFile = new JarFile(file)) {
JarEntry metadataEntry = jarFile.getJarEntry("META-INF/spring-configuration-metadata.json");
if (metadataEntry != null) {
builder.withJsonResource(jarFile.getInputStream(metadataEntry));
}
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return builder.build();
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata-changelog-generator\src\main\java\org\springframework\boot\configurationmetadata\changelog\ChangelogGenerator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getSchedulerName() {
return this.schedulerName;
}
public void setSchedulerName(@Nullable String schedulerName) {
this.schedulerName = schedulerName;
}
public boolean isAutoStartup() {
return this.autoStartup;
}
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
public Duration getStartupDelay() {
return this.startupDelay;
}
public void setStartupDelay(Duration startupDelay) {
this.startupDelay = startupDelay;
} | public boolean isWaitForJobsToCompleteOnShutdown() {
return this.waitForJobsToCompleteOnShutdown;
}
public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
}
public boolean isOverwriteExistingJobs() {
return this.overwriteExistingJobs;
}
public void setOverwriteExistingJobs(boolean overwriteExistingJobs) {
this.overwriteExistingJobs = overwriteExistingJobs;
}
public Map<String, String> getProperties() {
return this.properties;
}
} | repos\spring-boot-4.0.1\module\spring-boot-quartz\src\main\java\org\springframework\boot\quartz\autoconfigure\QuartzProperties.java | 2 |
请完成以下Java代码 | private void createAndSavePickingCandidates(final ProductsToPickRow productsToPickRow)
{
pickingCandidateService.createAndSavePickingCandidates(createPickRequest(productsToPickRow, false));
}
@NonNull
public ImmutableList<WebuiPickHUResult> pick(final List<ProductsToPickRow> selectedRows)
{
return streamRowsEligibleForPicking(selectedRows)
.map(row -> {
final PickHUResult result = pickingCandidateService.pickHU(createPickRequest(row));
return WebuiPickHUResult.of(row.getId(), result.getPickingCandidate());
})
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<WebuiPickHUResult> setPackingInstruction(final List<ProductsToPickRow> selectedRows, final PackToSpec packToSpec)
{
final Map<PickingCandidateId, DocumentId> rowIdsByPickingCandidateId = streamRowsEligibleForPacking(selectedRows)
.collect(ImmutableMap.toImmutableMap(ProductsToPickRow::getPickingCandidateId, ProductsToPickRow::getId));
final Set<PickingCandidateId> pickingCandidateIds = rowIdsByPickingCandidateId.keySet();
final List<PickingCandidate> pickingCandidates = pickingCandidateService.setHuPackingInstructionId(pickingCandidateIds, packToSpec);
return pickingCandidates.stream()
.map(cand -> WebuiPickHUResult.of(rowIdsByPickingCandidateId.get(cand.getId()), cand))
.collect(ImmutableList.toImmutableList());
}
public boolean anyRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return streamRowsEligibleForPacking(selectedRows).findAny().isPresent(); | }
private Stream<ProductsToPickRow> streamRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream()
.filter(ProductsToPickRow::isEligibleForPacking);
}
public boolean noRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return !streamRowsEligibleForPicking(selectedRows).findAny().isPresent();
}
@NonNull
private Stream<ProductsToPickRow> streamRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream()
.filter(ProductsToPickRow::isEligibleForPicking);
}
private PickRequest createPickRequest(final ProductsToPickRow row)
{
final PickingConfigV2 pickingConfig = getPickingConfig();
return createPickRequest(row, pickingConfig.isPickingReviewRequired());
}
protected final PickingConfigV2 getPickingConfig()
{
return pickingConfigRepo.getPickingConfig();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public byte[] generatorCode(GenConfig genConfig) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//查询表信息
Entity table = queryTable(genConfig.getRequest());
//查询列信息
List<Entity> columns = queryColumns(genConfig.getRequest());
//生成代码
CodeGenUtil.generatorCode(genConfig, table, columns, zip);
IoUtil.close(zip);
return outputStream.toByteArray();
}
@SneakyThrows
private Entity queryTable(TableRequest request) {
HikariDataSource dataSource = DbUtil.buildFromTableRequest(request);
Db db = new Db(dataSource);
String paramSql = StrUtil.EMPTY;
if (StrUtil.isNotBlank(request.getTableName())) {
paramSql = "and table_name = ?"; | }
String sql = String.format(TABLE_SQL_TEMPLATE, paramSql);
Entity entity = db.queryOne(sql, request.getTableName());
dataSource.close();
return entity;
}
@SneakyThrows
private List<Entity> queryColumns(TableRequest request) {
HikariDataSource dataSource = DbUtil.buildFromTableRequest(request);
Db db = new Db(dataSource);
List<Entity> query = db.query(COLUMN_SQL_TEMPLATE, request.getTableName());
dataSource.close();
return query;
}
} | repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\service\impl\CodeGenServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return Objects.equals(id, student.id) &&
Objects.equals(firstName, student.firstName) &&
Objects.equals(lastName, student.lastName);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName);
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\index\Student.java | 2 |
请完成以下Java代码 | private boolean projectIssueHasExpense (int S_TimeExpenseLine_ID)
{
if (m_projectIssues == null)
m_projectIssues = m_project.getIssues();
for (int i = 0; i < m_projectIssues.length; i++)
{
if (m_projectIssues[i].getS_TimeExpenseLine_ID() == S_TimeExpenseLine_ID)
return true;
}
return false;
} // projectIssueHasExpense
/**
* Check if Project Issue already has Receipt
* @param M_InOutLine_ID line | * @return true if exists
*/
private boolean projectIssueHasReceipt (int M_InOutLine_ID)
{
if (m_projectIssues == null)
m_projectIssues = m_project.getIssues();
for (int i = 0; i < m_projectIssues.length; i++)
{
if (m_projectIssues[i].getM_InOutLine_ID() == M_InOutLine_ID)
return true;
}
return false;
} // projectIssueHasReceipt
} // ProjectIssue | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectIssue.java | 1 |
请完成以下Java代码 | public @NonNull RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509PemWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try {
return (RSAPublicKey) this.keyFactory.generatePublic(new X509EncodedKeySpec(x509));
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509PemWrapper(String line) {
return !X509_PEM_HEADER.equals(line) && !X509_PEM_FOOTER.equals(line);
}
}
private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> {
private final CertificateFactory certificateFactory;
X509CertificateDecoder(CertificateFactory certificateFactory) {
this.certificateFactory = certificateFactory;
} | @Override
public @NonNull RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509CertificateWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try (InputStream x509CertStream = new ByteArrayInputStream(x509)) {
X509Certificate certificate = (X509Certificate) this.certificateFactory
.generateCertificate(x509CertStream);
return (RSAPublicKey) certificate.getPublicKey();
}
catch (CertificateException | IOException ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509CertificateWrapper(String line) {
return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\converter\RsaKeyConverters.java | 1 |
请完成以下Java代码 | public class SubProcessImpl extends ActivityImpl implements SubProcess {
protected static Attribute<Boolean> triggeredByEventAttribute;
protected static ChildElementCollection<LaneSet> laneSetCollection;
protected static ChildElementCollection<FlowElement> flowElementCollection;
protected static ChildElementCollection<Artifact> artifactCollection;
/** camunda extensions */
protected static Attribute<Boolean> camundaAsyncAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(SubProcess.class, BPMN_ELEMENT_SUB_PROCESS)
.namespaceUri(BPMN20_NS)
.extendsType(Activity.class)
.instanceProvider(new ModelTypeInstanceProvider<SubProcess>() {
public SubProcess newInstance(ModelTypeInstanceContext instanceContext) {
return new SubProcessImpl(instanceContext);
}
});
triggeredByEventAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_TRIGGERED_BY_EVENT)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
laneSetCollection = sequenceBuilder.elementCollection(LaneSet.class)
.build();
flowElementCollection = sequenceBuilder.elementCollection(FlowElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
/** camunda extensions */
camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC)
.namespace(CAMUNDA_NS)
.defaultValue(false)
.build();
typeBuilder.build();
}
public SubProcessImpl(ModelTypeInstanceContext context) {
super(context);
}
public SubProcessBuilder builder() {
return new SubProcessBuilder((BpmnModelInstance) modelInstance, this);
}
public boolean triggeredByEvent() {
return triggeredByEventAttribute.getValue(this);
}
public void setTriggeredByEvent(boolean triggeredByEvent) {
triggeredByEventAttribute.setValue(this, triggeredByEvent);
} | public Collection<LaneSet> getLaneSets() {
return laneSetCollection.get(this);
}
public Collection<FlowElement> getFlowElements() {
return flowElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
/** camunda extensions */
/**
* @deprecated use isCamundaAsyncBefore() instead.
*/
@Deprecated
public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this);
}
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubProcessImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
return ObjectUtils.toString(this);
}
public final ArrayKey buildKey()
{
return Util.mkKey(keyParts.toArray());
}
public void add(final Object keyPart)
{
keyParts.add(keyPart);
}
public void setTrxName(String trxName)
{
this.trxName = trxName;
}
public String getTrxName()
{
return trxName;
}
public void setSkipCaching()
{
this.skipCaching = true; | }
public boolean isSkipCaching()
{
return skipCaching;
}
/**
* Advices the caching engine to refresh the cached value, instead of checking the cache.
*
* NOTE: this option will have NO affect if {@link #isSkipCaching()}.
*/
public void setCacheReload()
{
this.cacheReload = true;
}
/** @return true if instead the underlying method shall be invoked and cache shall be refreshed with that value */
public boolean isCacheReload()
{
return cacheReload;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheKeyBuilder.java | 1 |
请完成以下Java代码 | public void print(
@NonNull final Resource reportData,
@NonNull final ArchiveInfo archiveInfo)
{
final ArchiveResult archiveResult = archiveService.archive(ArchiveRequest.builder()
.ctx(Env.getCtx())
.trxName(ITrx.TRXNAME_ThreadInherited)
.data(reportData)
.force(true) // archive it even if AutoArchive says no
.save(true)
.isReport(archiveInfo.isReport())
.recordRef(archiveInfo.getRecordRef())
.processId(archiveInfo.getProcessId())
.pinstanceId(archiveInfo.getPInstanceId())
.archiveName(archiveInfo.getName()) | .bpartnerId(archiveInfo.getBpartnerId())
//
// Ask our printing service to printing it right now:
.isDirectEnqueue(true)
.isDirectProcessQueueItem(true)
.copies(archiveInfo.getCopies())
//
.build());
if (archiveResult.isNoArchive())
{
throw new AdempiereException("No archive created for " + reportData + " and " + archiveInfo);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\adapter\MassPrintingService.java | 1 |
请完成以下Java代码 | protected void performStart(CmmnActivityExecution execution) {
VariableMap variables = getInputVariables(execution);
String businessKey = getBusinessKey(execution);
triggerCallableElement(execution, variables, businessKey);
if (execution.isActive() && !isBlocking(execution)) {
execution.complete();
}
}
public void transferVariables(VariableScope sourceScope, CmmnActivityExecution caseExecution) {
VariableMap variables = getOutputVariables(sourceScope);
caseExecution.setVariables(variables);
}
public CallableElement getCallableElement() {
return (CallableElement) callableElement;
} | protected String getBusinessKey(CmmnActivityExecution execution) {
return getCallableElement().getBusinessKey(execution);
}
protected VariableMap getInputVariables(CmmnActivityExecution execution) {
return getCallableElement().getInputVariables(execution);
}
protected VariableMap getOutputVariables(VariableScope variableScope) {
return getCallableElement().getOutputVariables(variableScope);
}
protected abstract void triggerCallableElement(CmmnActivityExecution execution, Map<String, Object> variables, String businessKey);
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\ProcessOrCaseTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public Optional<FreightCostBreak> getBreak(
@NonNull final ShipperId shipperId,
@NonNull final CountryId countryId,
@NonNull final LocalDate date,
@NonNull final Money shipmentValueAmt)
{
final FreightCostShipper shipper = getShipperIfExists(shipperId, date).orElse(null);
if (shipper == null)
{
return Optional.empty();
}
return shipper.getBreak(countryId, shipmentValueAmt);
}
public FreightCostShipper getShipper(@NonNull final ShipperId shipperId, @NonNull final LocalDate date)
{ | Optional<FreightCostShipper> shipperIfExists = getShipperIfExists(shipperId, date);
return shipperIfExists.orElseThrow(() -> new AdempiereException("@NotFound@ @M_FreightCostShipper_ID@ (@M_Shipper_ID@:" + shipperId + ", @M_FreightCost_ID@:" + getName() + ")"));
}
public Optional<FreightCostShipper> getShipperIfExists(@NonNull final ShipperId shipperId, @NonNull final LocalDate date)
{
return shippers.stream()
.filter(shipper -> shipper.isMatching(shipperId, date))
.sorted(Comparator.comparing(FreightCostShipper::getValidFrom))
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCost.java | 1 |
请完成以下Java代码 | private static final class AdempierePaneDividerBorder implements Border, UIResource
{
public static final transient AdempierePaneDividerBorder instance = new AdempierePaneDividerBorder();
private final Color highlight;
private final Color shadow;
private AdempierePaneDividerBorder()
{
super();
highlight = UIManager.getColor("SplitPane.highlight");
shadow = UIManager.getColor("SplitPane.darkShadow");
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height)
{
if (!(c instanceof BasicSplitPaneDivider))
{
return;
}
final JSplitPane splitPane = ((BasicSplitPaneDivider)c).getBasicSplitPaneUI().getSplitPane();
// This is needed for the space between the divider and end of splitpane.
g.setColor(c.getBackground());
g.drawRect(x, y, width - 1, height - 1);
if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT)
{
Component child = splitPane.getLeftComponent();
if (child != null)
{
g.setColor(highlight);
g.drawLine(x, y, x, y + height);
}
child = splitPane.getRightComponent();
if (child != null)
{
g.setColor(shadow);
g.drawLine(x + width - 1, y, x + width - 1, y + height);
}
}
else
{
Component child = splitPane.getLeftComponent();
if (child != null)
{
g.setColor(highlight);
g.drawLine(x, y, x + width, y);
}
child = splitPane.getRightComponent();
if (child != null)
{
g.setColor(shadow); | g.drawLine(x, y + height - 1, x + width, y + height - 1);
}
}
}
@Override
public Insets getBorderInsets(final Component c)
{
final Insets insets = new Insets(0, 0, 0, 0);
if (c instanceof BasicSplitPaneDivider)
{
final BasicSplitPaneUI bspui = ((BasicSplitPaneDivider)c).getBasicSplitPaneUI();
if (bspui != null)
{
final JSplitPane splitPane = bspui.getSplitPane();
if (splitPane != null)
{
if (splitPane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT)
{
insets.top = insets.bottom = 0;
insets.left = insets.right = 1;
return insets;
}
// VERTICAL_SPLIT
insets.top = insets.bottom = 1;
insets.left = insets.right = 0;
return insets;
}
}
}
insets.top = insets.bottom = insets.left = insets.right = 1;
return insets;
}
@Override
public boolean isBorderOpaque()
{
return true;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereSplitPaneUI.java | 1 |
请完成以下Java代码 | public String getDefaultHistoryLevel() {
return defaultHistoryLevel;
}
public void setDefaultHistoryLevel(String defaultHistoryLevel) {
this.defaultHistoryLevel = defaultHistoryLevel;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public boolean isIgnoreDataAccessException() {
return ignoreDataAccessException;
}
public void setIgnoreDataAccessException(boolean ignoreDataAccessException) {
this.ignoreDataAccessException = ignoreDataAccessException;
}
public CamundaBpmProperties getCamundaBpmProperties() {
return camundaBpmProperties;
}
public void setCamundaBpmProperties(CamundaBpmProperties camundaBpmProperties) {
this.camundaBpmProperties = camundaBpmProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(jdbcTemplate, "a jdbc template must be set");
Assert.notNull(camundaBpmProperties, "Camunda Platform properties must be set");
String historyLevelDefault = camundaBpmProperties.getHistoryLevelDefault();
if (StringUtils.hasText(historyLevelDefault)) {
defaultHistoryLevel = historyLevelDefault;
}
}
@Override
public String determineHistoryLevel() {
Integer historyLevelFromDb = null;
try {
historyLevelFromDb = jdbcTemplate.queryForObject(getSql(), Integer.class);
log.debug("found history '{}' in database", historyLevelFromDb);
} catch (DataAccessException e) {
if (ignoreDataAccessException) {
log.warn("unable to fetch history level from database: {}", e.getMessage());
log.debug("unable to fetch history level from database", e);
} else {
throw e;
} | }
return getHistoryLevelFrom(historyLevelFromDb);
}
protected String getSql() {
String tablePrefix = camundaBpmProperties.getDatabase().getTablePrefix();
if (tablePrefix == null) {
tablePrefix = "";
}
return SQL_TEMPLATE.replace(TABLE_PREFIX_PLACEHOLDER, tablePrefix);
}
protected String getHistoryLevelFrom(Integer historyLevelFromDb) {
String result = defaultHistoryLevel;
if (historyLevelFromDb != null) {
for (HistoryLevel historyLevel : historyLevels) {
if (historyLevel.getId() == historyLevelFromDb.intValue()) {
result = historyLevel.getName();
log.debug("found matching history level '{}'", result);
break;
}
}
}
return result;
}
public void addCustomHistoryLevels(Collection<HistoryLevel> customHistoryLevels) {
historyLevels.addAll(customHistoryLevels);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\jdbc\HistoryLevelDeterminatorJdbcTemplateImpl.java | 1 |
请完成以下Java代码 | public void init(final IModelValidationEngine engine)
{
CopyRecordFactory.enableForTableName(I_C_Phonecall_Schema_Version.Table_Name);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_ValidFrom })
public void forbidNewVersionWithSameValidFromDate(final I_C_Phonecall_Schema_Version phonecallSchemaVersion)
{
final PhonecallSchemaId schemaId = PhonecallSchemaId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID());
final PhonecallSchemaVersionId versionId = PhonecallSchemaVersionId.ofRepoIdOrNull(schemaId, phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID());
final LocalDate validFrom = TimeUtil.asLocalDate(phonecallSchemaVersion.getValidFrom());
final PhonecallSchema phonecallSchema = phonecallSchemaRepo.getById(schemaId);
final PhonecallSchemaVersion existingVersion = phonecallSchema.getVersionByValidFrom(validFrom).orElse(null);
if (existingVersion != null
&& (versionId == null || !versionId.equals(existingVersion.getId())))
{
throw new AdempiereException(MSG_Existing_Phonecall_Schema_Version_Same_ValidFrom,
phonecallSchemaVersion.getName(),
validFrom); | }
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_C_Phonecall_Schema_ID })
public void updateLinesOnSchemaChanged(final I_C_Phonecall_Schema_Version phonecallSchemaVersion)
{
phonecallSchemaRepo.updateLinesOnSchemaChanged(PhonecallSchemaVersionId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID(), phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Phonecall_Schema_Version.COLUMNNAME_C_Phonecall_Schema_ID })
public void updateSchedulesOnSchemaChanged(final I_C_Phonecall_Schema_Version phonecallSchemaVersion)
{
phonecallSchemaRepo.updateSchedulesOnSchemaChanged(PhonecallSchemaVersionId.ofRepoId(phonecallSchemaVersion.getC_Phonecall_Schema_ID(), phonecallSchemaVersion.getC_Phonecall_Schema_Version_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\model\interceptor\C_Phonecall_Schema_Version.java | 1 |
请完成以下Java代码 | public GraphicInfo getSourceDockerInfo() {
return sourceDockerInfo;
}
public void setSourceDockerInfo(GraphicInfo sourceDockerInfo) {
this.sourceDockerInfo = sourceDockerInfo;
}
public GraphicInfo getTargetDockerInfo() {
return targetDockerInfo;
}
public void setTargetDockerInfo(GraphicInfo targetDockerInfo) {
this.targetDockerInfo = targetDockerInfo;
}
public void addWaypoint(GraphicInfo graphicInfo) {
this.waypoints.add(graphicInfo);
} | public List<GraphicInfo> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<GraphicInfo> waypoints) {
this.waypoints = waypoints;
}
public GraphicInfo getLabelGraphicInfo() {
return labelGraphicInfo;
}
public void setLabelGraphicInfo(GraphicInfo labelGraphicInfo) {
this.labelGraphicInfo = labelGraphicInfo;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnDiEdge.java | 1 |
请完成以下Java代码 | private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
Node<T> it = head;
while (it != null) {
if (isNodeReachableFromLoopNode(it, loopNodeParam)) {
Node<T> loopStart = it;
findEndNodeAndBreakCycle(loopStart);
break;
}
it = it.next;
}
}
private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
do {
if (it == loopNode) {
return true; | }
loopNode = loopNode.next;
} while (loopNode.next != loopNodeParam);
return false;
}
private static <T> void findEndNodeAndBreakCycle(Node<T> loopStartParam) {
Node<T> loopStart = loopStartParam;
while (loopStart.next != loopStartParam) {
loopStart = loopStart.next;
}
loopStart.next = null;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\linkedlist\CycleRemovalBruteForce.java | 1 |
请完成以下Java代码 | public void save(PublicKeyCredentialUserEntity userEntity) {
Assert.notNull(userEntity, "userEntity cannot be null");
int rows = updateUserEntity(userEntity);
if (rows == 0) {
insertUserEntity(userEntity);
}
}
private void insertUserEntity(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity);
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
this.jdbcOperations.update(SAVE_USER_SQL, pss);
}
private int updateUserEntity(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity);
SqlParameterValue userEntityId = parameters.remove(0);
parameters.add(userEntityId);
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
return this.jdbcOperations.update(UPDATE_USER_SQL, pss);
}
@Override
public void delete(Bytes id) {
Assert.notNull(id, "id cannot be null");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, id.toBase64UrlString()), };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(DELETE_USER_SQL, pss);
}
private static class UserEntityParametersMapper
implements Function<PublicKeyCredentialUserEntity, List<SqlParameterValue>> {
@Override
public List<SqlParameterValue> apply(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = new ArrayList<>(); | parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getId().toBase64UrlString()));
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getName()));
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getDisplayName()));
return parameters;
}
}
private static class UserEntityRecordRowMapper implements RowMapper<PublicKeyCredentialUserEntity> {
@Override
public PublicKeyCredentialUserEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
Bytes id = Bytes.fromBase64(new String(rs.getString("id").getBytes()));
String name = rs.getString("name");
String displayName = rs.getString("display_name");
return ImmutablePublicKeyCredentialUserEntity.builder().id(id).name(name).displayName(displayName).build();
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\JdbcPublicKeyCredentialUserEntityRepository.java | 1 |
请完成以下Java代码 | public double getSubtract() {
return subtract;
}
public void setSubtract(double subtract) {
this.subtract = subtract;
}
public double getMultiply() {
return multiply;
}
public void setMultiply(double multiply) {
this.multiply = multiply;
}
public double getDivide() {
return divide;
}
public void setDivide(double divide) {
this.divide = divide;
}
public double getDivideAlphabetic() {
return divideAlphabetic;
}
public void setDivideAlphabetic(double divideAlphabetic) {
this.divideAlphabetic = divideAlphabetic;
}
public double getModulo() {
return modulo;
}
public void setModulo(double modulo) {
this.modulo = modulo;
}
public double getModuloAlphabetic() {
return moduloAlphabetic;
}
public void setModuloAlphabetic(double moduloAlphabetic) { | this.moduloAlphabetic = moduloAlphabetic;
}
public double getPowerOf() {
return powerOf;
}
public void setPowerOf(double powerOf) {
this.powerOf = powerOf;
}
public double getBrackets() {
return brackets;
}
public void setBrackets(double brackets) {
this.brackets = brackets;
}
@Override
public String toString() {
return "SpelArithmetic{" +
"add=" + add +
", addString='" + addString + '\'' +
", subtract=" + subtract +
", multiply=" + multiply +
", divide=" + divide +
", divideAlphabetic=" + divideAlphabetic +
", modulo=" + modulo +
", moduloAlphabetic=" + moduloAlphabetic +
", powerOf=" + powerOf +
", brackets=" + brackets +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelArithmetic.java | 1 |
请完成以下Java代码 | public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId)); | }
@Override
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
@Override
public List<DmnDecision> getDecisionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetDecisionsForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForProcessDefinitionCmd(processDefinitionId));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\RepositoryServiceImpl.java | 1 |
请完成以下Java代码 | public String getScript() {
for (FieldExtension fieldExtension : fieldExtensions) {
if ("script".equalsIgnoreCase(fieldExtension.getFieldName())) {
String script = fieldExtension.getStringValue();
if (StringUtils.isNotEmpty(script)) {
return script;
}
return fieldExtension.getExpression();
}
}
return null;
}
public boolean isAutoStoreVariables() {
return autoStoreVariables;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
} | inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public ScriptServiceTask clone() {
ScriptServiceTask clone = new ScriptServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ScriptServiceTask otherElement) {
super.setValues(otherElement);
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ScriptServiceTask.java | 1 |
请完成以下Java代码 | public PageData<Rpc> findAllByDeviceId(TenantId tenantId, DeviceId deviceId, PageLink pageLink) {
log.trace("Executing findAllByDeviceIdAndStatus, tenantId [{}], deviceId [{}], pageLink [{}]", tenantId, deviceId, pageLink);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validatePageLink(pageLink);
return rpcDao.findAllByDeviceId(tenantId, deviceId, pageLink);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findById(tenantId, new RpcId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findRpcByIdAsync(tenantId, new RpcId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() { | return EntityType.RPC;
}
private final PaginatedRemover<TenantId, Rpc> tenantRpcRemover = new PaginatedRemover<>() {
@Override
protected PageData<Rpc> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return rpcDao.findAllRpcByTenantId(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Rpc entity) {
deleteRpc(tenantId, entity.getId());
}
};
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\rpc\BaseRpcService.java | 1 |
请完成以下Java代码 | public Builder newContextForFetchingList()
{
return prepareNewContext()
.requiresParameters(dependsOnContextVariables)
.requiresFilterAndLimit();
}
private LookupDataSourceContext.Builder prepareNewContext()
{
return LookupDataSourceContext.builder(LOOKUP_TABLE_NAME);
}
@Override
public LookupValue retrieveLookupValueById(@NonNull final LookupDataSourceContext evalCtx)
{
final Integer listValueIdAsInt = CTX_NAME_LIST_VALUE_ID.getValueAsInteger(evalCtx);
if (listValueIdAsInt <= 0)
{
return null;
}
final DataEntryListValueId listValueId = DataEntryListValueId.ofRepoId(listValueIdAsInt);
return id2LookupValue.get(listValueId);
}
@Override
public LookupValuesPage retrieveEntities(@NonNull final LookupDataSourceContext evalCtx)
{
return LookupValuesList.fromCollection(id2LookupValue.values())
.pageByOffsetAndLimit(
evalCtx.getOffset(0),
evalCtx.getLimit(Integer.MAX_VALUE));
}
private IntegerLookupValue createLookupValue(@NonNull final DataEntryListValue dataEntryListValue)
{
return IntegerLookupValue.of(
dataEntryListValue.getId(),
dataEntryListValue.getName(),
dataEntryListValue.getDescription());
}
@Override
public boolean isCached()
{
return true;
} | @Override
public String getCachePrefix()
{
return DataEntryListValueDataSourceFetcher.class.getSimpleName();
}
@Override
public Optional<String> getLookupTableName()
{
return Optional.of(LOOKUP_TABLE_NAME);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
/**
* Does nothing; this class doesn't use a cache; it is disposed as one.
*/
@Override
public void cacheInvalidate()
{
}
public DataEntryListValueId getListValueIdForLookup(@Nullable final IntegerLookupValue value)
{
return id2LookupValue.inverse().get(value);
}
public Object getLookupForForListValueId(@Nullable final DataEntryListValueId dataEntryListValueId)
{
return id2LookupValue.get(dataEntryListValueId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryListValueDataSourceFetcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
private final Map<Integer, OAuth2AuthorizationConsent> authorizationConsents = new ConcurrentHashMap<>();
/**
* Constructs an {@code InMemoryOAuth2AuthorizationConsentService}.
*/
public InMemoryOAuth2AuthorizationConsentService() {
this(Collections.emptyList());
}
/**
* Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided
* parameters.
* @param authorizationConsents the authorization consent(s)
*/
public InMemoryOAuth2AuthorizationConsentService(OAuth2AuthorizationConsent... authorizationConsents) {
this(Arrays.asList(authorizationConsents));
}
/**
* Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided
* parameters.
* @param authorizationConsents the authorization consent(s)
*/
public InMemoryOAuth2AuthorizationConsentService(List<OAuth2AuthorizationConsent> authorizationConsents) {
Assert.notNull(authorizationConsents, "authorizationConsents cannot be null");
authorizationConsents.forEach((authorizationConsent) -> {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
Assert.isTrue(!this.authorizationConsents.containsKey(id),
"The authorizationConsent must be unique. Found duplicate, with registered client id: ["
+ authorizationConsent.getRegisteredClientId() + "] and principal name: ["
+ authorizationConsent.getPrincipalName() + "]");
this.authorizationConsents.put(id, authorizationConsent);
});
}
@Override | public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
this.authorizationConsents.put(id, authorizationConsent);
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
this.authorizationConsents.remove(id, authorizationConsent);
}
@Override
@Nullable
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
int id = getId(registeredClientId, principalName);
return this.authorizationConsents.get(id);
}
private static int getId(String registeredClientId, String principalName) {
return Objects.hash(registeredClientId, principalName);
}
private static int getId(OAuth2AuthorizationConsent authorizationConsent) {
return getId(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\InMemoryOAuth2AuthorizationConsentService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void timeoutExample() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
try {
System.out.println("Start");
Thread.sleep(5000);
System.out.println("End");
} catch (InterruptedException e) {
System.err.println("Error occured: " + e.getMessage());
}
return "Task completed";
});
try {
String result = future.get(2, TimeUnit.SECONDS); | System.out.println("Result: " + result);
} catch (TimeoutException e) {
System.err.println("Task execution timed out!");
future.cancel(true);
} catch (Exception e) {
System.err.println("Error occured: " + e.getMessage());
} finally {
executor.shutdown();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
timeoutExample();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executorservicevscompletablefuture\ExecutorServiceDemo.java | 2 |
请完成以下Java代码 | public List<String> getNewExecutionIds() {
return newExecutionIds;
}
public boolean hasNewExecutionId(String executionId) {
return newExecutionIds.contains(executionId);
}
public void setNewExecutionIds(List<String> newExecutionIds) {
this.newExecutionIds = newExecutionIds;
}
public void addNewExecutionId(String executionId) {
this.newExecutionIds.add(executionId);
}
public ExecutionEntity getCreatedEventSubProcess(String processDefinitionId) {
return createdEventSubProcesses.get(processDefinitionId);
}
public void addCreatedEventSubProcess(String processDefinitionId, ExecutionEntity executionEntity) {
createdEventSubProcesses.put(processDefinitionId, executionEntity);
}
public Map<String, Map<String, Object>> getFlowElementLocalVariableMap() {
return flowElementLocalVariableMap;
}
public void setFlowElementLocalVariableMap(Map<String, Map<String, Object>> flowElementLocalVariableMap) { | this.flowElementLocalVariableMap = flowElementLocalVariableMap;
}
public void addLocalVariableMap(String activityId, Map<String, Object> localVariables) {
this.flowElementLocalVariableMap.put(activityId, localVariables);
}
public static class FlowElementMoveEntry {
protected FlowElement originalFlowElement;
protected FlowElement newFlowElement;
public FlowElementMoveEntry(FlowElement originalFlowElement, FlowElement newFlowElement) {
this.originalFlowElement = originalFlowElement;
this.newFlowElement = newFlowElement;
}
public FlowElement getOriginalFlowElement() {
return originalFlowElement;
}
public FlowElement getNewFlowElement() {
return newFlowElement;
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\MoveExecutionEntityContainer.java | 1 |
请完成以下Java代码 | public BigDecimal getValue (String groupColumnName, String functionColumnName,
char function)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf == null)
return null;
return pdf.getValue(function);
} // getValue
/**
* Reset Function values
* @param groupColumnName group column name (or TOTAL)
* @param functionColumnName function column name
*/
public void reset (String groupColumnName, String functionColumnName)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf != null)
pdf.reset();
} // reset
/**************************************************************************
* String Representation
* @return info
*/
public String toString ()
{
return toString(false);
} // toString
/**
* String Representation
* @param withData with data
* @return info
*/
public String toString (boolean withData)
{
StringBuffer sb = new StringBuffer("PrintDataGroup[");
sb.append("Groups=");
for (int i = 0; i < m_groups.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_groups.get(i)); | }
if (withData)
{
Iterator it = m_groupMap.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupMap.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append(";Functions=");
for (int i = 0; i < m_functions.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_functions.get(i));
}
if (withData)
{
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupFunction.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append("]");
return sb.toString();
} // toString
} // PrintDataGroup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataGroup.java | 1 |
请完成以下Java代码 | public PickingSlotQueuesSummary getNotEmptyQueuesSummary(@NonNull final PickingSlotQueueQuery query)
{
// TODO: improve performance by really running the aggregates in database
// i.e. we need to implement something like org.adempiere.ad.dao.IQueryBuilder.aggregateOnColumn(java.lang.String, java.lang.Class<TargetModelType>)
// but which is more low-level focuses, e.g. aggregate().groupBy(col1).groupBy(col2).countDistinct("colAlias", col3, col4).streamAsMaps()...
final PickingSlotQueues queues = getNotEmptyQueues(query);
return queues.getQueues()
.stream()
.map(queue -> PickingSlotQueueSummary.builder()
.pickingSlotId(queue.getPickingSlotId())
.countHUs(queue.getCountHUs())
.build())
.collect(PickingSlotQueuesSummary.collect());
}
public PickingSlotQueues getNotEmptyQueues(@NonNull final PickingSlotQueueQuery query)
{
final ImmutableListMultimap<PickingSlotId, PickingSlotQueueItem> items = dao.retrieveAllPickingSlotHUs(query)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
PickingSlotQueueRepository::extractPickingSlotId,
PickingSlotQueueRepository::fromRecord
));
return items.keySet()
.stream()
.map(pickingSlotId -> PickingSlotQueue.builder()
.pickingSlotId(pickingSlotId)
.items(items.get(pickingSlotId))
.build())
.collect(PickingSlotQueues.collect());
}
public PickingSlotQueue getPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId)
{
final ImmutableList<PickingSlotQueueItem> items = dao.retrievePickingSlotHUs(ImmutableSet.of(pickingSlotId))
.stream()
.map(PickingSlotQueueRepository::fromRecord) | .collect(ImmutableList.toImmutableList());
return PickingSlotQueue.builder()
.pickingSlotId(pickingSlotId)
.items(items)
.build();
}
private static @NonNull PickingSlotId extractPickingSlotId(final I_M_PickingSlot_HU queueItemRecord)
{
return PickingSlotId.ofRepoId(queueItemRecord.getM_PickingSlot_ID());
}
private static PickingSlotQueueItem fromRecord(final I_M_PickingSlot_HU queueItemRecord)
{
return PickingSlotQueueItem.builder()
.huId(HuId.ofRepoId(queueItemRecord.getM_HU_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotQueueRepository.java | 1 |
请完成以下Java代码 | public class X_AD_PrinterHW_MediaSize extends org.compiere.model.PO implements I_AD_PrinterHW_MediaSize, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1034681283L;
/** Standard Constructor */
public X_AD_PrinterHW_MediaSize (Properties ctx, int AD_PrinterHW_MediaSize_ID, String trxName)
{
super (ctx, AD_PrinterHW_MediaSize_ID, trxName);
}
/** Load Constructor */
public X_AD_PrinterHW_MediaSize (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public de.metas.printing.model.I_AD_PrinterHW getAD_PrinterHW()
{
return get_ValueAsPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class);
}
@Override
public void setAD_PrinterHW(de.metas.printing.model.I_AD_PrinterHW AD_PrinterHW)
{
set_ValueFromPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class, AD_PrinterHW);
}
@Override
public void setAD_PrinterHW_ID (int AD_PrinterHW_ID)
{
if (AD_PrinterHW_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_ID, Integer.valueOf(AD_PrinterHW_ID));
}
@Override
public int getAD_PrinterHW_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID);
}
@Override | public void setAD_PrinterHW_MediaSize_ID (int AD_PrinterHW_MediaSize_ID)
{
if (AD_PrinterHW_MediaSize_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaSize_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaSize_ID, Integer.valueOf(AD_PrinterHW_MediaSize_ID));
}
@Override
public int getAD_PrinterHW_MediaSize_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaSize_ID);
}
@Override
public void setName (java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_MediaSize.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getDateCreated()
{
return super.getDateCreated();
}
/**
*
* @return the date when the remote endpoint actually confirmed the data receipt.
*/
public Date getDateConfirmed()
{
return dateConfirmed;
}
public void setDateConfirmed(Date dateConfirmed)
{
this.dateConfirmed = dateConfirmed;
}
/**
*
* @return the date when our local endpoint received the remote endpoint's confirmation.
*/
public Date getDateConfirmReceived()
{
return dateConfirmReceived; | }
public void setDateConfirmReceived(Date dateConfirmReceived)
{
this.dateConfirmReceived = dateConfirmReceived;
}
public long getEntryId()
{
return entryId;
}
public void setEntryId(long entryId)
{
this.entryId = entryId;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java | 2 |
请完成以下Java代码 | public static final void close(Closeable c)
{
try
{
c.close();
}
catch (final IOException e)
{
// e.printStackTrace();
}
}
/**
* Writes the given {@link Throwable}s stack trace into a string.
*
* @param e
* @return
*/
public static String dumpStackTraceToString(Throwable e)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
/**
* Smart converting given exception to string
*
* @param e
* @return
*/
public static String getErrorMsg(Throwable e)
{
// save the exception for displaying to user
String msg = e.getLocalizedMessage();
if (Check.isEmpty(msg, true))
{
msg = e.getMessage();
}
if (Check.isEmpty(msg, true))
{
// note that e.g. a NullPointerException doesn't have a nice message
msg = dumpStackTraceToString(e);
}
return msg;
} | public static String replaceNonDigitCharsWithZero(String stringToModify)
{
final int size = stringToModify.length();
final StringBuilder stringWithZeros = new StringBuilder();
for (int i = 0; i < size; i++)
{
final char currentChar = stringToModify.charAt(i);
if (!Character.isDigit(currentChar))
{
stringWithZeros.append('0');
}
else
{
stringWithZeros.append(currentChar);
}
}
return stringWithZeros.toString();
}
public static int getMinimumOfThree(final int no1, final int no2, final int no3)
{
return no1 < no2 ? (no1 < no3 ? no1 : no3) : (no2 < no3 ? no2 : no3);
}
} // Util | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Util.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getTaskCreatedBefore() {
return taskCreatedBefore;
}
public Boolean getIncludeTaskLocalVariables() {
return includeTaskLocalVariables;
}
public void setIncludeTaskLocalVariables(Boolean includeTaskLocalVariables) {
this.includeTaskLocalVariables = includeTaskLocalVariables;
}
public Boolean getIncludeProcessVariables() {
return includeProcessVariables;
}
public void setIncludeProcessVariables(Boolean includeProcessVariables) {
this.includeProcessVariables = includeProcessVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class)
public List<QueryVariable> getTaskVariables() {
return taskVariables;
}
public void setTaskVariables(List<QueryVariable> taskVariables) {
this.taskVariables = taskVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutProcessInstanceId() {
return withoutProcessInstanceId;
}
public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) {
this.withoutProcessInstanceId = withoutProcessInstanceId;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
} | public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java | 2 |
请完成以下Spring Boot application配置 | spring:
# ShardingSphere 配置项
shardingsphere:
datasource:
# 所有数据源的名字
names: ds-orders, ds-users
# 订单 orders 数据源配置
ds-orders:
type: com.zaxxer.hikari.HikariDataSource # 使用 Hikari 数据库连接池
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password:
# 订单 users 数据源配置
ds-users:
type: com.zaxxer.hikari.HikariDataSource # 使用 Hikari 数据库连接池
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/test_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password:
# 分片规则
sharding:
tables:
# orders 表配置
orders:
actualDataNodes: ds-orders.orders # 映射到 ds-ord | ers 数据源的 orders 表
# users 表配置
users:
actualDataNodes: ds-users.users # 映射到 ds-users 数据源的 users 表
# mybatis 配置内容
mybatis:
config-location: classpath:mybatis-config.xml # 配置 MyBatis 配置文件路径
mapper-locations: classpath:mapper/*.xml # 配置 Mapper XML 地址
type-aliases-package: cn.iocoder.springboot.lab17.dynamicdatasource.dataobject # 配置数据库实体包路径 | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-sharding-jdbc-01\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FlowableUserDetailsService
implements UserDetailsService {
protected final IdmIdentityService identityService;
public FlowableUserDetailsService(IdmIdentityService identityService) {
this.identityService = identityService;
}
@Override
public UserDetails loadUserByUsername(String userId)
throws UsernameNotFoundException {
User user = null;
try {
user = this.identityService.createUserQuery()
.userId(userId)
.singleResult();
} catch (FlowableException ex) {
// don't care
}
if (null == user) {
throw new UsernameNotFoundException(
String.format("user (%s) could not be found", userId));
}
return createFlowableUser(user);
} | protected FlowableUser createFlowableUser(User user) {
String userId = user.getId();
List<Privilege> userPrivileges = identityService.createPrivilegeQuery().userId(userId).list();
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Privilege userPrivilege : userPrivileges) {
grantedAuthorities.add(new SimpleGrantedAuthority(userPrivilege.getName()));
}
List<Group> groups = identityService.createGroupQuery().groupMember(userId).list();
if (!groups.isEmpty()) {
List<String> groupIds = new ArrayList<>(groups.size());
for (Group group : groups) {
groupIds.add(group.getId());
}
List<Privilege> groupPrivileges = identityService.createPrivilegeQuery().groupIds(groupIds).list();
for (Privilege groupPrivilege : groupPrivileges) {
grantedAuthorities.add(new SimpleGrantedAuthority(groupPrivilege.getName()));
}
}
// We have to create new UserDto as the User returned by IDM is not serialized properly
// (it extends AbstractEntity which is not serializable) and leads to the id not being serialized
// We have to create new GroupDetails as Group returned bby IDM is not serialized properly. Same reasoning as with the User
return new FlowableUser(UserDto.create(user), true, GroupDetails.create(groups), grantedAuthorities);
}
} | repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\FlowableUserDetailsService.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getReply() {
return reply;
}
public void setReply(String reply) {
this.reply = reply;
}
public Post getPost() { | return post;
}
public void setPost(Post post) {
this.post = post;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entitygraph\model\Comment.java | 1 |
请完成以下Java代码 | public IHUAttributeTransferRequestBuilder setAttributeStorageFrom(final IAttributeSet attributeStorageFrom)
{
this.attributeStorageFrom = attributeStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageTo(final IAttributeStorage attributeStorageTo)
{
this.attributeStorageTo = attributeStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageFrom(final IHUStorage huStorageFrom)
{
this.huStorageFrom = huStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageTo(final IHUStorage huStorageTo) | {
this.huStorageTo = huStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQtyUnloaded(final BigDecimal qtyUnloaded)
{
this.qtyUnloaded = qtyUnloaded;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setVHUTransfer(final boolean vhuTransfer)
{
this.vhuTransfer = vhuTransfer;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequestBuilder.java | 1 |
请完成以下Java代码 | private static void createDatabaseTables(Connection conn) throws SQLException {
Statement sql = conn.createStatement();
sql.executeUpdate("CREATE TABLE Employee (" +
" id INTEGER PRIMARY KEY, name VARCHAR, isEmployed timyint(1)) " +
" WITH \"template=replicated\"");
sql.executeUpdate("CREATE INDEX idx_employee_name ON Employee (name)");
}
private static void insertData(Connection conn) throws SQLException {
PreparedStatement sql =
conn.prepareStatement("INSERT INTO Employee (id, name, isEmployed) VALUES (?, ?, ?)");
sql.setLong(1, 1);
sql.setString(2, "James");
sql.setBoolean(3, true);
sql.executeUpdate(); | sql.setLong(1, 2);
sql.setString(2, "Monica");
sql.setBoolean(3, false);
sql.executeUpdate();
}
private static void getData(Connection conn) throws SQLException {
Statement sql = conn.createStatement();
ResultSet rs = sql.executeQuery("SELECT e.name, e.isEmployed " +
" FROM Employee e " +
" WHERE e.isEmployed = TRUE ");
while (rs.next())
System.out.println(rs.getString(1) + ", " + rs.getString(2));
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\ignite\jdbc\IgniteJDBC.java | 1 |
请完成以下Java代码 | public boolean checkEquals(final InvoiceCandidateInfo infoAfterChange)
{
final InvoiceCandidateInfo infoBeforeChange = this;
Check.assume(infoAfterChange.getC_Invoice_Candidate_ID() == infoBeforeChange.getC_Invoice_Candidate_ID(),
"Old info {} and New info {} shall share the same C_Invoice_Candidate_ID", infoBeforeChange, infoAfterChange);
boolean hasChanges = false;
final TokenizedStringBuilder changesInfo = new TokenizedStringBuilder(", ");
if (infoAfterChange.getLineNetAmt().compareTo(infoBeforeChange.getLineNetAmt()) != 0)
{
changesInfo.append("@LineNetAmt@: " + infoBeforeChange.getLineNetAmt() + "->" + infoAfterChange.getLineNetAmt());
hasChanges = true;
}
if (infoAfterChange.getC_Tax_ID() != infoBeforeChange.getC_Tax_ID())
{
changesInfo.append("@C_Tax_ID@: " + infoBeforeChange.getC_Tax_ID() + "->" + infoAfterChange.getC_Tax_ID());
hasChanges = true;
}
if (hasChanges)
{
Loggables.addLog(infoAfterChange.getC_Invoice_Candidate_ID() + ": " + changesInfo);
}
return !hasChanges;
} | public int getC_Invoice_Candidate_ID()
{
return invoiceCandidateId;
}
public BigDecimal getLineNetAmt()
{
return netAmtToInvoice;
}
public int getC_Tax_ID()
{
return taxId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesChangesChecker.java | 1 |
请在Spring Boot框架中完成以下Java代码 | SecurityFilterChain userFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(requests -> requests
.antMatchers("/login", "/register", "/newuserregister" ,"/test", "/test2").permitAll()
.antMatchers("/**").hasRole("USER"))
.formLogin(login -> login
.loginPage("/login")
.loginProcessingUrl("/userloginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/"); // Redirect on success
})
.failureHandler((request, response, exception) -> {
response.sendRedirect("/login?error=true"); // Redirect on failure
}))
.logout(logout -> logout.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID"))
.exceptionHandling(exception -> exception
.accessDeniedPage("/403") // Custom 403 page
);
http.csrf(csrf -> csrf.disable());
return http.build();
}
} | @Bean
UserDetailsService userDetailsService() {
return username -> {
User user = UserService.getUserByUsername(username);
if(user == null) {
throw new UsernameNotFoundException("User with username " + username + " not found.");
}
String role = user.getRole().equals("ROLE_ADMIN") ? "ADMIN":"USER";
return org.springframework.security.core.userdetails.User
.withUsername(username)
.passwordEncoder(input->passwordEncoder().encode(input))
.password(user.getPassword())
.roles(role)
.build();
};
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\configuration\SecurityConfiguration.java | 2 |
请完成以下Java代码 | public Vector addDocument(int id, String content)
{
Vector result = query(content);
if (result == null) return null;
storage.put(id, result);
return result;
}
/**
* 查询最相似的前10个文档
*
* @param query 查询语句(或者说一个文档的内容)
* @return
*/
public List<Map.Entry<Integer, Float>> nearest(String query)
{
return queryNearest(query, 10);
}
/**
* 查询最相似的前n个文档
*
* @param query 查询语句(或者说一个文档的内容)
* @return
*/
public List<Map.Entry<Integer, Float>> nearest(String query, int n)
{
return queryNearest(query, n);
}
/**
* 将一个文档转为向量
*
* @param content 文档
* @return 向量
*/
public Vector query(String content)
{
if (content == null || content.length() == 0) return null;
List<Term> termList = segment.seg(content);
if (filter)
{
CoreStopWordDictionary.apply(termList);
}
Vector result = new Vector(dimension());
int n = 0;
for (Term term : termList)
{
Vector vector = wordVectorModel.vector(term.word);
if (vector == null)
{
continue;
}
++n;
result.addToSelf(vector);
}
if (n == 0)
{
return null;
} | result.normalize();
return result;
}
@Override
public int dimension()
{
return wordVectorModel.dimension();
}
/**
* 文档相似度计算
*
* @param what
* @param with
* @return
*/
public float similarity(String what, String with)
{
Vector A = query(what);
if (A == null) return -1f;
Vector B = query(with);
if (B == null) return -1f;
return A.cosineForUnitVector(B);
}
public Segment getSegment()
{
return segment;
}
public void setSegment(Segment segment)
{
this.segment = segment;
}
/**
* 是否激活了停用词过滤器
*
* @return
*/
public boolean isFilterEnabled()
{
return filter;
}
/**
* 激活/关闭停用词过滤器
*
* @param filter
*/
public void enableFilter(boolean filter)
{
this.filter = filter;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java | 1 |
请完成以下Java代码 | private void throwException(@NonNull final ProductExclude productExclude, @NonNull final AdMessageKey adMessage)
{
final String partnerName = bpartnerDAO.getBPartnerNameById(productExclude.getBpartnerId());
final String msg = msgBL.getMsg(adMessage,
ImmutableList.of(partnerName, productExclude.getReason()));
throw new AdempiereException(msg);
}
@Override
public void setProductCodeFieldsFromGTIN(@NonNull final I_C_BPartner_Product record, @Nullable final GTIN gtin)
{
final EAN13 ean13 = gtin != null ? gtin.toEAN13().orElse(null) : null;
record.setGTIN(gtin != null ? gtin.getAsString() : null);
record.setEAN_CU(ean13 != null ? ean13.getAsString() : null);
record.setUPC(gtin != null ? gtin.getAsString() : null);
if (gtin != null)
{ | record.setEAN13_ProductCode(null);
}
}
@Override
public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_C_BPartner_Product record, @Nullable final EAN13ProductCode ean13ProductCode)
{
record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null);
if (ean13ProductCode != null)
{
record.setGTIN(null);
record.setEAN_CU(null);
record.setUPC(null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner_product\impl\BPartnerProductBL.java | 1 |
请完成以下Java代码 | private static final int suggestDisplayType(final Class<?> returnType)
{
if (returnType == String.class)
{
return DisplayType.String;
}
else if (returnType == Boolean.class || returnType == boolean.class)
{
return DisplayType.YesNo;
}
else if (returnType == BigDecimal.class)
{
return DisplayType.Amount;
}
else if (returnType == Integer.class)
{
return DisplayType.Integer;
}
else if (Date.class.isAssignableFrom(returnType))
{
return DisplayType.Date;
}
else
{
return -1;
}
}
private int getDisplayType(final Method method)
{
if (method == null)
{
return -1;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return -1;
}
final int displayType = info.displayType();
return displayType > 0 ? displayType : -1;
}
private boolean isSelectionColumn(final PropertyDescriptor pd)
{ | Boolean selectionColumn = getSelectionColumn(pd.getReadMethod());
if (selectionColumn == null)
{
selectionColumn = getSelectionColumn(pd.getWriteMethod());
}
return selectionColumn != null ? selectionColumn : false;
}
private Boolean getSelectionColumn(final Method method)
{
if (method == null)
{
return null;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return null;
}
return info.selectionColumn();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableModelMetaInfo.java | 1 |
请完成以下Java代码 | public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(String caseInstanceId) {
return getList("selectSentryPartInstanceByCaseInstanceIdAndNullPlanItemInstanceId", caseInstanceId);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByPlanItemInstanceId(String planItemInstanceId) {
return getList("selectSentryPartInstanceByPlanItemInstanceId", planItemInstanceId, sentryPartByPlanItemInstanceIdEntityMatched);
}
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
bulkDelete("deleteSentryPartInstancesByCaseInstanceId", sentryPartByCaseInstanceIdEntityMatched, caseInstanceId);
}
public static class SentryPartByCaseInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) {
return sentryPartInstanceEntity.getPlanItemInstanceId() == null | && sentryPartInstanceEntity.getCaseInstanceId().equals(param);
}
}
public static class SentryPartByPlanItemInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) {
return sentryPartInstanceEntity.getPlanItemInstanceId() != null
&& sentryPartInstanceEntity.getPlanItemInstanceId().equals(param);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisSentryPartInstanceDataManagerImpl.java | 1 |
请完成以下Java代码 | public ViewRowIdsOrderedSelection getSelection(final DocumentQueryOrderByList orderBys)
{
final ViewRowIdsOrderedSelection selection = getSelectionOrNull(orderBys);
if (selection == null)
{
throw new AdempiereException("No selection found for " + orderBys + " in " + this);
}
return selection;
}
private ViewRowIdsOrderedSelection getSelectionOrNull(final DocumentQueryOrderByList orderBys)
{
if (orderBys == null || orderBys.isEmpty())
{
return defaultSelection;
}
if (DocumentQueryOrderByList.equals(defaultSelection.getOrderBys(), orderBys))
{
return defaultSelection;
} | return selectionsByOrderBys.get(orderBys);
}
public ImmutableSet<String> getSelectionIds()
{
final ImmutableSet.Builder<String> selectionIds = ImmutableSet.builder();
selectionIds.add(defaultSelection.getSelectionId());
for (final ViewRowIdsOrderedSelection selection : selectionsByOrderBys.values())
{
selectionIds.add(selection.getSelectionId());
}
return selectionIds.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelections.java | 1 |
请完成以下Java代码 | public I_C_Flatrate_Term retrieveTopExtendedTerm(@NonNull final I_C_Flatrate_Term term)
{
I_C_Flatrate_Term nextTerm = term.getC_FlatrateTerm_Next();
if (nextTerm != null)
{
nextTerm = retrieveTopExtendedTerm(nextTerm);
}
return nextTerm == null ? term : nextTerm;
}
@Nullable
public OrderId getContractOrderId(@NonNull final I_C_Flatrate_Term term)
{
if (term.getC_OrderLine_Term_ID() <= 0)
{
return null;
}
final IOrderDAO orderRepo = Services.get(IOrderDAO.class);
final de.metas.interfaces.I_C_OrderLine ol = orderRepo.getOrderLineById(term.getC_OrderLine_Term_ID());
if (ol == null)
{
return null;
}
return OrderId.ofRepoId(ol.getC_Order_ID());
}
public boolean isContractSalesOrder(@NonNull final OrderId orderId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId) | .addNotNull(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID)
.create()
.anyMatch();
}
public void save(@NonNull final I_C_Order order)
{
InterfaceWrapperHelper.save(order);
}
public void setOrderContractStatusAndSave(@NonNull final I_C_Order order, @NonNull final String contractStatus)
{
order.setContractStatus(contractStatus);
save(order);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\ContractOrderService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArticleMapping articleMapping = (ArticleMapping) o;
return Objects.equals(this._id, articleMapping._id) &&
Objects.equals(this.customerId, articleMapping.customerId) &&
Objects.equals(this.updated, articleMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, customerId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ArticleMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n"); | sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\ArticleMapping.java | 2 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_DirectDebitLine[")
.append(get_ID()).append("]");
return sb.toString();
}
@Override
public I_C_DirectDebit getC_DirectDebit() throws Exception
{
return get_ValueAsPO(COLUMNNAME_C_DirectDebit_ID, org.compiere.model.I_C_DirectDebit.class);
}
/** Set C_DirectDebit_ID.
@param C_DirectDebit_ID C_DirectDebit_ID */
@Override
public void setC_DirectDebit_ID (int C_DirectDebit_ID)
{
if (C_DirectDebit_ID < 1)
throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory.");
set_Value (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID));
}
/** Get C_DirectDebit_ID.
@return C_DirectDebit_ID */
@Override
public int getC_DirectDebit_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set C_DirectDebitLine_ID.
@param C_DirectDebitLine_ID C_DirectDebitLine_ID */
@Override
public void setC_DirectDebitLine_ID (int C_DirectDebitLine_ID)
{
if (C_DirectDebitLine_ID < 1)
throw new IllegalArgumentException ("C_DirectDebitLine_ID is mandatory.");
set_ValueNoCheck (COLUMNNAME_C_DirectDebitLine_ID, Integer.valueOf(C_DirectDebitLine_ID)); | }
/** Get C_DirectDebitLine_ID.
@return C_DirectDebitLine_ID */
@Override
public int getC_DirectDebitLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public I_C_Invoice getC_Invoice() throws Exception
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
/** Set Invoice.
@param C_Invoice_ID
Invoice Identifier
*/
@Override
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
throw new IllegalArgumentException ("C_Invoice_ID is mandatory.");
set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
/** Get Invoice.
@return Invoice Identifier
*/
@Override
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_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\org\compiere\model\X_C_DirectDebitLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<DecisionDefinition> executeList(CommandContext commandContext, Page page) {
if (isDmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getDecisionDefinitionManager()
.findDecisionDefinitionsByQueryCriteria(this, page);
}
return Collections.emptyList();
}
@Override
public void checkQueryOk() {
super.checkQueryOk();
// latest() makes only sense when used with key() or keyLike()
if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){
throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)");
}
}
private boolean isDmnEnabled(CommandContext commandContext) {
return commandContext
.getProcessEngineConfiguration()
.isDmnEnabled();
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getDeploymentId() {
return deploymentId;
} | public Date getDeployedAfter() {
return deployedAfter;
}
public Date getDeployedAt() {
return deployedAt;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
public String getVersionTag() {
return versionTag;
}
public String getVersionTagLike() {
return versionTagLike;
}
public boolean isLatest() {
return latest;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeController {
@Autowired
private MongoDB mongoDB;
@Autowired
private SequenceGeneratorService sequenceGeneratorService;
@GetMapping("/all")
public List<Employees> getAllEmployee(){
return mongoDB.findAll();
}
@GetMapping("/employee/{id}")
public ResponseEntity <Employees> getEmployeeById(@PathVariable(value = "id") String employeeId) throws ResourceNotFoundException{
Employees employees = mongoDB.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id::" + employeeId));
return ResponseEntity.ok().body(employees);
}
@PostMapping("/employees")
public Employees createEmployees(@Valid @RequestBody Employees employees) {
//
employees.setId(sequenceGeneratorService.generateSequence(Employees.SEQUENCE_NAME));
return mongoDB.save(employees);
}
@PutMapping("/employees/{id}")
public ResponseEntity <Employees> updateEmployee(@PathVariable(value = "id") String employeeId, @Valid @RequestBody Employees details) throws ResourceNotFoundException {
//
Employees employees = mongoDB.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found this id::" + employeeId));
employees.setName(details.getName()); | employees.setPhone(details.getPhone());
employees.setAge(details.getAge());
employees.setPosition(details.getPosition());
final Employees updatedEmployee = mongoDB.save(employees);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") String id) throws ResourceNotFoundException {
//
Employees employees = mongoDB.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id::" + id));
mongoDB.delete(employees);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
} | repos\Spring-Boot-Advanced-Projects-main\SpringBoot-MongoDB-NoSQL-CRUD\src\main\java\com\urunov\mongodb\controller\EmployeeController.java | 2 |
请完成以下Java代码 | public void setC_Invoice_Verification_Set_ID (final int C_Invoice_Verification_Set_ID)
{
if (C_Invoice_Verification_Set_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, C_Invoice_Verification_Set_ID);
}
@Override
public int getC_Invoice_Verification_Set_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Set_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription() | {
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_Set.java | 1 |
请完成以下Java代码 | public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
}
@Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/ | @Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String index() {
return "index";
}
@RequestMapping( value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
public String login(HttpServletRequest req, UserCredentials cred, RedirectAttributes attr) {
if(req.getMethod().equals(RequestMethod.GET.toString())) {
return "login";
} else {
Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(
cred.getUsername(), cred.getPassword(), cred.isRememberMe());
try {
subject.login(token);
} catch (AuthenticationException ae) {
ae.printStackTrace();
attr.addFlashAttribute("error", "Invalid Credentials");
return "redirect:/login";
}
}
return "redirect:/secure";
}
}
@GetMapping("/secure")
public String secure(ModelMap modelMap) {
Subject currentUser = SecurityUtils.getSubject();
String role = "", permission = "";
if(currentUser.hasRole("admin")) {
role = role + "You are an Admin";
}
else if(currentUser.hasRole("editor")) {
role = role + "You are an Editor"; | }
else if(currentUser.hasRole("author")) {
role = role + "You are an Author";
}
if(currentUser.isPermitted("articles:compose")) {
permission = permission + "You can compose an article, ";
} else {
permission = permission + "You are not permitted to compose an article!, ";
}
if(currentUser.isPermitted("articles:save")) {
permission = permission + "You can save articles, ";
} else {
permission = permission + "\nYou can not save articles, ";
}
if(currentUser.isPermitted("articles:publish")) {
permission = permission + "\nYou can publish articles";
} else {
permission = permission + "\nYou can not publish articles";
}
modelMap.addAttribute("username", currentUser.getPrincipal());
modelMap.addAttribute("permission", permission);
modelMap.addAttribute("role", role);
return "secure";
}
@PostMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/";
}
} | repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\controllers\ShiroSpringController.java | 2 |
请完成以下Java代码 | protected String getManagementHost(ServiceInstance instance) {
String managementServerHost = getMetadataValue(instance, KEYS_MANAGEMENT_ADDRESS);
if (hasText(managementServerHost)) {
return managementServerHost;
}
return getServiceUrl(instance).getHost();
}
protected int getManagementPort(ServiceInstance instance) {
String managementPort = getMetadataValue(instance, KEYS_MANAGEMENT_PORT);
if (hasText(managementPort)) {
return Integer.parseInt(managementPort);
}
return getServiceUrl(instance).getPort();
}
protected String getManagementPath(ServiceInstance instance) {
String managementPath = getMetadataValue(instance, KEYS_MANAGEMENT_PATH);
if (hasText(managementPath)) {
return managementPath;
}
return this.managementContextPath;
}
protected URI getServiceUrl(ServiceInstance instance) {
return instance.getUri();
}
protected Map<String, String> getMetadata(ServiceInstance instance) {
return (instance.getMetadata() != null) ? instance.getMetadata()
.entrySet()
.stream()
.filter((e) -> e.getKey() != null && e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : emptyMap();
} | public String getManagementContextPath() {
return this.managementContextPath;
}
public void setManagementContextPath(String managementContextPath) {
this.managementContextPath = managementContextPath;
}
public String getHealthEndpointPath() {
return this.healthEndpointPath;
}
public void setHealthEndpointPath(String healthEndpointPath) {
this.healthEndpointPath = healthEndpointPath;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\DefaultServiceInstanceConverter.java | 1 |
请完成以下Java代码 | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName() {
return fullName;
}
@PrePersist
public void logNewUserAttempt() {
log.info("Attempting to add new user with username: " + userName);
}
@PostPersist
public void logNewUserAdded() {
log.info("Added user '" + userName + "' with ID: " + id);
}
@PreRemove
public void logUserRemovalAttempt() {
log.info("Attempting to delete user: " + userName);
}
@PostRemove
public void logUserRemoval() {
log.info("Deleted user: " + userName);
} | @PreUpdate
public void logUserUpdateAttempt() {
log.info("Attempting to update user: " + userName);
}
@PostUpdate
public void logUserUpdate() {
log.info("Updated user: " + userName);
}
@PostLoad
public void logUserLoad() {
fullName = firstName + " " + lastName;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-annotations\src\main\java\com\baeldung\lifecycleevents\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMorningMessage() {
return morningMessage;
}
public void setMorningMessage(String morningMessage) {
this.morningMessage = morningMessage;
}
public String getAfternoonMessage() {
return afternoonMessage;
}
public void setAfternoonMessage(String afternoonMessage) {
this.afternoonMessage = afternoonMessage;
}
public String getEveningMessage() { | return eveningMessage;
}
public void setEveningMessage(String eveningMessage) {
this.eveningMessage = eveningMessage;
}
public String getNightMessage() {
return nightMessage;
}
public void setNightMessage(String nightMessage) {
this.nightMessage = nightMessage;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-custom-starter\greeter-spring-boot-autoconfigure\src\main\java\com\baeldung\greeter\autoconfigure\GreeterProperties.java | 2 |
请完成以下Java代码 | public static String stripDiacritics(String s)
{
/* JAVA5 behaviour */
return s;
/*
* JAVA6 behaviour * if (s == null) { return s; } String normStr = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD);
*
* StringBuffer sb = new StringBuffer(); for (int i = 0; i < normStr.length(); i++) { char ch = normStr.charAt(i); if (ch < 255) sb.append(ch); } return sb.toString(); /*
*/
}
/**
* Check if given string contains digits only.
*
* @param stringToVerify
* @return {@link code true} if the given string consists only of digits (i.e. contains no letter, whitespace decimal point etc).
*/
public static final boolean isNumber(final String stringToVerify)
{
// Null or empty strings are not numbers
if (stringToVerify == null || stringToVerify.isEmpty())
{
return false;
}
final int length = stringToVerify.length();
for (int i = 0; i < length; i++)
{
if (!Character.isDigit(stringToVerify.charAt(i)))
{
return false; | }
}
return true;
}
public static final String toString(final Collection<?> collection, final String separator)
{
if (collection == null)
{
return "null";
}
if (collection.isEmpty())
{
return "";
}
final StringBuilder sb = new StringBuilder();
for (final Object item : collection)
{
if (sb.length() > 0)
{
sb.append(separator);
}
sb.append(String.valueOf(item));
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\util\StringUtils.java | 1 |
请完成以下Java代码 | public BadUserRequestException processDefinitionDoesNotExist(String processDefinitionId, String type) {
return new BadUserRequestException(exceptionMessage(
"008",
"{} process definition with id '{}' does not exist",
type, processDefinitionId
));
}
public ProcessEngineException cannotMigrateBetweenTenants(String sourceTenantId, String targetTenantId) {
return new ProcessEngineException(exceptionMessage(
"09",
"Cannot migrate process instances between processes of different tenants ('{}' != '{}')",
sourceTenantId,
targetTenantId));
}
public ProcessEngineException cannotMigrateInstanceBetweenTenants(String processInstanceId, String sourceTenantId, String targetTenantId) {
String detailMessage = null;
if (sourceTenantId != null) {
detailMessage = exceptionMessage(
"010",
"Cannot migrate process instance '{}' to a process definition of a different tenant ('{}' != '{}')",
processInstanceId,
sourceTenantId,
targetTenantId);
}
else { | detailMessage = exceptionMessage(
"010",
"Cannot migrate process instance '{}' without tenant to a process definition with a tenant ('{}')",
processInstanceId,
targetTenantId);
}
return new ProcessEngineException(detailMessage);
}
public ProcessEngineException cannotHandleChild(MigratingScopeInstance scopeInstance, MigratingProcessElementInstance childCandidate) {
return new ProcessEngineException(
exceptionMessage(
"011",
"Scope instance of type {} cannot have child of type {}",
scopeInstance.getClass().getSimpleName(),
childCandidate.getClass().getSimpleName())
);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationLogger.java | 1 |
请完成以下Java代码 | public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName () | {
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Drucker.
@param PrinterName
Name of the Printer
*/
@Override
public void setPrinterName (java.lang.String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Drucker.
@return Name of the Printer
*/
@Override
public java.lang.String getPrinterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrinterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFormat.java | 1 |
请完成以下Java代码 | public final BigDecimal getAppliedAmt_APAdjusted()
{
return adjustAP(getAppliedAmt());
}
protected static final BigDecimal notNullOrZero(final BigDecimal value)
{
return value == null ? BigDecimal.ZERO : value;
}
/**
* AP Adjust given amount (by using {@link #getMultiplierAP()}).
*
* @param amount
* @return AP adjusted amount
*/
protected final BigDecimal adjustAP(final BigDecimal amount)
{
final BigDecimal multiplierAP = getMultiplierAP();
final BigDecimal amount_APAdjusted = amount.multiply(multiplierAP); | return amount_APAdjusted;
}
public final PaymentDirection getPaymentDirection()
{
return PaymentDirection.ofInboundPaymentFlag(isCustomerDocument());
}
@Override
public final boolean isVendorDocument()
{
return getMultiplierAP().signum() < 0;
}
@Override
public final boolean isCustomerDocument()
{
return getMultiplierAP().signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\AbstractAllocableDocRow.java | 1 |
请完成以下Java代码 | public void addExecutionListener(String eventName, ExecutionListener executionListener) {
addExecutionListener(eventName, executionListener, -1);
}
public void addExecutionListener(String eventName, ExecutionListener executionListener, int index) {
List<ExecutionListener> listeners = executionListeners.get(eventName);
if (listeners == null) {
listeners = new ArrayList<>();
executionListeners.put(eventName, listeners);
}
if (index < 0) {
listeners.add(executionListener);
} else {
listeners.add(index, executionListener);
}
}
public Map<String, List<ExecutionListener>> getExecutionListeners() { | return executionListeners;
}
// getters and setters //////////////////////////////////////////////////////
@Override
public List<ActivityImpl> getActivities() {
return activities;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ScopeImpl.java | 1 |
请完成以下Java代码 | public final class WebSocketConnectHandlerDecoratorFactory implements WebSocketHandlerDecoratorFactory {
private static final Log logger = LogFactory.getLog(WebSocketConnectHandlerDecoratorFactory.class);
private final ApplicationEventPublisher eventPublisher;
/**
* Creates a new instance.
* @param eventPublisher the {@link ApplicationEventPublisher} to use. Cannot be null.
*/
public WebSocketConnectHandlerDecoratorFactory(ApplicationEventPublisher eventPublisher) {
Assert.notNull(eventPublisher, "eventPublisher cannot be null");
this.eventPublisher = eventPublisher;
}
@Override
public WebSocketHandler decorate(WebSocketHandler handler) {
return new SessionWebSocketHandler(handler);
}
private final class SessionWebSocketHandler extends WebSocketHandlerDecorator {
SessionWebSocketHandler(WebSocketHandler delegate) {
super(delegate);
}
@Override | public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception {
super.afterConnectionEstablished(wsSession);
publishEvent(new SessionConnectEvent(this, wsSession));
}
private void publishEvent(ApplicationEvent event) {
try {
WebSocketConnectHandlerDecoratorFactory.this.eventPublisher.publishEvent(event);
}
catch (Throwable ex) {
logger.error("Error publishing " + event + ".", ex);
}
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\handler\WebSocketConnectHandlerDecoratorFactory.java | 1 |
请完成以下Java代码 | public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
@Override
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Override
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
@Override
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override | public Long getWorkTimeInMillis() {
if (endTime == null || claimTime == null) {
return null;
}
return endTime.getTime() - claimTime.getTime();
}
@Override
public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricTaskInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntity.java | 1 |
请完成以下Java代码 | protected void postProcessJob(T configuration, JobEntity job, T jobConfiguration) {
// do nothing as default
}
protected JobEntity createBatchJob(BatchEntity batch, ByteArrayEntity configuration) {
BatchJobContext creationContext = new BatchJobContext(batch, configuration);
return getJobDeclaration().createJobInstance(creationContext);
}
@Override
public void deleteJobs(BatchEntity batch) {
List<JobEntity> jobs = Context.getCommandContext()
.getJobManager()
.findJobsByJobDefinitionId(batch.getBatchJobDefinitionId());
for (JobEntity job : jobs) {
job.delete();
}
}
@Override
public BatchJobConfiguration newConfiguration(String canonicalString) {
return new BatchJobConfiguration(canonicalString);
}
@Override
public void onDelete(BatchJobConfiguration configuration, JobEntity jobEntity) {
String byteArrayId = configuration.getConfigurationByteArrayId();
if (byteArrayId != null) {
Context.getCommandContext().getByteArrayManager()
.deleteByteArrayById(byteArrayId);
}
}
protected ByteArrayEntity saveConfiguration(ByteArrayManager byteArrayManager, T jobConfiguration) {
ByteArrayEntity configurationEntity = new ByteArrayEntity();
configurationEntity.setBytes(writeConfiguration(jobConfiguration));
byteArrayManager.insert(configurationEntity);
return configurationEntity;
}
@Override
public byte[] writeConfiguration(T configuration) {
JsonElement jsonObject = getJsonConverterInstance().toJsonObject(configuration);
return JsonUtil.asBytes(jsonObject);
}
@Override
public T readConfiguration(byte[] serializedConfiguration) {
return getJsonConverterInstance().toObject(JsonUtil.asObject(serializedConfiguration));
}
protected abstract AbstractBatchConfigurationObjectConverter<T> getJsonConverterInstance();
@Override | public Class<? extends DbEntity> getEntityType() {
return BatchEntity.class;
}
@Override
public OptimisticLockingResult failedOperation(final DbOperation operation) {
if (operation instanceof DbEntityOperation) {
return OptimisticLockingResult.IGNORE;
}
return OptimisticLockingResult.THROW;
}
@Override
public int calculateInvocationsPerBatchJob(String batchType, T configuration) {
ProcessEngineConfigurationImpl engineConfig = Context.getProcessEngineConfiguration();
Map<String, Integer> invocationsPerBatchJobByBatchType = engineConfig.getInvocationsPerBatchJobByBatchType();
Integer invocationCount = invocationsPerBatchJobByBatchType.get(batchType);
if (invocationCount != null) {
return invocationCount;
} else {
return engineConfig.getInvocationsPerBatchJob();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\AbstractBatchJobHandler.java | 1 |
请完成以下Java代码 | private I_AD_Column createColumn(final ColumnSource sourceColumn, final I_AD_Table targetTable)
{
final I_AD_Column colTarget = InterfaceWrapperHelper.newInstance(I_AD_Column.class);
colTarget.setAD_Org_ID(0);
colTarget.setAD_Table_ID(targetTable.getAD_Table_ID());
colTarget.setEntityType(getEntityType());
final Properties ctx = Env.getCtx();
M_Element element = M_Element.get(ctx, sourceColumn.getName());
if (element == null)
{
element = new M_Element(ctx, sourceColumn.getName(), targetTable.getEntityType(), ITrx.TRXNAME_ThreadInherited);
element.setColumnName(sourceColumn.getName());
element.setName(sourceColumn.getName());
element.setPrintName(sourceColumn.getName());
element.saveEx(ITrx.TRXNAME_ThreadInherited); | addLog("@AD_Element_ID@ " + element.getColumnName() + ": @Created@"); // metas
}
colTarget.setAD_Element_ID(element.getAD_Element_ID());
colTarget.setName(targetTable.getName());
colTarget.setIsAllowLogging(false);
colTarget.setFieldLength(sourceColumn.getLength());
colTarget.setAD_Reference_ID(sourceColumn.getType());
colTarget.setIsActive(true);
colTarget.setIsUpdateable(true);
save(colTarget);
addLog("@AD_Column_ID@ " + targetTable.getTableName() + "." + colTarget.getColumnName() + ": @Created@");
return colTarget;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\CreateColumnsProducer.java | 1 |
请完成以下Java代码 | public void addWatermarkToExistingPdf() throws IOException {
StoryTime storyTime = new StoryTime();
String outputPdf = "output/aliceupdated.pdf";
String watermark = "CONFIDENTIAL";
try (PdfDocument pdfDocument = new PdfDocument(new PdfReader("output/alicepaulwithoutwatermark.pdf"), new PdfWriter(outputPdf))) {
Document document = new Document(pdfDocument);
Paragraph paragraph = storyTime.createWatermarkParagraph(watermark);
PdfExtGState transparentGraphicState = new PdfExtGState().setFillOpacity(0.5f);
for (int i = 1; i <= document.getPdfDocument()
.getNumberOfPages(); i++) {
storyTime.addWatermarkToExistingPage(document, i, paragraph, transparentGraphicState, 0f);
}
}
}
public Paragraph createWatermarkParagraph(String watermark) throws IOException {
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
Text text = new Text(watermark);
text.setFont(font);
text.setFontSize(56);
text.setOpacity(0.5f);
return new Paragraph(text);
}
public void addWatermarkToPage(Document document, int pageIndex, Paragraph paragraph, float verticalOffset) {
PdfPage pdfPage = document.getPdfDocument()
.getPage(pageIndex);
PageSize pageSize = (PageSize) pdfPage.getPageSizeWithRotation();
float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
float y = (pageSize.getTop() + pageSize.getBottom()) / 2;
float xOffset = 100f / 2;
float rotationInRadians = (float) (PI / 180 * 45f);
document.showTextAligned(paragraph, x - xOffset, y + verticalOffset, pageIndex, CENTER, TOP, rotationInRadians);
}
public void addWatermarkToExistingPage(Document document, int pageIndex, Paragraph paragraph, PdfExtGState graphicState, float verticalOffset) { | PdfDocument pdfDoc = document.getPdfDocument();
PdfPage pdfPage = pdfDoc.getPage(pageIndex);
PageSize pageSize = (PageSize) pdfPage.getPageSizeWithRotation();
float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
float y = (pageSize.getTop() + pageSize.getBottom()) / 2;
PdfCanvas over = new PdfCanvas(pdfDoc.getPage(pageIndex));
over.saveState();
over.setExtGState(graphicState);
float xOffset = 100f / 2;
float rotationInRadians = (float) (PI / 180 * 45f);
document.showTextAligned(paragraph, x - xOffset, y + verticalOffset, pageIndex, CENTER, TOP, rotationInRadians);
document.flush();
over.restoreState();
over.release();
}
} | repos\tutorials-master\libraries-files\src\main\java\com\baeldung\iTextPDF\StoryTime.java | 1 |
请完成以下Java代码 | public Builder header(String headerName, String... headerValues) {
return new StrictFirewallBuilder(this.delegate.header(headerName, headerValues));
}
@Override
public Builder headers(Consumer<HttpHeaders> headersConsumer) {
return new StrictFirewallBuilder(this.delegate.headers(headersConsumer));
}
@Override
public Builder sslInfo(SslInfo sslInfo) {
return new StrictFirewallBuilder(this.delegate.sslInfo(sslInfo));
}
@Override
public Builder remoteAddress(InetSocketAddress remoteAddress) {
return new StrictFirewallBuilder(this.delegate.remoteAddress(remoteAddress));
} | @Override
public Builder localAddress(InetSocketAddress localAddress) {
return new StrictFirewallBuilder(this.delegate.localAddress(localAddress));
}
@Override
public ServerHttpRequest build() {
return new StrictFirewallHttpRequest(this.delegate.build());
}
}
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\StrictServerWebExchangeFirewall.java | 1 |
请完成以下Java代码 | public int getMSV3_BestellungAuftrag_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAuftrag_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3_BestellungPosition.
@param MSV3_BestellungPosition_ID MSV3_BestellungPosition */
@Override
public void setMSV3_BestellungPosition_ID (int MSV3_BestellungPosition_ID)
{
if (MSV3_BestellungPosition_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungPosition_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungPosition_ID, Integer.valueOf(MSV3_BestellungPosition_ID));
}
/** Get MSV3_BestellungPosition.
@return MSV3_BestellungPosition */
@Override
public int getMSV3_BestellungPosition_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungPosition_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* MSV3_Liefervorgabe AD_Reference_ID=540821
* Reference name: MSV3_Liefervorgabe
*/
public static final int MSV3_LIEFERVORGABE_AD_Reference_ID=540821;
/** Normal = Normal */
public static final String MSV3_LIEFERVORGABE_Normal = "Normal";
/** MaxVerbund = MaxVerbund */
public static final String MSV3_LIEFERVORGABE_MaxVerbund = "MaxVerbund";
/** MaxNachlieferung = MaxNachlieferung */
public static final String MSV3_LIEFERVORGABE_MaxNachlieferung = "MaxNachlieferung";
/** MaxDispo = MaxDispo */
public static final String MSV3_LIEFERVORGABE_MaxDispo = "MaxDispo";
/** Set Liefervorgabe.
@param MSV3_Liefervorgabe Liefervorgabe */
@Override
public void setMSV3_Liefervorgabe (java.lang.String MSV3_Liefervorgabe)
{
set_Value (COLUMNNAME_MSV3_Liefervorgabe, MSV3_Liefervorgabe);
}
/** Get Liefervorgabe.
@return Liefervorgabe */
@Override
public java.lang.String getMSV3_Liefervorgabe ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Liefervorgabe);
}
/** Set MSV3_Menge. | @param MSV3_Menge MSV3_Menge */
@Override
public void setMSV3_Menge (int MSV3_Menge)
{
set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge));
}
/** Get MSV3_Menge.
@return MSV3_Menge */
@Override
public int getMSV3_Menge ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3_Pzn.
@param MSV3_Pzn MSV3_Pzn */
@Override
public void setMSV3_Pzn (java.lang.String MSV3_Pzn)
{
set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn);
}
/** Get MSV3_Pzn.
@return MSV3_Pzn */
@Override
public java.lang.String getMSV3_Pzn ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungPosition.java | 1 |
请完成以下Java代码 | public class Timetable {
private String name;
@ProblemFactCollectionProperty
@ValueRangeProvider
private List<Timeslot> timeslots;
@ProblemFactCollectionProperty
@ValueRangeProvider
private List<Room> rooms;
@PlanningEntityCollectionProperty
private List<Lesson> lessons;
@PlanningScore
private HardSoftScore score;
// Ignored by Timefold, used by the UI to display solve or stop solving button
private SolverStatus solverStatus;
// No-arg constructor required for Timefold
public Timetable() {
}
public Timetable(String name, HardSoftScore score, SolverStatus solverStatus) {
this.name = name;
this.score = score;
this.solverStatus = solverStatus;
}
public Timetable(String name, List<Timeslot> timeslots, List<Room> rooms, List<Lesson> lessons) {
this.name = name;
this.timeslots = timeslots;
this.rooms = rooms;
this.lessons = lessons;
}
// ************************************************************************
// Getters and setters
// ************************************************************************
public String getName() { | return name;
}
public List<Timeslot> getTimeslots() {
return timeslots;
}
public List<Room> getRooms() {
return rooms;
}
public List<Lesson> getLessons() {
return lessons;
}
public HardSoftScore getScore() {
return score;
}
public SolverStatus getSolverStatus() {
return solverStatus;
}
public void setSolverStatus(SolverStatus solverStatus) {
this.solverStatus = solverStatus;
}
} | repos\springboot-demo-master\Timefold Solver\src\main\java\org\acme\schooltimetabling\domain\Timetable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult<UmsMenu> getItem(@PathVariable Long id) {
UmsMenu umsMenu = menuService.getItem(id);
return CommonResult.success(umsMenu);
}
@ApiOperation("根据ID删除后台菜单")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = menuService.delete(id);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("分页查询后台菜单")
@RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<UmsMenu>> list(@PathVariable Long parentId,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<UmsMenu> menuList = menuService.list(parentId, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(menuList));
}
@ApiOperation("树形结构返回所有菜单列表")
@RequestMapping(value = "/treeList", method = RequestMethod.GET)
@ResponseBody | public CommonResult<List<UmsMenuNode>> treeList() {
List<UmsMenuNode> list = menuService.treeList();
return CommonResult.success(list);
}
@ApiOperation("修改菜单显示状态")
@RequestMapping(value = "/updateHidden/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateHidden(@PathVariable Long id, @RequestParam("hidden") Integer hidden) {
int count = menuService.updateHidden(id, hidden);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsMenuController.java | 2 |
请完成以下Java代码 | public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public InstructorDetail getInstructorDetail() {
return instructorDetail;
}
public void setInstructorDetail(InstructorDetail instructorDetail) { | this.instructorDetail = instructorDetail;
}
@Override
public String toString() {
return "Instructor [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", instructorDetail=" + instructorDetail + "]";
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\model\Instructor.java | 1 |
请完成以下Java代码 | public void addBuiltInTaskListener(String eventName, TaskListener taskListener) {
CollectionUtil.addToMapOfLists(builtinTaskListeners, eventName, taskListener);
// re-calculate combined map to ensure order of listener execution
populateAllTaskListeners();
}
public void addTimeoutTaskListener(String timeoutId, TaskListener taskListener) {
timeoutTaskListeners.put(timeoutId, taskListener);
}
public FormDefinition getFormDefinition() {
return formDefinition;
}
public void setFormDefinition(FormDefinition formDefinition) {
this.formDefinition = formDefinition;
}
public Expression getFormKey() {
return formDefinition.getFormKey();
}
public void setFormKey(Expression formKey) {
this.formDefinition.setFormKey(formKey);
}
public Expression getCamundaFormDefinitionKey() {
return formDefinition.getCamundaFormDefinitionKey(); | }
public String getCamundaFormDefinitionBinding() {
return formDefinition.getCamundaFormDefinitionBinding();
}
public Expression getCamundaFormDefinitionVersion() {
return formDefinition.getCamundaFormDefinitionVersion();
}
// helper methods ///////////////////////////////////////////////////////////
protected void populateAllTaskListeners() {
// reset allTaskListeners to build it from zero
allTaskListeners = new HashMap<>();
// ensure builtinTaskListeners are executed before regular taskListeners
CollectionUtil.mergeMapsOfLists(allTaskListeners, builtinTaskListeners);
CollectionUtil.mergeMapsOfLists(allTaskListeners, taskListeners);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDefinition.java | 1 |
请完成以下Java代码 | public class UnwrappedUser {
public int id;
@JsonUnwrapped
public Name name;
public UnwrappedUser() {
}
public UnwrappedUser(final int id, final Name name) {
this.id = id;
this.name = name;
} | public static class Name {
public String firstName;
public String lastName;
public Name() {
}
public Name(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
} | repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\annotation\UnwrappedUser.java | 1 |
请完成以下Java代码 | public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID()));
}
/** Set Opt-out Date.
@param OptOutDate
Date the contact opted out
*/
public void setOptOutDate (Timestamp OptOutDate)
{
set_ValueNoCheck (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Opt-out Date.
@return Date the contact opted out
*/
public Timestamp getOptOutDate ()
{
return (Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
public I_R_InterestArea getR_InterestArea() throws RuntimeException
{
return (I_R_InterestArea)MTable.get(getCtx(), I_R_InterestArea.Table_Name)
.getPO(getR_InterestArea_ID(), get_TrxName()); }
/** Set Interest Area.
@param R_InterestArea_ID | Interest Area or Topic
*/
public void setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subscribe Date.
@param SubscribeDate
Date the contact actively subscribed
*/
public void setSubscribeDate (Timestamp SubscribeDate)
{
set_ValueNoCheck (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Subscribe Date.
@return Date the contact actively subscribed
*/
public Timestamp getSubscribeDate ()
{
return (Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_ContactInterest.java | 1 |
请完成以下Java代码 | public void saveToken(@Nullable CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (token == null) {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(this.sessionAttributeName);
}
}
else {
HttpSession session = request.getSession();
session.setAttribute(this.sessionAttributeName, token);
}
}
@Override
public @Nullable CsrfToken loadToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return null;
}
return (CsrfToken) session.getAttribute(this.sessionAttributeName);
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
/**
* Sets the {@link HttpServletRequest} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
this.parameterName = parameterName; | }
/**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
this.headerName = headerName;
}
/**
* Sets the {@link HttpSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributename cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\HttpSessionCsrfTokenRepository.java | 1 |
请完成以下Java代码 | public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isValidatingSchema() {
return validatingSchema;
}
public void setValidatingSchema(boolean validatingSchema) {
this.validatingSchema = validatingSchema;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId; | }
@Override
public List<ProcessDefinition> getDeployedProcessDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class);
}
@Override
public List<CaseDefinition> getDeployedCaseDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class);
}
@Override
public List<DecisionDefinition> getDeployedDecisionDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class);
}
@Override
public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ ", source=" + source
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() { | return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\boot\domain\Customer.java | 2 |
请完成以下Java代码 | public class JmsOperationsOutboundEventChannelAdapter implements OutboundEventChannelAdapter<String> {
protected JmsOperations jmsOperations;
protected String destination;
protected JmsMessageCreator<String> messageCreator;
public JmsOperationsOutboundEventChannelAdapter(JmsOperations jmsOperations, String destination) {
this(jmsOperations, destination, (event, headerMap, session) -> {
TextMessage textMessage = session.createTextMessage(event);
for (String headerKey : headerMap.keySet()) {
textMessage.setObjectProperty(headerKey, headerMap.get(headerKey));
}
return textMessage;
});
}
public JmsOperationsOutboundEventChannelAdapter(JmsOperations jmsOperations, String destination, JmsMessageCreator<String> messageCreator) {
this.jmsOperations = jmsOperations;
this.destination = destination;
this.messageCreator = messageCreator;
}
@Override
public void sendEvent(String rawEvent, Map<String, Object> headerMap) {
jmsOperations.send(destination, session -> getMessageCreator().toMessage(rawEvent, headerMap, session));
}
public JmsOperations getJmsOperations() {
return jmsOperations;
}
public void setJmsOperations(JmsOperations jmsOperations) {
this.jmsOperations = jmsOperations;
} | public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public JmsMessageCreator<String> getMessageCreator() {
return messageCreator;
}
public void setMessageCreator(JmsMessageCreator<String> messageCreator) {
this.messageCreator = messageCreator;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsOperationsOutboundEventChannelAdapter.java | 1 |
请完成以下Java代码 | private CostElementAccountsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private CostElementAccountsMap retrieveMap()
{
final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map = queryBL
.createQueryBuilder(I_M_CostElement_Acct.class)
.addOnlyActiveRecordsFilter()
.stream()
.collect(ImmutableMap.toImmutableMap(
CostElementAccountsRepository::extractCostElementIdAndAcctSchemaId,
CostElementAccountsRepository::fromRecord));
return new CostElementAccountsMap(map);
}
private static CostElementIdAndAcctSchemaId extractCostElementIdAndAcctSchemaId(final I_M_CostElement_Acct record)
{
return CostElementIdAndAcctSchemaId.of(
CostElementId.ofRepoId(record.getM_CostElement_ID()),
AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()));
}
private static CostElementAccounts fromRecord(final I_M_CostElement_Acct record)
{
return CostElementAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.P_CostClearing_Acct(AccountId.ofRepoId(record.getP_CostClearing_Acct()))
.build();
}
@Value(staticConstructor = "of") | private static class CostElementIdAndAcctSchemaId
{
@NonNull CostElementId costTypeId;
@NonNull AcctSchemaId acctSchemaId;
}
private static class CostElementAccountsMap
{
private final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map;
public CostElementAccountsMap(
@NonNull final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map)
{
this.map = map;
}
public CostElementAccounts getAccounts(
@NonNull final CostElementId costElementId,
@NonNull final AcctSchemaId acctSchemaId)
{
final CostElementAccounts accounts = map.get(CostElementIdAndAcctSchemaId.of(costElementId, acctSchemaId));
if (accounts == null)
{
throw new AdempiereException("No accounts found for " + costElementId + " and " + acctSchemaId);
}
return accounts;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\CostElementAccountsRepository.java | 1 |
请完成以下Java代码 | public OAuth2TokenIntrospection convert(Map<String, Object> source) {
Map<String, Object> parsedClaims = this.claimTypeConverter.convert(source);
return OAuth2TokenIntrospection.withClaims(parsedClaims).build();
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
}
private static List<String> convertScope(Object scope) {
if (scope == null) {
return Collections.emptyList();
}
return Arrays.asList(StringUtils.delimitedListToStringArray(scope.toString(), " "));
}
}
private static final class OAuth2TokenIntrospectionMapConverter
implements Converter<OAuth2TokenIntrospection, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2TokenIntrospection source) {
Map<String, Object> responseClaims = new LinkedHashMap<>(source.getClaims());
if (!CollectionUtils.isEmpty(source.getScopes())) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, | StringUtils.collectionToDelimitedString(source.getScopes(), " "));
}
if (source.getExpiresAt() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.EXP, source.getExpiresAt().getEpochSecond());
}
if (source.getIssuedAt() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.IAT, source.getIssuedAt().getEpochSecond());
}
if (source.getNotBefore() != null) {
responseClaims.put(OAuth2TokenIntrospectionClaimNames.NBF, source.getNotBefore().getEpochSecond());
}
return responseClaims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\http\converter\OAuth2TokenIntrospectionHttpMessageConverter.java | 1 |
请完成以下Java代码 | public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonNode node = p.readValueAsTree();
Registration.Builder builder = Registration.builder();
builder.name(firstNonNullAsText(node, "name"));
if (node.hasNonNull("url")) {
String url = firstNonNullAsText(node, "url");
builder.healthUrl(url.replaceFirst("/+$", "") + "/health").managementUrl(url);
}
else {
builder.healthUrl(firstNonNullAsText(node, "healthUrl", "health_url"));
builder.managementUrl(firstNonNullAsText(node, "managementUrl", "management_url"));
builder.serviceUrl(firstNonNullAsText(node, "serviceUrl", "service_url"));
}
if (node.has("metadata")) {
node.get("metadata")
.properties() | .forEach((entry) -> builder.metadata(entry.getKey(), entry.getValue().asText()));
}
builder.source(firstNonNullAsText(node, "source"));
return builder.build();
}
private String firstNonNullAsText(JsonNode node, String... fieldNames) {
for (String fieldName : fieldNames) {
if (node.hasNonNull(fieldName)) {
return node.get(fieldName).asText();
}
}
return null;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\utils\jackson\RegistrationDeserializer.java | 1 |
请完成以下Java代码 | public BpmPlatformXmlParse execute() {
super.execute();
return this;
}
/** We know this is a <code><bpm-platform ../></code> element */
protected void parseRootElement() {
JobExecutorXmlImpl jobExecutor = new JobExecutorXmlImpl();
List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>();
for (Element element : rootElement.elements()) {
if(JOB_EXECUTOR.equals(element.getTagName())) {
parseJobExecutor(element, jobExecutor);
} else if(PROCESS_ENGINE.equals(element.getTagName())) {
parseProcessEngine(element, processEngines);
}
}
bpmPlatformXml = new BpmPlatformXmlImpl(jobExecutor, processEngines);
}
/**
* parse a <code><job-executor .../></code> element and add it to the list of parsed elements
*/
protected void parseJobExecutor(Element element, JobExecutorXmlImpl jobExecutorXml) {
List<JobAcquisitionXml> jobAcquisitions = new ArrayList<JobAcquisitionXml>();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(JOB_ACQUISITION.equals(childElement.getTagName())) {
parseJobAcquisition(childElement, jobAcquisitions);
}else if(PROPERTIES.equals(childElement.getTagName())){
parseProperties(childElement, properties);
}
}
jobExecutorXml.setJobAcquisitions(jobAcquisitions);
jobExecutorXml.setProperties(properties);
} | /**
* parse a <code><job-acquisition .../></code> element and add it to the
* list of parsed elements
*/
protected void parseJobAcquisition(Element element, List<JobAcquisitionXml> jobAcquisitions) {
JobAcquisitionXmlImpl jobAcquisition = new JobAcquisitionXmlImpl();
// set name
jobAcquisition.setName(element.attribute(NAME));
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if (JOB_EXECUTOR_CLASS_NAME.equals(childElement.getTagName())) {
jobAcquisition.setJobExecutorClassName(childElement.getText());
} else if (PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties);
}
}
// set collected properties
jobAcquisition.setProperties(properties);
// add to list
jobAcquisitions.add(jobAcquisition);
}
public BpmPlatformXml getBpmPlatformXml() {
return bpmPlatformXml;
}
public BpmPlatformXmlParse sourceUrl(URL url) {
super.sourceUrl(url);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\metadata\BpmPlatformXmlParse.java | 1 |
请完成以下Java代码 | private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) {
// valid log item
XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(handleCallbackParam.getLogId());
if (log == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log item not found.");
}
if (log.getHandleCode() > 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log repeate callback."); // avoid repeat callback, trigger child job etc
}
// handle msg
StringBuffer handleMsg = new StringBuffer();
if (log.getHandleMsg()!=null) {
handleMsg.append(log.getHandleMsg()).append("<br>");
} | if (handleCallbackParam.getHandleMsg() != null) {
handleMsg.append(handleCallbackParam.getHandleMsg());
}
// success, save log
log.setHandleTime(new Date());
log.setHandleCode(handleCallbackParam.getHandleCode());
log.setHandleMsg(handleMsg.toString());
XxlJobCompleter.updateHandleInfoAndFinish(log);
return ReturnT.SUCCESS;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobCompleteHelper.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
return null; // Not updateable
}
public long getLogNumber() {
return logNumber;
}
public void setLogNumber(long logNumber) {
this.logNumber = logNumber;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) { | this.userId = userId;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public String getLockTime() {
return lockTime;
}
public void setLockTime(String lockTime) {
this.lockTime = lockTime;
}
public int getProcessed() {
return isProcessed;
}
public void setProcessed(int isProcessed) {
this.isProcessed = isProcessed;
}
@Override
public String toString() {
return timeStamp.toString() + " : " + type;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java | 1 |
请完成以下Java代码 | public JobQuery orderByExecutionId() {
return orderBy(JobQueryProperty.EXECUTION_ID);
}
@Override
public JobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
@Override
public JobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
@Override
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
@Override
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobEntityManager()
.findJobCountByQueryCriteria(this);
}
@Override
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobEntityManager()
.findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getHandlerType() {
return this.handlerType;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() { | return processDefinitionId;
}
public boolean isRetriesLeft() {
return retriesLeft;
}
public boolean isExecutable() {
return executable;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java | 1 |
请完成以下Java代码 | public <T> Span setTag(Tag<T> tag, T value) {
return null;
}
@Override
public Span log(Map<String, ?> fields) {
return null;
}
@Override
public Span log(long timestampMicroseconds, Map<String, ?> fields) {
return null;
}
@Override
public Span log(String event) {
return null;
}
@Override
public Span log(long timestampMicroseconds, String event) {
return null;
}
@Override
public Span setBaggageItem(String key, String value) {
return null;
}
@Override
public String getBaggageItem(String key) {
return null;
} | @Override
public Span setOperationName(String operationName) {
return null;
}
@Override
public void finish() {
transaction.setStatus(Transaction.SUCCESS);
transaction.complete();
}
@Override
public void finish(long finishMicros) {
}
} | repos\SpringBoot-Labs-master\lab-61\lab-61-cat-opentracing\src\main\java\cn\iocoder\springboot\lab61\cat\opentracing\CatSpan.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
*/
SUMMARY,
/**
* Show a verbose summary.
*/
VERBOSE
}
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards
* compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/** | * Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE,
/**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java | 2 |
请完成以下Java代码 | public void setIsKeepTargetPlant (final boolean IsKeepTargetPlant)
{
set_Value (COLUMNNAME_IsKeepTargetPlant, IsKeepTargetPlant);
}
@Override
public boolean isKeepTargetPlant()
{
return get_ValueAsBoolean(COLUMNNAME_IsKeepTargetPlant);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper()
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setM_WarehouseSource_ID (final int M_WarehouseSource_ID)
{
if (M_WarehouseSource_ID < 1)
set_Value (COLUMNNAME_M_WarehouseSource_ID, null);
else
set_Value (COLUMNNAME_M_WarehouseSource_ID, M_WarehouseSource_ID);
}
@Override
public int getM_WarehouseSource_ID()
{
return get_ValueAsInt(COLUMNNAME_M_WarehouseSource_ID);
}
@Override
public void setPercent (final BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public BigDecimal getPercent()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percent);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriorityNo (final int PriorityNo)
{ | set_Value (COLUMNNAME_PriorityNo, PriorityNo);
}
@Override
public int getPriorityNo()
{
return get_ValueAsInt(COLUMNNAME_PriorityNo);
}
@Override
public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistributionLine.java | 1 |
请完成以下Java代码 | public static void revalidateSession(HttpServletRequest request, UserAuthentication authentication) {
HttpSession session = request.getSession();
Authentications authentications = getAuthsFromSession(session);
// invalidate old & create new session
session.invalidate();
session = request.getSession(true);
if (authentication != null) {
authentications.addOrReplace(authentication);
session.setAttribute(CAM_AUTH_SESSION_KEY, authentications);
}
}
/**
* Store authentications in current session.
*/
public static void updateSession(HttpSession session, Authentications authentications) {
if (session != null) {
session.setAttribute(CAM_AUTH_SESSION_KEY, authentications);
}
}
/**
* <p>Update/remove authentications when cache validation time (= x + TTL) is due.
*
* <p>The following information is updated:<ul>
* <li>{@code groupIds}
* <li>{@code tenantIds}
* <li>{@code authorizedApps}
*
* <p>An authorization is only removed if the user doesn't exist anymore (user was deleted).
*/
public static void updateCache(Authentications authentications,
HttpSession session,
long cacheTimeToLive) {
synchronized (getSessionMutex(session)) {
for (UserAuthentication authentication : authentications.getAuthentications()) {
Date cacheValidationTime = authentication.getCacheValidationTime();
if (cacheValidationTime == null ||
ClockUtil.getCurrentTime().after(cacheValidationTime)) {
String userId = authentication.getIdentityId();
String engineName = authentication.getProcessEngineName(); | UserAuthentication updatedAuth = createAuthentication(engineName, userId);
if (updatedAuth != null) {
if (cacheTimeToLive > 0) {
Date newCacheValidationTime = new Date(ClockUtil.getCurrentTime().getTime() + cacheTimeToLive);
updatedAuth.setCacheValidationTime(newCacheValidationTime);
LOGGER.traceCacheValidationTimeUpdated(cacheValidationTime, newCacheValidationTime);
}
LOGGER.traceAuthenticationUpdated(engineName);
authentications.addOrReplace(updatedAuth);
} else {
authentications.removeByEngineName(engineName);
LOGGER.traceAuthenticationRemoved(engineName);
}
}
}
}
}
/**
* <p>Returns the session mutex to synchronize on.
* <p>Avoids updating the auth cache by multiple HTTP requests in parallel.
*/
protected static Object getSessionMutex(HttpSession session) {
Object mutex = session.getAttribute(AUTH_TIME_SESSION_MUTEX);
if (mutex == null) {
mutex = session; // synchronize on session if session mutex doesn't exist
}
return mutex;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\AuthenticationUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ByteArrayType implements VariableType {
public static final String TYPE_NAME = "bytes";
private static final long serialVersionUID = 1L;
protected final VariableLengthVerifier lengthVerifier;
public ByteArrayType() {
this(NoopVariableLengthVerifier.INSTANCE);
}
public ByteArrayType(VariableLengthVerifier lengthVerifier) {
this.lengthVerifier = lengthVerifier != null ? lengthVerifier : NoopVariableLengthVerifier.INSTANCE;
}
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override | public Object getValue(ValueFields valueFields) {
return valueFields.getBytes();
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setBytes(null);
return;
}
byte[] bytes = (byte[]) value;
lengthVerifier.verifyLength(bytes.length, valueFields, this);
valueFields.setBytes((byte[]) value);
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return byte[].class.isAssignableFrom(value.getClass());
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\ByteArrayType.java | 2 |
请完成以下Java代码 | public String getPeriodAction ()
{
return (String)get_Value(COLUMNNAME_PeriodAction);
}
/** Set Period No.
@param PeriodNo
Unique Period Number
*/
public void setPeriodNo (int PeriodNo)
{
set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo));
}
/** Get Period No.
@return Unique Period Number
*/
public int getPeriodNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Period Status.
@param PeriodStatus
Current state of this period
*/
public void setPeriodStatus (String PeriodStatus)
{
set_Value (COLUMNNAME_PeriodStatus, PeriodStatus);
}
/** Get Period Status.
@return Current state of this period
*/
public String getPeriodStatus ()
{
return (String)get_Value(COLUMNNAME_PeriodStatus);
}
/** 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 Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Period.java | 1 |
请完成以下Java代码 | public class HMMPOSTagger extends HMMTrainer implements POSTagger
{
POSTagSet tagSet;
public HMMPOSTagger(HiddenMarkovModel model)
{
super(model);
tagSet = new POSTagSet();
}
public HMMPOSTagger()
{
super();
tagSet = new POSTagSet();
}
@Override
protected List<String[]> convertToSequence(Sentence sentence)
{
List<Word> wordList = sentence.toSimpleWordList();
List<String[]> xyList = new ArrayList<String[]>(wordList.size());
for (Word word : wordList)
{
xyList.add(new String[]{word.getValue(), word.getLabel()});
}
return xyList;
}
@Override
protected TagSet getTagSet()
{
return tagSet;
}
@Override
public String[] tag(String... words)
{
int[] obsArray = new int[words.length]; | for (int i = 0; i < obsArray.length; i++)
{
obsArray[i] = vocabulary.idOf(words[i]);
}
int[] tagArray = new int[obsArray.length];
model.predict(obsArray, tagArray);
String[] tags = new String[obsArray.length];
for (int i = 0; i < tagArray.length; i++)
{
tags[i] = tagSet.stringOf(tagArray[i]);
}
return tags;
}
@Override
public String[] tag(List<String> wordList)
{
return tag(wordList.toArray(new String[0]));
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMPOSTagger.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.