instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, LogoutSuccessHandler webSecurityUserLogoutHandler)
throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.requestMatchers("/").hasRole("USER")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(withDefaults())
.httpBasic(withDefaults())
.logout((logout) -> logout
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.logoutSuccessHandler(webSecurityUserLogoutHandler)
.deleteCookies("JSESSIONID"));
return http.build();
}
@Bean
public LogoutSuccessHandler webSecurityUserLogoutHandler() {
return (request, response, authentication) -> {
System.out.println("User logged out successfully!");
response.sendRedirect("/app");
};
}
@Bean
@Profile("inmemory")
public UserDetailsService inMemoryUserDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder.encode("password"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
|
@Bean
@Profile("jdbc")
public UserDetailsManager jdbcUserDetailsManager(DataSource dataSource, PasswordEncoder passwordEncoder) {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder.encode("password"))
.roles("ADMIN")
.build();
jdbcUserDetailsManager.createUser(user);
jdbcUserDetailsManager.createUser(admin);
return jdbcUserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-5\src\main\java\com\baeldung\securityconfig\configuration\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public int getProcessVariablesIndex() {
return processVariablesIndex;
}
public int getProcessIdIndex() {
return processIdIndex;
}
public boolean requiresProcessId() {
return this.processIdIndex > -1;
}
public boolean requiresProcessVariablesMap() {
return processVariablesIndex > -1;
}
public String getBeanName() {
return beanName;
}
public Map<Integer, String> getProcessVariablesExpected() {
return processVariablesExpected;
}
public Method getHandlerMethod() {
return handlerMethod;
}
public Object getHandler() {
return handler;
}
public String getStateName() {
|
return stateName;
}
public String getProcessName() {
return processName;
}
@Override
public String toString() {
return super.toString() + "["
+ "processVariablesExpected=" + processVariablesExpected + ", "
+ "handlerMethod=" + handlerMethod + ", "
+ "handler=" + handler + ", "
+ "stateName=" + stateName + ", "
+ "beanName=" + beanName + ", "
+ "processVariablesIndex=" + processVariablesIndex + ", "
+ "processIdIndex=" + processIdIndex + ", "
+ "processName=" + processName + "]";
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\registry\ActivitiStateHandlerRegistration.java
| 1
|
请完成以下Java代码
|
protected static String getValue(String attrName, Attributes attributes) {
Attribute attribute = attributes.get(attrName);
if (attribute != null) {
try {
return (String) attribute.get();
} catch (NamingException e) {
throw new IdentityProviderException("Error occurred while retrieving the value.", e);
}
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public static NamingEnumeration<String> getAllMembers(String attributeId, LdapSearchResults searchResults) {
SearchResult result = searchResults.nextElement();
Attributes attributes = result.getAttributes();
|
if (attributes != null) {
Attribute memberAttribute = attributes.get(attributeId);
if (memberAttribute != null) {
try {
return (NamingEnumeration<String>) memberAttribute.getAll();
} catch (NamingException e) {
throw new IdentityProviderException("Value couldn't be retrieved.", e);
}
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapClient.java
| 1
|
请完成以下Java代码
|
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
}
public long getFinishedBatchesCount() {
return finishedBatchesCount;
}
public void setFinishedBatchesCount(long finishedBatchCount) {
this.finishedBatchesCount = finishedBatchCount;
}
public long getCleanableBatchesCount() {
return cleanableBatchesCount;
}
public void setCleanableBatchesCount(long cleanableBatchCount) {
this.cleanableBatchesCount = cleanableBatchCount;
}
protected CleanableHistoricBatchReport createNewReportQuery(ProcessEngine engine) {
|
return engine.getHistoryService().createCleanableHistoricBatchReport();
}
public static List<CleanableHistoricBatchReportResultDto> convert(List<CleanableHistoricBatchReportResult> reportResult) {
List<CleanableHistoricBatchReportResultDto> dtos = new ArrayList<CleanableHistoricBatchReportResultDto>();
for (CleanableHistoricBatchReportResult current : reportResult) {
CleanableHistoricBatchReportResultDto dto = new CleanableHistoricBatchReportResultDto();
dto.setBatchType(current.getBatchType());
dto.setHistoryTimeToLive(current.getHistoryTimeToLive());
dto.setFinishedBatchesCount(current.getFinishedBatchesCount());
dto.setCleanableBatchesCount(current.getCleanableBatchesCount());
dtos.add(dto);
}
return dtos;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\CleanableHistoricBatchReportResultDto.java
| 1
|
请完成以下Java代码
|
public void createOrUpdatePayment(@NonNull final POSPaymentExternalId externalId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexByExternalId(externalId).orElse(-1);
updatePaymentByIndex(paymentIdx, updater);
}
public void updatePaymentByExternalId(@NonNull final POSPaymentExternalId externalId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexByExternalId(externalId)
.orElseThrow(() -> new AdempiereException("No payment found for " + externalId + " in " + payments));
updatePaymentByIndex(paymentIdx, updater);
}
public void updatePaymentById(@NonNull POSPaymentId posPaymentId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexById(posPaymentId);
updatePaymentByIndex(paymentIdx, updater);
}
private void updatePaymentByIndex(final int paymentIndex, @NonNull final UnaryOperator<POSPayment> updater)
{
final POSPayment payment = paymentIndex >= 0 ? payments.get(paymentIndex) : null;
final POSPayment paymentChanged = updater.apply(payment);
if (paymentIndex >= 0)
{
payments.set(paymentIndex, paymentChanged);
}
else
{
payments.add(paymentChanged);
}
updateTotals();
}
private int getPaymentIndexById(final @NonNull POSPaymentId posPaymentId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentId.equals(payments.get(i).getLocalId(), posPaymentId))
{
return i;
}
|
}
throw new AdempiereException("No payment found for " + posPaymentId + " in " + payments);
}
private OptionalInt getPaymentIndexByExternalId(final @NonNull POSPaymentExternalId externalId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentExternalId.equals(payments.get(i).getExternalId(), externalId))
{
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
public void removePaymentsIf(@NonNull final Predicate<POSPayment> predicate)
{
updateAllPayments(payment -> {
// skip payments marked as DELETED
if (payment.isDeleted())
{
return payment;
}
if (!predicate.test(payment))
{
return payment;
}
if (payment.isAllowDeleteFromDB())
{
payment.assertAllowDelete();
return null;
}
else
{
return payment.changingStatusToDeleted();
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrder.java
| 1
|
请完成以下Java代码
|
public class MResourceUnAvailable extends X_S_ResourceUnAvailable
{
/**
*
*/
private static final long serialVersionUID = 5532695704071630122L;
/**
* Check if a resource is not available
*/
public static boolean isUnAvailable(final int resourceRepoId, @NonNull Instant date)
{
Check.assumeGreaterThanZero(resourceRepoId, "resourceRepoId");
final String whereClause = COLUMNNAME_S_Resource_ID + "=?"
+ " AND TRUNC(" + COLUMNNAME_DateFrom + ") <= TRUNC(?)"
+ " AND TRUNC(" + COLUMNNAME_DateTo + ") >= TRUNC(?)";
return new Query(Env.getCtx(), MResourceUnAvailable.Table_Name, whereClause, ITrx.TRXNAME_ThreadInherited)
.setParameters(resourceRepoId, date, date)
.anyMatch();
}
/**
* Standard Constructor
*
* @param ctx context
* @param S_ResourceUnAvailable_ID id
* @param trxName trx
*/
public MResourceUnAvailable(Properties ctx, int S_ResourceUnAvailable_ID, String trxName)
{
super(ctx, S_ResourceUnAvailable_ID, trxName);
} // MResourceUnAvailable
/**
* MResourceUnAvailable
*
* @param ctx context
* @param rs result set
*/
public MResourceUnAvailable(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MResourceUnAvailable
@Override
|
protected boolean beforeSave(boolean newRecord)
{
if (getDateTo() == null)
setDateTo(getDateFrom());
if (getDateFrom().after(getDateTo()))
{
throw new AdempiereException("@DateTo@ > @DateFrom@");
}
return true;
} // beforeSave
/**
* Check if the resource is unavailable for date
* @return true if valid
*/
public boolean isUnAvailable(final Instant dateTime)
{
final ZoneId zoneId = SystemTime.zoneId();
LocalDate date = dateTime.atZone(zoneId).toLocalDate();
LocalDate dateFrom = TimeUtil.asLocalDate(getDateFrom(), zoneId);
LocalDate dateTo = TimeUtil.asLocalDate(getDateTo(), zoneId);
if (dateFrom != null && date.isBefore(dateFrom))
return false;
if (dateTo != null && date.isAfter(dateTo))
return false;
return true;
}
} // MResourceUnAvailable
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MResourceUnAvailable.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springbatch
username: root
password: 123456
batch:
jdbc:
schema: classpath:org/springframework/batch/core/schema-mysql.sql
initialize-
|
schema: always #Since Spring Boot 2.5.0 use spring.batch.jdbc.initialize-schema=never
job:
enabled: true
|
repos\springboot-demo-master\SpringBatch\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Boolean getSignRequest() {
return this.signRequest;
}
public void setSignRequest(@Nullable Boolean signRequest) {
this.signRequest = signRequest;
}
}
/**
* Verification details for an Identity Provider.
*/
public static class Verification {
/**
* Credentials used for verification of incoming SAML messages.
*/
private List<Credential> credentials = new ArrayList<>();
public List<Credential> getCredentials() {
return this.credentials;
}
public void setCredentials(List<Credential> credentials) {
this.credentials = credentials;
}
public static class Credential {
/**
* Locations of the X.509 certificate used for verification of incoming
* SAML messages.
*/
private @Nullable Resource certificate;
public @Nullable Resource getCertificateLocation() {
return this.certificate;
}
public void setCertificateLocation(@Nullable Resource certificate) {
this.certificate = certificate;
}
}
}
}
/**
* Single logout details.
*/
public static class Singlelogout {
/**
|
* Location where SAML2 LogoutRequest gets sent to.
*/
private @Nullable String url;
/**
* Location where SAML2 LogoutResponse gets sent to.
*/
private @Nullable String responseUrl;
/**
* Whether to redirect or post logout requests.
*/
private @Nullable Saml2MessageBinding binding;
public @Nullable String getUrl() {
return this.url;
}
public void setUrl(@Nullable String url) {
this.url = url;
}
public @Nullable String getResponseUrl() {
return this.responseUrl;
}
public void setResponseUrl(@Nullable String responseUrl) {
this.responseUrl = responseUrl;
}
public @Nullable Saml2MessageBinding getBinding() {
return this.binding;
}
public void setBinding(@Nullable Saml2MessageBinding binding) {
this.binding = binding;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java
| 2
|
请完成以下Java代码
|
public void info(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().info(WindowNo, AD_Message, message);
}
@Override
public IAskDialogBuilder ask()
{
return getCurrentInstance().ask();
}
@Override
public boolean ask(final int WindowNo, final String AD_Message)
{
return getCurrentInstance().ask(WindowNo, AD_Message);
}
@Override
public boolean ask(final int WindowNo, final String AD_Message, final String message)
{
return getCurrentInstance().ask(WindowNo, AD_Message, message);
}
@Override
public void warn(final int WindowNo, final String AD_Message)
{
getCurrentInstance().warn(WindowNo, AD_Message);
}
@Override
public void warn(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().warn(WindowNo, AD_Message, message);
}
@Override
public void warn(final int WindowNo, final Throwable e)
{
getCurrentInstance().warn(WindowNo, e);
}
@Override
public void error(final int WindowNo, final String AD_Message)
{
getCurrentInstance().error(WindowNo, AD_Message);
}
@Override
public void error(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().error(WindowNo, AD_Message, message);
}
@Override
public void error(int WindowNo, Throwable e)
{
getCurrentInstance().error(WindowNo, e);
}
@Override
public void download(final byte[] data, final String contentType, final String filename)
{
getCurrentInstance().download(data, contentType, filename);
}
@Override
public void downloadNow(final InputStream content, final String contentType, final String filename)
{
|
getCurrentInstance().downloadNow(content, contentType, filename);
}
@Override
public void invokeLater(final int windowNo, final Runnable runnable)
{
getCurrentInstance().invokeLater(windowNo, runnable);
}
@Override
public Thread createUserThread(final Runnable runnable, final String threadName)
{
return getCurrentInstance().createUserThread(runnable, threadName);
}
@Override
public String getClientInfo()
{
return getCurrentInstance().getClientInfo();
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{
// nothing
}
@Override
public void showWindow(final Object model)
{
getCurrentInstance().showWindow(model);
}
@Override
public void executeLongOperation(final Object component, final Runnable runnable)
{
getCurrentInstance().executeLongOperation(component, runnable);
}
@Override
public IClientUIInvoker invoke()
{
return getCurrentInstance().invoke();
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
return getCurrentInstance().invokeAsync();
}
@Override
public void showURL(String url)
{
getCurrentInstance().showURL(url);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java
| 1
|
请完成以下Java代码
|
public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID)
{
if (M_Nutrition_Fact_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID));
}
/** Get Nutrition Fact.
@return Nutrition Fact */
@Override
public int getM_Nutrition_Fact_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_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_Nutrition_Fact.java
| 1
|
请完成以下Java代码
|
public class InvoiceCalculateTax extends JavaProcess
{
public static final String PARAM_C_Invoice_ID = "C_Invoice_ID";
private int p_C_Invoice_ID = 0;
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
final String name = para.getParameterName();
if (para.getParameter() == null)
{
}
else if (name.equals(PARAM_C_Invoice_ID))
{
p_C_Invoice_ID = para.getParameterAsInt();
}
}
if (p_C_Invoice_ID <= 0)
{
throw new FillMandatoryException(PARAM_C_Invoice_ID);
}
}
@Override
protected String doIt() throws Exception
{
final MInvoice invoice = new MInvoice(getCtx(), p_C_Invoice_ID, get_TrxName());
recalculateTax(invoice);
//
return "@ProcessOK@";
}
public static void recalculateTax(final MInvoice invoice)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner partner = bpartnerDAO.getById(invoice.getC_BPartner_ID());
|
//
// Delete accounting /UnPost
MPeriod.testPeriodOpen(invoice.getCtx(), invoice.getDateAcct(), invoice.getC_DocType_ID(), invoice.getAD_Org_ID());
Services.get(IFactAcctDAO.class).deleteForDocument(invoice);
//
// Update Invoice
invoice.calculateTaxTotal();
invoice.setPosted(false);
invoice.saveEx();
// FRESH-152 Update bpartner stats
Services.get(IBPartnerStatisticsUpdater.class)
.updateBPartnerStatistics(BPartnerStatisticsUpdateRequest.builder()
.bpartnerId(partner.getC_BPartner_ID())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\process\InvoiceCalculateTax.java
| 1
|
请完成以下Java代码
|
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Startdatum.
@param StartTime Startdatum */
@Override
public void setStartTime (java.sql.Timestamp StartTime)
{
set_Value (COLUMNNAME_StartTime, StartTime);
}
/** Get Startdatum.
@return Startdatum */
@Override
public java.sql.Timestamp getStartTime ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_StartTime);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
|
}
/**
* TaskStatus AD_Reference_ID=366
* Reference name: R_Request TaskStatus
*/
public static final int TASKSTATUS_AD_Reference_ID=366;
/** 0% Not Started = 0 */
public static final String TASKSTATUS_0NotStarted = "0";
/** 100% Complete = D */
public static final String TASKSTATUS_100Complete = "D";
/** 20% Started = 2 */
public static final String TASKSTATUS_20Started = "2";
/** 80% Nearly Done = 8 */
public static final String TASKSTATUS_80NearlyDone = "8";
/** 40% Busy = 4 */
public static final String TASKSTATUS_40Busy = "4";
/** 60% Good Progress = 6 */
public static final String TASKSTATUS_60GoodProgress = "6";
/** 90% Finishing = 9 */
public static final String TASKSTATUS_90Finishing = "9";
/** 95% Almost Done = A */
public static final String TASKSTATUS_95AlmostDone = "A";
/** 99% Cleaning up = C */
public static final String TASKSTATUS_99CleaningUp = "C";
/** Set Task Status.
@param TaskStatus
Status of the Task
*/
@Override
public void setTaskStatus (java.lang.String TaskStatus)
{
set_Value (COLUMNNAME_TaskStatus, TaskStatus);
}
/** Get Task Status.
@return Status of the Task
*/
@Override
public java.lang.String getTaskStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_TaskStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Request.java
| 1
|
请完成以下Java代码
|
private Comparator<CCacheStats> getActualComparator()
{
Comparator<CCacheStats> comparator = this._actualComparator;
if (comparator == null)
{
comparator = this._actualComparator = createActualComparator();
}
return comparator;
}
private Comparator<CCacheStats> createActualComparator()
{
Comparator<CCacheStats> result = parts.get(0).toComparator();
for (int i = 1; i < parts.size(); i++)
{
final Comparator<CCacheStats> partComparator = parts.get(i).toComparator();
result = result.thenComparing(partComparator);
}
return result;
}
//
//
//
public enum Field
{
name,
size,
hitRate,
missRate,
}
@NonNull
@Value(staticConstructor = "of")
public static class Part
{
@NonNull Field field;
boolean ascending;
Comparator<CCacheStats> toComparator()
{
Comparator<CCacheStats> comparator;
switch (field)
{
case name:
comparator = Comparator.comparing(CCacheStats::getName);
break;
case size:
comparator = Comparator.comparing(CCacheStats::getSize);
break;
case hitRate:
|
comparator = Comparator.comparing(CCacheStats::getHitRate);
break;
case missRate:
comparator = Comparator.comparing(CCacheStats::getMissRate);
break;
default:
throw new AdempiereException("Unknown field type!");
}
if (!ascending)
{
comparator = comparator.reversed();
}
return comparator;
}
static Part parse(@NonNull final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
if (stringNorm == null)
{
throw new AdempiereException("Invalid part: `" + string + "`");
}
final String fieldName;
final boolean ascending;
if (stringNorm.charAt(0) == '+')
{
fieldName = stringNorm.substring(1);
ascending = true;
}
else if (stringNorm.charAt(0) == '-')
{
fieldName = stringNorm.substring(1);
ascending = false;
}
else
{
fieldName = stringNorm;
ascending = true;
}
final Field field = Field.valueOf(fieldName);
return of(field, ascending);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheStatsOrderBy.java
| 1
|
请完成以下Java代码
|
public MFColor setLineDistance(final int distance)
{
if (!isLine())
{
return this;
}
return toBuilder().lineDistance(distance).build();
}
public MFColor toFlatColor()
{
switch (getType())
{
case FLAT:
return this;
case GRADIENT:
return ofFlatColor(getGradientUpperColor());
case LINES:
return ofFlatColor(getLineBackColor());
case TEXTURE:
return ofFlatColor(getTextureTaintColor());
default:
throw new IllegalStateException("Type not supported: " + getType());
}
}
|
public String toHexString()
{
final Color awtColor = toFlatColor().getFlatColor();
return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
public static String toHexString(final int red, final int green, final int blue)
{
Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red);
Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green);
Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue);
return String.format("#%02x%02x%02x", red, green, blue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java
| 1
|
请完成以下Java代码
|
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findDashboardById(tenantId, new DashboardId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findDashboardByIdAsync(tenantId, new DashboardId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return dashboardDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.DASHBOARD;
}
private class CustomerDashboardsRemover extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsRemover(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
|
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
unassignDashboardFromCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer.getId());
}
}
private class CustomerDashboardsUpdater extends PaginatedRemover<Customer, DashboardInfo> {
private final Customer customer;
CustomerDashboardsUpdater(Customer customer) {
this.customer = customer;
}
@Override
protected PageData<DashboardInfo> findEntities(TenantId tenantId, Customer customer, PageLink pageLink) {
return dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(customer.getTenantId().getId(), customer.getId().getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, DashboardInfo entity) {
updateAssignedCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer);
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\dashboard\DashboardServiceImpl.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standardpreis.
@param PriceStd
Standardpreis
*/
@Override
public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standardpreis.
@return Standardpreis
*/
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
|
return Env.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_ProductScalePrice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void validate() {
StringBuilder validationErrorBuilder = new StringBuilder("Process engine configuration is invalid: \n");
boolean isValid = true;
if(datasourceJndiName == null || datasourceJndiName.isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'datasource' cannot be null \n");
}
if(engineName == null || engineName.isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'engineName' cannot be null \n");
}
for (int i = 0; i < pluginConfigurations.size(); i++) {
ProcessEnginePluginXml pluginConfiguration = pluginConfigurations.get(i);
if (pluginConfiguration.getPluginClass() == null || pluginConfiguration.getPluginClass().isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'class' in plugin[" + i + "] cannot be null \n");
}
}
if(!isValid) {
throw new ProcessEngineException(validationErrorBuilder.toString());
}
}
private Map<String, String> selectProperties(Map<String, String> allProperties, boolean selectFoxProperties) {
Map<String, String> result = null;
if (selectFoxProperties) {
result = new HashMap<String, String>();
String isAutoSchemaUpdate = allProperties.get(PROP_IS_AUTO_SCHEMA_UPDATE);
String isActivateJobExecutor = allProperties.get(PROP_IS_ACTIVATE_JOB_EXECUTOR);
String isIdentityUsed = allProperties.get(PROP_IS_IDENTITY_USED);
String dbTablePrefix = allProperties.get(PROP_DB_TABLE_PREFIX);
String jobExecutorAcquisitionName = allProperties.get(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
|
if (isAutoSchemaUpdate != null) {
result.put(PROP_IS_AUTO_SCHEMA_UPDATE, isAutoSchemaUpdate);
}
if (isActivateJobExecutor != null) {
result.put(PROP_IS_ACTIVATE_JOB_EXECUTOR, isActivateJobExecutor);
}
if (isIdentityUsed != null) {
result.put(PROP_IS_IDENTITY_USED, isIdentityUsed);
}
if (dbTablePrefix != null) {
result.put(PROP_DB_TABLE_PREFIX, dbTablePrefix);
}
if (jobExecutorAcquisitionName != null) {
result.put(PROP_JOB_EXECUTOR_ACQUISITION_NAME, jobExecutorAcquisitionName);
}
} else {
result = new HashMap<String, String>(allProperties);
result.remove(PROP_IS_AUTO_SCHEMA_UPDATE);
result.remove(PROP_IS_ACTIVATE_JOB_EXECUTOR);
result.remove(PROP_IS_IDENTITY_USED);
result.remove(PROP_DB_TABLE_PREFIX);
result.remove(PROP_JOB_EXECUTOR_ACQUISITION_NAME);
}
return result;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\config\ManagedProcessEngineMetadata.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BookSearchController {
private final VectorStore vectorStore;
private final ChatClient chatClient;
public BookSearchController(VectorStore vectorStore, ChatClient.Builder chatClientBuilder) {
this.vectorStore = vectorStore;
this.chatClient = chatClientBuilder.build();
}
@PostMapping("/search")
List<String> semanticSearch(@RequestBody String query) {
return vectorStore.similaritySearch(SearchRequest.builder()
.query(query)
.topK(3)
.build())
.stream()
.map(Document::getText)
.toList();
|
}
@PostMapping("/enhanced-search")
String enhancedSearch(@RequestBody String query) {
String context = vectorStore.similaritySearch(SearchRequest.builder()
.query(query)
.topK(3)
.build())
.stream()
.map(Document::getText)
.reduce("", (a, b) -> a + b + "\n");
return chatClient.prompt()
.system(context)
.user(query)
.call()
.content();
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai\src\main\java\com\baeldung\springai\semanticsearch\BookSearchController.java
| 2
|
请完成以下Java代码
|
public String getClientSoftwareKennung() {
return clientSoftwareKennung;
}
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
/**
* Gets the value of the retourenavisAnfrageType property.
*
* @return
* possible object is
* {@link RetourenavisAnfrageType }
*
*/
public RetourenavisAnfrageType getRetourenavisAnfrageType() {
return retourenavisAnfrageType;
|
}
/**
* Sets the value of the retourenavisAnfrageType property.
*
* @param value
* allowed object is
* {@link RetourenavisAnfrageType }
*
*/
public void setRetourenavisAnfrageType(RetourenavisAnfrageType value) {
this.retourenavisAnfrageType = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfragen.java
| 1
|
请完成以下Java代码
|
public void setRememberMeRequestAttribute(String rememberMeRequestAttribute) {
if (rememberMeRequestAttribute == null) {
throw new IllegalArgumentException("rememberMeRequestAttribute cannot be null");
}
this.rememberMeRequestAttribute = rememberMeRequestAttribute;
}
/**
* Set the value for the {@code SameSite} cookie directive. The default value is
* {@code Lax}.
* @param sameSite the SameSite directive value
* @since 2.1.0
*/
public void setSameSite(String sameSite) {
this.sameSite = sameSite;
}
private String getDomainName(HttpServletRequest request) {
if (this.domainName != null) {
return this.domainName;
}
if (this.domainNamePattern != null) {
Matcher matcher = this.domainNamePattern.matcher(request.getServerName());
if (matcher.matches()) {
return matcher.group(1);
}
}
return null;
}
private String getCookiePath(HttpServletRequest request) {
if (this.cookiePath == null) {
String contextPath = request.getContextPath();
return (contextPath != null && contextPath.length() > 0) ? contextPath : "/";
}
return this.cookiePath;
}
|
/**
* Gets the name of the request attribute that is checked to see if the cookie should
* be written with {@link Integer#MAX_VALUE}.
* @return the remember me request attribute
* @since 3.2
*/
public String getRememberMeRequestAttribute() {
return this.rememberMeRequestAttribute;
}
/**
* Allows defining whether the generated cookie carries the Partitioned attribute.
* @param partitioned whether the generate cookie is partitioned
* @since 3.4
*/
public void setPartitioned(boolean partitioned) {
this.partitioned = partitioned;
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\DefaultCookieSerializer.java
| 1
|
请完成以下Java代码
|
public BasicPrincipalAuthenticator basicPrincipalAuthenticator(
SecuritySettings securitySettings, CredentialsStrategy credentialsStrategy,
@Named("restx.admin.passwordHash") String defaultAdminPasswordHash, ObjectMapper mapper) {
return new StdBasicPrincipalAuthenticator(new StdUserService<>(
// use file based users repository.
// Developer's note: prefer another storage mechanism for your users if you need real user management
// and better perf
new FileBasedUserRepository<>(
StdUser.class, // this is the class for the User objects, that you can get in your app code
// with RestxSession.current().getPrincipal().get()
// it can be a custom user class, it just need to be json deserializable
mapper,
// this is the default restx admin, useful to access the restx admin console.
// if one user with restx-admin role is defined in the repository, this default user won't be
// available anymore
|
new StdUser("admin", ImmutableSet.<String>of("*")),
// the path where users are stored
Paths.get("data/users.json"),
// the path where credentials are stored. isolating both is a good practice in terms of security
// it is strongly recommended to follow this approach even if you use your own repository
Paths.get("data/credentials.json"),
// tells that we want to reload the files dynamically if they are touched.
// this has a performance impact, if you know your users / credentials never change without a
// restart you can disable this to get better perfs
true),
credentialsStrategy, defaultAdminPasswordHash),
securitySettings);
}
}
|
repos\tutorials-master\web-modules\restx\src\main\java\restx\demo\AppModule.java
| 1
|
请完成以下Java代码
|
public static void closeQuietly(InputStream is)
{
try
{
if (is != null) is.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(Reader r)
{
try
{
if (r != null) r.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(OutputStream os)
{
try
{
if (os != null) os.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(Writer w)
{
try
{
if (w != null) w.close();
}
|
catch (IOException ignored)
{
}
}
/**
* 数组分割
*
* @param from 源
* @param to 目标
* @param <T> 类型
* @return 目标
*/
public static <T> T[] shrink(T[] from, T[] to)
{
assert to.length <= from.length;
System.arraycopy(from, 0, to, 0, to.length);
return to;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Utility.java
| 1
|
请完成以下Java代码
|
public Map<String, Object> getDebugProperties()
{
final ImmutableMap.Builder<String, Object> debugProperties = ImmutableMap.builder();
if (debugProcessClassname != null)
{
debugProperties.put("debug-classname", debugProcessClassname);
}
return debugProperties.build();
}
public boolean isDisplayedOn(@NonNull final DisplayPlace displayPlace)
{
return getDisplayPlaces().contains(displayPlace);
}
@Value
private static class ValueAndDuration<T>
{
|
public static <T> ValueAndDuration<T> fromSupplier(final Supplier<T> supplier)
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final T value = supplier.get();
final Duration duration = Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS));
return new ValueAndDuration<>(value, duration);
}
T value;
Duration duration;
private ValueAndDuration(final T value, final Duration duration)
{
this.value = value;
this.duration = duration;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\WebuiRelatedProcessDescriptor.java
| 1
|
请完成以下Java代码
|
public PlanItemTransition getStandardEvent() {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(PlanItemTransition standardEvent) {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemOnPart.class, CMMN_ELEMENT_PLAN_ITEM_ON_PART)
.extendsType(OnPart.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemOnPart>() {
public PlanItemOnPart newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemOnPartImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(PlanItem.class)
.build();
exitCriterionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERION_REF)
.idAttributeReference(ExitCriterion.class)
|
.build();
sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF)
.namespace(CMMN10_NS)
.idAttributeReference(Sentry.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemOnPartImpl.java
| 1
|
请完成以下Java代码
|
public Object getValue(VariableContainer variableContainer) {
ELContext elContext = Context.getProcessEngineConfiguration().getExpressionManager().getElContext((VariableScope) variableContainer);
try {
ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
return invocation.getInvocationResult();
} catch (PropertyNotFoundException pnfe) {
throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe);
} catch (MethodNotFoundException mnfe) {
throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe);
} catch (ELException ele) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, ele);
} catch (Exception e) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, e);
}
}
@Override
public void setValue(Object value, VariableContainer variableContainer) {
ELContext elContext = Context.getProcessEngineConfiguration().getExpressionManager().getElContext((VariableScope) variableContainer);
try {
ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (Exception e) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, e);
}
|
}
@Override
public String toString() {
if (valueExpression != null) {
return valueExpression.getExpressionString();
}
return super.toString();
}
@Override
public String getExpressionText() {
return expressionText;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java
| 1
|
请完成以下Java代码
|
public void processOpts() {
super.processOpts();
// Handle sourceFolder config option
if (additionalProperties().containsKey(CodegenConstants.SOURCE_FOLDER)) {
sourceFolder = ((String) additionalProperties().get(CodegenConstants.SOURCE_FOLDER));
}
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
public String modelFileFolder() {
return outputFolder() + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder() + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
/**
|
* Use this callback to extend the standard set of lambdas available to templates.
* @return
*/
@Override
protected ImmutableMap.Builder<String, Mustache.Lambda> addMustacheLambdas() {
// Start with parent lambdas
ImmutableMap.Builder<String, Mustache.Lambda> builder = super.addMustacheLambdas();
// Add custom lambda to convert operationIds in suitable java constants
return builder.put("javaconstant", new JavaConstantLambda())
.put("path", new PathLambda());
}
static final List<String> JAVA_RESERVED_WORDS = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "continue", "const", "default", "do", "double", "else", "enum", "exports", "extends", "final", "finally",
"float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "module", "native", "new", "package", "private", "protected", "public", "requires", "return", "short", "static", "strictfp", "super", "switch",
"synchronized", "this", "throw", "throws", "transient", "try", "var", "void", "volatile", "while");
}
|
repos\tutorials-master\spring-swagger-codegen-modules\openapi-custom-generator\src\main\java\com\baeldung\openapi\generators\camelclient\JavaCamelClientGenerator.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getAttendCount() {
return attendCount;
}
public void setAttendCount(Integer attendCount) {
this.attendCount = attendCount;
}
public Integer getAttentionCount() {
return attentionCount;
}
public void setAttentionCount(Integer attentionCount) {
this.attentionCount = attentionCount;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
|
this.readCount = readCount;
}
public String getAwardName() {
return awardName;
}
public void setAwardName(String awardName) {
this.awardName = awardName;
}
public String getAttendType() {
return attendType;
}
public void setAttendType(String attendType) {
this.attendType = attendType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", name=").append(name);
sb.append(", createTime=").append(createTime);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", attendCount=").append(attendCount);
sb.append(", attentionCount=").append(attentionCount);
sb.append(", readCount=").append(readCount);
sb.append(", awardName=").append(awardName);
sb.append(", attendType=").append(attendType);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopic.java
| 1
|
请完成以下Java代码
|
public class KPIPermissionsProvider
{
@NonNull private final IUserRolePermissionsDAO userRolePermissionsDAO;
public IUserRolePermissions getUserRolePermissions(@NonNull final KPIDataContext context)
{
// assume all these context values are set
// see de.metas.ui.web.kpi.descriptor.sql.SQLDatasourceDescriptor.PERMISSION_REQUIRED_PARAMS
final RoleId roleId = context.getRoleId();
final UserId userId = context.getUserId();
final ClientId clientId = context.getClientId();
if (roleId == null || userId == null || clientId == null)
{
throw new AdempiereException("Cannot extract role permissions from context: " + context);
}
return userRolePermissionsDAO.getUserRolePermissions(
roleId,
|
userId,
clientId,
SystemTime.asLocalDate());
}
public String addAccessSQL(
@NonNull final String sql,
@NonNull final String sourceTableName,
@NonNull final KPIDataContext context)
{
final IUserRolePermissions permissions = getUserRolePermissions(context);
return permissions.addAccessSQL(sql, sourceTableName, true, Access.READ);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIPermissionsProvider.java
| 1
|
请完成以下Java代码
|
public void setRuleColumn(String ruleColumn) {
this.ruleColumn = ruleColumn;
}
public String getRuleConditions() {
return ruleConditions;
}
public void setRuleConditions(String ruleConditions) {
this.ruleConditions = ruleConditions;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
|
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java
| 1
|
请完成以下Java代码
|
public synchronized final void cancelAndReset()
{
// Eagerly mark as done.
final boolean alreadyDone = done.getAndSet(true);
//
// If not already done, try stop the current running future (if any)
if (!alreadyDone)
{
final ScheduledFuture<?> future = this.future;
if (future != null && !future.isDone())
{
// Try to cancel current execution.
// If this was not possible, then wait until it finishes.
if (!future.cancel(false))
{
try
|
{
future.get();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
// Create a new instance of "done" flag and set it to false.
// We do this because existing enqueued tasks will work with the old "done" reference which was set to "true".
done = new AtomicBoolean(false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\DelayedRunnableExecutor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CCacheStats
{
//
// Cache Info
long cacheId;
@NonNull String name;
@NonNull ImmutableSet<CacheLabel> labels;
@NonNull CCacheConfig config;
@Nullable String debugAcquireStacktrace;
//
// Actual Stats
long size;
long hitCount;
long missCount;
@NonNull Percent hitRate;
@NonNull Percent missRate;
@Builder
@Jacksonized
private CCacheStats(
final long cacheId,
@NonNull final String name,
|
@Nullable final ImmutableSet<CacheLabel> labels,
@NonNull final CCacheConfig config,
@Nullable final String debugAcquireStacktrace,
final long size,
final long hitCount,
final long missCount)
{
this.cacheId = cacheId;
this.name = name;
this.labels = labels != null ? labels : ImmutableSet.of();
this.config = config;
this.debugAcquireStacktrace = debugAcquireStacktrace;
this.size = size;
this.hitCount = hitCount;
this.missCount = missCount;
this.hitRate = Percent.of(hitCount, hitCount + missCount);
this.missRate = Percent.ONE_HUNDRED.subtract(hitRate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheStats.java
| 2
|
请完成以下Java代码
|
public UIComponent getUIComponent(
final @NonNull WFProcess wfProcess,
final @NonNull WFActivity wfActivity,
final @NonNull JsonOpts jsonOpts)
{
return UserConfirmationSupportUtil.createUIComponent(
UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity).build()
);
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
return wfActivity.getStatus();
}
@Override
public WFProcess userConfirmed(final UserConfirmationRequest request)
{
ManufacturingJob job = issueForWhatWasReceived(request);
job = jobService.withActivityCompleted(job, extractManufacturingJobActivityId(request));
return ManufacturingRestService.toWFProcess(job);
}
@NonNull
private ManufacturingJob issueForWhatWasReceived(@NonNull final UserConfirmationRequest request)
{
return jobService.autoIssueWhatWasReceived(
extractManufacturingJob(request),
extractIssueStrategy(request)
);
}
@NonNull
private static RawMaterialsIssueStrategy extractIssueStrategy(@NonNull final UserConfirmationRequest request)
{
final ManufacturingJobActivity activity = extractManufacturingJobActivity(request);
final IssueOnlyWhatWasReceivedConfig config = activity.getIssueOnlyWhatWasReceivedConfig();
return config != null ? config.getIssueStrategy() : RawMaterialsIssueStrategy.DEFAULT;
}
@NonNull
|
private static ManufacturingJobActivity extractManufacturingJobActivity(final @NotNull UserConfirmationRequest request)
{
final ManufacturingJob job = extractManufacturingJob(request);
final ManufacturingJobActivityId manufacturingJobActivityId = extractManufacturingJobActivityId(request);
return job.getActivityById(manufacturingJobActivityId);
}
@NonNull
private static ManufacturingJob extractManufacturingJob(final @NotNull UserConfirmationRequest request)
{
return ManufacturingMobileApplication.getManufacturingJob(request.getWfProcess());
}
@NonNull
private static ManufacturingJobActivityId extractManufacturingJobActivityId(final @NotNull UserConfirmationRequest request)
{
return request.getWfActivity().getId().getAsId(ManufacturingJobActivityId.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\RawMaterialsIssueOnlyWhatWasReceivedActivityHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Object createInstance(String configurationClassName) {
try {
Class<?> configurationClass = getClass().getClassLoader().loadClass(configurationClassName);
return configurationClass.newInstance();
} catch (Exception e) {
throw new ProcessEngineException("Could not load '"+configurationClassName+"': the class must be visible from the camunda-wildfly-subsystem module.", e);
}
}
public Injector<TransactionManager> getTransactionManagerInjector() {
return transactionManagerInjector;
}
public Injector<DataSourceReferenceFactoryService> getDatasourceBinderServiceInjector() {
return datasourceBinderServiceInjector;
}
public InjectedValue<MscRuntimeContainerJobExecutor> getMscRuntimeContainerJobExecutorInjector() {
return mscRuntimeContainerJobExecutorInjector;
}
public static void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration, MscManagedProcessEngineController service,
ServiceBuilder<ProcessEngine> serviceBuilder, String jobExecutorName) {
ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName());
|
serviceBuilder.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, service.getTransactionManagerInjector())
.addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, service.getDatasourceBinderServiceInjector())
.addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, service.getRuntimeContainerDelegateInjector())
.addDependency(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName), MscRuntimeContainerJobExecutor.class, service.getMscRuntimeContainerJobExecutorInjector())
.addDependency(ServiceNames.forMscExecutorService())
.setInitialMode(Mode.ACTIVE);
if(processEngineConfiguration.isDefault()) {
serviceBuilder.addAliases(ServiceNames.forDefaultProcessEngine());
}
JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector(), false);
}
public ProcessEngine getProcessEngine() {
return processEngine;
}
public InjectedValue<ExecutorService> getExecutorInjector() {
return executorInjector;
}
public ManagedProcessEngineMetadata getProcessEngineMetadata() {
return processEngineMetadata;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngineController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DemoActivitiesImpl implements DemoActivities {
private static final Logger log = LoggerFactory.getLogger(DemoActivitiesImpl.class);
/**
* Activity executed before waiting for the signal.
*
* <p>Intentionally minimal implementation for demo purposes.
* In production, this would contain pre-signal business logic.
*
* @param cloudEvent the CloudEvent containing input data
*/
@Override
public void before(CloudEvent cloudEvent) {
log.info("Before activity executed with event ID: {}", cloudEvent.getId());
// Intentionally empty - placeholder for demo purposes
|
}
/**
* Activity executed after receiving the signal.
*
* <p>Intentionally minimal implementation for demo purposes.
* In production, this would contain post-signal business logic.
*
* @param cloudEvent the CloudEvent containing input data
*/
@Override
public void after(CloudEvent cloudEvent) {
log.info("After activity executed with event ID: {}", cloudEvent.getId());
// Intentionally empty - placeholder for demo purposes
}
}
|
repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\activities\DemoActivitiesImpl.java
| 2
|
请完成以下Java代码
|
public HistoricCaseActivityInstanceEntity findHistoricCaseActivityInstance(String caseActivityId, String caseInstanceId) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("caseActivityId", caseActivityId);
parameters.put("caseInstanceId", caseInstanceId);
return (HistoricCaseActivityInstanceEntity) getDbEntityManager().selectOne("selectHistoricCaseActivityInstance", parameters);
}
public long findHistoricCaseActivityInstanceCountByQueryCriteria(HistoricCaseActivityInstanceQueryImpl historicCaseActivityInstanceQuery) {
configureHistoricCaseActivityInstanceQuery(historicCaseActivityInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectHistoricCaseActivityInstanceCountByQueryCriteria", historicCaseActivityInstanceQuery);
}
@SuppressWarnings("unchecked")
public List<HistoricCaseActivityInstance> findHistoricCaseActivityInstancesByQueryCriteria(HistoricCaseActivityInstanceQueryImpl historicCaseActivityInstanceQuery, Page page) {
configureHistoricCaseActivityInstanceQuery(historicCaseActivityInstanceQuery);
|
return getDbEntityManager().selectList("selectHistoricCaseActivityInstancesByQueryCriteria", historicCaseActivityInstanceQuery, page);
}
@SuppressWarnings("unchecked")
public List<HistoricCaseActivityInstance> findHistoricCaseActivityInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbEntityManager().selectListWithRawParameter("selectHistoricCaseActivityInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricCaseActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricCaseActivityInstanceCountByNativeQuery", parameterMap);
}
protected void configureHistoricCaseActivityInstanceQuery(HistoricCaseActivityInstanceQueryImpl query) {
getTenantManager().configureQuery(query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricCaseActivityInstanceManager.java
| 1
|
请完成以下Java代码
|
public final IPricingContext create()
{
//
// Create Pricing Context
final IEditablePricingContext pricingCtx = pricingBL.createInitialContext(
-1, // AD_Org_ID - will be set later
-1, // M_Product_ID - will be set later
-1, // billBPartnerId - will be set later
-1, // C_UOM_ID - will be set later
BigDecimal.ZERO, // Qty - will be set later
false // IsSOTrx=false => we are on purchasing side
);
//
// Update pricing context
updatePricingContextFromVendorInvoicingInfo(pricingCtx);
return pricingCtx;
}
/**
* Updates the pricing context from original invoice candidate. Following informations will be set:
* <ul>
* <li>bill bpartner
* <li>pricing system and price list
* <li>currency
* <li>IsSOTrx to <code>false</code>
|
* <li>will NOT be set: product
* </ul>
*
* @param pricingCtx
*/
private void updatePricingContextFromVendorInvoicingInfo(final IEditablePricingContext pricingCtx)
{
final IVendorInvoicingInfo vendorInvoicingInfo = getVendorInvoicingInfo();
//
// Extract infos from original invoice candidate
final BPartnerId billBPartnerId = vendorInvoicingInfo.getBill_BPartner_ID();
final PricingSystemId pricingSytemId = vendorInvoicingInfo.getPricingSystemId();
final CurrencyId currencyId = CurrencyId.ofRepoId(vendorInvoicingInfo.getC_Currency_ID());
final I_M_PriceList_Version priceListVersion = vendorInvoicingInfo.getM_PriceList_Version();
//
// Update pricing context
pricingCtx.setSOTrx(SOTrx.PURCHASE); // we are always on purchase side
pricingCtx.setBPartnerId(billBPartnerId);
pricingCtx.setCurrencyId(currencyId);
pricingCtx.setPricingSystemId(pricingSytemId);
pricingCtx.setPriceListVersionId(PriceListVersionId.ofRepoId(priceListVersion.getM_PriceList_Version_ID()));
pricingCtx.setPriceDate(TimeUtil.asLocalDate(priceListVersion.getValidFrom())); // just to drive home this point
pricingCtx.setCountryId(vendorInvoicingInfo.getCountryId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PricingContextBuilder.java
| 1
|
请完成以下Java代码
|
public static <T> InSetPredicate<T> onlyOrAny(@Nullable final T value)
{
return value != null ? only(value) : any();
}
public static <T> InSetPredicate<T> onlyOrNone(@Nullable final T value)
{
return value != null ? only(value) : none();
}
private static <T> Set<T> toUnmodifiableSet(@NonNull final Collection<T> collection)
{
if (collection.isEmpty())
{
return ImmutableSet.of();
}
else if (collection instanceof ImmutableSet)
{
return (ImmutableSet<T>)collection;
}
else
{
// avoid using ImmutableSet because the given set might contain null values
return Collections.unmodifiableSet(new HashSet<>(collection));
}
}
public boolean isAny() {return mode == Mode.ANY;}
public boolean isNone() {return mode == Mode.NONE;}
public boolean isOnly() {return mode == Mode.ONLY;}
@Override
public boolean test(@Nullable final T value)
{
if (mode == Mode.ANY)
{
return true;
}
else if (mode == Mode.NONE)
{
return false;
}
else if (mode == Mode.ONLY)
{
return onlyValues.contains(value);
}
else
{
throw Check.mkEx("Unknown mode: " + this); // shall not happen
}
}
private void assertNotAny()
{
if (isAny())
{
throw Check.mkEx("Expected predicate to not be ANY");
}
}
public @NonNull Set<T> toSet()
{
assertNotAny();
return onlyValues; // we can return it as is because it's already readonly
}
@SafeVarargs
public final InSetPredicate<T> intersectWith(@NonNull final T... onlyValues)
{
return intersectWith(only(onlyValues));
}
public InSetPredicate<T> intersectWith(@NonNull final Set<T> onlyValues)
{
|
return intersectWith(only(onlyValues));
}
public InSetPredicate<T> intersectWith(@NonNull final InSetPredicate<T> other)
{
if (isNone() || other.isNone())
{
return none();
}
if (isAny())
{
return other;
}
else if (other.isAny())
{
return this;
}
return only(Sets.intersection(this.toSet(), other.toSet()));
}
public interface CaseConsumer<T>
{
void anyValue();
void noValue();
void onlyValues(Set<T> onlyValues);
}
public void apply(@NonNull final CaseConsumer<T> caseConsumer)
{
switch (mode)
{
case ANY:
caseConsumer.anyValue();
break;
case NONE:
caseConsumer.noValue();
break;
case ONLY:
caseConsumer.onlyValues(onlyValues);
break;
default:
throw new IllegalStateException("Unknown mode: " + mode); // shall not happen
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\InSetPredicate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class M_Inventory
{
public static final AdMessageKey MSG_NOT_ALL_LINES_COUNTED = AdMessageKey.of("de.metas.inventory.interceptor.NotAllLinesCounted");
@Init
public void onInit()
{
// Setup event bus topics on which swing client notification listener shall subscribe
Services.get(IEventBusFactory.class).addAvailableUserNotificationsTopic(InventoryUserNotificationsProducer.EVENTBUS_TOPIC);
}
@DocValidate(timings = ModelValidator.TIMING_BEFORE_COMPLETE)
public void onlyCompleteIfCounted(final I_M_Inventory inventory)
{
if (!isPhysicalInventoryDocType(inventory))
{
return; // nothing to do
}
final IInventoryDAO inventoryDAO = Services.get(IInventoryDAO.class);
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
final boolean allLinesCounted = inventoryDAO.retrieveLinesForInventoryId(inventoryId)
.stream()
.allMatch(I_M_InventoryLine::isCounted);
if (!allLinesCounted)
{
throw new AdempiereException(MSG_NOT_ALL_LINES_COUNTED)
.markAsUserValidationError();
|
}
}
private boolean isPhysicalInventoryDocType(final I_M_Inventory inventoryRecord)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(inventoryRecord.getC_DocType_ID());
if (docTypeId == null)
{
return false;
}
final IDocTypeDAO docTypesRepo = Services.get(IDocTypeDAO.class);
final DocBaseAndSubType docBaseAndSubType = docTypesRepo.getDocBaseAndSubTypeById(docTypeId);
return AggregationType.MULTIPLE_HUS.getDocBaseAndSubType().equals(docBaseAndSubType)
|| AggregationType.SINGLE_HU.getDocBaseAndSubType().equals(docBaseAndSubType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\interceptor\M_Inventory.java
| 2
|
请完成以下Java代码
|
public Collection<CaseFileItemDefinition> getCaseFileItemDefinitions() {
return caseFileItemDefinitionCollection.get(this);
}
public Collection<Case> getCases() {
return caseCollection.get(this);
}
public Collection<Process> getProcesses() {
return processCollection.get(this);
}
public Collection<Decision> getDecisions() {
return decisionCollection.get(this);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
public Collection<Relationship> getRelationships() {
return relationshipCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, CMMN_ELEMENT_DEFINITIONS)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() {
public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
});
idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID)
.idAttribute()
.build();
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
targetNamespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_NAMESPACE)
.required()
.build();
expressionLanguageAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue(XPATH_NS)
.build();
|
exporterAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
authorAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHOR)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build();
caseFileItemDefinitionCollection = sequenceBuilder.elementCollection(CaseFileItemDefinition.class)
.build();
caseCollection = sequenceBuilder.elementCollection(Case.class)
.build();
processCollection = sequenceBuilder.elementCollection(Process.class)
.build();
decisionCollection = sequenceBuilder.elementCollection(Decision.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.minOccurs(0)
.maxOccurs(1)
.build();
relationshipCollection = sequenceBuilder.elementCollection(Relationship.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DefinitionsImpl.java
| 1
|
请完成以下Java代码
|
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
if (cmmnEngineConfiguration.isLoggingSessionEnabled()) {
CmmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_ENTER,
"Executing service task with java class " + planItemJavaDelegate.getClass().getName(),
planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper());
}
CompletableFuture<Object> future = planItemJavaDelegate.execute(planItemInstanceEntity, cmmnEngineConfiguration.getAsyncTaskInvoker());
CommandContextUtil.getAgenda(commandContext)
.planFutureOperation(future, new DelegateCompleteAction(planItemInstanceEntity, cmmnEngineConfiguration.isLoggingSessionEnabled()));
}
protected class DelegateCompleteAction implements BiConsumer<Object, Throwable> {
protected final PlanItemInstanceEntity planItemInstance;
protected final boolean loggingSessionEnabled;
public DelegateCompleteAction(PlanItemInstanceEntity planItemInstance, boolean loggingSessionEnabled) {
this.planItemInstance = planItemInstance;
this.loggingSessionEnabled = loggingSessionEnabled;
}
@Override
public void accept(Object value, Throwable throwable) {
|
if (throwable == null) {
planItemJavaDelegate.afterExecution(planItemInstance, value);
if (loggingSessionEnabled) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration();
CmmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXIT,
"Executed service task with java class " + planItemJavaDelegate.getClass().getName(),
planItemInstance, cmmnEngineConfiguration.getObjectMapper());
}
CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(planItemInstance);
} else {
sneakyThrow(throwable);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemFutureJavaDelegateActivityBehavior.java
| 1
|
请完成以下Java代码
|
private static final ZonedDateTime max(final ZonedDateTime date1, final ZonedDateTime date2)
{
if (date1 == null)
{
return date2;
}
else if (date2 == null)
{
return date1;
}
else
{
return date1.isAfter(date2) ? date1 : date2;
}
}
public void updateLastSalesInvoiceInfo(@NonNull final LastInvoiceInfo lastSalesInvoice)
{
if (lastSalesInvoice.isAfter(this.lastSalesInvoice))
{
this.lastSalesInvoice = lastSalesInvoice;
}
}
@Value
@Builder
public static class LastInvoiceInfo
{
@NonNull
private InvoiceId invoiceId;
@NonNull
private LocalDate invoiceDate;
@NonNull
private Money price;
public boolean isAfter(@Nullable LastInvoiceInfo other)
{
|
if (other == null)
{
return true;
}
else if (this.invoiceDate.compareTo(other.invoiceDate) > 0)
{
return true;
}
else if (this.invoiceDate.compareTo(other.invoiceDate) == 0)
{
return this.invoiceId.getRepoId() > other.invoiceId.getRepoId();
}
else // if(this.invoiceDate.compareTo(other.invoiceDate) < 0)
{
return false;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStats.java
| 1
|
请完成以下Java代码
|
public double doubleValue()
{
return value.doubleValue();
}
@Override
public float floatValue()
{
return value.floatValue();
}
@Override
public int intValue()
{
return value.intValue();
}
@Override
public long longValue()
{
return value.longValue();
}
@Override
public short shortValue()
{
return value.shortValue();
}
public void add(final BigDecimal augend)
{
value = value.add(augend);
}
public void subtract(final BigDecimal subtrahend)
{
value = value.subtract(subtrahend);
}
public void multiply(final BigDecimal multiplicand)
{
value = value.multiply(multiplicand);
|
}
public void divide(final BigDecimal divisor, final int scale, final RoundingMode roundingMode)
{
value = value.divide(divisor, scale, roundingMode);
}
public boolean comparesEqualTo(final BigDecimal val)
{
return value.compareTo(val) == 0;
}
public int signum()
{
return value.signum();
}
public MutableBigDecimal min(final MutableBigDecimal value)
{
if (this.value.compareTo(value.getValue()) <= 0)
{
return this;
}
else
{
return value;
}
}
public MutableBigDecimal max(final MutableBigDecimal value)
{
if (this.value.compareTo(value.getValue()) >= 0)
{
return this;
}
else
{
return value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableBigDecimal.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<PmsProduct> list(String keyword) {
PmsProductExample productExample = new PmsProductExample();
PmsProductExample.Criteria criteria = productExample.createCriteria();
criteria.andDeleteStatusEqualTo(0);
if(!StrUtil.isEmpty(keyword)){
criteria.andNameLike("%" + keyword + "%");
productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%");
}
return productMapper.selectByExample(productExample);
}
/**
* 建立和插入关系表操作
*
* @param dao 可以操作的dao
* @param dataList 要插入的数据
* @param productId 建立关系的id
*/
private void relateAndInsertList(Object dao, List dataList, Long productId) {
try {
if (CollectionUtils.isEmpty(dataList)) return;
|
for (Object item : dataList) {
Method setId = item.getClass().getMethod("setId", Long.class);
setId.invoke(item, (Long) null);
Method setProductId = item.getClass().getMethod("setProductId", Long.class);
setProductId.invoke(item, productId);
}
Method insertList = dao.getClass().getMethod("insertList", List.class);
insertList.invoke(dao, dataList);
} catch (Exception e) {
LOGGER.warn("创建商品出错:{}", e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductServiceImpl.java
| 2
|
请完成以下Java代码
|
private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
|
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
}
|
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\avltree\AVLTree.java
| 1
|
请完成以下Java代码
|
public class CellValues
{
public static int extractDisplayTypeFromValue(final Object value)
{
if (value == null)
{
return -1;
}
else if (value instanceof Timestamp)
{
return DisplayType.Date;
// TODO: handle DateTime
}
else if (value instanceof Number)
{
if (value instanceof Integer)
{
return DisplayType.Integer;
}
else
{
return DisplayType.Number;
}
}
else if (value instanceof RepoIdAware)
{
return DisplayType.Integer;
}
else if (value instanceof Boolean)
{
return DisplayType.YesNo;
}
else
{
return DisplayType.String;
}
}
/**
* @return a list that could contain {@code null} values
*/
public static ArrayList<CellValue> toCellValues(@NonNull final List<?> row)
{
final ArrayList<CellValue> result = new ArrayList<>();
for (final Object value : row)
{
result.add(toCellValue(value));
}
return result;
}
public static CellValue toCellValue(@Nullable final Object value)
{
if (value == null)
{
|
return null;
}
final int displayType = extractDisplayTypeFromValue(value);
return toCellValue(value, displayType);
}
public static CellValue toCellValue(final Object value, final int displayType)
{
if (value == null)
{
return null;
}
if (DisplayType.isDate(displayType))
{
final Date date = TimeUtil.asDate(value);
return CellValue.ofDate(date);
}
else if (displayType == DisplayType.Integer)
{
final Integer valueInteger = NumberUtils.asInteger(value, null);
return valueInteger != null
? CellValue.ofNumber(valueInteger)
: null;
}
else if (DisplayType.isNumeric(displayType))
{
if (value instanceof Number)
{
return CellValue.ofNumber((Number)value);
}
else
{
final BigDecimal number = NumberUtils.asBigDecimal(value, null);
return number != null ? CellValue.ofNumber(number) : null;
}
}
else if (displayType == DisplayType.YesNo)
{
final boolean bool = DisplayType.toBoolean(value);
return CellValue.ofBoolean(bool);
}
else
{
return CellValue.ofString(value.toString());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\CellValues.java
| 1
|
请完成以下Java代码
|
private ImmutableListMultimap<ProductId, JsonProductBPartner> retrieveJsonProductVendors(final Set<ProductId> productIds)
{
return servicesFacade.getBPartnerProductRecords(productIds)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
record -> ProductId.ofRepoId(record.getM_Product_ID()),
this::toJsonProductBPartner));
}
private JsonProductBPartner toJsonProductBPartner(final I_C_BPartner_Product record)
{
final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(record);
return JsonProductBPartner.builder()
.bpartnerId(BPartnerId.ofRepoId(record.getC_BPartner_ID()))
//
|
.productNo(record.getProductNo())
.productName(trls.getColumnTrl(I_C_BPartner_Product.COLUMNNAME_ProductName, record.getProductName()).translate(adLanguage))
.productDescription(trls.getColumnTrl(I_C_BPartner_Product.COLUMNNAME_ProductDescription, record.getProductDescription()).translate(adLanguage))
.productCategory(trls.getColumnTrl(I_C_BPartner_Product.COLUMNNAME_ProductCategory, record.getProductCategory()).translate(adLanguage))
//
.ean(record.getUPC())
//
.vendor(record.isUsedForVendor())
.currentVendor(record.isUsedForVendor() && record.isCurrentVendor())
.customer(record.isUsedForCustomer())
//
.leadTimeInDays(record.getDeliveryTime_Promised())
//
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\command\GetProductsCommand.java
| 1
|
请完成以下Java代码
|
public class BPMNTimerConverter {
public TimerPayload convertToTimerPayload(AbstractJobEntity jobEntity) {
TimerPayload timerPayload = new TimerPayload();
timerPayload.setDuedate(jobEntity.getDuedate());
timerPayload.setEndDate(jobEntity.getEndDate());
timerPayload.setRetries(jobEntity.getRetries());
timerPayload.setMaxIterations(jobEntity.getMaxIterations());
timerPayload.setRepeat(jobEntity.getRepeat());
timerPayload.setExceptionMessage(jobEntity.getExceptionMessage());
return timerPayload;
}
public BPMNTimerImpl convertToBPMNTimer(ActivitiEntityEvent internalEvent) {
AbstractJobEntity jobEntity = (AbstractJobEntity) internalEvent.getEntity();
|
BPMNTimerImpl timer = new BPMNTimerImpl(
TimerEventHandler.getActivityIdFromConfiguration(jobEntity.getJobHandlerConfiguration())
);
timer.setProcessDefinitionId(internalEvent.getProcessDefinitionId());
timer.setProcessInstanceId(internalEvent.getProcessInstanceId());
timer.setTimerPayload(convertToTimerPayload(jobEntity));
return timer;
}
public boolean isTimerRelatedEvent(ActivitiEvent event) {
return (
event instanceof ActivitiEntityEvent &&
AbstractJobEntity.class.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass()) &&
((AbstractJobEntity) ((ActivitiEntityEvent) event).getEntity()).getJobType().equals("timer")
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\impl\BPMNTimerConverter.java
| 1
|
请完成以下Java代码
|
public class FileWritingBolt extends BaseRichBolt {
public static Logger logger = LoggerFactory.getLogger(FileWritingBolt.class);
private BufferedWriter writer;
private String filePath;
private ObjectMapper objectMapper;
@Override
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
try {
writer = new BufferedWriter(new FileWriter(filePath));
} catch (IOException e) {
logger.error("Failed to open a file for writing.", e);
}
}
@Override
public void execute(Tuple tuple) {
int sumOfOperations = tuple.getIntegerByField("sumOfOperations");
long beginningTimestamp = tuple.getLongByField("beginningTimestamp");
long endTimestamp = tuple.getLongByField("endTimestamp");
if(sumOfOperations > 200) {
AggregatedWindow aggregatedWindow = new AggregatedWindow(sumOfOperations, beginningTimestamp, endTimestamp);
try {
writer.write(objectMapper.writeValueAsString(aggregatedWindow));
writer.write("\n");
writer.flush();
} catch (IOException e) {
logger.error("Failed to write data to file.", e);
}
}
}
|
public FileWritingBolt(String filePath) {
this.filePath = filePath;
}
@Override
public void cleanup() {
try {
writer.close();
} catch (IOException e) {
logger.error("Failed to close the writer!");
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
}
}
|
repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\storm\bolt\FileWritingBolt.java
| 1
|
请完成以下Java代码
|
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
@Override
public String getValidateFormFields() {
return validateFormFields;
}
@Override
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
public String getTaskIdVariableName() {
return taskIdVariableName;
}
public void setTaskIdVariableName(String taskIdVariableName) {
this.taskIdVariableName = taskIdVariableName;
}
public String getTaskCompleterVariableName() {
return taskCompleterVariableName;
}
public void setTaskCompleterVariableName(String taskCompleterVariableName) {
this.taskCompleterVariableName = taskCompleterVariableName;
}
@Override
public UserTask clone() {
UserTask clone = new UserTask();
clone.setValues(this);
return clone;
}
public void setValues(UserTask otherElement) {
|
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setValidateFormFields(otherElement.getValidateFormFields());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks);
formProperties = new ArrayList<>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (FlowableListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\UserTask.java
| 1
|
请完成以下Java代码
|
public boolean isPickedFrom() {return pickedHUs != null;}
public void assertNotPickedFrom()
{
if (isPickedFrom()) {throw new AdempiereException("Already Picked From");}
}
public void assertNotStarted()
{
Check.assume(status == DDOrderMoveScheduleStatus.NOT_STARTED, "Expected status NOT_STARTED but was {}", status);
}
public void assertPickedFrom()
{
if (!isPickedFrom()) {throw new AdempiereException("Pick from required first");}
}
public void assertInTransit()
{
assertNotDroppedTo();
assertPickedFrom();
}
public void removePickedHUs()
{
this.pickedHUs = null;
this.qtyNotPickedReason = null;
updateStatus();
}
public void markAsPickedFrom(
@Nullable final QtyRejectedReasonCode qtyNotPickedReason,
@NonNull final DDOrderMoveSchedulePickedHUs pickedHUs)
{
assertNotPickedFrom();
final Quantity qtyPicked = pickedHUs.getQtyPicked();
Quantity.assertSameUOM(this.qtyToPick, qtyPicked);
if (qtyPicked.signum() <= 0)
{
throw new AdempiereException("QtyPicked must be greater than zero");
}
if (!this.qtyToPick.qtyAndUomCompareToEquals(qtyPicked))
{
if (qtyNotPickedReason == null)
{
throw new AdempiereException("Reason must be provided when not picking the whole scheduled qty");
}
this.qtyNotPickedReason = qtyNotPickedReason;
}
else
{
this.qtyNotPickedReason = null;
}
this.pickedHUs = pickedHUs;
updateStatus();
}
public boolean isDropTo()
{
return pickedHUs != null && pickedHUs.isDroppedTo();
}
public void assertNotDroppedTo()
{
if (isDropTo())
{
throw new AdempiereException("Already Dropped To");
}
}
|
public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
assertInTransit();
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId);
updateStatus();
}
private void updateStatus()
{
this.status = computeStatus();
}
private DDOrderMoveScheduleStatus computeStatus()
{
if (isDropTo())
{
return DDOrderMoveScheduleStatus.COMPLETED;
}
else if (isPickedFrom())
{
return DDOrderMoveScheduleStatus.IN_PROGRESS;
}
else
{
return DDOrderMoveScheduleStatus.NOT_STARTED;
}
}
@NonNull
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
if (pickedHUs == null)
{
return ExplainedOptional.emptyBecause("Schedule is not picked yet");
}
return pickedHUs.getInTransitLocatorId();
}
@NonNull
public ImmutableSet<HuId> getPickedHUIds()
{
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
return pickedHUs.getActualHUIdsPicked();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
private final OAuth2Properties oAuth2Properties;
public SecurityConfiguration(OAuth2Properties oAuth2Properties) {
this.oAuth2Properties = oAuth2Properties;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
|
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) {
return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient);
}
@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
RestTemplate restTemplate = new RestTemplate();
customizer.customize(restTemplate);
return restTemplate;
}
@Bean
@Qualifier("vanillaRestTemplate")
public RestTemplate vanillaRestTemplate() {
return new RestTemplate();
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\config\SecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public List<HistoricVariableInstance> findHistoricVariableInstancesByQueryCriteria(
HistoricVariableInstanceQueryImpl historicProcessVariableQuery,
Page page
) {
return historicVariableInstanceDataManager.findHistoricVariableInstancesByQueryCriteria(
historicProcessVariableQuery,
page
);
}
@Override
public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
}
@Override
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
List<HistoricVariableInstanceEntity> historicProcessVariables =
historicVariableInstanceDataManager.findHistoricVariableInstancesByTaskId(taskId);
for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
delete((HistoricVariableInstanceEntity) historicProcessVariable);
}
}
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicVariableInstanceDataManager.findHistoricVariableInstancesByNativeQuery(
parameterMap,
firstResult,
maxResults
|
);
}
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
}
public HistoricVariableInstanceDataManager getHistoricVariableInstanceDataManager() {
return historicVariableInstanceDataManager;
}
public void setHistoricVariableInstanceDataManager(
HistoricVariableInstanceDataManager historicVariableInstanceDataManager
) {
this.historicVariableInstanceDataManager = historicVariableInstanceDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setLog_ID (final int Log_ID)
{
if (Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Log_ID, Log_ID);
}
@Override
public int getLog_ID()
{
return get_ValueAsInt(COLUMNNAME_Log_ID);
}
@Override
public void setP_Date (final @Nullable java.sql.Timestamp P_Date)
{
set_ValueNoCheck (COLUMNNAME_P_Date, P_Date);
}
@Override
public java.sql.Timestamp getP_Date()
{
return get_ValueAsTimestamp(COLUMNNAME_P_Date);
}
@Override
public void setP_Msg (final @Nullable java.lang.String P_Msg)
{
set_ValueNoCheck (COLUMNNAME_P_Msg, P_Msg);
}
@Override
public java.lang.String getP_Msg()
{
return get_ValueAsString(COLUMNNAME_P_Msg);
}
@Override
public void setP_Number (final @Nullable BigDecimal P_Number)
{
set_ValueNoCheck (COLUMNNAME_P_Number, P_Number);
}
@Override
public BigDecimal getP_Number()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_P_Number);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
|
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setWarnings (final @Nullable java.lang.String Warnings)
{
set_Value (COLUMNNAME_Warnings, Warnings);
}
@Override
public java.lang.String getWarnings()
{
return get_ValueAsString(COLUMNNAME_Warnings);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Log.java
| 1
|
请完成以下Java代码
|
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddress(from);
}
@Override
public I_C_Invoice_Candidate getWrappedRecord()
{
return delegate;
|
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OverrideBillLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OverrideBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Invoice_Candidate.class));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\location\adapter\OverrideBillLocationAdapter.java
| 1
|
请完成以下Java代码
|
public boolean isDltTopic() {
return Type.DLT.equals(this.type);
}
public boolean isRetryTopic() {
return Type.RETRY.equals(this.type) || Type.REUSABLE_RETRY_TOPIC.equals(this.type);
}
public String suffix() {
return this.suffix;
}
public long delay() {
return this.delayMs;
}
/**
* Return the number of partitions the
* retry topics should be created with.
* @return the number of partitions.
* @since 2.7.13
*/
public int numPartitions() {
return this.numPartitions;
}
@Nullable
public Boolean autoStartDltHandler() {
return this.autoStartDltHandler;
}
public Set<Class<? extends Throwable>> usedForExceptions() {
return this.usedForExceptions;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Properties that = (Properties) o;
return this.delayMs == that.delayMs
&& this.maxAttempts == that.maxAttempts
&& this.numPartitions == that.numPartitions
&& this.suffix.equals(that.suffix)
&& this.type == that.type
&& this.dltStrategy == that.dltStrategy
&& this.kafkaOperations.equals(that.kafkaOperations);
}
@Override
public int hashCode() {
return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions,
|
this.dltStrategy, this.kafkaOperations);
}
@Override
public String toString() {
return "Properties{" +
"delayMs=" + this.delayMs +
", suffix='" + this.suffix + '\'' +
", type=" + this.type +
", maxAttempts=" + this.maxAttempts +
", numPartitions=" + this.numPartitions +
", dltStrategy=" + this.dltStrategy +
", kafkaOperations=" + this.kafkaOperations +
", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout +
'}';
}
public boolean isMainEndpoint() {
return Type.MAIN.equals(this.type);
}
}
enum Type {
MAIN,
RETRY,
/**
* A retry topic reused along sequential retries
* with the same back off interval.
*
* @since 3.0.4
*/
REUSABLE_RETRY_TOPIC,
DLT,
NO_OPS
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java
| 1
|
请完成以下Java代码
|
public Date getDeploymentTime() {
return activiti5Deployment.getDeploymentTime();
}
@Override
public String getCategory() {
return activiti5Deployment.getCategory();
}
@Override
public String getKey() {
return null;
}
@Override
public String getTenantId() {
return activiti5Deployment.getTenantId();
}
@Override
public boolean isNew() {
return ((DeploymentEntity) activiti5Deployment).isNew();
}
@Override
public Map<String, EngineResource> getResources() {
return null;
|
}
@Override
public String getDerivedFrom() {
return null;
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getParentDeploymentId() {
return null;
}
@Override
public String getEngineVersion() {
return Flowable5Util.V5_ENGINE_TAG;
}
public org.activiti.engine.repository.Deployment getRawObject() {
return activiti5Deployment;
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5DeploymentWrapper.java
| 1
|
请完成以下Java代码
|
public static float bytesHighFirstToFloat(byte[] bytes, int start)
{
int l = bytesHighFirstToInt(bytes, start);
return Float.intBitsToFloat(l);
}
/**
* 无符号整型输出
* @param out
* @param uint
* @throws IOException
*/
public static void writeUnsignedInt(DataOutputStream out, int uint) throws IOException
{
out.writeByte((byte) ((uint >>> 8) & 0xFF));
out.writeByte((byte) ((uint >>> 0) & 0xFF));
}
|
public static int convertTwoCharToInt(char high, char low)
{
int result = high << 16;
result |= low;
return result;
}
public static char[] convertIntToTwoChar(int n)
{
char[] result = new char[2];
result[0] = (char) (n >>> 16);
result[1] = (char) (0x0000FFFF & n);
return result;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\ByteUtil.java
| 1
|
请完成以下Java代码
|
public boolean isCamundaAsyncBefore() {
return camundaAsyncBefore.getValue(this);
}
public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) {
camundaAsyncBefore.setValue(this, isCamundaAsyncBefore);
}
public boolean isCamundaAsyncAfter() {
return camundaAsyncAfter.getValue(this);
}
public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) {
camundaAsyncAfter.setValue(this, isCamundaAsyncAfter);
}
public boolean isCamundaExclusive() {
return camundaExclusive.getValue(this);
}
public void setCamundaExclusive(boolean isCamundaExclusive) {
camundaExclusive.setValue(this, isCamundaExclusive);
}
|
public String getCamundaCollection() {
return camundaCollection.getValue(this);
}
public void setCamundaCollection(String expression) {
camundaCollection.setValue(this, expression);
}
public String getCamundaElementVariable() {
return camundaElementVariable.getValue(this);
}
public void setCamundaElementVariable(String variableName) {
camundaElementVariable.setValue(this, variableName);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java
| 1
|
请完成以下Java代码
|
public BaseElement getBpmnElement() {
return bpmnElementAttribute.getReferenceTargetElement(this);
}
public void setBpmnElement(BaseElement bpmnElement) {
bpmnElementAttribute.setReferenceTargetElement(this, bpmnElement);
}
public DiagramElement getSourceElement() {
return sourceElementAttribute.getReferenceTargetElement(this);
}
public void setSourceElement(DiagramElement sourceElement) {
sourceElementAttribute.setReferenceTargetElement(this, sourceElement);
}
public DiagramElement getTargetElement() {
return targetElementAttribute.getReferenceTargetElement(this);
}
public void setTargetElement(DiagramElement targetElement) {
|
targetElementAttribute.setReferenceTargetElement(this, targetElement);
}
public MessageVisibleKind getMessageVisibleKind() {
return messageVisibleKindAttribute.getValue(this);
}
public void setMessageVisibleKind(MessageVisibleKind messageVisibleKind) {
messageVisibleKindAttribute.setValue(this, messageVisibleKind);
}
public BpmnLabel getBpmnLabel() {
return bpmnLabelChild.getChild(this);
}
public void setBpmnLabel(BpmnLabel bpmnLabel) {
bpmnLabelChild.setChild(this, bpmnLabel);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnEdgeImpl.java
| 1
|
请完成以下Java代码
|
public class X_ExternalSystem_Config_WooCommerce extends org.compiere.model.PO implements I_ExternalSystem_Config_WooCommerce, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1117767929L;
/** Standard Constructor */
public X_ExternalSystem_Config_WooCommerce (final Properties ctx, final int ExternalSystem_Config_WooCommerce_ID, @Nullable final String trxName)
{
super (ctx, ExternalSystem_Config_WooCommerce_ID, trxName);
}
/** Load Constructor */
public X_ExternalSystem_Config_WooCommerce (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCamelHttpResourceAuthKey (final @Nullable java.lang.String CamelHttpResourceAuthKey)
{
set_Value (COLUMNNAME_CamelHttpResourceAuthKey, CamelHttpResourceAuthKey);
}
@Override
public java.lang.String getCamelHttpResourceAuthKey()
{
return get_ValueAsString(COLUMNNAME_CamelHttpResourceAuthKey);
}
@Override
public de.metas.externalsystem.model.I_ExternalSystem_Config getExternalSystem_Config()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, de.metas.externalsystem.model.I_ExternalSystem_Config.class);
}
@Override
public void setExternalSystem_Config(final de.metas.externalsystem.model.I_ExternalSystem_Config ExternalSystem_Config)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, de.metas.externalsystem.model.I_ExternalSystem_Config.class, ExternalSystem_Config);
}
|
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystem_Config_WooCommerce_ID (final int ExternalSystem_Config_WooCommerce_ID)
{
if (ExternalSystem_Config_WooCommerce_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_WooCommerce_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_WooCommerce_ID, ExternalSystem_Config_WooCommerce_ID);
}
@Override
public int getExternalSystem_Config_WooCommerce_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_WooCommerce_ID);
}
@Override
public void setExternalSystemValue (final java.lang.String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
}
@Override
public java.lang.String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_WooCommerce.java
| 1
|
请完成以下Java代码
|
public class DataObjectReferenceImpl extends FlowElementImpl implements DataObjectReference {
protected static AttributeReference<ItemDefinition> itemSubjectRefAttribute;
protected static AttributeReference<DataObject> dataObjectRefAttribute;
protected static ChildElement<DataState> dataStateChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataObjectReference.class, BPMN_ELEMENT_DATA_OBJECT_REFERENCE)
.namespaceUri(BPMN20_NS)
.extendsType(FlowElement.class)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<DataObjectReference>() {
public DataObjectReference newInstance(ModelTypeInstanceContext instanceContext) {
return new DataObjectReferenceImpl(instanceContext);
}
});
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
dataObjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DATA_OBJECT_REF)
.idAttributeReference(DataObject.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public DataObjectReferenceImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
|
public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
public DataState getDataState() {
return dataStateChild.getChild(this);
}
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
public DataObject getDataObject() {
return dataObjectRefAttribute.getReferenceTargetElement(this);
}
public void setDataObject(DataObject dataObject) {
dataObjectRefAttribute.setReferenceTargetElement(this, dataObject);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataObjectReferenceImpl.java
| 1
|
请完成以下Java代码
|
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Integer getForwardCount() {
return forwardCount;
}
public void setForwardCount(Integer forwardCount) {
this.forwardCount = forwardCount;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
|
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", title=").append(title);
sb.append(", pic=").append(pic);
sb.append(", productCount=").append(productCount);
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", createTime=").append(createTime);
sb.append(", collectCount=").append(collectCount);
sb.append(", readCount=").append(readCount);
sb.append(", commentCount=").append(commentCount);
sb.append(", albumPics=").append(albumPics);
sb.append(", description=").append(description);
sb.append(", showStatus=").append(showStatus);
sb.append(", forwardCount=").append(forwardCount);
sb.append(", categoryName=").append(categoryName);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionId() {
return superExecutionId;
}
public void setSuperExecutionId(String superExecutionId) {
this.superExecutionId = superExecutionId;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionUrl() {
return superExecutionUrl;
}
public void setSuperExecutionUrl(String superExecutionUrl) {
this.superExecutionUrl = superExecutionUrl;
}
@ApiModelProperty(example = "5")
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5")
|
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public boolean isSuspended() {
return suspended;
}
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
@ApiModelProperty(example = "null")
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int getC_POS_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_ID);
}
@Override
public void setC_POS_Journal_ID (final int C_POS_Journal_ID)
{
if (C_POS_Journal_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, C_POS_Journal_ID);
}
@Override
public int getC_POS_Journal_ID()
{
return get_ValueAsInt(COLUMNNAME_C_POS_Journal_ID);
}
@Override
public void setDateTrx (final java.sql.Timestamp DateTrx)
{
set_Value (COLUMNNAME_DateTrx, DateTrx);
}
@Override
public java.sql.Timestamp getDateTrx()
{
return get_ValueAsTimestamp(COLUMNNAME_DateTrx);
}
@Override
public void setDocumentNo (final java.lang.String DocumentNo)
|
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setIsClosed (final boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, IsClosed);
}
@Override
public boolean isClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsClosed);
}
@Override
public void setOpeningNote (final @Nullable java.lang.String OpeningNote)
{
set_Value (COLUMNNAME_OpeningNote, OpeningNote);
}
@Override
public java.lang.String getOpeningNote()
{
return get_ValueAsString(COLUMNNAME_OpeningNote);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java
| 2
|
请完成以下Java代码
|
private void saveCandidateAndPostCreatedEvent(
@NonNull final PurchaseCandidateRequestedEvent requestedEvent,
@NonNull final PurchaseCandidate newPurchaseCandidate)
{
try
{
INTERCEPTOR_SHALL_POST_EVENT_FOR_PURCHASE_CANDIDATE_RECORD.set(false);
final PurchaseCandidateId newPurchaseCandidateId = purchaseCandidateRepository.save(newPurchaseCandidate);
final PurchaseCandidateCreatedEvent purchaseCandidateCreatedEvent = createCandidateCreatedEvent(requestedEvent,
newPurchaseCandidate.getVendorId(),
newPurchaseCandidateId);
postMaterialEventService.enqueueEventAfterNextCommit(purchaseCandidateCreatedEvent);
}
finally
{
INTERCEPTOR_SHALL_POST_EVENT_FOR_PURCHASE_CANDIDATE_RECORD.set(true);
|
}
}
@VisibleForTesting
static PurchaseCandidateCreatedEvent createCandidateCreatedEvent(
@NonNull final PurchaseCandidateRequestedEvent requestedEvent,
@NonNull final BPartnerId vendorId,
@NonNull final PurchaseCandidateId newPurchaseCandidateId)
{
return PurchaseCandidateCreatedEvent.builder()
.eventDescriptor(requestedEvent.getEventDescriptor().withNewEventId())
.purchaseCandidateRepoId(newPurchaseCandidateId.getRepoId())
.vendorId(vendorId.getRepoId())
.purchaseMaterialDescriptor(requestedEvent.getPurchaseMaterialDescriptor())
.supplyCandidateRepoId(requestedEvent.getSupplyCandidateRepoId())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\material\event\PurchaseCandidateRequestedHandler.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(SecondBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(5)
.measurementIterations(2)
.build();
Collection<RunResult> results = new Runner(opt).run();
ResultExporter.exportResult("单线程与多线程求和性能", results, "length", "微秒");
}
@Benchmark
public long singleThreadBench() {
return singleThreadCalc.sum(numbers);
}
@Benchmark
public long multiThreadBench() {
return multiThreadCalc.sum(numbers);
|
}
@Setup
public void prepare() {
numbers = IntStream.rangeClosed(1, length).toArray();
singleThreadCalc = new SinglethreadCalculator();
multiThreadCalc = new MultithreadCalculator(Runtime.getRuntime().availableProcessors());
}
@TearDown
public void shutdown() {
singleThreadCalc.shutdown();
multiThreadCalc.shutdown();
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\sum\SecondBenchmark.java
| 1
|
请完成以下Java代码
|
public String[] getProcessDefinitionIdIn() {
return processDefinitionIdIn;
}
public String[] getProcessDefinitionKeyIn() {
return processDefinitionKeyIn;
}
public String[] getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
|
public boolean isCompact() {
return isCompact;
}
protected void provideHistoryCleanupStrategy(CommandContext commandContext) {
String historyCleanupStrategy = commandContext.getProcessEngineConfiguration()
.getHistoryCleanupStrategy();
isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy);
}
public boolean isHistoryCleanupStrategyRemovalTimeBased() {
return isHistoryCleanupStrategyRemovalTimeBased;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricProcessInstanceReportImpl.java
| 1
|
请完成以下Java代码
|
public void validate(MigratingActivityInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingActivityInstanceValidationReportImpl instanceReport) {
if (isInvalid(migratingInstance)) {
instanceReport.addFailure("There is no migration instruction for this instance's activity");
}
}
@Override
public void validate(MigratingTransitionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingTransitionInstanceValidationReportImpl instanceReport) {
if (isInvalid(migratingInstance)) {
instanceReport.addFailure("There is no migration instruction for this instance's activity");
}
}
@Override
public void validate(MigratingCompensationEventSubscriptionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) {
if (isInvalid(migratingInstance)) {
ancestorInstanceReport.addFailure(
"Cannot migrate subscription for compensation handler '" + migratingInstance.getSourceScope().getId() + "'. "
+ "There is no migration instruction for the compensation boundary event");
}
}
@Override
public void validate(MigratingEventScopeInstance migratingInstance, MigratingProcessInstance migratingProcessInstance,
MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) {
if (isInvalid(migratingInstance)) {
ancestorInstanceReport.addFailure(
"Cannot migrate subscription for compensation handler '" + migratingInstance.getEventSubscription().getSourceScope().getId() + "'. "
|
+ "There is no migration instruction for the compensation start event");
}
}
protected boolean isInvalid(MigratingActivityInstance migratingInstance) {
return hasNoInstruction(migratingInstance) && migratingInstance.getChildren().isEmpty();
}
protected boolean isInvalid(MigratingEventScopeInstance migratingInstance) {
return hasNoInstruction(migratingInstance.getEventSubscription()) && migratingInstance.getChildren().isEmpty();
}
protected boolean isInvalid(MigratingTransitionInstance migratingInstance) {
return hasNoInstruction(migratingInstance);
}
protected boolean isInvalid(MigratingCompensationEventSubscriptionInstance migratingInstance) {
return hasNoInstruction(migratingInstance);
}
protected boolean hasNoInstruction(MigratingProcessElementInstance migratingInstance) {
return migratingInstance.getMigrationInstruction() == null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\NoUnmappedLeafInstanceValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class ElasticsearchClientConfigurations {
@Import({ JacksonJsonpMapperConfiguration.class, Jackson2JsonpMapperConfiguration.class,
JsonbJsonpMapperConfiguration.class, SimpleJsonpMapperConfiguration.class })
static class JsonpMapperConfiguration {
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(JsonpMapper.class)
@ConditionalOnClass(JsonMapper.class)
static class JacksonJsonpMapperConfiguration {
@Bean
Jackson3JsonpMapper jacksonJsonpMapper() {
return new Jackson3JsonpMapper();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(JsonpMapper.class)
@ConditionalOnClass(ObjectMapper.class)
@Deprecated(since = "4.0.0", forRemoval = true)
static class Jackson2JsonpMapperConfiguration {
@Bean
JacksonJsonpMapper jacksonJsonpMapper() {
return new JacksonJsonpMapper();
}
}
@ConditionalOnMissingBean(JsonpMapper.class)
@ConditionalOnBean(Jsonb.class)
@Configuration(proxyBeanMethods = false)
static class JsonbJsonpMapperConfiguration {
@Bean
JsonbJsonpMapper jsonbJsonpMapper(Jsonb jsonb) {
return new JsonbJsonpMapper(JsonProvider.provider(), jsonb);
}
}
@ConditionalOnMissingBean(JsonpMapper.class)
@Configuration(proxyBeanMethods = false)
static class SimpleJsonpMapperConfiguration {
@Bean
SimpleJsonpMapper simpleJsonpMapper() {
return new SimpleJsonpMapper();
}
|
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(ElasticsearchTransport.class)
static class ElasticsearchTransportConfiguration {
@Bean
Rest5ClientTransport restClientTransport(Rest5Client restClient, JsonpMapper jsonMapper,
ObjectProvider<Rest5ClientOptions> restClientOptions) {
return new Rest5ClientTransport(restClient, jsonMapper, restClientOptions.getIfAvailable());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ElasticsearchTransport.class)
static class ElasticsearchClientConfiguration {
@Bean
@ConditionalOnMissingBean
ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) {
return new ElasticsearchClient(transport);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchClientConfigurations.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void newAuthor() {
Author author = new Author();
author.setId(1L);
author.setName("Joana Nimar");
author.setGenre("History");
author.setAge(34);
authorRepository.save(author);
|
}
public void fetchAuthor() {
Author author = authorRepository.findById(1L).orElseThrow();
System.out.println(author);
}
@Transactional
public void updateAuthor() {
Author author = authorRepository.findById(1L).orElseThrow();
author.setAge(45);
}
public void deleteAuthor() {
authorRepository.deleteById(1L);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootImmutableEntity\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public class AD_Table_CopyColumnsToAllImportTables extends JavaProcess implements IProcessPrecondition
{
private final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class);
private static final String TABLENAME_X_ImportTableTemplate = "X_ImportTableTemplate";
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final AdTableId adTableId = AdTableId.ofRepoId(context.getSingleSelectedRecordId());
String tableName = adTablesRepo.retrieveTableName(adTableId);
if (!TABLENAME_X_ImportTableTemplate.equals(tableName))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Not the import table template");
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt()
|
{
final I_AD_Table importTableTemplate = adTablesRepo.retrieveTable(TABLENAME_X_ImportTableTemplate);
final List<I_AD_Column> importTableTemplateColumns = adTablesRepo.retrieveColumnsForTable(importTableTemplate);
for (final I_AD_Table importTable : adTablesRepo.retrieveAllImportTables())
{
final CopyColumnsResult result = CopyColumnsProducer.newInstance()
.setLogger(Loggables.nop())
.setTargetTable(importTable)
.setSourceColumns(importTableTemplateColumns)
.setSyncDatabase(true)
.create();
addLog("" + result);
}
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\AD_Table_CopyColumnsToAllImportTables.java
| 1
|
请完成以下Java代码
|
protected List<CellValue> getNextRow()
{
return CellValues.toCellValues(getNextRawDataRow());
}
private List<Object> getNextRawDataRow()
{
try
{
final List<Object> row = new ArrayList<>();
for (int col = 1; col <= getColumnCount(); col++)
{
final Object o = m_resultSet.getObject(col);
row.add(o);
}
noDataAddedYet = false;
return row;
}
catch (final SQLException e)
{
|
throw DBException.wrapIfNeeded(e);
}
}
@Override
protected boolean hasNextRow()
{
try
{
return m_resultSet.next();
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\JdbcExcelExporter.java
| 1
|
请完成以下Java代码
|
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
@Override
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Steuerbetrag.
@param TaxAmt
Tax Amount for a document
*/
@Override
|
public void setTaxAmt (java.math.BigDecimal TaxAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Steuerbetrag.
@return Tax Amount for a document
*/
@Override
public java.math.BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Bezugswert.
@param TaxBaseAmt
Base for calculating the tax amount
*/
@Override
public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
/** Get Bezugswert.
@return Base for calculating the tax amount
*/
@Override
public java.math.BigDecimal getTaxBaseAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationLine.java
| 1
|
请完成以下Java代码
|
public void setIsAddressLinesReverse (boolean IsAddressLinesReverse)
{
set_Value (COLUMNNAME_IsAddressLinesReverse, Boolean.valueOf(IsAddressLinesReverse));
}
/** Get Reverse Address Lines.
@return Print Address in reverse Order
*/
@Override
public boolean isAddressLinesReverse ()
{
Object oo = get_Value(COLUMNNAME_IsAddressLinesReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Media Size.
@param MediaSize
Java Media Size
*/
@Override
public void setMediaSize (java.lang.String MediaSize)
{
set_Value (COLUMNNAME_MediaSize, MediaSize);
}
/** Get Media Size.
@return Java Media Size
*/
@Override
public java.lang.String getMediaSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_MediaSize);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
|
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Region.
@param RegionName
Name of the Region
*/
@Override
public void setRegionName (java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name of the Region
*/
@Override
public java.lang.String getRegionName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RegionName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country.java
| 1
|
请完成以下Java代码
|
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] paramValues
) {
return child.invoke(bindings, context, returnType, paramTypes, paramValues);
}
public Class<?> getType(Bindings bindings, ELContext context) {
return child.getType(bindings, context);
}
public boolean isLiteralText() {
return child.isLiteralText();
}
|
public boolean isReadOnly(Bindings bindings, ELContext context) {
return child.isReadOnly(bindings, context);
}
public void setValue(Bindings bindings, ELContext context, Object value) {
child.setValue(bindings, context, value);
}
public int getCardinality() {
return 1;
}
public AstNode getChild(int i) {
return i == 0 ? child : null;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstEval.java
| 1
|
请完成以下Java代码
|
public WFProcess pickAll(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
final PickingJob pickingJob = pickingJobRestService.pickAll(pickingJobId, callerId);
return toWFProcess(pickingJob);
}
public PickingJobQtyAvailable getQtyAvailable(final WFProcessId wfProcessId, final @NotNull UserId callerId)
{
final PickingJobId pickingJobId = toPickingJobId(wfProcessId);
return pickingJobRestService.getQtyAvailable(pickingJobId, callerId);
}
public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(final @NonNull JsonGetNextEligibleLineRequest request, final @NotNull UserId callerId)
{
|
final GetNextEligibleLineToPackResponse response = pickingJobRestService.getNextEligibleLineToPack(
GetNextEligibleLineToPackRequest.builder()
.callerId(callerId)
.pickingJobId(toPickingJobId(request.getWfProcessId()))
.excludeLineId(request.getExcludeLineId())
.huScannedCode(request.getHuScannedCode())
.build()
);
return JsonGetNextEligibleLineResponse.builder()
.lineId(response.getLineId())
.logs(response.getLogs())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\PickingMobileApplication.java
| 1
|
请完成以下Java代码
|
public int getDataEntry_Record_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set DataEntry_RecordData.
@param DataEntry_RecordData
Holds the (JSON-)data of all fields for a data entry. The json is supposed to be rendered into the respective fields, the column is not intended for actual display
*/
@Override
public void setDataEntry_RecordData (java.lang.String DataEntry_RecordData)
{
set_Value (COLUMNNAME_DataEntry_RecordData, DataEntry_RecordData);
}
/** Get DataEntry_RecordData.
@return Holds the (JSON-)data of all fields for a data entry. The json is supposed to be rendered into the respective fields, the column is not intended for actual display
*/
@Override
public java.lang.String getDataEntry_RecordData ()
{
return (java.lang.String)get_Value(COLUMNNAME_DataEntry_RecordData);
}
@Override
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class);
}
@Override
public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab)
{
set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab);
}
/** Set Unterregister.
@param DataEntry_SubTab_ID Unterregister */
@Override
public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID)
{
if (DataEntry_SubTab_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null);
|
else
set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID));
}
/** Get Unterregister.
@return Unterregister */
@Override
public int getDataEntry_SubTab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
| 1
|
请完成以下Java代码
|
public class BusinessKnowledgeModelImpl extends DrgElementImpl implements BusinessKnowledgeModel {
protected static ChildElement<EncapsulatedLogic> encapsulatedLogicChild;
protected static ChildElement<Variable> variableChild;
protected static ChildElementCollection<KnowledgeRequirement> knowledgeRequirementCollection;
protected static ChildElementCollection<AuthorityRequirement> authorityRequirementCollection;
public BusinessKnowledgeModelImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public EncapsulatedLogic getEncapsulatedLogic() {
return encapsulatedLogicChild.getChild(this);
}
public void setEncapsulatedLogic(EncapsulatedLogic encapsulatedLogic) {
encapsulatedLogicChild.setChild(this, encapsulatedLogic);
}
public Variable getVariable() {
return variableChild.getChild(this);
}
public void setVariable(Variable variable) {
variableChild.setChild(this, variable);
}
public Collection<KnowledgeRequirement> getKnowledgeRequirement() {
return knowledgeRequirementCollection.get(this);
}
public Collection<AuthorityRequirement> getAuthorityRequirement() {
return authorityRequirementCollection.get(this);
|
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BusinessKnowledgeModel.class, DMN_ELEMENT_BUSINESS_KNOWLEDGE_MODEL)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DrgElement.class)
.instanceProvider(new ModelTypeInstanceProvider<BusinessKnowledgeModel>() {
public BusinessKnowledgeModel newInstance(ModelTypeInstanceContext instanceContext) {
return new BusinessKnowledgeModelImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
encapsulatedLogicChild = sequenceBuilder.element(EncapsulatedLogic.class)
.build();
variableChild = sequenceBuilder.element(Variable.class)
.build();
knowledgeRequirementCollection = sequenceBuilder.elementCollection(KnowledgeRequirement.class)
.build();
authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\BusinessKnowledgeModelImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void init(AuthenticationManagerBuilder auth) {
auth.apply(new InitializeAuthenticationProviderManagerConfigurer());
}
class InitializeAuthenticationProviderManagerConfigurer extends GlobalAuthenticationConfigurerAdapter {
private final Log logger = LogFactory.getLog(getClass());
@Override
public void configure(AuthenticationManagerBuilder auth) {
if (auth.isConfigured()) {
return;
}
String[] beanNames = InitializeAuthenticationProviderBeanManagerConfigurer.this.context
.getBeanNamesForType(AuthenticationProvider.class);
if (beanNames.length == 0) {
return;
}
else if (beanNames.length > 1) {
this.logger.info(LogMessage.format("Found %s AuthenticationProvider beans, with names %s. "
+ "Global Authentication Manager will not be configured with AuthenticationProviders. "
|
+ "Consider publishing a single AuthenticationProvider bean, or wiring your Providers directly "
+ "using the DSL.", beanNames.length, Arrays.toString(beanNames)));
return;
}
AuthenticationProvider authenticationProvider = InitializeAuthenticationProviderBeanManagerConfigurer.this.context
.getBean(beanNames[0], AuthenticationProvider.class);
auth.authenticationProvider(authenticationProvider);
this.logger.info(LogMessage.format(
"Global AuthenticationManager configured with AuthenticationProvider bean with name %s",
beanNames[0]));
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\InitializeAuthenticationProviderBeanManagerConfigurer.java
| 2
|
请完成以下Java代码
|
public class CoapAdaptorUtils {
public static TransportProtos.GetAttributeRequestMsg toGetAttributeRequestMsg(Request inbound) throws AdaptorException {
List<String> queryElements = inbound.getOptions().getUriQuery();
TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder();
if (queryElements != null && queryElements.size() > 0) {
Set<String> clientKeys = toKeys(queryElements, "clientKeys");
Set<String> sharedKeys = toKeys(queryElements, "sharedKeys");
if (clientKeys != null) {
result.addAllClientAttributeNames(clientKeys);
}
if (sharedKeys != null) {
result.addAllSharedAttributeNames(sharedKeys);
}
}
result.setOnlyShared(false);
return result.build();
}
|
private static Set<String> toKeys(List<String> queryElements, String attributeName) throws AdaptorException {
String keys = null;
for (String queryElement : queryElements) {
String[] queryItem = queryElement.split("=");
if (queryItem.length == 2 && queryItem[0].equals(attributeName)) {
keys = queryItem[1];
}
}
if (keys != null && !StringUtils.isEmpty(keys)) {
return new HashSet<>(Arrays.asList(keys.split(",")));
} else {
return null;
}
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\adaptors\CoapAdaptorUtils.java
| 1
|
请完成以下Java代码
|
public int getC_Currency_ID_To ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID_To);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Divisor.
@param DivideRate
To convert Source number to Target number, the Source is divided
*/
@Override
public void setDivideRate (java.math.BigDecimal DivideRate)
{
set_Value (COLUMNNAME_DivideRate, DivideRate);
}
/** Get Divisor.
@return To convert Source number to Target number, the Source is divided
*/
@Override
public java.math.BigDecimal getDivideRate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Faktor.
@param MultiplyRate
Rate to multiple the source by to calculate the target.
*/
@Override
public void setMultiplyRate (java.math.BigDecimal MultiplyRate)
{
set_Value (COLUMNNAME_MultiplyRate, MultiplyRate);
}
/** Get Faktor.
@return Rate to multiple the source by to calculate the target.
*/
@Override
public java.math.BigDecimal getMultiplyRate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Gültig ab.
|
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Conversion_Rate.java
| 1
|
请完成以下Java代码
|
public class SetMaxAgeHeaderAfterCacheExchangeMutator implements AfterCacheExchangeMutator {
private static final String MAX_AGE_PREFIX = "max-age=";
private final Duration configuredTimeToLive;
private final Clock clock;
private final boolean ignoreNoCacheUpdate;
public SetMaxAgeHeaderAfterCacheExchangeMutator(Duration configuredTimeToLive, Clock clock,
boolean ignoreNoCacheUpdate) {
this.configuredTimeToLive = configuredTimeToLive;
this.clock = clock;
this.ignoreNoCacheUpdate = ignoreNoCacheUpdate;
}
@Override
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) {
ServerHttpResponse response = exchange.getResponse();
long calculatedMaxAgeInSeconds = calculateMaxAgeInSeconds(exchange.getRequest(), cachedResponse,
configuredTimeToLive);
rewriteCacheControlMaxAge(response.getHeaders(), calculatedMaxAgeInSeconds);
}
private long calculateMaxAgeInSeconds(ServerHttpRequest request, CachedResponse cachedResponse,
Duration configuredTimeToLive) {
boolean noCache = LocalResponseCacheUtils.isNoCacheRequest(request);
long maxAge;
if (noCache && ignoreNoCacheUpdate || configuredTimeToLive.getSeconds() < 0) {
maxAge = 0;
}
else {
long calculatedMaxAge = configuredTimeToLive.minus(getElapsedTimeInSeconds(cachedResponse)).getSeconds();
maxAge = Math.max(0, calculatedMaxAge);
}
return maxAge;
}
private Duration getElapsedTimeInSeconds(CachedResponse cachedResponse) {
return Duration.ofMillis(clock.millis() - cachedResponse.timestamp().getTime());
}
private static void rewriteCacheControlMaxAge(HttpHeaders headers, long seconds) {
boolean isMaxAgePresent = headers.getCacheControl() != null
|
&& headers.getCacheControl().contains(MAX_AGE_PREFIX);
List<String> newCacheControlDirectives = new ArrayList<>();
if (isMaxAgePresent) {
List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL);
cacheControlHeaders = cacheControlHeaders == null ? Collections.emptyList() : cacheControlHeaders;
for (String value : cacheControlHeaders) {
if (value.contains(MAX_AGE_PREFIX)) {
if (seconds == -1) {
List<String> removedMaxAgeList = Arrays.stream(value.split(","))
.filter(i -> !i.trim().startsWith(MAX_AGE_PREFIX))
.collect(Collectors.toList());
value = String.join(",", removedMaxAgeList);
}
else {
value = value.replaceFirst("\\bmax-age=\\d+\\b", MAX_AGE_PREFIX + seconds);
}
}
newCacheControlDirectives.add(value);
}
}
else {
List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL);
newCacheControlDirectives = cacheControlHeaders == null ? new ArrayList<>()
: new ArrayList<>(cacheControlHeaders);
newCacheControlDirectives.add("max-age=" + seconds);
}
headers.remove(HttpHeaders.CACHE_CONTROL);
headers.addAll(HttpHeaders.CACHE_CONTROL, newCacheControlDirectives);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\postprocessor\SetMaxAgeHeaderAfterCacheExchangeMutator.java
| 1
|
请完成以下Java代码
|
public int getAD_Process_Access_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Access_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Process getAD_Process() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process(org.compiere.model.I_AD_Process AD_Process)
{
set_ValueFromPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class, AD_Process);
}
/** Set Prozess.
@param AD_Process_ID
Process or Report
*/
@Override
public void setAD_Process_ID (int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID));
}
/** Get Prozess.
@return Process or Report
*/
@Override
public int getAD_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
|
/** Set Rolle.
@param AD_Role_ID
Responsibility Role
*/
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Rolle.
@return Responsibility Role
*/
@Override
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Access.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<FileEvidence> getFiles()
{
return files;
}
public void setFiles(List<FileEvidence> files)
{
this.files = files;
}
public AddEvidencePaymentDisputeRequest lineItems(List<OrderLineItems> lineItems)
{
this.lineItems = lineItems;
return this;
}
public AddEvidencePaymentDisputeRequest addLineItemsItem(OrderLineItems lineItemsItem)
{
if (this.lineItems == null)
{
this.lineItems = new ArrayList<>();
}
this.lineItems.add(lineItemsItem);
return this;
}
/**
* This required array identifies the order line item(s) for which the evidence file(s) will be applicable. Both the itemId and lineItemID fields are needed to identify each order line item, and both of these values are returned under the evidenceRequests.lineItems array in the getPaymentDispute response.
*
* @return lineItems
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "This required array identifies the order line item(s) for which the evidence file(s) will be applicable. Both the itemId and lineItemID fields are needed to identify each order line item, and both of these values are returned under the evidenceRequests.lineItems array in the getPaymentDispute response.")
public List<OrderLineItems> getLineItems()
{
return lineItems;
}
public void setLineItems(List<OrderLineItems> lineItems)
{
this.lineItems = lineItems;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
AddEvidencePaymentDisputeRequest addEvidencePaymentDisputeRequest = (AddEvidencePaymentDisputeRequest)o;
return Objects.equals(this.evidenceType, addEvidencePaymentDisputeRequest.evidenceType) &&
Objects.equals(this.files, addEvidencePaymentDisputeRequest.files) &&
Objects.equals(this.lineItems, addEvidencePaymentDisputeRequest.lineItems);
}
@Override
public int hashCode()
|
{
return Objects.hash(evidenceType, files, lineItems);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class AddEvidencePaymentDisputeRequest {\n");
sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n");
sb.append(" files: ").append(toIndentedString(files)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AddEvidencePaymentDisputeRequest.java
| 2
|
请完成以下Java代码
|
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
/**
* DocStatus AD_Reference_ID=131
* Reference name: _Document Status
*/
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */
public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** NotApproved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */
public static final String DOCSTATUS_Invalid = "IN";
/** Reversed = RE */
|
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** InProgress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** WaitingConfirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
@Override
public void setDocStatus (final @Nullable java.lang.String DocStatus)
{
throw new IllegalArgumentException ("DocStatus is virtual column"); }
@Override
public java.lang.String getDocStatus()
{
return get_ValueAsString(COLUMNNAME_DocStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Term_Alloc.java
| 1
|
请完成以下Java代码
|
public void setSortOrder(String sortOrder) {
if (!VALID_SORT_ORDER_VALUES.contains(sortOrder)) {
throw new InvalidRequestException(Status.BAD_REQUEST, "sortOrder parameter has invalid value: " + sortOrder);
}
this.sortOrder = sortOrder;
}
public void setSorting(List<SortingDto> sorting) {
this.sortings = sorting;
}
public List<SortingDto> getSorting() {
return sortings;
}
protected abstract boolean isValidSortByValue(String value);
protected boolean sortOptionsValid() {
return (sortBy != null && sortOrder != null) || (sortBy == null && sortOrder == null);
}
public T toQuery(ProcessEngine engine) {
T query = createNewQuery(engine);
applyFilters(query);
if (!sortOptionsValid()) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Only a single sorting parameter specified. sortBy and sortOrder required");
}
applySortingOptions(query, engine);
return query;
}
protected abstract T createNewQuery(ProcessEngine engine);
protected abstract void applyFilters(T query);
protected void applySortingOptions(T query, ProcessEngine engine) {
if (sortBy != null) {
applySortBy(query, sortBy, null, engine);
}
if (sortOrder != null) {
applySortOrder(query, sortOrder);
}
if (sortings != null) {
for (SortingDto sorting : sortings) {
String sortingOrder = sorting.getSortOrder();
String sortingBy = sorting.getSortBy();
if (sortingBy != null) {
|
applySortBy(query, sortingBy, sorting.getParameters(), engine);
}
if (sortingOrder != null) {
applySortOrder(query, sortingOrder);
}
}
}
}
protected abstract void applySortBy(T query, String sortBy, Map<String, Object> parameters, ProcessEngine engine);
protected void applySortOrder(T query, String sortOrder) {
if (sortOrder != null) {
if (sortOrder.equals(SORT_ORDER_ASC_VALUE)) {
query.asc();
} else if (sortOrder.equals(SORT_ORDER_DESC_VALUE)) {
query.desc();
}
}
}
public static String sortOrderValueForDirection(Direction direction) {
if (Direction.ASCENDING.equals(direction)) {
return SORT_ORDER_ASC_VALUE;
}
else if (Direction.DESCENDING.equals(direction)) {
return SORT_ORDER_DESC_VALUE;
}
else {
throw new RestException("Unknown query sorting direction " + direction);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractQueryDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AlipayCore {
/**
* 调试用,创建TXT日志文件夹路径
*/
private static final String LOG_PATH = AlipayConfigUtil.readConfig("log_path");
/**
* 除去数组中的空值和签名参数
* @param sArray 签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<String, String>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* @param sWord 要写入日志里的文本内容
*/
public static void logResult(String sWord) {
FileWriter writer = null;
try {
writer = new FileWriter(LOG_PATH + "alipay_log_" + System.currentTimeMillis()+".txt");
|
writer.write(sWord);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 生成文件摘要
* @param strFilePath 文件路径
* @param file_digest_type 摘要算法
* @return 文件摘要结果
*/
public static String getAbstract(String strFilePath, String file_digest_type) throws IOException {
PartSource file = new FilePartSource(new File(strFilePath));
if(file_digest_type.equals("MD5")){
return DigestUtils.md5Hex(file.createInputStream());
}
else if(file_digest_type.equals("SHA")) {
return DigestUtils.sha256Hex(file.createInputStream());
}
else {
return "";
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\AlipayCore.java
| 2
|
请完成以下Java代码
|
private ViewId createView(final KPIZoomIntoDetailsInfo detailsInfo)
{
final WindowId targetWindowId = getTargetWindowId(detailsInfo);
return viewRepo.createView(CreateViewRequest.builder(targetWindowId)
.addStickyFilters(DocumentFilter.builder()
.filterId("userDashboardItem")
.caption(detailsInfo.getFilterCaption())
.addParameter(DocumentFilterParam.ofSqlWhereClause(detailsInfo.getSqlWhereClause()))
.build())
.setUseAutoFilters(true)
.build())
.getViewId();
}
private WindowId getTargetWindowId(final KPIZoomIntoDetailsInfo detailsInfo)
{
final WindowId targetWindowId = detailsInfo.getTargetWindowId();
if (targetWindowId != null)
{
return targetWindowId;
}
return RecordWindowFinder.findAdWindowId(detailsInfo.getTableName())
.map(WindowId::of)
.orElseThrow(() -> new AdempiereException("No window available to show the details"));
}
@PatchMapping("/kpis/{itemId}")
public JSONDashboardItem changeKPIItem(@PathVariable("itemId") final int itemId, @RequestBody final List<JSONPatchEvent<DashboardItemPatchPath>> events)
{
return changeDashboardItem(DashboardWidgetType.KPI, UserDashboardItemId.ofRepoId(itemId), events);
}
@PatchMapping("/targetIndicators/{itemId}")
public JSONDashboardItem changeTargetIndicatorItem(@PathVariable("itemId") final int itemId, @RequestBody final List<JSONPatchEvent<DashboardItemPatchPath>> events)
{
return changeDashboardItem(DashboardWidgetType.TargetIndicator, UserDashboardItemId.ofRepoId(itemId), events);
}
private JSONDashboardItem changeDashboardItem(
final DashboardWidgetType widgetType,
final UserDashboardItemId itemId,
final List<JSONPatchEvent<DashboardItemPatchPath>> events)
{
|
userSession.assertLoggedIn();
//
// Change the dashboard item
final UserDashboardItemChangeRequest request = UserDashboardItemChangeRequest.of(widgetType, itemId, userSession.getAD_Language(), events);
final UserDashboardItemChangeResult changeResult = dashboardRepo.changeUserDashboardItem(getUserDashboard().get(), request);
//
// Notify on websocket
final UserDashboard dashboard = getUserDashboard().get();
websocketSender.sendDashboardItemChangedEvent(dashboard, changeResult);
// Return the changed item
{
final UserDashboardItem item = dashboard.getItemById(widgetType, itemId);
final UserDashboardItemDataResponse data = dashboardDataService.getData(dashboard.getId())
.getItemData(UserDashboardItemDataRequest.builder()
.itemId(item.getId())
.widgetType(widgetType)
.context(KPIDataContext.ofUserSession(userSession))
.build());
return JSONDashboardItem.of(item, data, newKPIJsonOptions());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\DashboardRestController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class UpdateShipmentScheduleRequest
{
@NonNull
ShipmentScheduleId shipmentScheduleId;
@Nullable
ZonedDateTime deliveryDate;
@Nullable
LocationBasicInfo bPartnerLocation;
@Nullable
String bPartnerCode;
@Nullable
List<CreateAttributeInstanceReq> attributes;
@Nullable
DeliveryRule deliveryRule;
@Nullable
ShipperId shipperId;
@Builder
public UpdateShipmentScheduleRequest(
@NonNull final ShipmentScheduleId shipmentScheduleId,
@Nullable final ZonedDateTime deliveryDate,
@Nullable final LocationBasicInfo bPartnerLocation,
@Nullable final String bPartnerCode,
@Nullable final DeliveryRule deliveryRule,
@Nullable final List<CreateAttributeInstanceReq> attributes,
@Nullable final ShipperId shipperId)
{
if (Check.isNotBlank(bPartnerCode) && bPartnerLocation == null)
{
|
throw new AdempiereException("Invalid request! The bPartenr cannot be changed without changing the location!");
}
if (deliveryDate == null
&& bPartnerLocation == null
&& Check.isBlank(bPartnerCode)
&& Check.isEmpty(attributes)
&& deliveryRule == null
&& shipperId == null)
{
throw new AdempiereException("Empty request");
}
this.shipmentScheduleId = shipmentScheduleId;
this.deliveryDate = deliveryDate;
this.bPartnerLocation = bPartnerLocation;
this.bPartnerCode = bPartnerCode;
this.attributes = attributes;
this.deliveryRule = deliveryRule;
this.shipperId = shipperId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\UpdateShipmentScheduleRequest.java
| 2
|
请完成以下Java代码
|
public DetailsBuilder waitTimeInMillis(int waitTimeInMillis) {
this.waitTimeInMillis = waitTimeInMillis;
return this;
}
public DetailsBuilder processEngineName(String processEngineName) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.add(processEngineName);
return this;
}
public DetailsBuilder processEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.addAll(processEngineNames);
return this;
}
public DetailsBuilder clearProcessEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames != null) {
this.processEngineNames.clear();
}
return this;
}
public Details build() {
return new Details(this);
}
}
public String getName() {
return name;
}
|
public String getLockOwner() {
return lockOwner;
}
public int getLockTimeInMillis() {
return lockTimeInMillis;
}
public int getMaxJobsPerAcquisition() {
return maxJobsPerAcquisition;
}
public int getWaitTimeInMillis() {
return waitTimeInMillis;
}
public Set<String> getProcessEngineNames() {
return processEngineNames;
}
@Override
public String toString() {
return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis="
+ lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition
+ ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames
+ "]";
}
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\actuator\JobExecutorHealthIndicator.java
| 1
|
请完成以下Java代码
|
public Attachment getAttachment(String attachmentId) {
return commandExecutor.execute(new GetAttachmentCmd(attachmentId));
}
public Attachment getTaskAttachment(String taskId, String attachmentId) {
return commandExecutor.execute(new GetTaskAttachmentCmd(taskId, attachmentId));
}
public List<Attachment> getTaskAttachments(String taskId) {
return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId));
}
public List<Attachment> getProcessInstanceAttachments(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId));
}
public void saveAttachment(Attachment attachment) {
commandExecutor.execute(new SaveAttachmentCmd(attachment));
}
public List<Task> getSubTasks(String parentTaskId) {
return commandExecutor.execute(new GetSubTasksCmd(parentTaskId));
}
public TaskReport createTaskReport() {
return new TaskReportImpl(commandExecutor);
}
@Override
public void handleBpmnError(String taskId, String errorCode) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode));
|
}
@Override
public void handleBpmnError(String taskId, String errorCode, String errorMessage) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage));
}
@Override
public void handleBpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage, variables));
}
@Override
public void handleEscalation(String taskId, String escalationCode) {
commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode));
}
@Override
public void handleEscalation(String taskId, String escalationCode, Map<String, Object> variables) {
commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode, variables));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskServiceImpl.java
| 1
|
请完成以下Java代码
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
|
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventSubscriptionEntity other = (EventSubscriptionEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Propagation {
/**
* Tracing context propagation types produced and consumed by the application.
* Setting this property overrides the more fine-grained propagation type
* properties.
*/
private @Nullable List<PropagationType> type;
/**
* Tracing context propagation types produced by the application.
*/
private List<PropagationType> produce = List.of(PropagationType.W3C);
/**
* Tracing context propagation types consumed by the application.
*/
private List<PropagationType> consume = List.of(PropagationType.values());
public void setType(@Nullable List<PropagationType> type) {
this.type = type;
}
public void setProduce(List<PropagationType> produce) {
this.produce = produce;
}
public void setConsume(List<PropagationType> consume) {
this.consume = consume;
}
public @Nullable List<PropagationType> getType() {
return this.type;
}
public List<PropagationType> getProduce() {
return this.produce;
}
public List<PropagationType> getConsume() {
|
return this.consume;
}
/**
* Supported propagation types. The declared order of the values matter.
*/
public enum PropagationType {
/**
* <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation.
*/
W3C,
/**
* <a href="https://github.com/openzipkin/b3-propagation#single-header">B3
* single header</a> propagation.
*/
B3,
/**
* <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3
* multiple headers</a> propagation.
*/
B3_MULTI
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java
| 2
|
请完成以下Java代码
|
public static boolean ask (final int WindowNo, final Container c, final String AD_Message, final String msg)
{
return new SwingAskDialogBuilder()
.setParentWindowNo(WindowNo)
.setParentComponent(c)
.setAD_Message(AD_Message)
.setAdditionalMessage(msg)
.getAnswer();
} // ask
/**
* Ask Question with question icon and (OK) (Cancel) buttons
* @param WindowNo Number of Window
* @param c Container (owner)
* @param AD_Message Message to be translated
* @return true, if OK
*/
public static boolean ask (int WindowNo, Container c, String AD_Message)
{
return ask (WindowNo, c, AD_Message, null);
|
} // ask
/**************************************************************************
* Beep
*/
public static void beep()
{
Toolkit.getDefaultToolkit().beep();
} // beep
// metas: begin
public static void error (int WindowNo, Container c, Throwable ex)
{
String adMessage = "Error";
String msg = ex.getLocalizedMessage();
log.warn(msg, ex);
error(WindowNo, c, adMessage, msg);
}
// metas: end
} // Dialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ADialog.java
| 1
|
请完成以下Java代码
|
public String toString()
{
final ImmutableList<String> nextNodeNames = getTransitions(ClientId.SYSTEM)
.stream()
.map(transition -> transition.getNextNode().getName().getDefaultValue())
.collect(ImmutableList.toImmutableList());
return MoreObjects.toStringHelper(this)
.add("name", getName().getDefaultValue())
.add("next", nextNodeNames)
.toString();
}
public WFNode unbox() { return node; }
public @NonNull WFNodeId getId() {return node.getId();}
public @NonNull WorkflowId getWorkflowId() { return workflowModel.getId(); }
public @NonNull ClientId getClientId() {return node.getClientId();}
public @NonNull WFNodeAction getAction() {return node.getAction();}
public @NonNull ITranslatableString getName() {return node.getName();}
@NonNull
public ITranslatableString getDescription() {return node.getDescription();}
@NonNull
public ITranslatableString getHelp() {return node.getHelp();}
public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();}
public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();}
|
public void setXPosition(final int x) { this.xPosition = x; }
public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();}
public void setYPosition(final int y) { this.yPosition = y; }
public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId)
{
return node.getTransitions(clientId)
.stream()
.map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition))
.collect(ImmutableList.toImmutableList());
}
public void saveEx()
{
workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder()
.nodeId(getId())
.xPosition(getXPosition())
.yPosition(getYPosition())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
mvc:
throw-exception-if-no-handler-found: true
jackson:
deserialization:
FAIL_ON_UNKNOWN_PROPERTIES: true
property-naming-strategy: SNAKE_CASE
jpa:
open-in-view: false
generate-ddl: true
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
thread-executor: standard
docker:
compose:
enabled: false
autocon
|
figure:
exclude: org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
cors:
allow:
origins: ${CORS_ALLOWED_ORIGINS:*}
credentials: ${CORS_ALLOW_CREDENTIALS:false}
|
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UOMConversionsMap
{
public static final UOMConversionsMap EMPTY = new UOMConversionsMap();
ProductId productId;
ImmutableMap<FromAndToUomIds, UOMConversionRate> rates;
/**
* {@code true} if this map is about a productId *and* contains at least one mapping besides the trivial times-one-mapping to and from the product's own stocking-UOM.
*/
boolean hasRatesForNonStockingUOMs;
@Builder
private UOMConversionsMap(
@Nullable final ProductId productId,
@Nullable final Boolean hasRatesForNonStockingUOMs,
@NonNull @Singular final List<UOMConversionRate> rates)
{
this.productId = productId;
this.hasRatesForNonStockingUOMs = CoalesceUtil.coalesceNotNull(hasRatesForNonStockingUOMs, false);
this.rates = Maps.uniqueIndex(rates, UOMConversionsMap::toFromAndToUomIds);
}
private UOMConversionsMap()
{
productId = null;
hasRatesForNonStockingUOMs = false;
rates = ImmutableMap.of();
}
public UOMConversionRate getRate(@NonNull final UomId fromUomId, @NonNull final UomId toUomId)
{
final UOMConversionRate rate = getRateOrNull(fromUomId, toUomId);
if (rate == null)
{
throw new NoUOMConversionException(productId, fromUomId, toUomId);
}
return rate;
}
public Optional<UOMConversionRate> getRateIfExists(@NonNull final UomId fromUomId, @NonNull final UomId toUomId)
{
return Optional.ofNullable(getRateOrNull(fromUomId, toUomId));
}
@Nullable
private UOMConversionRate getRateOrNull(@NonNull final UomId fromUomId, @NonNull final UomId toUomId)
{
if (fromUomId.equals(toUomId))
{
return UOMConversionRate.one(fromUomId);
}
final FromAndToUomIds key = FromAndToUomIds.builder()
.fromUomId(fromUomId)
.toUomId(toUomId)
.build();
final UOMConversionRate directRate = rates.get(key);
if (directRate != null)
{
return directRate;
}
final UOMConversionRate invertedRate = rates.get(key.invert());
if (invertedRate != null)
{
return invertedRate.invert();
}
return null;
|
}
public boolean isEmpty()
{
return rates.isEmpty();
}
public ImmutableSet<UomId> getCatchUomIds()
{
if (rates.isEmpty())
{
return ImmutableSet.of();
}
return rates.values()
.stream()
.filter(UOMConversionRate::isCatchUOMForProduct)
.map(UOMConversionRate::getToUomId)
.collect(ImmutableSet.toImmutableSet());
}
private static FromAndToUomIds toFromAndToUomIds(final UOMConversionRate conversion)
{
return FromAndToUomIds.builder()
.fromUomId(conversion.getFromUomId())
.toUomId(conversion.getToUomId())
.build();
}
@Value
@Builder
public static class FromAndToUomIds
{
@NonNull
UomId fromUomId;
@NonNull
UomId toUomId;
public FromAndToUomIds invert()
{
return builder().fromUomId(toUomId).toUomId(fromUomId).build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionsMap.java
| 2
|
请完成以下Java代码
|
public void invalidateShipmentSchedsForLines(final I_M_InOut inoutRecord)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord))
{
// Only if it's a shipment
if (!inoutRecord.isSOTrx())
{
return;
}
// we only need to invalidate for the respective lines, because basically we only need to shift the qty from QtyPicked to QtyDelivered.
// No other shipment schedule will have anything more or less after that.
trxManager.runAfterCommit(() -> shipmentScheduleInvalidateBL.invalidateJustForLines(inoutRecord));
}
}
/**
* Note: a deletion of an InOut in the GUI doesn't cause M_InOutLine's model validator to be fired
*
* @param shipment
*/
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void onDelete(final I_M_InOut inoutRecord)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord))
{
if (!inoutRecord.isSOTrx())
{
return;
}
final IShipmentScheduleInvalidateBL shipmentScheduleInvalidateBL = Services.get(IShipmentScheduleInvalidateBL.class);
shipmentScheduleInvalidateBL.invalidateJustForLines(inoutRecord); // make sure that at least the lines themselves are invalidated
shipmentScheduleInvalidateBL.notifySegmentsChangedForShipment(inoutRecord);
}
}
@ModelChange(//
timings = ModelValidator.TYPE_AFTER_CHANGE, // note: on AFTER_NEW, there can't be any M_ShipmentSchedule_QtyPicked records to update yet, so we don't have to fire
ifColumnsChanged = I_M_InOut.COLUMNNAME_Processed)
|
public void updateM_ShipmentSchedule_QtyPicked_Processed(final I_M_InOut inoutRecord)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord))
{
if (!inoutRecord.isSOTrx())
{
return;
}
final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO = Services.get(IShipmentScheduleAllocDAO.class);
shipmentScheduleAllocDAO.updateM_ShipmentSchedule_QtyPicked_ProcessedForShipment(inoutRecord);
}
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void closePartiallyShipped_ShipmentSchedules(@NonNull final I_M_InOut inoutRecord)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord))
{
Services.get(IShipmentScheduleBL.class).closePartiallyShipped_ShipmentSchedules(inoutRecord);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_InOut_Shipment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CommentCollectionResource {
private List<CommentResource> taskComments;
/**
* Adds the comment.
*
* @param comment
* the comment
*/
public void addComment(CommentResource comment) {
if (this.taskComments == null) {
this.taskComments = new ArrayList<>();
}
this.taskComments.add(comment);
}
/**
* @return the taskComments
*/
public List<CommentResource> getTaskComments() {
return taskComments;
}
/**
* @param taskComments
* the taskComments to set
*/
public void setTaskComments(List<CommentResource> taskComments) {
this.taskComments = taskComments;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((taskComments == null) ? 0 : taskComments.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentCollectionResource other = (CommentCollectionResource) obj;
if (taskComments == null) {
if (other.taskComments != null)
return false;
} else if (!taskComments.equals(other.taskComments))
return false;
|
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CommentCollectionResource [taskComments=" + taskComments + "]";
}
}
/**
* Inner class to perform the de-serialization of the comments array
*
* @author anilallewar
*
*/
class CommentsCollectionDeserializer extends JsonDeserializer<CommentCollectionResource> {
@Override
public CommentCollectionResource deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
CommentCollectionResource commentArrayResource = new CommentCollectionResource();
CommentResource commentResource = null;
JsonNode jsonNode = jp.readValueAsTree();
for (JsonNode childNode : jsonNode) {
if (childNode.has(CommentResource.JP_TASKID)) {
commentResource = new CommentResource();
commentResource.setTaskId(childNode.get(CommentResource.JP_TASKID).asText());
commentResource.setComment(childNode.get(CommentResource.JP_COMMENT).asText());
commentResource.setPosted(new Date(childNode.get(CommentResource.JP_POSTED).asLong()));
commentArrayResource.addComment(commentResource);
}
}
return commentArrayResource;
}
}
|
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\model\CommentCollectionResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Application {
@Bean("writer1")
public Writer getWriter1() {
return new Writer("Writer 1");
}
@Bean("writer2")
public Writer getWriter2() {
return new Writer("Writer 2");
}
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Application context initialized!!!");
Writer writer1 = ctx.getBean("writer1", Writer.class);
writer1.write("First message");
Writer writer2 = ctx.getBean("writer2", Writer.class);
writer2.write("Second message");
}
|
/*
This method shows how to set lazy initialization and start the application using SpringApplicationBuilder
*/
private static ApplicationContext runUsingSpringApplicationBuilder(String[] args){
return new SpringApplicationBuilder(Application.class)
.lazyInitialization(true)
.build(args)
.run();
}
/*
This method shows how to set lazy initialization and start the application using SpringApplication
*/
private static ApplicationContext runUsingSpringApplication(String[] args){
SpringApplication app = new SpringApplication(Application.class);
app.setLazyInitialization(true);
return app.run(args);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-performance\src\main\java\com\baeldung\lazyinitialization\Application.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.