instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){
@Override
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String)rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(MD5Util.encode((String)rawPassword));
}}); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
|
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
}
}
|
repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
protected void deleteFlatrateTermDataEntriesOnReactivate(final de.metas.contracts.model.I_C_Flatrate_Term term)
{
// nothing
}
/**
* Create new {@link de.metas.contracts.model.I_C_Flatrate_DataEntry}s using {@link PMMContractBuilder#newBuilder(I_C_Flatrate_Term)}.
* The new dataEntries use data from the dataEntries of the given <code>oldTerm</code>.
*
* @task https://github.com/metasfresh/metasfresh/issues/549
*/
@Override
public void afterSaveOfNextTermForPredecessor(final de.metas.contracts.model.I_C_Flatrate_Term next, final de.metas.contracts.model.I_C_Flatrate_Term predecessor)
{
final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class);
final I_C_Flatrate_Term oldTermtoUse = InterfaceWrapperHelper.create(predecessor, I_C_Flatrate_Term.class);
final I_C_Flatrate_Term newTermtoUse = InterfaceWrapperHelper.create(next, I_C_Flatrate_Term.class);
newTermtoUse.setPMM_Product(oldTermtoUse.getPMM_Product());
InterfaceWrapperHelper.save(newTermtoUse);
final List<I_C_Flatrate_DataEntry> oldDataEntries = flatrateDAO.retrieveDataEntries(predecessor, null, null);
final PMMContractBuilder builder = newPMMContractBuilder(newTermtoUse)
.setComplete(false);
oldDataEntries
.forEach(e -> {
Check.errorUnless(e.getC_Period() != null, "{} has a missing C_Period", e);
final Timestamp dateOldEntry = e.getC_Period().getStartDate();
final Timestamp dateNewEntry;
if (dateOldEntry.before(newTermtoUse.getStartDate()))
{
dateNewEntry = TimeUtil.addYears(dateOldEntry, 1);
}
else
{
dateNewEntry = dateOldEntry;
}
if (InterfaceWrapperHelper.isNull(e, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM))
|
{
// if the current entry has a null value, then also the new entry shall have a null value
builder.setFlatrateAmtPerUOM(dateNewEntry, null);
}
else
{
builder.setFlatrateAmtPerUOM(dateNewEntry, e.getFlatrateAmtPerUOM());
}
builder.addQtyPlanned(dateNewEntry, e.getQty_Planned());
});
builder.build();
}
@VisibleForTesting
PMMContractBuilder newPMMContractBuilder(final I_C_Flatrate_Term term)
{
return PMMContractBuilder.newBuilder(term);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\contracts\ProcurementFlatrateHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<CalculatedField> removeAllByEntityId(TenantId tenantId, EntityId entityId) {
return DaoUtil.convertDataList(calculatedFieldRepository.removeAllByTenantIdAndEntityId(tenantId.getId(), entityId.getId()));
}
@Override
public long countByEntityIdAndTypeNot(TenantId tenantId, EntityId entityId, CalculatedFieldType type) {
return calculatedFieldRepository.countByTenantIdAndEntityIdAndTypeNot(tenantId.getId(), entityId.getId(), type.name());
}
@Override
public PageData<CalculatedField> findByTenantIdAndFilter(TenantId tenantId, CalculatedFieldFilter filter, PageLink pageLink) {
return DaoUtil.toPageData(calculatedFieldRepository.findByTenantIdAndFilter(tenantId.getId(),
filter.getTypes().stream().map(Enum::name).toList(),
filter.getEntityTypes().stream().map(Enum::name).toList(),
CollectionUtils.isNotEmpty(filter.getEntityIds()) ? filter.getEntityIds() : null,
CollectionUtils.isNotEmpty(filter.getNames()) ? filter.getNames() : null,
pageLink.getTextSearch(), DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<String> findNamesByTenantIdAndType(TenantId tenantId, CalculatedFieldType type, PageLink pageLink) {
return DaoUtil.pageToPageData(calculatedFieldRepository.findNamesByTenantIdAndType(tenantId.getId(), type.name(),
Strings.emptyToNull(pageLink.getTextSearch()), DaoUtil.toPageable(pageLink, false)));
}
|
@Override
protected Class<CalculatedFieldEntity> getEntityClass() {
return CalculatedFieldEntity.class;
}
@Override
protected JpaRepository<CalculatedFieldEntity, UUID> getRepository() {
return calculatedFieldRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.CALCULATED_FIELD;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\cf\JpaCalculatedFieldDao.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ScannableCodeFormat
{
@NonNull ScannableCodeFormatId id;
@NonNull String name;
@Nullable String description;
@NonNull ImmutableList<ScannableCodeFormatPart> parts;
@Builder
private ScannableCodeFormat(
@NonNull final ScannableCodeFormatId id,
@NonNull final String name,
@Nullable final String description,
@NonNull final ImmutableList<ScannableCodeFormatPart> parts)
{
this.id = id;
this.name = name;
this.description = description;
this.parts = parts;
}
public ExplainedOptional<ParsedScannedCode> parse(@NonNull final ScannedCode scannedCode)
{
if (parts.isEmpty())
{
return ExplainedOptional.emptyBecause("No parts configured");
}
|
try
{
final ParsedScannedCodeBuilder result = ParsedScannedCode.builder()
.scannedCode(scannedCode);
for (final ScannableCodeFormatPart part : parts)
{
final BooleanWithReason ok = part.parseAndUpdateResult(scannedCode, result);
if (ok.isFalse())
{
return ExplainedOptional.emptyBecause(ok.getReason());
}
}
return ExplainedOptional.of(result.build());
}
catch (final Exception ex)
{
return ExplainedOptional.emptyBecause(ex.getLocalizedMessage());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormat.java
| 2
|
请完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final ArchiveGetDataResponse other = (ArchiveGetDataResponse)obj;
if (adArchiveId != other.adArchiveId)
{
return false;
}
if (!Arrays.equals(data, other.data))
{
return false;
}
|
return true;
}
public int getAdArchiveId()
{
return adArchiveId;
}
public void setAdArchiveId(final int adArchiveId)
{
this.adArchiveId = adArchiveId;
}
public byte[] getData()
{
return data;
}
public void setData(final byte[] data)
{
this.data = data;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive.api\src\main\java\de\metas\document\archive\esb\api\ArchiveGetDataResponse.java
| 1
|
请完成以下Java代码
|
public class InfoQueryCriteriaBPSonsor extends InfoQueryCriteriaBPSonsorAbstract
{
private CTextField fieldSponsorNo;
private SponsorNoAutoCompleter fieldSponsorNoAutocompleter;
@Override
public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText)
{
fieldSponsorNo = new CTextField();
fieldSponsorNo.setPreferredSize(new Dimension(200, (int)fieldSponsorNo.getPreferredSize().getHeight()));
fieldSponsorNoAutocompleter = new SponsorNoAutoCompleter(fieldSponsorNo);
fieldSponsorNoAutocompleter.setUserObject(null);
}
@Override
public Object getParameterComponent(int index)
|
{
if (index == 0)
return fieldSponsorNo;
else
return null;
}
protected SponsorNoObject getSponsorNoObject()
{
return (SponsorNoObject)fieldSponsorNoAutocompleter.getUserOject();
}
@Override
public String getText()
{
return fieldSponsorNo.getText();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaBPSonsor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Config {
// Trust the last (right-most) value in the "X-Forwarded-For" header by default,
// which represents the last reverse proxy that was used when calling the gateway.
private int maxTrustedIndex = 1;
private List<String> sources = new ArrayList<>();
public int getMaxTrustedIndex() {
return this.maxTrustedIndex;
}
public Config setMaxTrustedIndex(int maxTrustedIndex) {
this.maxTrustedIndex = maxTrustedIndex;
return this;
}
public List<String> getSources() {
|
return this.sources;
}
public Config setSources(List<String> sources) {
this.sources = sources;
return this;
}
public Config setSources(String... sources) {
this.sources = Arrays.asList(sources);
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\XForwardedRemoteAddrRoutePredicateFactory.java
| 2
|
请完成以下Java代码
|
public final class PaymentAllocationTotals
{
public static final Builder builder()
{
return new Builder();
}
private final BigDecimal invoicedAmt;
//
private final BigDecimal paymentTotalAmt;
private final BigDecimal paymentExistingAmt;
private final BigDecimal paymentCandidatesAmt;
//
private final BigDecimal diffInvoiceMinusPay;
private PaymentAllocationTotals(final Builder builder)
{
super();
this.invoicedAmt = builder.invoicedAmt;
this.paymentExistingAmt = builder.paymentExistingAmt;
this.paymentCandidatesAmt = builder.paymentCandidatesAmt;
this.paymentTotalAmt = paymentExistingAmt.add(paymentCandidatesAmt);
this.diffInvoiceMinusPay = invoicedAmt.subtract(paymentTotalAmt);
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
public BigDecimal getInvoicedAmt()
{
return invoicedAmt;
}
public BigDecimal getPaymentExistingAmt()
{
return paymentExistingAmt;
}
public BigDecimal getPaymentCandidatesAmt()
{
return paymentCandidatesAmt;
}
public BigDecimal getDiffInvoiceMinusPay()
{
return diffInvoiceMinusPay;
}
public boolean hasDifferences()
{
return diffInvoiceMinusPay.signum() != 0;
}
public boolean isMoreInvoicedThanPaid()
{
final int invoicedAmtSign = invoicedAmt.signum();
final int paymentAmtSign = paymentTotalAmt.signum();
if (invoicedAmtSign >= 0)
{
// Positive invoiced, positive paid
if (paymentAmtSign >= 0)
{
return invoicedAmt.compareTo(paymentTotalAmt) > 0;
}
|
// Positive invoiced, negative paid
else
{
return true; // more invoiced than paid
}
}
else
{
// Negative invoiced, positive paid
if (paymentAmtSign >= 0)
{
return false; // more paid than invoiced
}
// Negative invoiced, negative paid
else
{
return invoicedAmt.abs().compareTo(paymentTotalAmt.abs()) > 0;
}
}
}
//
//
// ------------------------------------------------------------------------------------------------------------------------------
//
//
public static final class Builder
{
private BigDecimal invoicedAmt = BigDecimal.ZERO;
private BigDecimal paymentExistingAmt = BigDecimal.ZERO;
private BigDecimal paymentCandidatesAmt = BigDecimal.ZERO;
private Builder()
{
super();
}
public PaymentAllocationTotals build()
{
return new PaymentAllocationTotals(this);
}
public Builder setInvoicedAmt(final BigDecimal invoicedAmt)
{
this.invoicedAmt = invoicedAmt;
return this;
}
public Builder setPaymentExistingAmt(final BigDecimal paymentExistingAmt)
{
this.paymentExistingAmt = paymentExistingAmt;
return this;
}
public Builder setPaymentCandidatesAmt(final BigDecimal paymentCandidatesAmt)
{
this.paymentCandidatesAmt = paymentCandidatesAmt;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationTotals.java
| 1
|
请完成以下Java代码
|
public class FreeMarkerCompiledScript extends CompiledScript {
protected final ScriptEngine scriptEngine;
protected final Template template;
public FreeMarkerCompiledScript(ScriptEngine scriptEngine, String script, Configuration configuration) throws ScriptException {
this(scriptEngine, "unknown", script, configuration);
}
public FreeMarkerCompiledScript(ScriptEngine scriptEngine, Reader script, Configuration configuration) throws ScriptException {
this(scriptEngine, "unknown", script, configuration);
}
public FreeMarkerCompiledScript(ScriptEngine scriptEngine, String filename, String script, Configuration configuration) throws ScriptException {
this(scriptEngine, filename, new StringReader(script), configuration);
}
public FreeMarkerCompiledScript(ScriptEngine scriptEngine, String filename, Reader script, Configuration configuration) throws ScriptException {
this.scriptEngine = scriptEngine;
try {
template = new Template(filename, script, configuration);
} catch (IOException e) {
throw new ScriptException(e);
}
}
public Object eval(ScriptContext context) throws ScriptException {
|
Writer writer = new StringWriter();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
try {
template.process(bindings, writer);
writer.flush();
} catch (Exception e) {
throw new ScriptException(e);
}
return writer.toString();
}
public ScriptEngine getEngine() {
return scriptEngine;
}
}
|
repos\camunda-bpm-platform-master\freemarker-template-engine\src\main\java\org\camunda\templateengines\FreeMarkerCompiledScript.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private int calculateFinalScore(@Nullable Integer scoreRelativeToPar) {
int finalScore = scoreRelativeToPar != null ? scoreRelativeToPar : 0;
int parForCourse = getGolfTournament()
.map(GolfTournament::getGolfCourse)
.map(GolfCourse::getParForCourse)
.orElse(GolfCourse.STANDARD_PAR_FOR_COURSE);
return parForCourse + finalScore;
}
private int calculateRunningScore(@Nullable Integer currentScore) {
int runningScore = currentScore != null ? currentScore : 0;
int scoreDelta = this.random.nextInt(SCORE_DELTA_BOUND);
|
scoreDelta *= this.random.nextBoolean() ? -1 : 1;
return runningScore + scoreDelta;
}
private void finish(@NonNull GolfTournament golfTournament) {
for (GolfTournament.Pairing pairing : golfTournament) {
if (pairing.signScorecard()) {
updateScore(this::calculateFinalScore, pairing.getPlayerOne());
updateScore(this::calculateFinalScore, pairing.getPlayerTwo());
}
}
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\PgaTourService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class OrgChangeHistoryId implements RepoIdAware
{
@JsonCreator
public static OrgChangeHistoryId ofRepoId(final int repoId)
{
return new OrgChangeHistoryId(repoId);
}
@Nullable
public static OrgChangeHistoryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new OrgChangeHistoryId(repoId) : null;
}
public static int toRepoId(final OrgChangeHistoryId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private OrgChangeHistoryId(final int repoId)
|
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_OrgChange_History_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final OrgChangeHistoryId o1, @Nullable final OrgChangeHistoryId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\service\OrgChangeHistoryId.java
| 2
|
请完成以下Java代码
|
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
|
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
private static final long serialVersionUID = 2738859149330833739L;
}
|
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\data\User.java
| 1
|
请完成以下Java代码
|
public class LwM2MClientFwOtaInfo extends LwM2MClientOtaInfo<LwM2MFirmwareUpdateStrategy, FirmwareUpdateState, FirmwareUpdateResult> {
private Integer deliveryMethod;
public LwM2MClientFwOtaInfo(String endpoint, String baseUrl, LwM2MFirmwareUpdateStrategy strategy) {
super(endpoint, baseUrl, strategy);
}
@JsonIgnore
@Override
public OtaPackageType getType() {
return OtaPackageType.FIRMWARE;
}
public void update(FirmwareUpdateResult result) {
this.result = result;
|
if (result.getCode() > UPDATE_SUCCESSFULLY.getCode()) {
failedPackageId = getPackageId(targetName, targetVersion);
}
switch (result) {
case INITIAL:
break;
case UPDATE_SUCCESSFULLY:
retryAttempts = 0;
break;
default:
break;
}
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\ota\firmware\LwM2MClientFwOtaInfo.java
| 1
|
请完成以下Java代码
|
public boolean isMandatory()
{
return false;
}
@Override
public boolean isNew()
{
return isGeneratedAttribute;
}
@Override
protected void setInternalValueDate(Date value)
{
this.valueDate = value;
}
@Override
protected Date getInternalValueDate()
{
return valueDate;
}
|
@Override
protected void setInternalValueDateInitial(Date value)
{
this.valueInitialDate = value;
}
@Override
protected Date getInternalValueDateInitial()
{
return valueInitialDate;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\PlainAttributeValue.java
| 1
|
请完成以下Java代码
|
public ChartOfAccounts getById(@NonNull final ChartOfAccountsId chartOfAccountsId)
{
return chartOfAccountsRepository.getById(chartOfAccountsId);
}
public List<ChartOfAccounts> getByIds(@NonNull final Set<ChartOfAccountsId> chartOfAccountsIds)
{
return chartOfAccountsRepository.getByIds(chartOfAccountsIds);
}
public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return chartOfAccountsRepository.getByName(chartOfAccountsName, clientId, orgId);
}
public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId)
{
return chartOfAccountsRepository.getByTreeId(treeId);
}
public ChartOfAccounts createChartOfAccounts(@NonNull final ChartOfAccountsCreateRequest request)
|
{
final AdTreeId chartOfAccountsTreeId = createChartOfAccountsTree(request.getName(), request.getOrgId());
return chartOfAccountsRepository.createChartOfAccounts(request.getName(), request.getClientId(), request.getOrgId(), chartOfAccountsTreeId);
}
private AdTreeId createChartOfAccountsTree(@NonNull final String name, @NonNull final OrgId orgId)
{
final I_AD_Tree tree = InterfaceWrapperHelper.newInstance(I_AD_Tree.class);
tree.setAD_Table_ID(adTreeDAO.retrieveTableId(I_C_ElementValue.Table_Name));
tree.setName(name);
tree.setTreeType(X_AD_Tree.TREETYPE_ElementValue);
tree.setIsAllNodes(true);
tree.setAD_Org_ID(orgId.getRepoId());
InterfaceWrapperHelper.save(tree);
return AdTreeId.ofRepoId(tree.getAD_Tree_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class KPIDataSetValuesMap
{
public static KPIDataSetValuesMapBuilder builder(@NonNull final KPIDataSetValuesAggregationKey key)
{
return new KPIDataSetValuesMapBuilder().key(key);
}
KPIDataSetValuesAggregationKey key;
ImmutableMap<String, KPIDataValue> values;
private KPIDataSetValuesMap(final KPIDataSetValuesMapBuilder builder)
{
this.key = builder.key;
this.values = ImmutableMap.copyOf(builder.values);
}
public static class KPIDataSetValuesMapBuilder
{
private KPIDataSetValuesAggregationKey key;
private final HashMap<String, KPIDataValue> values = new HashMap<>();
public KPIDataSetValuesMap build()
{
return new KPIDataSetValuesMap(this);
}
private KPIDataSetValuesMapBuilder key(@NonNull final KPIDataSetValuesAggregationKey key)
|
{
this.key = key;
return this;
}
public KPIDataSetValuesMapBuilder put(@NonNull final String name, @NonNull final KPIDataValue value)
{
values.put(name, value);
return this;
}
public void putIfAbsent(@NonNull final String name, @NonNull final KPIDataValue value)
{
values.putIfAbsent(name, value);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataSetValuesMap.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public DeviceConfig.Builder setAssignedWarehouseIds(final Set<WarehouseId> assignedWareouseIds)
{
this.assignedWareouseIds = assignedWareouseIds;
return this;
}
private ImmutableSet<WarehouseId> getAssignedWarehouseIds()
{
return assignedWareouseIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedWareouseIds);
}
@NonNull
private ImmutableSet<LocatorId> getAssignedLocatorIds()
{
return assignedLocatorIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedLocatorIds);
}
@NonNull
public DeviceConfig.Builder setAssignedLocatorIds(final Set<LocatorId> assignedLocatorIds)
{
this.assignedLocatorIds = assignedLocatorIds;
return this;
}
@NonNull
public DeviceConfig.Builder setBeforeHooksClassname(@NonNull final ImmutableList<String> beforeHooksClassname)
{
this.beforeHooksClassname = beforeHooksClassname;
return this;
}
@NonNull
private ImmutableList<String> getBeforeHooksClassname()
{
return Optional.ofNullable(beforeHooksClassname).orElseGet(ImmutableList::of);
}
|
@NonNull
public DeviceConfig.Builder setDeviceConfigParams(@NonNull final ImmutableMap<String, String> deviceConfigParams)
{
this.deviceConfigParams = deviceConfigParams;
return this;
}
@NonNull
private ImmutableMap<String, String> getDeviceConfigParams()
{
return deviceConfigParams == null ? ImmutableMap.of() : deviceConfigParams;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfig.java
| 2
|
请完成以下Java代码
|
public OrgId effectiveValueOrNull(@NonNull final OrgId orgId)
{
return effectiveValueOr(orgId, null);
}
private OrgId effectiveValueOr(@NonNull final OrgId orgId, final OrgId nullValue)
{
if (this == Client)
{
return nullValue;
}
else if (this == Organization)
{
if (orgId.isAny())
{
throw new AdempiereException("Regular organization expected when costing level is Organization");
}
return orgId;
}
else if (this == BatchLot)
{
return nullValue;
}
else
{
throw new AdempiereException("Unknown costingLevel: " + this);
}
}
public AttributeSetInstanceId effectiveValue(@NonNull final AttributeSetInstanceId asiId)
{
return effectiveValueOr(asiId, AttributeSetInstanceId.NONE);
}
public AttributeSetInstanceId effectiveValueOrNull(@NonNull final AttributeSetInstanceId asiId)
{
return effectiveValueOr(asiId, null);
}
private AttributeSetInstanceId effectiveValueOr(@NonNull final AttributeSetInstanceId asiId, final AttributeSetInstanceId nullValue)
{
if (this == Client)
|
{
return nullValue;
}
else if (this == Organization)
{
return nullValue;
}
else if (this == BatchLot)
{
if (asiId.isNone())
{
throw new AdempiereException("Regular ASI expected when costing level is Batch/Lot");
}
return asiId;
}
else
{
throw new AdempiereException("Unknown costingLevel: " + this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\costing\CostingLevel.java
| 1
|
请完成以下Java代码
|
public static PickingUnit ofJson(@NonNull final String json)
{
if (Objects.equals(TU.json, json))
{
return TU;
}
else if (Objects.equals(CU.json, json))
{
return CU;
}
else
{
throw new AdempiereException("Cannot convert json `" + json + "` to " + PickingUnit.class.getSimpleName());
}
}
|
@JsonValue
public String toJson() {return json;}
public boolean isTU() {return TU.equals(this);}
public boolean isCU() {return CU.equals(this);}
public void assertIsCU()
{
if (!isCU())
{
throw new AdempiereException("Expected Picking Unit to be CU");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingUnit.java
| 1
|
请完成以下Java代码
|
public ShipperGatewayClient newClientForShipperId(@NonNull final ShipperId shipperId)
{
final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository.retrieveConfigForShipperId(shipperId.getRepoId());
return createClient(shipperConfig);
}
@VisibleForTesting
DerKurierClient createClient(@NonNull final DerKurierShipperConfig shipperConfig)
{
final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri(shipperConfig.getRestApiBaseUrl());
final RestTemplate restTemplate = restTemplateBuilder.build();
extractAndConfigureObjectMapperOfRestTemplate(restTemplate);
return new DerKurierClient(
restTemplate,
converters,
derKurierDeliveryOrderService,
derKurierDeliveryOrderRepository);
}
/**
* Put JavaTimeModule into the rest template's jackson object mapper.
* <b>
* Note 1: there have to be better ways to achieve this, but i don't know them.
|
* thx to https://stackoverflow.com/a/47176770/1012103
* <b>
* Note 2: visible because this is the object mapper we run with; we want our unit tests to use it as well.
*/
@VisibleForTesting
public static ObjectMapper extractAndConfigureObjectMapperOfRestTemplate(@NonNull final RestTemplate restTemplate)
{
final MappingJackson2HttpMessageConverter messageConverter = restTemplate
.getMessageConverters()
.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow(() -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
final ObjectMapper objectMapper = messageConverter.getObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierClientFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebConfig implements WebMvcConfigurer {
private final Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Autowired
private LoginAuthenticationFilter loginAuthenticationFilter;
@Autowired
private AuthorizationInterceptor authorizationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.htm");
}
/**
* Add {@link CommonFilter} to the server, this is the simplest way to use Sentinel
* for Web application.
*/
@Bean
public FilterRegistrationBean sentinelFilterRegistration() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setFilter(new CommonFilter());
registration.addUrlPatterns("/*");
registration.setName("sentinelFilter");
registration.setOrder(1);
// If this is enabled, the entrance of all Web URL resources will be unified as a single context name.
// In most scenarios that's enough, and it could reduce the memory footprint.
registration.addInitParameter(CommonFilter.WEB_CONTEXT_UNIFY, "true");
logger.info("Sentinel servlet CommonFilter registered");
return registration;
}
|
@PostConstruct
public void doInit() {
Set<String> suffixSet = new HashSet<>(Arrays.asList(".js", ".css", ".html", ".ico", ".txt",
".woff", ".woff2"));
// Example: register a UrlCleaner to exclude URLs of common static resources.
WebCallbackManager.setUrlCleaner(url -> {
if (StringUtil.isEmpty(url)) {
return url;
}
if (suffixSet.stream().anyMatch(url::endsWith)) {
return null;
}
return url;
});
}
@Bean
public FilterRegistrationBean authenticationFilterRegistration() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setFilter(loginAuthenticationFilter);
registration.addUrlPatterns("/*");
registration.setName("authenticationFilter");
registration.setOrder(0);
return registration;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\config\WebConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
@Nullable OrderSchedulingContext extractContext(final @NotNull org.compiere.model.I_C_Order orderRecord)
{
final Money grandTotal = orderBL.getGrandTotal(orderRecord);
if (grandTotal.isZero())
{
return null;
}
final PaymentTermId paymentTermId = orderBL.getPaymentTermId(orderRecord);
final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId);
if (!paymentTerm.isComplex())
{
return null;
}
return OrderSchedulingContext.builder()
.orderId(OrderId.ofRepoId(orderRecord.getC_Order_ID()))
|
.orderDate(TimeUtil.asLocalDate(orderRecord.getDateOrdered()))
.letterOfCreditDate(TimeUtil.asLocalDate(orderRecord.getLC_Date()))
.billOfLadingDate(TimeUtil.asLocalDate(orderRecord.getBLDate()))
.ETADate(TimeUtil.asLocalDate(orderRecord.getETA()))
.invoiceDate(TimeUtil.asLocalDate(orderRecord.getInvoiceDate()))
.grandTotal(grandTotal)
.precision(orderBL.getAmountPrecision(orderRecord))
.paymentTerm(paymentTerm)
.build();
}
public void create(@NonNull final OrderPayScheduleCreateRequest request)
{
orderPayScheduleRepository.create(request);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleService.java
| 2
|
请完成以下Java代码
|
public class EscalationEventDefinitionImpl extends EventDefinitionImpl implements EscalationEventDefinition {
protected static AttributeReference<Escalation> escalationRefAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(EscalationEventDefinition.class, BPMN_ELEMENT_ESCALATION_EVENT_DEFINITION)
.namespaceUri(BPMN20_NS)
.extendsType(EventDefinition.class)
.instanceProvider(new ModelTypeInstanceProvider<EscalationEventDefinition>() {
public EscalationEventDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new EscalationEventDefinitionImpl(instanceContext);
}
});
escalationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ESCALATION_REF)
.qNameAttributeReference(Escalation.class)
.build();
|
typeBuilder.build();
}
public EscalationEventDefinitionImpl(ModelTypeInstanceContext context) {
super(context);
}
public Escalation getEscalation() {
return escalationRefAttribute.getReferenceTargetElement(this);
}
public void setEscalation(Escalation escalation) {
escalationRefAttribute.setReferenceTargetElement(this, escalation);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\EscalationEventDefinitionImpl.java
| 1
|
请完成以下Java代码
|
public void setNamespacePrefix(String namespacePrefix) {
this.namespacePrefix = namespacePrefix;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public Map<String, List<ExtensionElement>> getChildElements() {
return childElements;
}
public void addChildElement(ExtensionElement childElement) {
if (childElement != null && StringUtils.isNotEmpty(childElement.getName())) {
List<ExtensionElement> elementList = null;
if (!this.childElements.containsKey(childElement.getName())) {
elementList = new ArrayList<ExtensionElement>();
this.childElements.put(childElement.getName(), elementList);
}
this.childElements.get(childElement.getName()).add(childElement);
}
}
public void setChildElements(Map<String, List<ExtensionElement>> childElements) {
this.childElements = childElements;
}
public ExtensionElement clone() {
ExtensionElement clone = new ExtensionElement();
clone.setValues(this);
return clone;
}
public void setValues(ExtensionElement otherElement) {
setName(otherElement.getName());
|
setNamespacePrefix(otherElement.getNamespacePrefix());
setNamespace(otherElement.getNamespace());
setElementText(otherElement.getElementText());
setAttributes(otherElement.getAttributes());
childElements = new LinkedHashMap<String, List<ExtensionElement>>();
if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) {
for (String key : otherElement.getChildElements().keySet()) {
List<ExtensionElement> otherElementList = otherElement.getChildElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<ExtensionElement> elementList = new ArrayList<ExtensionElement>();
for (ExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
childElements.put(key, elementList);
}
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ExtensionElement.java
| 1
|
请完成以下Java代码
|
protected void addAuthorizationsFromIterator(CommandContext commandContext, List<String> expressions,
ProcessDefinitionEntity processDefinition, ExpressionType expressionType) {
if (expressions != null) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
IdentityLinkService identityLinkService = processEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService();
ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
Iterator<String> iterator = expressions.iterator();
while (iterator.hasNext()) {
@SuppressWarnings("cast")
String expressionStr = iterator.next();
Expression expression = expressionManager.createExpression(expressionStr);
Object value = expression.getValue(NoExecutionVariableScope.getSharedInstance());
if (value != null) {
Collection<String> candidates = CandidateUtil.extractCandidates(value);
for (String candidate : candidates) {
IdentityLinkEntity identityLink = identityLinkService.createIdentityLink();
identityLink.setProcessDefId(processDefinition.getId());
if (expressionType == ExpressionType.USER) {
identityLink.setUserId(candidate);
} else if (expressionType == ExpressionType.GROUP) {
identityLink.setGroupId(candidate);
}
identityLink.setType(IdentityLinkType.CANDIDATE);
identityLinkService.insertIdentityLink(identityLink);
}
}
}
}
}
|
public TimerManager getTimerManager() {
return timerManager;
}
public void setTimerManager(TimerManager timerManager) {
this.timerManager = timerManager;
}
public EventSubscriptionManager getEventSubscriptionManager() {
return eventSubscriptionManager;
}
public void setEventSubscriptionManager(EventSubscriptionManager eventSubscriptionManager) {
this.eventSubscriptionManager = eventSubscriptionManager;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\deployer\BpmnDeploymentHelper.java
| 1
|
请完成以下Java代码
|
public int getEXP_Processor_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Host.
@param Host Host */
public void setHost (String Host)
{
set_Value (COLUMNNAME_Host, Host);
}
/** Get Host.
@return Host */
public String getHost ()
{
return (String)get_Value(COLUMNNAME_Host);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
|
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Password Info.
@param PasswordInfo Password Info */
public void setPasswordInfo (String PasswordInfo)
{
set_Value (COLUMNNAME_PasswordInfo, PasswordInfo);
}
/** Get Password Info.
@return Password Info */
public String getPasswordInfo ()
{
return (String)get_Value(COLUMNNAME_PasswordInfo);
}
/** Set Port.
@param Port Port */
public void setPort (int Port)
{
set_Value (COLUMNNAME_Port, Integer.valueOf(Port));
}
/** Get Port.
@return Port */
public int getPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor.java
| 1
|
请完成以下Java代码
|
private Map<MaterialDescriptor, Collection<HUDescriptor>> createMaterialDescriptors(
@NonNull final TransactionDescriptor transaction,
@Nullable final BPartnerId customerId,
@Nullable final BPartnerId vendorId,
@NonNull final Collection<HUDescriptor> huDescriptors)
{
// aggregate HUDescriptors based on their product & attributes
final ImmutableListMultimap<ProductDescriptor, HUDescriptor> //
huDescriptorsByProduct = Multimaps.index(huDescriptors, HUDescriptor::getProductDescriptor);
final ImmutableMap.Builder<MaterialDescriptor, Collection<HUDescriptor>> result = ImmutableMap.builder();
for (final Map.Entry<ProductDescriptor, Collection<HUDescriptor>> entry : huDescriptorsByProduct.asMap().entrySet())
{
final ProductDescriptor productDescriptor = entry.getKey();
final Collection<HUDescriptor> huDescriptorsForCurrentProduct = entry.getValue();
final BigDecimal quantity = huDescriptorsForCurrentProduct
.stream()
.map(HUDescriptor::getQuantity)
.map(qty -> transaction.getMovementQty().signum() >= 0 ? qty : qty.negate()) // set signum according to transaction.movementQty
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
final MaterialDescriptor materialDescriptor = MaterialDescriptor.builder()
.warehouseId(transaction.getWarehouseId())
.locatorId(transaction.getLocatorId())
.date(transaction.getTransactionDate())
.productDescriptor(productDescriptor)
.customerId(customerId)
.vendorId(vendorId)
.quantity(quantity)
.build();
result.put(materialDescriptor, huDescriptorsForCurrentProduct);
}
return result.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\HUDescriptorsFromHUAssignmentService.java
| 1
|
请完成以下Java代码
|
public String getType() {
return Batch.TYPE_SET_EXTERNAL_TASK_RETRIES;
}
@Override
public void executeHandler(SetRetriesBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
commandContext.executeWithOperationLogPrevented(
new SetExternalTasksRetriesCmd(
new UpdateExternalTaskRetriesBuilderImpl(
batchConfiguration.getIds(),
batchConfiguration.getRetries())));
}
|
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected SetRetriesBatchConfiguration createJobConfiguration(SetRetriesBatchConfiguration configuration,
List<String> processIdsForJob) {
return new SetRetriesBatchConfiguration(processIdsForJob, configuration.getRetries());
}
@Override
protected SetExternalTaskRetriesBatchConfigurationJsonConverter getJsonConverterInstance() {
return SetExternalTaskRetriesBatchConfigurationJsonConverter.INSTANCE;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\externaltask\SetExternalTaskRetriesJobHandler.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return "@AD_Column_ID@="
+ (this == ANY ? "*" : AD_Table_ID + "/" + AD_Column_ID);
}
@Override
public int hashCode()
{
if (hashcode == 0)
{
hashcode = new HashcodeBuilder()
.append(31) // seed
.append(AD_Table_ID)
.append(AD_Column_ID)
.toHashcode();
}
return hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
|
return true;
}
final TableColumnResource other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(AD_Table_ID, other.AD_Table_ID)
.append(AD_Column_ID, other.AD_Column_ID)
.isEqual();
}
public int getAD_Table_ID()
{
return AD_Table_ID;
}
public int getAD_Column_ID()
{
return AD_Column_ID;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnResource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
SpanExporters spanExporters(ObjectProvider<SpanExporter> spanExporters) {
return SpanExporters.of(spanExporters.orderedStream().toList());
}
@Bean
@ConditionalOnMissingBean
Tracer otelTracer(OpenTelemetry openTelemetry) {
return openTelemetry.getTracer("org.springframework.boot", SpringBootVersion.getVersion());
}
@Bean
@ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class)
OtelTracer micrometerOtelTracer(Tracer tracer, EventPublisher eventPublisher,
OtelCurrentTraceContext otelCurrentTraceContext) {
List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
List<String> tagFields = this.tracingProperties.getBaggage().getTagFields();
return new OtelTracer(tracer, otelCurrentTraceContext, eventPublisher,
new OtelBaggageManager(otelCurrentTraceContext, remoteFields, tagFields));
}
@Bean
@ConditionalOnMissingBean
OtelPropagator otelPropagator(ContextPropagators contextPropagators, Tracer tracer) {
return new OtelPropagator(contextPropagators, tracer);
}
@Bean
@ConditionalOnMissingBean
EventPublisher otelTracerEventPublisher(List<EventListener> eventListeners) {
return new OTelEventPublisher(eventListeners);
}
@Bean
@ConditionalOnMissingBean
OtelCurrentTraceContext otelCurrentTraceContext() {
return new OtelCurrentTraceContext();
|
}
@Bean
@ConditionalOnMissingBean
Slf4JEventListener otelSlf4JEventListener() {
return new Slf4JEventListener();
}
@Bean
@ConditionalOnMissingBean(SpanCustomizer.class)
OtelSpanCustomizer otelSpanCustomizer() {
return new OtelSpanCustomizer();
}
static class OTelEventPublisher implements EventPublisher {
private final List<EventListener> listeners;
OTelEventPublisher(List<EventListener> listeners) {
this.listeners = listeners;
}
@Override
public void publishEvent(Object event) {
for (EventListener listener : this.listeners) {
listener.onEvent(event);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Map embed(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
EmbeddingResponse embeddingResponse = this.embeddingClient.embedForResponse(List.of(message));
return Map.of("embedding", embeddingResponse);
}
@Autowired
StreamingChatClient streamingChatClient;
@GetMapping("/ai/chat")
public String chat(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(message);
return chatClient.call(prompt).getResult().getOutput().getContent();
}
@GetMapping(value = "/ai/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(message);
Flux<ChatResponse> flux= streamingChatClient.stream(prompt);
SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
//订阅流式数据并使用SseEmitter发送
flux.subscribe(
data -> {
try {
|
emitter.send(data);
} catch (IOException e) {
emitter.completeWithError(e);
}
},
error -> {
emitter.completeWithError(error);
},
() -> {
emitter.complete();
}
);
return emitter;
}
}
|
repos\springboot-demo-master\ai\src\main\java\com\et\ai\controller\HelloWorldController.java
| 2
|
请完成以下Java代码
|
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
@PrePersist
public void onPrePersist() {
logger.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
logger.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
logger.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
public enum OPERATION {
|
INSERT, UPDATE, DELETE;
private String value;
OPERATION() {
value = toString();
}
public static OPERATION parse(final String value) {
OPERATION operation = null;
for (final OPERATION op : OPERATION.values()) {
if (op.getValue().equals(value)) {
operation = op;
break;
}
}
return operation;
}
public String getValue() {
return value;
}
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MessagesConsumer {
public static final String HEADER_X_RETRIES_COUNT = "x-retries-count";
private static final Logger log = LoggerFactory.getLogger(MessagesConsumer.class);
private final RabbitTemplate rabbitTemplate;
public MessagesConsumer(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
@RabbitListener(queues = SimpleDLQAmqpConfiguration.QUEUE_MESSAGES)
public void receiveMessage(Message message) throws BusinessException {
log.info("Received message: {}", message.toString());
throw new BusinessException();
}
@Bean
@ConditionalOnProperty(
value = "amqp.configuration.current",
havingValue = "simple-dlq")
public SimpleDLQAmqpContainer simpleAmqpContainer() {
return new SimpleDLQAmqpContainer(rabbitTemplate);
}
@Bean
@ConditionalOnProperty(
value = "amqp.configuration.current",
havingValue = "routing-dlq")
|
public RoutingDLQAmqpContainer routingDLQAmqpContainer() {
return new RoutingDLQAmqpContainer(rabbitTemplate);
}
@Bean
@ConditionalOnProperty(
value = "amqp.configuration.current",
havingValue = "dlx-custom")
public DLQCustomAmqpContainer dlqAmqpContainer() {
return new DLQCustomAmqpContainer(rabbitTemplate);
}
@Bean
@ConditionalOnProperty(
value = "amqp.configuration.current",
havingValue = "parking-lot-dlx")
public ParkingLotDLQAmqpContainer parkingLotDLQAmqpContainer() {
return new ParkingLotDLQAmqpContainer(rabbitTemplate);
}
}
|
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\consumer\MessagesConsumer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void fetchAuthorsAsStreamable() {
Streamable<Author> authors = authorRepository.findByGenre("Anthology");
authors.forEach(System.out::println);
}
public void fetchAuthorsDtoAsStreamable() {
Streamable<AuthorName> authors = authorRepository.findBy();
authors.forEach(a -> System.out.println(a.getName()));
}
public void fetchAuthorsByGenreAndAgeGreaterThan() {
Streamable<Author> authors = authorRepository.findByGenreAndAgeGreaterThan("Anthology", 40);
authors.forEach(System.out::println);
}
public void fetchAuthorsByGenreOrAgeGreaterThan() {
Streamable<Author> authors = authorRepository.findByGenreOrAgeGreaterThan("Anthology", 40);
authors.forEach(System.out::println);
}
// Caution: Don't do this! Fetch all columns just to drop a part of them
public void fetchAuthorsNames1() {
Streamable<String> authors = authorRepository.findByGenre("Anthology")
.map(Author::getName);
authors.forEach(System.out::println);
}
// Do this
public void fetchAuthorsNames2() {
Streamable<AuthorName> authors = authorRepository.queryByGenre("Anthology");
authors.forEach(a -> System.out.println(a.getName()));
}
// Caution: Don't do this! Fetch more rows than needed just to throw away a part of it
|
public void fetchAuthorsOlderThanAge1() {
Streamable<Author> authors = authorRepository.findByGenre("Anthology")
.filter(a -> a.getAge() > 40);
authors.forEach(System.out::println);
}
// Do this! Fetch more rows than needed just to throw away a part of it
public void fetchAuthorsOlderThanAge2() {
Streamable<Author> authors = authorRepository.findByGenreAndAgeGreaterThan("Anthology", 40);
authors.forEach(System.out::println);
}
// Caution: It triggers two SELECT statements and the
// final result is the concatenation of the these two results sets!
@Transactional(readOnly = true)
public void fetchAuthorsByGenreConcatAge() {
Streamable<Author> authors = authorRepository.findByGenre("Anthology")
.and(authorRepository.findByAgeGreaterThan(40));
authors.forEach(System.out::println);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootStreamable\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public void setC_OrderPaySchedule_ID (final int C_OrderPaySchedule_ID)
{
if (C_OrderPaySchedule_ID < 1)
set_Value (COLUMNNAME_C_OrderPaySchedule_ID, null);
else
set_Value (COLUMNNAME_C_OrderPaySchedule_ID, C_OrderPaySchedule_ID);
}
@Override
public int getC_OrderPaySchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderPaySchedule_ID);
}
@Override
public org.compiere.model.I_C_PaySchedule getC_PaySchedule()
{
return get_ValueAsPO(COLUMNNAME_C_PaySchedule_ID, org.compiere.model.I_C_PaySchedule.class);
}
@Override
public void setC_PaySchedule(final org.compiere.model.I_C_PaySchedule C_PaySchedule)
{
set_ValueFromPO(COLUMNNAME_C_PaySchedule_ID, org.compiere.model.I_C_PaySchedule.class, C_PaySchedule);
}
@Override
public void setC_PaySchedule_ID (final int C_PaySchedule_ID)
{
if (C_PaySchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, C_PaySchedule_ID);
}
@Override
public int getC_PaySchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaySchedule_ID);
}
@Override
public void setDiscountAmt (final @Nullable BigDecimal DiscountAmt)
{
set_Value (COLUMNNAME_DiscountAmt, DiscountAmt);
}
@Override
public BigDecimal getDiscountAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate)
{
set_Value (COLUMNNAME_DiscountDate, DiscountDate);
}
@Override
public java.sql.Timestamp getDiscountDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DiscountDate);
}
@Override
public void setDueAmt (final BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
@Override
public BigDecimal getDueAmt()
{
|
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java
| 1
|
请完成以下Java代码
|
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Requisition getM_Requisition() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Requisition_ID, org.compiere.model.I_M_Requisition.class);
}
@Override
public void setM_Requisition(org.compiere.model.I_M_Requisition M_Requisition)
{
set_ValueFromPO(COLUMNNAME_M_Requisition_ID, org.compiere.model.I_M_Requisition.class, M_Requisition);
}
/** Set Bedarf.
@param M_Requisition_ID
Material Requisition
*/
@Override
public void setM_Requisition_ID (int M_Requisition_ID)
{
if (M_Requisition_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Requisition_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Requisition_ID, Integer.valueOf(M_Requisition_ID));
}
/** Get Bedarf.
@return Material Requisition
*/
@Override
public int getM_Requisition_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Requisition_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bedarfs-Position.
@param M_RequisitionLine_ID
Material Requisition Line
*/
@Override
public void setM_RequisitionLine_ID (int M_RequisitionLine_ID)
{
if (M_RequisitionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_RequisitionLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID));
}
|
/** Get Bedarfs-Position.
@return Material Requisition Line
*/
@Override
public int getM_RequisitionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Einzelpreis.
@param PriceActual
Actual Price
*/
@Override
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Actual Price
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RequisitionLine.java
| 1
|
请完成以下Java代码
|
public Object get(Object key) {
for (Resolver scriptResolver : scriptResolvers) {
if (scriptResolver.containsKey(key)) {
return scriptResolver.get(key);
}
}
return defaultBindings.get(key);
}
@Override
public Object put(String name, Object value) {
if (storeScriptVariables) {
Object oldValue = null;
if (!UNSTORED_KEYS.contains(name)) {
oldValue = scopeContainer.getVariable(name);
scopeContainer.setVariable(name, value);
return oldValue;
}
}
return defaultBindings.put(name, value);
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
Set<Map.Entry<String, Object>> entries = new HashSet<>();
for (String key : inputVariableContainer.getVariableNames()) {
entries.add(Pair.of(key, inputVariableContainer.getVariable(key)));
}
return entries;
}
@Override
public Set<String> keySet() {
return inputVariableContainer.getVariableNames();
}
@Override
public int size() {
return inputVariableContainer.getVariableNames().size();
}
@Override
public Collection<Object> values() {
Set<String> variableNames = inputVariableContainer.getVariableNames();
List<Object> values = new ArrayList<>(variableNames.size());
for (String key : variableNames) {
values.add(inputVariableContainer.getVariable(key));
}
return values;
}
@Override
public void putAll(Map<? extends String, ? extends Object> toMerge) {
throw new UnsupportedOperationException();
|
}
@Override
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return defaultBindings.remove(key);
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public void addUnstoredKey(String unstoredKey) {
UNSTORED_KEYS.add(unstoredKey);
}
protected Map<String, Object> getVariables() {
if (this.scopeContainer instanceof VariableScope) {
return ((VariableScope) this.scopeContainer).getVariables();
}
return Collections.emptyMap();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
| 1
|
请完成以下Java代码
|
protected void executeWithErrorPropagation(ActivityExecution execution, Callable<Void> toExecute) throws Exception {
String activityInstanceId = execution.getActivityInstanceId();
try {
toExecute.call();
} catch (Exception ex) {
if (activityInstanceId.equals(execution.getActivityInstanceId())) {
try {
BpmnExceptionHandler.propagateException(execution, ex);
}
catch (ErrorPropagationException e) {
// exception has been logged by thrower
// re-throw the original exception so that it is logged
// and set as cause of the failure
throw ex;
}
}
else {
throw ex;
}
}
}
@Override
public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
if(SIGNAL_COMPENSATION_DONE.equals(signalName)) {
signalCompensationDone(execution);
} else {
|
super.signal(execution, signalName, signalData);
}
}
protected void signalCompensationDone(ActivityExecution execution) {
// default behavior is to join compensating executions and propagate the signal if all executions have compensated
// only wait for non-event-scope executions cause a compensation event subprocess consume the compensation event and
// do not have to compensate embedded subprocesses (which are still non-event-scope executions)
if(((PvmExecutionImpl) execution).getNonEventScopeExecutions().isEmpty()) {
if(execution.getParent() != null) {
ActivityExecution parent = execution.getParent();
execution.remove();
parent.signal(SIGNAL_COMPENSATION_DONE, null);
}
} else {
((ExecutionEntity)execution).forceUpdate();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\AbstractBpmnActivityBehavior.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return getSummaryMessage();
}
/**
* Keep in sync with {@link de.metas.ui.web.view.OrderCandidateViewHeaderPropertiesProvider#toViewHeaderProperties(de.metas.invoicecandidate.api.impl.InvoiceCandidatesAmtSelectionSummary)}
*/
public String getSummaryMessage()
{
final StringBuilder message = new StringBuilder();
message.append("@Netto@ (@ApprovalForInvoicing@): ");
final BigDecimal totalNetAmtApproved = getTotalNetAmtApproved();
message.append(getAmountFormatted(totalNetAmtApproved));
final BigDecimal huNetAmtApproved = getHUNetAmtApproved();
message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtApproved));
final BigDecimal cuNetAmtApproved = getCUNetAmtApproved();
message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtApproved));
message.append(" | @Netto@ (@NotApprovedForInvoicing@): ");
final BigDecimal totalNetAmtNotApproved = getTotalNetAmtNotApproved();
message.append(getAmountFormatted(totalNetAmtNotApproved));
final BigDecimal huNetAmtNotApproved = getHUNetAmtNotApproved();
message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtNotApproved));
final BigDecimal cuNetAmtNotApproved = getCUNetAmtNotApproved();
message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtNotApproved));
if (countTotalToRecompute > 0)
{
message.append(", @IsToRecompute@: ");
message.append(countTotalToRecompute);
}
return message.toString();
}
private String getAmountFormatted(final BigDecimal amt)
{
|
final DecimalFormat amountFormat = DisplayType.getNumberFormat(DisplayType.Amount);
final StringBuilder amountFormatted = new StringBuilder();
amountFormatted.append(amountFormat.format(amt));
final boolean isSameCurrency = currencySymbols.size() == 1;
String curSymbol = null;
if (isSameCurrency)
{
curSymbol = currencySymbols.iterator().next();
amountFormatted.append(curSymbol);
}
return amountFormatted.toString();
}
@Override
public String getSummaryMessageTranslated(final Properties ctx)
{
final String message = getSummaryMessage();
final String messageTrl = Services.get(IMsgBL.class).parseTranslation(ctx, message);
return messageTrl;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\invoicecandidate\ui\spi\impl\HUInvoiceCandidatesSelectionSummaryInfo.java
| 1
|
请完成以下Java代码
|
/* package */class CompositeQueryUpdaterExecutor<T>
extends CompositeQueryUpdater<T>
implements ICompositeQueryUpdaterExecutor<T>
{
private final IQuery<T> query;
private boolean executeDirectly = true;
public CompositeQueryUpdaterExecutor(@NonNull final IQuery<T> query)
{
this.query = query;
}
@Override
public int execute()
{
if (executeDirectly)
{
return query.updateDirectly(this);
}
else
{
return query.update(this);
}
}
@Override
public ICompositeQueryUpdaterExecutor<T> setExecuteDirectly(final boolean executeDirectly)
{
this.executeDirectly = executeDirectly;
return this;
}
@Override
public ICompositeQueryUpdaterExecutor<T> addQueryUpdater(final @NonNull IQueryUpdater<T> updater)
{
super.addQueryUpdater(updater);
return this;
}
@Override
public ICompositeQueryUpdaterExecutor<T> addSetColumnValue(final String columnName, @Nullable final Object value)
{
super.addSetColumnValue(columnName, value);
return this;
}
|
@Override
public ICompositeQueryUpdaterExecutor<T> addSetColumnFromColumn(final String columnName, final ModelColumnNameValue<T> fromColumnName)
{
super.addSetColumnFromColumn(columnName, fromColumnName);
return this;
}
@Override
public ICompositeQueryUpdaterExecutor<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd)
{
super.addAddValueToColumn(columnName, valueToAdd);
return this;
}
@Override
public ICompositeQueryUpdaterExecutor<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd, final IQueryFilter<T> onlyWhenFilter)
{
super.addAddValueToColumn(columnName, valueToAdd, onlyWhenFilter);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryUpdaterExecutor.java
| 1
|
请完成以下Java代码
|
public abstract class BaseResourceProcessor extends BaseEdgeProcessor {
@Autowired
private DataValidator<TbResource> resourceValidator;
protected boolean saveOrUpdateTbResource(TenantId tenantId, TbResourceId tbResourceId, ResourceUpdateMsg resourceUpdateMsg) {
boolean resourceKeyUpdated = false;
try {
TbResource resource = JacksonUtil.fromString(resourceUpdateMsg.getEntity(), TbResource.class, true);
if (resource == null) {
throw new RuntimeException("[{" + tenantId + "}] resourceUpdateMsg {" + resourceUpdateMsg + " } cannot be converted to resource");
}
boolean created = false;
TbResource resourceById = edgeCtx.getResourceService().findResourceById(tenantId, tbResourceId);
if (resourceById == null) {
resource.setCreatedTime(Uuids.unixTimestamp(tbResourceId.getId()));
created = true;
resource.setId(null);
} else {
resource.setId(tbResourceId);
}
String resourceKey = resource.getResourceKey();
ResourceType resourceType = resource.getResourceType();
if (!created && !resourceType.isUpdatable()) {
resource.setData(null);
}
PageDataIterable<TbResource> resourcesIterable = new PageDataIterable<>(
link -> edgeCtx.getResourceService().findTenantResourcesByResourceTypeAndPageLink(tenantId, resourceType, link), 1024);
for (TbResource tbResource : resourcesIterable) {
if (tbResource.getResourceKey().equals(resourceKey) && !tbResourceId.equals(tbResource.getId())) {
|
resourceKey = StringUtils.randomAlphabetic(15) + "_" + resourceKey;
log.warn("[{}] Resource with resource type {} and key {} already exists. Renaming resource key to {}",
tenantId, resourceType, resource.getResourceKey(), resourceKey);
resourceKeyUpdated = true;
}
}
resource.setResourceKey(resourceKey);
resourceValidator.validate(resource, TbResourceInfo::getTenantId);
if (created) {
resource.setId(tbResourceId);
}
edgeCtx.getResourceService().saveResource(resource, false);
} catch (Exception e) {
log.error("[{}] Failed to process resource update msg [{}]", tenantId, resourceUpdateMsg, e);
throw e;
}
return resourceKeyUpdated;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\resource\BaseResourceProcessor.java
| 1
|
请完成以下Java代码
|
/* package */class MInOutLineHUDocumentLine extends AbstractHUDocumentLine
{
private final I_M_InOutLine ioLine;
private String displayName;
public MInOutLineHUDocumentLine(final org.compiere.model.I_M_InOutLine ioLine, final I_M_Transaction mtrx)
{
super(
new MTransactionProductStorage(mtrx, loadOutOfTrx(ioLine.getC_UOM_ID(), I_C_UOM.class)), // storage
mtrx // referencedModel
);
Check.assumeNotNull(ioLine, "ioLine not null");
Check.assume(ioLine.getM_InOutLine_ID() > 0, "ioLine({}) is saved", ioLine);
this.ioLine = InterfaceWrapperHelper.create(ioLine, I_M_InOutLine.class);
}
@Override
public String getDisplayName()
{
if (displayName == null)
{
final String productName = Services.get(IProductBL.class).getProductName(getProductId());
displayName = new StringBuilder()
.append(ioLine.getLine()).append(": ")
.append(productName)
.append(" x ")
.append(getQty())
.append(getC_UOM().getUOMSymbol())
.toString();
}
return displayName;
}
@Override
public IHUAllocations getHUAllocations()
{
return null;
}
@Override
|
public I_M_Transaction getTrxReferencedModel()
{
return (I_M_Transaction)super.getTrxReferencedModel();
}
private MInOutLineHUDocumentLine reversalSourceLine = null;
@Override
public MInOutLineHUDocumentLine getReversal()
{
if (reversalSourceLine == null)
{
final org.compiere.model.I_M_InOutLine reversalLine = ioLine.getReversalLine();
final I_M_Transaction mtrx = getTrxReferencedModel();
final I_M_Transaction reversalMTrx = Services.get(IMTransactionDAO.class).retrieveReversalTransaction(reversalLine, mtrx);
reversalSourceLine = new MInOutLineHUDocumentLine(reversalLine, reversalMTrx);
reversalSourceLine.setReversal(this);
}
return reversalSourceLine;
}
private void setReversal(final MInOutLineHUDocumentLine reversalLine)
{
reversalSourceLine = reversalLine;
}
@Override
public int getC_BPartner_Location_ID()
{
final I_M_InOut inout = ioLine.getM_InOut();
return inout.getC_BPartner_Location_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutLineHUDocumentLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void doRelease(UUID scriptId, JsScriptInfo jsInfo) throws Exception {
String scriptHash = jsInfo.getHash();
if (scriptInfoMap.values().stream().map(JsScriptInfo::getHash).anyMatch(hash -> hash.equals(scriptHash))) {
return;
}
JsInvokeProtos.JsReleaseRequest jsRequest = JsInvokeProtos.JsReleaseRequest.newBuilder()
.setScriptHash(scriptHash)
.setFunctionName(jsInfo.getFunctionName()).build();
JsInvokeProtos.RemoteJsRequest jsRequestWrapper = JsInvokeProtos.RemoteJsRequest.newBuilder()
.setReleaseRequest(jsRequest)
.build();
ListenableFuture<TbProtoQueueMsg<JsInvokeProtos.RemoteJsResponse>> future = requestTemplate.send(new TbProtoJsQueueMsg<>(UUID.randomUUID(), jsRequestWrapper));
if (getMaxInvokeRequestsTimeout() > 0) {
future = Futures.withTimeout(future, getMaxInvokeRequestsTimeout(), TimeUnit.MILLISECONDS, timeoutExecutorService);
}
JsInvokeProtos.RemoteJsResponse response = future.get().getValue();
JsInvokeProtos.JsReleaseResponse releaseResponse = response.getReleaseResponse();
if (releaseResponse.getSuccess()) {
scriptsLock.lock();
try {
if (scriptInfoMap.values().stream().map(JsScriptInfo::getHash).noneMatch(hash -> hash.equals(scriptHash))) {
scriptHashToBodysMap.remove(scriptHash);
}
} finally {
scriptsLock.unlock();
|
}
} else {
log.debug("[{}] Failed to release script", scriptHash);
}
}
protected String constructFunctionName(UUID scriptId, String scriptHash) {
return "invokeInternal_" + scriptHash;
}
protected String getScriptHash(UUID scriptId) {
JsScriptInfo jsScriptInfo = scriptInfoMap.get(scriptId);
return jsScriptInfo != null ? jsScriptInfo.getHash() : null;
}
}
|
repos\thingsboard-master\common\script\remote-js-client\src\main\java\org\thingsboard\server\service\script\RemoteJsInvokeService.java
| 2
|
请完成以下Java代码
|
public CaseDefinitionBuilder createActivity(String id) {
CmmnActivity activity = activityStack.peek().createActivity(id);
activityStack.push(activity);
processElement = activity;
return this;
}
public CaseDefinitionBuilder endActivity() {
activityStack.pop();
processElement = activityStack.peek();
return this;
}
public CaseDefinitionBuilder behavior(CmmnActivityBehavior behavior) {
getActivity().setActivityBehavior(behavior);
return this;
}
public CaseDefinitionBuilder autoComplete(boolean autoComplete) {
getActivity().setProperty("autoComplete", autoComplete);
return this;
}
protected CmmnActivity getActivity() {
|
return activityStack.peek();
}
public CmmnCaseDefinition buildCaseDefinition() {
return caseDefinition;
}
public CaseDefinitionBuilder listener(String eventName, CaseExecutionListener planItemListener) {
activityStack.peek().addListener(eventName, planItemListener);
return this;
}
public CaseDefinitionBuilder property(String name, Object value) {
activityStack.peek().setProperty(name, value);
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CaseDefinitionBuilder.java
| 1
|
请完成以下Java代码
|
public synchronized void registerEventListenerForConditionsType(@NonNull final IFlatrateTermEventListener handlerNew, final String typeConditions)
{
Check.assumeNotEmpty(typeConditions, "typeConditions not empty");
// Validate handler
if (handlerNew instanceof CompositeFlatrateTermEventListener)
{
// enforce immutability of given handler: we are not accepting composite because it might be that on next registerHandler calls will will add a handler inside it.
throw new AdempiereException("Composite shall not be used: " + handlerNew);
}
//
final IFlatrateTermEventListener handlerCurrent = typeConditions2handlers.get(typeConditions);
final IFlatrateTermEventListener handlerComposed = CompositeFlatrateTermEventListener.compose(handlerCurrent, handlerNew);
typeConditions2handlers.put(typeConditions, handlerComposed);
logger.info("Registered {} for TYPE_CONDITIONS={}", handlerNew, typeConditions);
|
}
@Override
public IFlatrateTermEventListener getHandler(final String typeConditions)
{
final IFlatrateTermEventListener handlers = typeConditions2handlers.get(typeConditions);
if (handlers == null)
{
logger.debug("No handler found for TYPE_CONDITIONS={}. Returning default: {}", typeConditions, fallbackListener);
return fallbackListener;
}
return handlers;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateTermEventService.java
| 1
|
请完成以下Java代码
|
public RootPropertyResolver getRootPropertyResolver() {
return root;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return delegate.getCommonPropertyType(context, base);
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
return delegate.getType(context, base, property);
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
return delegate.getValue(context, base, property);
}
|
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return delegate.isReadOnly(context, base, property);
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
delegate.setValue(context, base, property, value);
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
return delegate.invoke(context, base, method, paramTypes, params);
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\util\SimpleResolver.java
| 1
|
请完成以下Java代码
|
public boolean tryAdvance(Consumer<? super Integer> action) {
if (currentIndex < elements.size()) {
action.accept(elements.get(currentIndex));
currentIndex++;
return true;
}
return false;
}
@Override
public Spliterator<Integer> trySplit() {
int currentSize = elements.size() - currentIndex;
if (currentSize < 2) {
return null;
}
|
int splitIndex = currentIndex + currentSize / 2;
CustomSpliterator newSpliterator = new CustomSpliterator(elements.subList(currentIndex, splitIndex));
currentIndex = splitIndex;
return newSpliterator;
}
@Override
public long estimateSize() {
return elements.size() - currentIndex;
}
@Override
public int characteristics() {
return ORDERED | SIZED | SUBSIZED | NONNULL;
}
}
|
repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\spliterator\CustomSpliterator.java
| 1
|
请完成以下Java代码
|
public class Jvm {
/**
* 当前JVM占用的内存总数(M)
*/
private double total;
/**
* JVM最大可用内存总数(M)
*/
private double max;
/**
* JVM空闲内存(M)
*/
private double free;
/**
* JDK版本
*/
private String version;
/**
* JDK路径
*/
private String home;
/**
* JDK启动时间
*/
private String startTime;
/**
* JDK运行时间
*/
private String runTime;
public double getTotal() {
return NumberUtil.div(total, (1024 * 1024), 2);
}
public void setTotal(double total) {
this.total = total;
}
public double getMax() {
return NumberUtil.div(max, (1024 * 1024), 2);
}
public void setMax(double max) {
this.max = max;
}
public double getFree() {
return NumberUtil.div(free, (1024 * 1024), 2);
}
public void setFree(double free) {
|
this.free = free;
}
public double getUsed() {
return NumberUtil.div(total - free, (1024 * 1024), 2);
}
public double getUsage() {
return NumberUtil.mul(NumberUtil.div(total - free, total, 4), 100);
}
/**
* 获取JDK名称
*/
public String getName() {
return ManagementFactory.getRuntimeMXBean().getVmName();
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStartTime() {
return DateUtil.formatDateTime(new Date(ManagementFactory.getRuntimeMXBean().getStartTime()));
}
public void setRunTime(String runTime) {
this.runTime = runTime;
}
public String getRunTime() {
long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
return DateUtil.formatBetween(DateUtil.current(false) - startTime);
}
}
|
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Jvm.java
| 1
|
请完成以下Java代码
|
public int getPostingError_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID);
}
/**
* PostingType AD_Reference_ID=125
* Reference name: _Posting Type
*/
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Actual Year End = Y */
public static final String POSTINGTYPE_ActualYearEnd = "Y";
@Override
public void setPostingType (final java.lang.String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
@Override
public java.lang.String getPostingType()
{
return get_ValueAsString(COLUMNNAME_PostingType);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_GL_Journal getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class);
}
@Override
public void setReversal(final org.compiere.model.I_GL_Journal Reversal)
{
set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
|
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
@Override
public void setSAP_GLJournal_ID (final int SAP_GLJournal_ID)
{
if (SAP_GLJournal_ID < 1)
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, SAP_GLJournal_ID);
}
@Override
public int getSAP_GLJournal_ID()
{
return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID);
}
@Override
public void setTotalCr (final BigDecimal TotalCr)
{
set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr);
}
@Override
public BigDecimal getTotalCr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalCr);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalDr (final BigDecimal TotalDr)
{
set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr);
}
@Override
public BigDecimal getTotalDr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalDr);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournal.java
| 1
|
请完成以下Java代码
|
public Map.Entry<String, Attribute> next()
{
// 保证首次调用找到一个词语
while (entryList.size() == 0 && begin < c.length)
{
entryList = trie.commonPrefixSearchWithValue(c, begin);
++begin;
}
// 之后调用仅在缓存用完的时候调用一次
if (entryList.size() == 0 && begin < c.length)
{
entryList = trie.commonPrefixSearchWithValue(c, begin);
++begin;
}
if (entryList.size() == 0)
{
return null;
}
Map.Entry<String, Attribute> result = entryList.get(0);
entryList.remove(0);
offset = begin - 1;
return result;
}
}
/**
* 通用词典中的词属性
*/
static public class Attribute
{
/**
* 词性列表
*/
public Nature nature[];
/**
* 词性对应的词频
*/
public int frequency[];
public int totalFrequency;
public Attribute(int size)
{
nature = new Nature[size];
frequency = new int[size];
}
public Attribute(Nature[] nature, int[] frequency)
{
this.nature = nature;
this.frequency = frequency;
}
public Attribute(Nature nature, int frequency)
{
this(1);
this.nature[0] = nature;
this.frequency[0] = frequency;
totalFrequency = frequency;
}
/**
* 使用单个词性,默认词频1000构造
*
* @param nature
*/
public Attribute(Nature nature)
{
this(nature, 1000);
}
/**
* 获取词性的词频
*
* @param nature 字符串词性
* @return 词频
* @deprecated 推荐使用Nature参数!
*/
public int getNatureFrequency(String nature)
{
try
{
Nature pos = Nature.create(nature);
return getNatureFrequency(pos);
|
}
catch (IllegalArgumentException e)
{
return 0;
}
}
/**
* 获取词性的词频
*
* @param nature 词性
* @return 词频
*/
public int getNatureFrequency(final Nature nature)
{
int result = 0;
int i = 0;
for (Nature pos : this.nature)
{
if (nature == pos)
{
return frequency[i];
}
++i;
}
return result;
}
@Override
public String toString()
{
return "Attribute{" +
"nature=" + Arrays.toString(nature) +
", frequency=" + Arrays.toString(frequency) +
'}';
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\EasyDictionary.java
| 1
|
请完成以下Java代码
|
public void setBlockQps(Long blockQps) {
this.blockQps = blockQps;
}
public Long getTotalQps() {
return totalQps;
}
public void setTotalQps(Long totalQps) {
this.totalQps = totalQps;
}
public Long getAverageRt() {
return averageRt;
}
public void setAverageRt(Long averageRt) {
this.averageRt = averageRt;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public Long getOneMinutePass() {
return oneMinutePass;
}
public void setOneMinutePass(Long oneMinutePass) {
this.oneMinutePass = oneMinutePass;
}
public Long getOneMinuteBlock() {
return oneMinuteBlock;
}
public void setOneMinuteBlock(Long oneMinuteBlock) {
|
this.oneMinuteBlock = oneMinuteBlock;
}
public Long getOneMinuteException() {
return oneMinuteException;
}
public void setOneMinuteException(Long oneMinuteException) {
this.oneMinuteException = oneMinuteException;
}
public Long getOneMinuteTotal() {
return oneMinuteTotal;
}
public void setOneMinuteTotal(Long oneMinuteTotal) {
this.oneMinuteTotal = oneMinuteTotal;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public List<ResourceTreeNode> getChildren() {
return children;
}
public void setChildren(List<ResourceTreeNode> children) {
this.children = children;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
| 1
|
请完成以下Java代码
|
private Map<DetailId, DocumentLayoutDetailDescriptor> buildAllDetails()
{
final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map = ImmutableMap.builder();
for (final DocumentLayoutDetailDescriptor detail : details)
{
buildDetailsRecurse(detail, map);
}
return map.build();
}
private void buildDetailsRecurse(
@NonNull final DocumentLayoutDetailDescriptor detail,
@NonNull final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map)
{
putIfNotEmpty(detail, map);
for (final DocumentLayoutDetailDescriptor subDetail : detail.getSubTabLayouts())
{
buildDetailsRecurse(subDetail, map);
}
}
private void putIfNotEmpty(final DocumentLayoutDetailDescriptor detail, final ImmutableMap.Builder<DetailId, DocumentLayoutDetailDescriptor> map)
{
if (detail.isEmpty())
{
return;
}
map.put(detail.getDetailId(), detail);
}
public Builder setWindowId(final WindowId windowId)
{
this.windowId = windowId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = TranslatableStrings.nullToEmpty(caption);
return this;
}
public Builder setDocumentSummaryElement(@Nullable final DocumentLayoutElementDescriptor documentSummaryElement)
{
this.documentSummaryElement = documentSummaryElement;
return this;
}
public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement)
{
this.docActionElement = docActionElement;
return this;
}
public Builder setGridView(final ViewLayout.Builder gridView)
{
this._gridView = gridView;
return this;
}
public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout)
{
this.singleRowLayout = singleRowLayout;
return this;
}
private DocumentLayoutSingleRow.Builder getSingleRowLayout()
{
return singleRowLayout;
|
}
private ViewLayout.Builder getGridView()
{
return _gridView;
}
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail)
{
if (detail == null)
{
return this;
}
if (detail.isEmpty())
{
logger.trace("Skip adding detail to layout because it is empty; detail={}", detail);
return this;
}
details.add(detail);
return this;
}
public Builder setSideListView(final ViewLayout sideListViewLayout)
{
this._sideListView = sideListViewLayout;
return this;
}
private ViewLayout getSideList()
{
Preconditions.checkNotNull(_sideListView, "sideList");
return _sideListView;
}
public Builder putDebugProperty(final String name, final String value)
{
debugProperties.put(name, value);
return this;
}
public Builder setStopwatch(final Stopwatch stopwatch)
{
this.stopwatch = stopwatch;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
| 1
|
请完成以下Java代码
|
public void add(int location,Object o)
{
try
{
elements[location] = o;
}
catch(java.lang.ArrayStoreException ase)
{
}
}
public void remove(int location)
{
elements[location] = null;
}
public int location(Object o) throws NoSuchObjectException
{
int loc = -1;
for ( int x = 0; x < elements.length; x++ )
{
if((elements[x] != null && elements[x] == o )||
(elements[x] != null && elements[x].equals(o)))
{
|
loc = x;
break;
}
}
if( loc == -1 )
throw new NoSuchObjectException();
return(loc);
}
public Object get(int location)
{
return elements[location];
}
public java.util.Enumeration elements()
{
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Array.java
| 1
|
请完成以下Java代码
|
public void setMaxFileSize(@Nullable DataSize maxFileSize) {
this.maxFileSize = maxFileSize;
}
/**
* Sets the maximum {@link DataSize} allowed for multipart/form-data requests.
* @param maxRequestSize the maximum request size
*/
public void setMaxRequestSize(@Nullable DataSize maxRequestSize) {
this.maxRequestSize = maxRequestSize;
}
/**
* Sets the {@link DataSize size} threshold after which files will be written to disk.
* @param fileSizeThreshold the file size threshold
*/
public void setFileSizeThreshold(@Nullable DataSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
}
/**
* Create a new {@link MultipartConfigElement} instance.
* @return the multipart config element
*/
public MultipartConfigElement createMultipartConfig() {
long maxFileSizeBytes = convertToBytes(this.maxFileSize, -1);
long maxRequestSizeBytes = convertToBytes(this.maxRequestSize, -1);
long fileSizeThresholdBytes = convertToBytes(this.fileSizeThreshold, 0);
return new MultipartConfigElement(this.location, maxFileSizeBytes, maxRequestSizeBytes,
|
(int) fileSizeThresholdBytes);
}
/**
* Return the amount of bytes from the specified {@link DataSize size}. If the size is
* {@code null} or negative, returns {@code defaultValue}.
* @param size the data size to handle
* @param defaultValue the default value if the size is {@code null} or negative
* @return the amount of bytes to use
*/
private long convertToBytes(@Nullable DataSize size, int defaultValue) {
if (size != null && !size.isNegative()) {
return size.toBytes();
}
return defaultValue;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\MultipartConfigFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SupplierReferenceType {
@XmlElement(name = "DocumentID", required = true)
protected String documentID;
@XmlElement(name = "ReferenceDate")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar referenceDate;
@XmlElement(name = "Description")
protected DescriptionType description;
/**
* The ID of the document.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocumentID() {
return documentID;
}
/**
* Sets the value of the documentID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocumentID(String value) {
this.documentID = value;
}
/**
* The date of the referenced document.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getReferenceDate() {
return referenceDate;
}
/**
* Sets the value of the referenceDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
|
*
*/
public void setReferenceDate(XMLGregorianCalendar value) {
this.referenceDate = value;
}
/**
* A description in free-text form of the referenced document.
*
* @return
* possible object is
* {@link DescriptionType }
*
*/
public DescriptionType getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link DescriptionType }
*
*/
public void setDescription(DescriptionType value) {
this.description = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\SupplierReferenceType.java
| 2
|
请完成以下Java代码
|
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance);
}
@Override
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
|
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID)
{
if (QM_Analysis_Report_ID < 1)
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID);
}
@Override
public int getQM_Analysis_Report_ID()
{
return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java
| 1
|
请完成以下Java代码
|
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getRestartedProcessInstanceId() {
return restartedProcessInstanceId;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId) {
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + startUserId
+ ", superProcessInstanceId=" + superProcessInstanceId
|
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", deleteReason=" + deleteReason
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", removalTime=" + removalTime
+ ", endActivityId=" + endActivityId
+ ", startActivityId=" + startActivityId
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ ", restartedProcessInstanceId=" + restartedProcessInstanceId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java
| 1
|
请完成以下Java代码
|
public class DepartIdModel implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
private String key;
/**
* 主键ID
*/
private String value;
/**
* 部门编码
*/
private String code;
/**
* 部门名称
*/
private String title;
List<DepartIdModel> children = new ArrayList<>();
/**
* 将SysDepartTreeModel的部分数据放在该对象当中
* @param treeModel
* @return
*/
public DepartIdModel convert(SysDepartTreeModel treeModel) {
this.key = treeModel.getId();
this.value = treeModel.getId();
this.title = treeModel.getDepartName();
return this;
}
/**
* 该方法为用户部门的实现类所使用
* @param sysDepart
* @return
*/
public DepartIdModel convertByUserDepart(SysDepart sysDepart) {
this.key = sysDepart.getId();
this.value = sysDepart.getId();
this.code = sysDepart.getOrgCode();
this.title = sysDepart.getDepartName();
return this;
}
public List<DepartIdModel> getChildren() {
return children;
}
|
public void setChildren(List<DepartIdModel> children) {
this.children = children;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\DepartIdModel.java
| 1
|
请完成以下Java代码
|
protected CamelContext resolveCamelContext(String camelContextValue, boolean isV5Execution) {
ProcessEngineConfiguration engineConfiguration = org.flowable.engine.impl.context.Context.getProcessEngineConfiguration();
if (isV5Execution) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
return (CamelContext) compatibilityHandler.getCamelContextObject(camelContextValue);
} else {
// Convert it to a SpringProcessEngineConfiguration. If this doesn't work, throw a RuntimeException.
try {
SpringProcessEngineConfiguration springConfiguration = (SpringProcessEngineConfiguration) engineConfiguration;
if (StringUtils.isEmpty(camelContextValue)) {
camelContextValue = springConfiguration.getDefaultCamelContext();
}
|
// Get the CamelContext object and set the super's member variable.
Object ctx = springConfiguration.getApplicationContext().getBean(camelContextValue);
if (!(ctx instanceof SpringCamelContext)) {
throw new FlowableException("Could not find CamelContext named " + camelContextValue + ".");
}
return (SpringCamelContext) ctx;
} catch (Exception e) {
throw new FlowableException("Expecting a SpringProcessEngineConfiguration for the Camel module.", e);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\SpringCamelBehavior.java
| 1
|
请完成以下Java代码
|
public Set<ScriptType> getSupportedScriptTypes()
{
return ImmutableSet.copyOf(supportedScriptTypes);
}
@Override
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase, final IScript script)
{
return createScriptExecutor(targetDatabase, script.getType());
}
@Override
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase)
{
return createScriptExecutor(targetDatabase, ScriptType.SQL);
}
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase, final ScriptType scriptType)
{
final Class<? extends IScriptExecutor> scriptExecutorClass = getScriptExecutorClass(targetDatabase.getDbType(), scriptType);
if (scriptExecutorClass == null)
{
throw new ScriptException("No script executors found for " + scriptType)
.addParameter("Database", targetDatabase);
}
if (dryRunMode)
{
return new NullScriptExecutor(targetDatabase);
}
try
{
final IScriptExecutor executor = scriptExecutorClass.getConstructor(IDatabase.class).newInstance(targetDatabase);
return executor;
}
catch (final Exception e)
{
throw new ScriptException("Cannot instantiate executor class: " + scriptExecutorClass, e);
}
}
/**
* Enable/Disable dry run mode.
*
* If dry run mode is enabled then scripts won't be actually executed (i.e. {@link NullScriptExecutor} will be used)
*
* @param dryRunMode
|
*/
@Override
public void setDryRunMode(final boolean dryRunMode)
{
this.dryRunMode = dryRunMode;
}
/**
* @return true if dry run mode is enabled
* @see #setDryRunMode(boolean)
*/
@Override
public boolean isDryRunMode()
{
return dryRunMode;
}
@Value(staticConstructor = "of")
private static class ScriptExecutorKey
{
final String dbType;
final ScriptType scriptType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\executor\impl\DefaultScriptExecutorFactory.java
| 1
|
请完成以下Java代码
|
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
log.info("OtherRealm doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
String username = userToken.getUsername();
if ("unknown".equals(username)) {
throw new UnknownAccountException("用户不存在");
}
if ("monster".equals(username)) {
throw new LockedAccountException("用户被锁定");
}
Object principal = username;
Object credentials = "7c4a8d09ca3762af61e59520943dc26494f8941b";
String realmName = getName();
log.info("doGetAuthenticationInfo username: {}", username);
|
/**
* 见 {@link ShiroConfig#myRealm} 的密码指定算法
*/
return new SimpleAuthenticationInfo(principal, credentials, realmName);
}
public static void main(String[] args) {
String hashAlgorithmName = "SHA1";
String credentials = "123456";
Object salt = null;
int hashIterations = 1;
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(simpleHash);
}
}
|
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\shiro\realm\OtherRealm.java
| 1
|
请完成以下Java代码
|
protected boolean shouldAggregateForSingleInstance() {
return false;
}
@Override
protected boolean shouldAggregateForMultipleInstances() {
return false;
}
public boolean isStage() {
if (isStage == null) {
isStage = isStage(planItemInstanceEntity);
}
return isStage;
}
@Override
public String getOperationName() {
return "[Exit plan item]";
}
public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
|
this.exitCriterionId = exitCriterionId;
}
public String getExitType() {
return exitType;
}
public void setExitType(String exitType) {
this.exitType = exitType;
}
public String getExitEventType() {
return exitEventType;
}
public void setExitEventType(String exitEventType) {
this.exitEventType = exitEventType;
}
public Boolean getStage() {
return isStage;
}
public void setStage(Boolean stage) {
isStage = stage;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ExitPlanItemInstanceOperation.java
| 1
|
请完成以下Java代码
|
public int getAD_Product_Category_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Product_Category_BoilerPlate_ID);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Product_Category_BoilerPlate.java
| 1
|
请完成以下Java代码
|
public Iterator<Object> iterator() {
return new Iterator<Object>() {
private Iterator<Entry<String, Object>> i = entrySet().iterator();
@Override
public boolean hasNext() {
return this.i.hasNext();
}
@Override
public Object next() {
return this.i.next().getValue();
}
@Override
public void remove() {
this.i.remove();
}
};
}
@Override
public int size() {
return SpringSessionMap.this.size();
|
}
@Override
public boolean isEmpty() {
return SpringSessionMap.this.isEmpty();
}
@Override
public void clear() {
SpringSessionMap.this.clear();
}
@Override
public boolean contains(Object v) {
return SpringSessionMap.this.containsValue(v);
}
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
| 1
|
请完成以下Java代码
|
public boolean isDebugProtocol ()
{
Object oo = get_Value(COLUMNNAME_IsDebugProtocol);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Port.
@param Port Port */
@Override
public void setPort (int Port)
{
set_Value (COLUMNNAME_Port, Integer.valueOf(Port));
}
/** Get Port.
@return Port */
@Override
public int getPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Port);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Protocol AD_Reference_ID=540906
* Reference name: C_InboundMailConfig_Protocol
*/
public static final int PROTOCOL_AD_Reference_ID=540906;
/** IMAP = imap */
public static final String PROTOCOL_IMAP = "imap";
/** IMAPS = imaps */
public static final String PROTOCOL_IMAPS = "imaps";
/** Set Protocol.
@param Protocol
Protocol
*/
@Override
public void setProtocol (java.lang.String Protocol)
{
set_Value (COLUMNNAME_Protocol, Protocol);
}
/** Get Protocol.
@return Protocol
*/
@Override
public java.lang.String getProtocol ()
{
return (java.lang.String)get_Value(COLUMNNAME_Protocol);
}
@Override
public org.compiere.model.I_R_RequestType getR_RequestType() throws RuntimeException
|
{
return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class);
}
@Override
public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType)
{
set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
}
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Nutzer-ID/Login.
@param UserName Nutzer-ID/Login */
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Nutzer-ID/Login.
@return Nutzer-ID/Login */
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java-gen\de\metas\inbound\mail\model\X_C_InboundMailConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity loginInfo() {
ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
Map<String, Object> map = new HashMap<>();
Set<String> permissions = Sets.newHashSet();
//TODO 获取当前用户所有的权限和角色
User user = userService.getById(shiroUser.getUserId().intValue());
map.put("roleList", user.getRoles());
map.put("permissionList", permissions);
map.put("userId", shiroUser.getUserId());
map.put("username", shiroUser.getLoginName());
return ResponseEntity.ok(map);
}
|
/**
* 注销
* @return
*/
@PostMapping("/logout")
public ResponseEntity logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return ResponseEntity.ok();
}
}
|
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\controller\LoginController.java
| 2
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameGenderEntity other = (NameGenderEntity) obj;
if (count == null) {
if (other.count != null)
return false;
} else if (!count.equals(other.count))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (name == null) {
|
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (probability == null) {
if (other.probability != null)
return false;
} else if (!probability.equals(other.probability))
return false;
return true;
}
@Override
public String toString() {
return "NameGenderModel [count=" + count + ", gender=" + gender + ", name=" + name + ", probability=" + probability + "]";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameGenderEntity.java
| 1
|
请完成以下Java代码
|
public void setFileCharset (final java.lang.String FileCharset)
{
set_Value (COLUMNNAME_FileCharset, FileCharset);
}
@Override
public java.lang.String getFileCharset()
{
return get_ValueAsString(COLUMNNAME_FileCharset);
}
/**
* FormatType AD_Reference_ID=209
* Reference name: AD_ImpFormat FormatType
*/
public static final int FORMATTYPE_AD_Reference_ID=209;
/** Fixed Position = F */
public static final String FORMATTYPE_FixedPosition = "F";
/** CommaSeparated = C */
public static final String FORMATTYPE_CommaSeparated = "C";
/** TabSeparated = T */
public static final String FORMATTYPE_TabSeparated = "T";
/** XML = X */
public static final String FORMATTYPE_XML = "X";
/** SemicolonSeparated = S */
public static final String FORMATTYPE_SemicolonSeparated = "S";
@Override
public void setFormatType (final java.lang.String FormatType)
{
set_Value (COLUMNNAME_FormatType, FormatType);
}
@Override
public java.lang.String getFormatType()
{
return get_ValueAsString(COLUMNNAME_FormatType);
}
@Override
public void setIsManualImport (final boolean IsManualImport)
{
set_Value (COLUMNNAME_IsManualImport, IsManualImport);
}
@Override
public boolean isManualImport()
{
return get_ValueAsBoolean(COLUMNNAME_IsManualImport);
}
@Override
public void setIsMultiLine (final boolean IsMultiLine)
{
set_Value (COLUMNNAME_IsMultiLine, IsMultiLine);
}
@Override
public boolean isMultiLine()
|
{
return get_ValueAsBoolean(COLUMNNAME_IsMultiLine);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSkipFirstNRows (final int SkipFirstNRows)
{
set_Value (COLUMNNAME_SkipFirstNRows, SkipFirstNRows);
}
@Override
public int getSkipFirstNRows()
{
return get_ValueAsInt(COLUMNNAME_SkipFirstNRows);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat.java
| 1
|
请完成以下Java代码
|
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Kommentar/Hilfe.
@param Help
Comment or Hint
*/
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Kommentar/Hilfe.
@return Comment or Hint
*/
@Override
public java.lang.String getHelp ()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
/** Set Kostenkategorie.
@param M_CostType_ID
Type of Cost (e.g. Current, Plan, Future)
*/
@Override
public void setM_CostType_ID (int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID));
}
|
/** Get Kostenkategorie.
@return Type of Cost (e.g. Current, Plan, Future)
*/
@Override
public int getM_CostType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageResult<Entity> listTables(TableRequest request) {
HikariDataSource dataSource = DbUtil.buildFromTableRequest(request);
Db db = new Db(dataSource);
Page page = new Page(request.getCurrentPage(), request.getPageSize());
int start = page.getStartPosition();
int pageSize = page.getPageSize();
String paramSql = StrUtil.EMPTY;
if (StrUtil.isNotBlank(request.getTableName())) {
paramSql = "and table_name like concat('%', ?, '%')";
}
String sql = String.format(TABLE_SQL_TEMPLATE, paramSql);
String countSql = String.format(COUNT_SQL_TEMPLATE, sql);
List<Entity> query;
BigDecimal count;
if (StrUtil.isNotBlank(request.getTableName())) {
query = db.query(sql + PAGE_SQL_TEMPLATE, request.getTableName(), start, pageSize);
count = (BigDecimal) db.queryNumber(countSql, request.getTableName());
} else {
query = db.query(sql + PAGE_SQL_TEMPLATE, start, pageSize);
count = (BigDecimal) db.queryNumber(countSql);
}
PageResult<Entity> pageResult = new PageResult<>(count.longValue(), page.getPageNumber(), page.getPageSize(), query);
dataSource.close();
return pageResult;
}
/**
* 生成代码
*
* @param genConfig 生成配置
* @return 代码压缩文件
*/
@Override
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
|
请完成以下Java代码
|
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread())) {
List<PropertySource<?>> propertySources = getPropertySources();
if (propertySources.isEmpty()) {
addPropertySource(propertySources, LEGACY_FILE_NAME, (file) -> "devtools-local");
}
propertySources.forEach(environment.getPropertySources()::addFirst);
}
}
private List<PropertySource<?>> getPropertySources() {
List<PropertySource<?>> propertySources = new ArrayList<>();
for (String fileName : FILE_NAMES) {
addPropertySource(propertySources, CONFIG_PATH + fileName, this::getPropertySourceName);
}
return propertySources;
}
private String getPropertySourceName(File file) {
return "devtools-local: [" + file.toURI() + "]";
}
private void addPropertySource(List<PropertySource<?>> propertySources, String fileName,
Function<File, String> propertySourceNamer) {
File home = getHomeDirectory();
File file = (home != null) ? new File(home, fileName) : null;
FileSystemResource resource = (file != null) ? new FileSystemResource(file) : null;
if (resource != null && resource.exists() && resource.isFile()) {
addPropertySource(propertySources, resource, propertySourceNamer);
}
}
private void addPropertySource(List<PropertySource<?>> propertySources, FileSystemResource resource,
Function<File, String> propertySourceNamer) {
try {
String name = propertySourceNamer.apply(resource.getFile());
for (PropertySourceLoader loader : PROPERTY_SOURCE_LOADERS) {
if (canLoadFileExtension(loader, resource.getFilename())) {
propertySources.addAll(loader.load(name, resource));
|
}
}
}
catch (IOException ex) {
throw new IllegalStateException("Unable to load " + resource.getFilename(), ex);
}
}
private boolean canLoadFileExtension(PropertySourceLoader loader, String name) {
return Arrays.stream(loader.getFileExtensions())
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension));
}
protected @Nullable File getHomeDirectory() {
return getHomeDirectory(() -> this.environmentVariables.get("SPRING_DEVTOOLS_HOME"),
() -> this.systemProperties.getProperty("spring.devtools.home"),
() -> this.systemProperties.getProperty("user.home"));
}
@SafeVarargs
private @Nullable File getHomeDirectory(Supplier<String>... pathSuppliers) {
for (Supplier<String> pathSupplier : pathSuppliers) {
String path = pathSupplier.get();
if (StringUtils.hasText(path)) {
return new File(path);
}
}
return null;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\env\DevToolsHomePropertiesPostProcessor.java
| 1
|
请完成以下Java代码
|
protected void registerPublicPermissions(Class<? extends Permission> clazz) {
Assert.notNull(clazz, "Class required");
Field[] fields = clazz.getFields();
for (Field field : fields) {
try {
Object fieldValue = field.get(null);
if (Permission.class.isAssignableFrom(fieldValue.getClass())) {
// Found a Permission static field
Permission perm = (Permission) fieldValue;
String permissionName = field.getName();
registerPermission(perm, permissionName);
}
}
catch (Exception ex) {
}
}
}
protected void registerPermission(Permission perm, String permissionName) {
Assert.notNull(perm, "Permission required");
Assert.hasText(permissionName, "Permission name required");
Integer mask = perm.getMask();
// Ensure no existing Permission uses this integer or code
Assert.isTrue(!this.registeredPermissionsByInteger.containsKey(mask),
() -> "An existing Permission already provides mask " + mask);
Assert.isTrue(!this.registeredPermissionsByName.containsKey(permissionName),
() -> "An existing Permission already provides name '" + permissionName + "'");
// Register the new Permission
this.registeredPermissionsByInteger.put(mask, perm);
this.registeredPermissionsByName.put(permissionName, perm);
}
@Override
public Permission buildFromMask(int mask) {
if (this.registeredPermissionsByInteger.containsKey(mask)) {
// The requested mask has an exact match against a statically-defined
// Permission, so return it
return this.registeredPermissionsByInteger.get(mask);
}
// To get this far, we have to use a CumulativePermission
CumulativePermission permission = new CumulativePermission();
for (int i = 0; i < 32; i++) {
int permissionToCheck = 1 << i;
|
if ((mask & permissionToCheck) == permissionToCheck) {
Permission p = this.registeredPermissionsByInteger.get(permissionToCheck);
Assert.state(p != null,
() -> "Mask '" + permissionToCheck + "' does not have a corresponding static Permission");
permission.set(p);
}
}
return permission;
}
@Override
public Permission buildFromName(String name) {
Permission p = this.registeredPermissionsByName.get(name);
Assert.notNull(p, "Unknown permission '" + name + "'");
return p;
}
@Override
public List<Permission> buildFromNames(List<String> names) {
if ((names == null) || names.isEmpty()) {
return Collections.emptyList();
}
List<Permission> permissions = new ArrayList<>(names.size());
for (String name : names) {
permissions.add(buildFromName(name));
}
return permissions;
}
}
|
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\DefaultPermissionFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void createNewFactRecords(
@NonNull final ImmutableList<CommissionFact> facts,
final int commissionShareRecordId,
@NonNull final OrgId orgId,
@NonNull final CommissionStagingRecords records)
{
final ImmutableList<I_C_Commission_Fact> factRecords = records.getSalesFactRecordsForShareRecordId(commissionShareRecordId);
final ImmutableMap<ArrayKey, I_C_Commission_Fact> idAndTypeAndTimestampToFactRecord = Maps.uniqueIndex(
factRecords,
r -> ArrayKey.of(r.getC_Commission_Share_ID(), r.getCommission_Fact_State(), r.getCommissionFactTimestamp()));
for (final CommissionFact fact : facts)
{
final I_C_Commission_Fact factRecordOrNull = idAndTypeAndTimestampToFactRecord.get(
ArrayKey.of(commissionShareRecordId, fact.getState().toString(), TimeUtil.serializeInstant(fact.getTimestamp())));
if (factRecordOrNull != null)
{
continue;
}
final I_C_Commission_Fact factRecord = newInstance(I_C_Commission_Fact.class);
factRecord.setAD_Org_ID(orgId.getRepoId());
factRecord.setC_Commission_Share_ID(commissionShareRecordId);
factRecord.setCommissionPoints(fact.getPoints().toBigDecimal());
factRecord.setCommission_Fact_State(fact.getState().toString());
factRecord.setCommissionFactTimestamp(TimeUtil.serializeInstant(fact.getTimestamp()));
saveRecord(factRecord);
}
}
@NonNull
|
private I_C_Commission_Instance loadOrNewInstanceRecord(@Nullable final CommissionInstanceId instanceId)
{
return loadOrNew(instanceId, I_C_Commission_Instance.class);
}
private void propagateAdditionalColumns(
@NonNull final OrderLineId orderLineId,
@NonNull final I_C_Commission_Instance commissionInstanceRecord)
{
final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId);
final I_C_Order order = orderDAO.getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
commissionInstanceRecord.setPOReference(order.getPOReference());
commissionInstanceRecord.setBill_BPartner_ID(orderLine.getC_BPartner_ID());
commissionInstanceRecord.setC_Order_ID(orderLine.getC_Order_ID());
commissionInstanceRecord.setM_Product_Order_ID(orderLine.getM_Product_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\repos\CommissionInstanceRepository.java
| 2
|
请完成以下Java代码
|
public int getC_RfQ_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set RfQ Subscriber.
@param C_RfQ_TopicSubscriber_ID
Request for Quotation Topic Subscriber
*/
@Override
public void setC_RfQ_TopicSubscriber_ID (int C_RfQ_TopicSubscriber_ID)
{
if (C_RfQ_TopicSubscriber_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, Integer.valueOf(C_RfQ_TopicSubscriber_ID));
}
/** Get RfQ Subscriber.
@return Request for Quotation Topic Subscriber
*/
@Override
public int getC_RfQ_TopicSubscriber_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum der Abmeldung.
@param OptOutDate
|
Date the contact opted out
*/
@Override
public void setOptOutDate (java.sql.Timestamp OptOutDate)
{
set_Value (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Datum der Abmeldung.
@return Date the contact opted out
*/
@Override
public java.sql.Timestamp getOptOutDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
/** Set Anmeldung.
@param SubscribeDate
Date the contact actively subscribed
*/
@Override
public void setSubscribeDate (java.sql.Timestamp SubscribeDate)
{
set_Value (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Anmeldung.
@return Date the contact actively subscribed
*/
@Override
public java.sql.Timestamp getSubscribeDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java
| 1
|
请完成以下Java代码
|
public static MWebProjectDomain get(Properties ctx, String ServerName, String trxName) {
MWebProjectDomain thisWebProjectDomain = null;
String sql = "SELECT * FROM CM_WebProject_Domain WHERE lower(FQDN) LIKE ? ORDER by CM_WebProject_Domain_ID DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setString(1, ServerName);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
thisWebProjectDomain = (new MWebProjectDomain(ctx, rs, trxName));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
|
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return thisWebProjectDomain;
}
} // MWebProjectDomain
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWebProjectDomain.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainController {
@Autowired
private NotificationService notificationService;
/**
* GET / -> show the index page.
*/
@RequestMapping("/")
public String index() {
return "index";
}
/**
* GET /notifications -> show the notifications page.
*/
@RequestMapping("/notifications")
public String notifications() {
return "notifications";
}
/**
* POST /some-action -> do an action.
*
|
* After the action is performed will be notified UserA.
*/
@RequestMapping(value = "/some-action", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> someAction() {
// Do an action here
// ...
// Send the notification to "UserA" (by username)
notificationService.notify(
new Notification("hello"), // notification object
"UserA" // username
);
// Return an http 200 status code
return new ResponseEntity<>(HttpStatus.OK);
}
} // class MainController
|
repos\spring-boot-samples-master\spring-boot-web-socket-user-notifications\src\main\java\netgloo\controllers\MainController.java
| 2
|
请完成以下Java代码
|
public OAuth2AuthorizedClientService authorizedClientService() {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository());
}
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
@Autowired
private Environment env;
private ClientRegistration getRegistration(String client) {
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
if (clientId == null) {
return null;
}
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
if (client.equals("google")) {
|
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
if (client.equals("facebook")) {
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
return null;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\SecurityConfig.java
| 1
|
请完成以下Java代码
|
public class PostalAddressType {
protected String pobox;
protected String street;
@XmlElement(required = true)
protected ZipType zip;
@XmlElement(required = true)
protected String city;
/**
* Gets the value of the pobox property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPobox() {
return pobox;
}
/**
* Sets the value of the pobox property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPobox(String value) {
this.pobox = value;
}
/**
* Gets the value of the street property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStreet() {
return street;
}
/**
* Sets the value of the street property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStreet(String value) {
this.street = value;
}
/**
* Gets the value of the zip property.
*
* @return
* possible object is
* {@link ZipType }
*
*/
public ZipType getZip() {
return zip;
|
}
/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link ZipType }
*
*/
public void setZip(ZipType value) {
this.zip = value;
}
/**
* Gets the value of the city property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCity() {
return city;
}
/**
* Sets the value of the city property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCity(String value) {
this.city = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\PostalAddressType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public MetadataGenerator metadataGenerator() {
MetadataGenerator metadataGenerator = new MetadataGenerator();
metadataGenerator.setEntityId(samlAudience);
metadataGenerator.setExtendedMetadata(extendedMetadata);
metadataGenerator.setIncludeDiscoveryExtension(false);
metadataGenerator.setKeyManager(keyManager);
return metadataGenerator;
}
@Bean
public SAMLProcessingFilter samlWebSSOProcessingFilter(AuthenticationManager authenticationManager) {
SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager);
samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(samlAuthSuccessHandler);
samlWebSSOProcessingFilter.setAuthenticationFailureHandler(samlAuthFailureHandler);
return samlWebSSOProcessingFilter;
}
@Bean
public FilterChainProxy samlFilter(SAMLProcessingFilter samlProcessingFilter) throws Exception {
List<SecurityFilterChain> chains = new ArrayList<>();
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
samlProcessingFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
samlDiscovery()));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
samlEntryPoint));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
samlLogoutFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
samlLogoutProcessingFilter));
return new FilterChainProxy(chains);
}
@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
return new MetadataGeneratorFilter(metadataGenerator());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception {
http
.csrf()
.disable();
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint);
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class)
|
.addFilterBefore(samlProcessingFilter, CsrfFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
http
.logout()
.addLogoutHandler((request, response, authentication) -> {
try {
response.sendRedirect("/saml/logout");
} catch (IOException e) {
e.printStackTrace();
}
});
http.authenticationProvider(samlAuthenticationProvider);
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
private Map<GLN, BPartnerLocationId> getGlnToNewLocationMap(final int bpartnerId)
{
return bPartnerDAO.retrieveBPartnerLocations(BPartnerId.ofRepoId(bpartnerId))
.stream()
.filter(loc -> !Check.isBlank(loc.getGLN()))
.collect(Collectors.toMap(param -> GLN.ofString(param.getGLN()), param -> BPartnerLocationId.ofRepoId(param.getC_BPartner_ID(), param.getC_BPartner_Location_ID())));
}
@NonNull
private Map<BPartnerLocationId, GLN> getOldLocationIdToGlnMap()
{
final Map<BPartnerLocationId, GLN> oldLocationToGlnMap = createQueryBuilder()
.andCollect(I_C_OLCand.COLUMNNAME_C_BPartner_Location_ID, I_C_BPartner_Location.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.filter(Objects::nonNull)
.filter(loc -> !Check.isBlank(loc.getGLN()))
.collect(Collectors.toMap(param -> BPartnerLocationId.ofRepoId(param.getC_BPartner_ID(), param.getC_BPartner_Location_ID()), param -> GLN.ofString(param.getGLN())));
if (oldLocationToGlnMap.size() == 0)
{
throw new AdempiereException(NO_GLNS);
}
return oldLocationToGlnMap;
}
@Override
protected String doIt() throws Exception
{
final OLCandUpdateResult result = olCandUpdateBL.updateOLCands(getCtx(), createIterator(), params);
return "@Success@: " + result.getUpdated() + " @Processed@, " + result.getSkipped() + " @Skipped@";
}
private Iterator<I_C_OLCand> createIterator()
{
return createQueryBuilder()
|
.create()
.setRequiredAccess(Access.READ) // 04471: enqueue only those records on which user has access to
.iterate(I_C_OLCand.class);
}
private IQueryBuilder<I_C_OLCand> createQueryBuilder()
{
final IQueryFilter<I_C_OLCand> queryFilter = getQueryFilter();
final IQueryBuilder<I_C_OLCand> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_C_OLCand.class, getCtx(), get_TrxName())
.filter(queryFilter)
.filter(ActiveRecordQueryFilter.getInstance(I_C_OLCand.class));
queryBuilder.orderBy()
.addColumn(I_C_OLCand.COLUMNNAME_C_OLCand_ID);
return queryBuilder;
}
@VisibleForTesting
protected IQueryFilter<I_C_OLCand> getQueryFilter()
{
return getProcessInfo().getQueryFilterOrElseFalse();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCand_SetOverrideValues.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getHeaderField(String key){
if(headers==null){
return null;
}
List<String> headerValues = headers.get(key);
if(headerValues==null || headerValues.isEmpty()){
return null;
}
return headerValues.get(headerValues.size()-1);
}
public String getContentType(){
return contentType;
}
public int getStatusCode() {
return statusCode;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
|
public String getExceptionMsg() {
return exceptionMsg;
}
public Exception getException() {
return exception;
}
public boolean isSuccess(){
return statusCode==200;
}
public boolean isError(){
return exception!=null;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpResult.java
| 2
|
请完成以下Java代码
|
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
this.inParameters.add(inParameter);
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
|
}
@Override
public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public ExternalWorkerServiceTask clone() {
ExternalWorkerServiceTask clone = new ExternalWorkerServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ExternalWorkerServiceTask otherElement) {
super.setValues(otherElement);
setTopic(otherElement.getTopic());
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ExternalWorkerServiceTask.java
| 1
|
请完成以下Java代码
|
public class AfterRoutePredicateFactory extends AbstractRoutePredicateFactory<AfterRoutePredicateFactory.Config> {
/**
* DateTime key.
*/
public static final String DATETIME_KEY = "datetime";
public AfterRoutePredicateFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Collections.singletonList(DATETIME_KEY);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange serverWebExchange) {
final ZonedDateTime now = ZonedDateTime.now();
return now.isAfter(config.getDatetime());
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("After: %s", config.getDatetime());
}
};
|
}
public static class Config {
@NotNull
private @Nullable ZonedDateTime datetime;
public @Nullable ZonedDateTime getDatetime() {
return datetime;
}
public void setDatetime(ZonedDateTime datetime) {
this.datetime = datetime;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\AfterRoutePredicateFactory.java
| 1
|
请完成以下Java代码
|
public class CyclicBarrierResetExample {
private int count;
private int threadCount;
private final AtomicInteger updateCount;
CyclicBarrierResetExample(int count, int threadCount) {
updateCount = new AtomicInteger(0);
this.count = count;
this.threadCount = threadCount;
}
public int countWaits() {
CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
ExecutorService es = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
es.execute(() -> {
try {
if (cyclicBarrier.getNumberWaiting() > 0) {
updateCount.incrementAndGet();
}
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
|
}
});
}
es.shutdown();
try {
es.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return updateCount.get();
}
public static void main(String[] args) {
CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7, 20);
System.out.println("Count : " + ex.countWaits());
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\cyclicbarrier\CyclicBarrierResetExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AttachmentResponse {
private String id;
private String url;
private String name;
private String userId;
private String description;
private String type;
private String taskUrl;
private String processInstanceUrl;
private String externalUrl;
private String contentUrl;
@JsonSerialize(using = DateToStringSerializer.class, as = Date.class)
private Date time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ApiModelProperty(value = "Can be any arbitrary value. When a valid formatted media-type (e.g. application/xml, text/plain) is included, the binary content HTTP response content-type will be set the given value.")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
|
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.")
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getContentUrl() {
return contentUrl;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java
| 2
|
请完成以下Java代码
|
public class LoginParam {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* Application ID
*/
private String appid;
/**
* IMEI码
*/
private String imei;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
|
this.password = password;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
}
|
repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\model\LoginParam.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
@Override
protected UserDetailsService userDetailsService() {
return super.userDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
auth.inMemoryAuthentication()
.withUser("admin")
.password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") //123
.roles("admin")
.and()
.withUser("sang")
.password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") //123
.roles("user");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/oauth/**").authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.and().csrf().disable();
}
}
|
repos\springboot-demo-master\oatuth2\src\main\java\com\et\oauth2\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
{
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
try {
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
return f.generateSecret(spec).getEncoded();
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
}
catch (InvalidKeySpecException ex) {
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
}
}
/**
* Hash a password in an immutable {@code String}.
*
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
* with zeros after use instead of lingering on the heap and elsewhere.
*
* @deprecated Use {@link #hash(char[])} instead
*/
@Deprecated
public String hash(String password)
{
return hash(password.toCharArray());
}
|
/**
* Authenticate with a password in an immutable {@code String} and a stored
* password token.
*
* @deprecated Use {@link #checkPassword(char[],String)} instead.
* @see #hash(String)
*/
@Deprecated
public boolean checkPassword(String password, String token)
{
return checkPassword(password.toCharArray(), token);
}
}
|
repos\tutorials-master\core-java-modules\core-java-security-2\src\main\java\com\baeldung\passwordhashing\PBKDF2Hasher.java
| 1
|
请完成以下Java代码
|
public class SpringUtil implements ApplicationContextAware {
private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
private static ApplicationContext applicationContext = null;
//库名和数据处理Bean映射Map
private static Map<String, Object> instanceMap = new HashMap<String, Object>();
//路劲和数据处理Method映射Map
private static Map<String, Method> handlerMap = new HashMap<String, Method>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
|
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
|
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\util\SpringUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<UmsMenu> getMenuList(Long adminId) {
return roleDao.getMenuList(adminId);
}
@Override
public List<UmsMenu> listMenu(Long roleId) {
return roleDao.getMenuListByRoleId(roleId);
}
@Override
public List<UmsResource> listResource(Long roleId) {
return roleDao.getResourceListByRoleId(roleId);
}
@Override
public int allocMenu(Long roleId, List<Long> menuIds) {
//先删除原有关系
UmsRoleMenuRelationExample example=new UmsRoleMenuRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
roleMenuRelationMapper.deleteByExample(example);
//批量插入新关系
for (Long menuId : menuIds) {
UmsRoleMenuRelation relation = new UmsRoleMenuRelation();
relation.setRoleId(roleId);
relation.setMenuId(menuId);
roleMenuRelationMapper.insert(relation);
}
|
return menuIds.size();
}
@Override
public int allocResource(Long roleId, List<Long> resourceIds) {
//先删除原有关系
UmsRoleResourceRelationExample example=new UmsRoleResourceRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
roleResourceRelationMapper.deleteByExample(example);
//批量插入新关系
for (Long resourceId : resourceIds) {
UmsRoleResourceRelation relation = new UmsRoleResourceRelation();
relation.setRoleId(roleId);
relation.setResourceId(resourceId);
roleResourceRelationMapper.insert(relation);
}
adminCacheService.delResourceListByRole(roleId);
return resourceIds.size();
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsRoleServiceImpl.java
| 2
|
请完成以下Java代码
|
public boolean hasChildElements() {
return false;
}
@Override
protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
CmmnDiEdge edgeInfo = conversionHelper.getCurrentDiEdge();
if (edgeInfo == null) {
return null;
}
boolean readyWithChildElements = false;
try {
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (CmmnXmlConstants.ELEMENT_DI_DOCKER.equals(xtr.getLocalName())) {
String type = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TYPE);
if ("source".equals(type) || "target".equals(type)) {
GraphicInfo graphicInfo = new GraphicInfo();
graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_X)));
graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_Y)));
if ("source".equals(type)) {
edgeInfo.setSourceDockerInfo(graphicInfo);
} else {
edgeInfo.setTargetDockerInfo(graphicInfo);
}
|
}
}
} else if (xtr.isEndElement()) {
if (CmmnXmlConstants.ELEMENT_DI_EXTENSION.equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
} catch (Exception ex) {
LOGGER.error("Error processing CMMN document", ex);
throw new XMLException("Error processing CMMN document", ex);
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CmmnDiExtensionXmlConverter.java
| 1
|
请完成以下Java代码
|
public class PeriodControlStatus extends JavaProcess
{
private int periodId;
@Override
protected void prepare()
{
// nothing
}
@Override
protected String doIt() throws Exception
{
final I_C_PeriodControl pc = getRecord(I_C_PeriodControl.class);
this.periodId = pc.getC_Period_ID();
// Permanently closed
if (X_C_PeriodControl.PERIODSTATUS_PermanentlyClosed.equals(pc.getPeriodStatus()))
{
throw new AdempiereException("@PeriodStatus@ = " + pc.getPeriodStatus());
}
// No Action => do nothing
if (X_C_PeriodControl.PERIODACTION_NoAction.equals(pc.getPeriodAction()))
{
|
return "@OK@";
}
//
// Update the period control
final String newPeriodStatus = Services.get(IPeriodBL.class).getPeriodStatusForAction(pc.getPeriodAction());
pc.setPeriodStatus(newPeriodStatus);
pc.setPeriodAction(X_C_PeriodControl.PERIODACTION_NoAction); // reset the action
InterfaceWrapperHelper.save(pc);
return "@OK@";
} // doIt
@Override
protected void postProcess(boolean success)
{
// Reset Cache
CacheMgt.get().reset(I_C_PeriodControl.Table_Name);
CacheMgt.get().reset(I_C_Period.Table_Name, periodId);
}
} // PeriodControlStatus
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\PeriodControlStatus.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getAuthOrgCode()
{
return ((TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials()).getOrgCode();
}
@NonNull
private JsonAttachment buildJsonAttachment(@NonNull final de.metas.camel.externalsystems.grssignum.to_grs.api.model.JsonAttachment attachment)
{
return JsonAttachmentUtil.createLocalFileJsonAttachment(
"",
attachment.getFileName(),
buildJsonTags(attachment));
}
@NonNull
private ImmutableList<JsonTag> buildJsonTags(@NonNull final de.metas.camel.externalsystems.grssignum.to_grs.api.model.JsonAttachment attachment)
{
final ImmutableList.Builder<JsonTag> jsonTagBuilder = ImmutableList.builder();
jsonTagBuilder.add(JsonTag.of(AttachmentTags.ID.getName(), attachment.getId()));
|
if (Check.isNotBlank(attachment.getValidUntil()))
{
jsonTagBuilder.add(JsonTag.of(AttachmentTags.VALID_TO.getName(), attachment.getValidUntil()));
}
if (Check.isNotBlank(attachment.getDocumentType()))
{
jsonTagBuilder.add(JsonTag.of(AttachmentTags.DOCUMENT_TYPE.getName(), attachment.getDocumentType()));
}
if (Check.isNotBlank(attachment.getDocumentGroup()))
{
jsonTagBuilder.add(JsonTag.of(AttachmentTags.DOCUMENT_GROUP.getName(), attachment.getDocumentGroup()));
}
return jsonTagBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\product\processor\RawMaterialAttachFileProcessor.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getExecutionUrl() {
return executionUrl;
}
public void setExecutionUrl(String executionUrl) {
this.executionUrl = executionUrl;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
|
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\EventSubscriptionResponse.java
| 2
|
请完成以下Java代码
|
public class UpdateProcessInstancesSuspendStateJobHandler extends AbstractBatchJobHandler<UpdateProcessInstancesSuspendStateBatchConfiguration> {
public static final BatchJobDeclaration JOB_DECLARATION = new BatchJobDeclaration(Batch.TYPE_PROCESS_INSTANCE_UPDATE_SUSPENSION_STATE);
@Override
public String getType() {
return Batch.TYPE_PROCESS_INSTANCE_UPDATE_SUSPENSION_STATE;
}
protected UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter getJsonConverterInstance() {
return UpdateProcessInstancesSuspendStateBatchConfigurationJsonConverter.INSTANCE;
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected UpdateProcessInstancesSuspendStateBatchConfiguration createJobConfiguration(UpdateProcessInstancesSuspendStateBatchConfiguration configuration, List<String> processIdsForJob) {
return new UpdateProcessInstancesSuspendStateBatchConfiguration(processIdsForJob, configuration.getSuspended());
}
|
@Override
public void executeHandler(UpdateProcessInstancesSuspendStateBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration()
.getCommandExecutorTxRequired();
commandContext.executeWithOperationLogPrevented(new UpdateProcessInstancesSuspendStateCmd(
commandExecutor,
new UpdateProcessInstancesSuspensionStateBuilderImpl(batchConfiguration.getIds()),
batchConfiguration.getSuspended()));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\update\UpdateProcessInstancesSuspendStateJobHandler.java
| 1
|
请完成以下Java代码
|
void readFully(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int amountRead = checkedRead(buffer, offset, length);
offset += amountRead;
length -= amountRead;
}
}
/**
* Read a single byte from the stream (checking that the end of the stream hasn't been
* reached).
* @return the content
* @throws IOException in case of I/O errors
*/
int checkedRead() throws IOException {
int b = read();
if (b == -1) {
throw new IOException("End of stream");
}
return (b & 0xff);
}
|
/**
* Read a number of bytes from the stream (checking that the end of the stream hasn't
* been reached).
* @param buffer the destination buffer
* @param offset the buffer offset
* @param length the length to read
* @return the amount of data read
* @throws IOException in case of I/O errors
*/
int checkedRead(byte[] buffer, int offset, int length) throws IOException {
int amountRead = read(buffer, offset, length);
if (amountRead == -1) {
throw new IOException("End of stream");
}
return amountRead;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\ConnectionInputStream.java
| 1
|
请完成以下Java代码
|
public LocalDate getDateInvoiced()
{
if (dateInvoicedSet)
{
return dateInvoiced;
}
else if (defaults != null)
{
return defaults.getDateInvoiced();
}
else
{
return null;
}
}
public void setDateInvoiced(final LocalDate dateInvoiced)
{
this.dateInvoiced = dateInvoiced;
dateInvoicedSet = true;
}
@Nullable
@Override
public LocalDate getDateAcct()
{
if (dateAcctSet)
{
return dateAcct;
}
else if (defaults != null)
{
return defaults.getDateAcct();
}
else
{
return null;
}
}
public void setDateAcct(final LocalDate dateAcct)
{
this.dateAcct = dateAcct;
dateAcctSet = true;
}
@Nullable
@Override
public String getPOReference()
{
if (poReferenceSet)
{
return poReference;
}
else if (defaults != null)
{
return defaults.getPOReference();
}
else
{
return null;
}
}
public void setPOReference(@Nullable final String poReference)
{
this.poReference = poReference;
poReferenceSet = true;
}
@Nullable
@Override
public BigDecimal getCheck_NetAmtToInvoice()
{
if (check_NetAmtToInvoice != null)
{
return check_NetAmtToInvoice;
}
else if (defaults != null)
{
return defaults.getCheck_NetAmtToInvoice();
}
return null;
}
@Override
public boolean isStoreInvoicesInResult()
{
if (storeInvoicesInResult != null)
{
return storeInvoicesInResult;
}
|
else if (defaults != null)
{
return defaults.isStoreInvoicesInResult();
}
else
{
return false;
}
}
public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult)
{
this.storeInvoicesInResult = storeInvoicesInResult;
return this;
}
@Override
public boolean isAssumeOneInvoice()
{
if (assumeOneInvoice != null)
{
return assumeOneInvoice;
}
else if (defaults != null)
{
return defaults.isAssumeOneInvoice();
}
else
{
return false;
}
}
public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice)
{
this.assumeOneInvoice = assumeOneInvoice;
return this;
}
public boolean isUpdateLocationAndContactForInvoice()
{
return updateLocationAndContactForInvoice;
}
public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice)
{
this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice;
}
public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices)
{
this.completeInvoices = completeInvoices;
return this;
}
@Override
public boolean isCompleteInvoices()
{
return completeInvoices;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java
| 1
|
请完成以下Java代码
|
public void propagateNamesAndTrl(final I_AD_Process adProcess)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(adProcess);
final String trxName = InterfaceWrapperHelper.getTrxName(adProcess);
for (final I_AD_Menu menu : MMenu.get(ctx, I_AD_Menu.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName))
{
menu.setIsActive(adProcess.isActive());
menu.setName(adProcess.getName());
menu.setDescription(adProcess.getDescription());
InterfaceWrapperHelper.save(menu);
}
for (final I_AD_WF_Node node : MWindow.getWFNodes(ctx, I_AD_WF_Node.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName))
{
boolean changed = false;
if (node.isActive() != adProcess.isActive())
{
node.setIsActive(adProcess.isActive());
changed = true;
|
}
if (node.isCentrallyMaintained())
{
node.setName(adProcess.getName());
node.setDescription(adProcess.getDescription());
node.setHelp(adProcess.getHelp());
changed = true;
}
//
if (changed)
{
InterfaceWrapperHelper.save(node);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\model\interceptor\AD_Process.java
| 1
|
请完成以下Java代码
|
public long getFinishedProcessInstanceCount() {
return finishedProcessInstanceCount;
}
public void setFinishedProcessInstanceCount(Long finishedProcessInstanceCount) {
this.finishedProcessInstanceCount = finishedProcessInstanceCount;
}
public long getCleanableProcessInstanceCount() {
return cleanableProcessInstanceCount;
}
public void setCleanableProcessInstanceCount(Long cleanableProcessInstanceCount) {
this.cleanableProcessInstanceCount = cleanableProcessInstanceCount;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
|
}
public String toString() {
return this.getClass().getSimpleName()
+ "[processDefinitionId = " + processDefinitionId
+ ", processDefinitionKey = " + processDefinitionKey
+ ", processDefinitionName = " + processDefinitionName
+ ", processDefinitionVersion = " + processDefinitionVersion
+ ", historyTimeToLive = " + historyTimeToLive
+ ", finishedProcessInstanceCount = " + finishedProcessInstanceCount
+ ", cleanableProcessInstanceCount = " + cleanableProcessInstanceCount
+ ", tenantId = " + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricProcessInstanceReportResultEntity.java
| 1
|
请完成以下Java代码
|
public class CaseFileImpl extends CmmnElementImpl implements CaseFile {
protected static ChildElementCollection<CaseFileItem> caseFileItemCollection;
public CaseFileImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<CaseFileItem> getCaseFileItems() {
return caseFileItemCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFile.class, CMMN_ELEMENT_CASE_FILE)
.namespaceUri(CMMN11_NS)
|
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<CaseFile>() {
public CaseFile newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
caseFileItemCollection = sequenceBuilder.elementCollection(CaseFileItem.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileImpl.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.