instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public Duration getMaxConnectionLifetime() {
return this.maxConnectionLifetime;
}
public void setMaxConnectionLifetime(Duration maxConnectionLifetime) {
this.maxConnectionLifetime = maxConnectionLifetime;
}
public Duration getConnectionAcquisitionTimeout() {
return this.connectionAcquisitionTimeout;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
this.connectionAcquisitionTimeout = connectionAcquisitionTimeout;
}
}
public static class Security {
/**
* Whether the driver should use encrypted traffic.
*/
private boolean encrypted;
/**
* Trust strategy to use.
*/
private TrustStrategy trustStrategy = TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES;
/**
* Path to the file that holds the trusted certificates.
*/
private @Nullable File certFile;
/**
* Whether hostname verification is required.
*/
private boolean hostnameVerificationEnabled = true;
public boolean isEncrypted() {
return this.encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public TrustStrategy getTrustStrategy() {
return this.trustStrategy;
}
public void setTrustStrategy(TrustStrategy trustStrategy) {
this.trustStrategy = trustStrategy;
}
public @Nullable File getCertFile() {
return this.certFile;
}
public void setCertFile(@Nullable File certFile) {
this.certFile = certFile;
} | public boolean isHostnameVerificationEnabled() {
return this.hostnameVerificationEnabled;
}
public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) {
this.hostnameVerificationEnabled = hostnameVerificationEnabled;
}
public enum TrustStrategy {
/**
* Trust all certificates.
*/
TRUST_ALL_CERTIFICATES,
/**
* Trust certificates that are signed by a trusted certificate.
*/
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES,
/**
* Trust certificates that can be verified through the local system store.
*/
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java | 2 |
请完成以下Java代码 | private static void treeMapSortByKey() {
TreeMap<String, Employee> sorted = new TreeMap<>(map);
sorted.putAll(map);
sorted.entrySet().forEach(System.out::println);
}
private static void arrayListSortByValue() {
List<Employee> employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);
System.out.println(employeeById);
}
private static void arrayListSortByKey() {
List<String> employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);
System.out.println(employeeByKey);
}
private static void initialize() { | Employee employee1 = new Employee(1L, "Mher");
map.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map.put(employee4.getName(), employee4);
}
private static void addDuplicates() {
Employee employee5 = new Employee(1L, "Mher");
map.put(employee5.getName(), employee5);
Employee employee6 = new Employee(22L, "Annie");
map.put(employee6.getName(), employee6);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\sort\SortHashMap.java | 1 |
请完成以下Java代码 | private boolean reActivateIt()
{
if (!isValidDocAction(ACTION_ReActivate))
{
return false;
}
final IDocument document = getDocument();
if (document.reActivateIt())
{
final String newDocStatus = STATUS_InProgress;
setDocStatusIntern(newDocStatus);
document.setDocStatus(newDocStatus);
return true;
}
else
{
return false;
}
}
/**
* @return all valid DocActions based on current DocStatus
*/
private Set<String> getValidDocActionsForCurrentDocStatus()
{
if (isInvalid())
{
return ImmutableSet.of(ACTION_Prepare, ACTION_Invalidate, ACTION_Unlock, ACTION_Void);
}
if (isDrafted())
{
return ImmutableSet.of(ACTION_Prepare, ACTION_Invalidate, ACTION_Complete, ACTION_Unlock, ACTION_Void);
}
if (isInProgress() || isApproved())
{
return ImmutableSet.of(ACTION_Complete, ACTION_WaitComplete, ACTION_Approve, ACTION_Reject, ACTION_Unlock, ACTION_Void, ACTION_Prepare);
}
if (isNotApproved())
{
return ImmutableSet.of(ACTION_Reject, ACTION_Prepare, ACTION_Unlock, ACTION_Void);
}
if (isWaiting())
{
return ImmutableSet.of(ACTION_Complete, ACTION_WaitComplete, ACTION_ReActivate, ACTION_Void, ACTION_Close);
}
if (isCompleted())
{
return ImmutableSet.of(ACTION_Close, ACTION_ReActivate, ACTION_Reverse_Accrual, ACTION_Reverse_Correct, ACTION_Post, ACTION_Void);
}
if (isClosed())
{
return ImmutableSet.of(ACTION_Post, ACTION_UnClose); | }
if (isReversed() || isVoided())
{
return ImmutableSet.of(ACTION_Post);
}
return ImmutableSet.of();
}
/**
* @return true if given docAction is valid for current docStatus.
*/
private boolean isValidDocAction(final String docAction)
{
final Set<String> availableDocActions = getValidDocActionsForCurrentDocStatus();
return availableDocActions.contains(docAction);
}
private String getDocAction()
{
return _docAction;
}
private void setDocActionIntern(final String newDocAction)
{
_docAction = newDocAction;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocumentEngine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
} | public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DecisionResponse.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsShowInMainMenu (final boolean IsShowInMainMenu)
{
set_Value (COLUMNNAME_IsShowInMainMenu, IsShowInMainMenu);
}
@Override
public boolean isShowInMainMenu()
{
return get_ValueAsBoolean(COLUMNNAME_IsShowInMainMenu);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
} | @Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setEventData (final @Nullable java.lang.String EventData)
{
set_ValueNoCheck (COLUMNNAME_EventData, EventData);
}
@Override
public java.lang.String getEventData()
{
return get_ValueAsString(COLUMNNAME_EventData);
}
@Override
public void setEventName (final @Nullable java.lang.String EventName)
{
set_Value (COLUMNNAME_EventName, EventName);
}
@Override
public java.lang.String getEventName()
{
return get_ValueAsString(COLUMNNAME_EventName);
}
@Override
public void setEventTime (final @Nullable java.sql.Timestamp EventTime)
{
set_ValueNoCheck (COLUMNNAME_EventTime, EventTime);
}
@Override
public java.sql.Timestamp getEventTime()
{
return get_ValueAsTimestamp(COLUMNNAME_EventTime);
}
@Override
public void setEventTopicName (final @Nullable java.lang.String EventTopicName)
{
set_Value (COLUMNNAME_EventTopicName, EventTopicName);
}
@Override
public java.lang.String getEventTopicName()
{
return get_ValueAsString(COLUMNNAME_EventTopicName);
}
/**
* EventTypeName AD_Reference_ID=540802
* Reference name: EventTypeName
*/
public static final int EVENTTYPENAME_AD_Reference_ID=540802;
/** LOCAL = LOCAL */
public static final String EVENTTYPENAME_LOCAL = "LOCAL";
/** DISTRIBUTED = DISTRIBUTED */
public static final String EVENTTYPENAME_DISTRIBUTED = "DISTRIBUTED";
@Override
public void setEventTypeName (final @Nullable java.lang.String EventTypeName) | {
set_Value (COLUMNNAME_EventTypeName, EventTypeName);
}
@Override
public java.lang.String getEventTypeName()
{
return get_ValueAsString(COLUMNNAME_EventTypeName);
}
@Override
public void setEvent_UUID (final java.lang.String Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID);
}
@Override
public java.lang.String getEvent_UUID()
{
return get_ValueAsString(COLUMNNAME_Event_UUID);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged)
{
set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged);
}
@Override
public boolean isErrorAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged);
}
@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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java | 1 |
请完成以下Java代码 | public void onError(ProducerRecord<K, V> record, @Nullable RecordMetadata recordMetadata, Exception exception) {
this.logger.error(exception, () -> {
StringBuilder logOutput = new StringBuilder();
logOutput.append("Exception thrown when sending a message");
if (this.includeContents) {
logOutput.append(" with key='")
.append(keyOrValue(record.key()))
.append("'")
.append(" and payload='")
.append(keyOrValue(record.value()))
.append("'");
}
logOutput.append(" to topic ").append(record.topic());
if (record.partition() != null) {
logOutput.append(" and partition ").append(recordMetadata != null
? recordMetadata.partition()
: record.partition());
}
logOutput.append(":");
return logOutput.toString();
});
} | private String keyOrValue(Object keyOrValue) {
if (keyOrValue instanceof byte[]) {
return "byte[" + ((byte[]) keyOrValue).length + "]";
}
else {
return toDisplayString(ObjectUtils.nullSafeToString(keyOrValue), this.maxContentLogged);
}
}
private String toDisplayString(String original, int maxCharacters) {
if (original.length() <= maxCharacters) {
return original;
}
return original.substring(0, maxCharacters) + "...";
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\LoggingProducerListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "John")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@ApiModelProperty(example = "Doe")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@ApiModelProperty(example = "John Doe")
public String getDisplayName() {
return displayName; | }
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getPassword() {
return passWord;
}
public void setPassword(String passWord) {
this.passWord = passWord;
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserResponse.java | 2 |
请完成以下Java代码 | public void fireJobSuccessfulEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_SUCCESS, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogSuccessfulEvt(job);
}
});
}
}
public void fireJobDeletedEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_DELETE, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogDeleteEvt(job);
}
});
} | }
// helper /////////////////////////////////////////////////////////
protected boolean isHistoryEventProduced(HistoryEventType eventType, Job job) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
return historyLevel.isHistoryEventProduced(eventType, job);
}
protected void configureQuery(HistoricJobLogQueryImpl query) {
getAuthorizationManager().configureHistoricJobLogQuery(query);
getTenantManager().configureQuery(query);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricJobLogManager.java | 1 |
请完成以下Java代码 | protected boolean beforeSave(final boolean newRecord)
{
final int yy = getYearAsInt();
if (yy <= 0)
{
throw new FillMandatoryException(COLUMNNAME_FiscalYear);
}
return true;
} // beforeSave
/**
* Create 12 Standard Periods from the specified start date.
* Creates also Period Control from DocType.
*
* @see DocumentTypeVerify#createPeriodControls(Properties, int, JavaProcess, String)
* @param locale locale
* @param startDate first day of the calendar year
* @param dateFormat SimpleDateFormat pattern for generating the period names.
*/
public static void createStdPeriods(final I_C_Year yearRecord, Locale locale, final Timestamp startDate, String dateFormat)
{
final Properties ctx = Env.getCtx();
final int calendarId = yearRecord.getC_Calendar_ID();
final int yearId = yearRecord.getC_Year_ID();
if (locale == null)
{
final MClient client = MClient.get(ctx);
locale = client.getLocale();
}
if (locale == null && Language.getLoginLanguage() != null)
{
locale = Language.getLoginLanguage().getLocale();
}
if (locale == null)
{
locale = Env.getLanguage(ctx).getLocale();
}
//
SimpleDateFormat formatter;
if (dateFormat == null || dateFormat.equals(""))
{
dateFormat = "MMM-yy";
}
formatter = new SimpleDateFormat(dateFormat, locale);
//
int year = getYearAsInt(yearRecord.getFiscalYear());
final GregorianCalendar cal = new GregorianCalendar(locale);
if (startDate != null)
{
cal.setTime(startDate);
if (cal.get(Calendar.YEAR) != year)
{
year = cal.get(Calendar.YEAR);
} | }
else
{
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
}
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
//
for (int month = 0; month < 12; month++)
{
final Timestamp start = new Timestamp(cal.getTimeInMillis());
final String name = formatter.format(start);
// get last day of same month
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
final Timestamp end = new Timestamp(cal.getTimeInMillis());
//
MPeriod period = MPeriod.findByCalendar(ctx, start, calendarId, ITrx.TRXNAME_ThreadInherited);
if (period == null)
{
period = new MPeriod(yearRecord, month + 1, name, start, end);
}
else
{
period.setC_Year_ID(yearId);
period.setPeriodNo(month + 1);
period.setName(name);
period.setStartDate(start);
period.setEndDate(end);
}
period.saveEx(ITrx.TRXNAME_ThreadInherited); // Creates Period Control
// get first day of next month
cal.add(Calendar.DAY_OF_YEAR, 1);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MYear.java | 1 |
请完成以下Java代码 | public Builder setHasAttributesSupport(final boolean hasAttributesSupport)
{
this.hasAttributesSupport = hasAttributesSupport;
return this;
}
public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout)
{
this.includedViewLayout = includedViewLayout;
return this;
}
public Builder clearViewCloseActions()
{
allowedViewCloseActions = new LinkedHashSet<>();
return this;
}
public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction)
{
if (allowedViewCloseActions == null)
{
allowedViewCloseActions = new LinkedHashSet<>();
}
allowedViewCloseActions.add(viewCloseAction);
return this;
}
private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions()
{
return allowedViewCloseActions != null
? ImmutableSet.copyOf(allowedViewCloseActions)
: DEFAULT_allowedViewCloseActions;
}
public Builder setHasTreeSupport(final boolean hasTreeSupport)
{
this.hasTreeSupport = hasTreeSupport;
return this;
}
public Builder setTreeCollapsible(final boolean treeCollapsible)
{
this.treeCollapsible = treeCollapsible; | return this;
}
public Builder setTreeExpandedDepth(final int treeExpandedDepth)
{
this.treeExpandedDepth = treeExpandedDepth;
return this;
}
public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails)
{
this.allowOpeningRowDetails = allowOpeningRowDetails;
return this;
}
public Builder setFocusOnFieldName(final String focusOnFieldName)
{
this.focusOnFieldName = focusOnFieldName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapper personMapper;
public static AtomicInteger atomicInteger = new AtomicInteger();
@Override
public List<Person> findAll() {
return personMapper.findAll();
}
@Override
public Page<Person> findByPage(int pageNo, int pageSize) {
PageHelper.startPage(pageNo, pageSize);
return personMapper.findByPage();
}
@Override
@Transactional(rollbackFor = Exception.class) | public void insert(Person person) {
personMapper.insert(person);
}
@Override
@Transactional(rollbackFor = Exception.class)
public int updateAge(long id) {
int result = personMapper.updateAge(id);
int i = atomicInteger.getAndIncrement();
if (i > 990) {
System.out.println(i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return result;
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java | 2 |
请完成以下Java代码 | public class ViewHeaderPropertiesProviderMap
{
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static ViewHeaderPropertiesProviderMap of(@NonNull final Optional<List<ViewHeaderPropertiesProvider>> optionalProviders)
{
return optionalProviders.map(ViewHeaderPropertiesProviderMap::of)
.orElse(ViewHeaderPropertiesProviderMap.EMPTY);
}
public static ViewHeaderPropertiesProviderMap of(@NonNull final List<ViewHeaderPropertiesProvider> providers)
{
return !providers.isEmpty()
? new ViewHeaderPropertiesProviderMap(providers)
: EMPTY;
}
private static final ViewHeaderPropertiesProviderMap EMPTY = new ViewHeaderPropertiesProviderMap();
private final ImmutableMap<String, ViewHeaderPropertiesProvider> providersByTableName;
private final ViewHeaderPropertiesProvider genericProviders;
private ViewHeaderPropertiesProviderMap()
{
this.providersByTableName = ImmutableMap.of();
this.genericProviders = NullViewHeaderPropertiesProvider.instance;
}
private ViewHeaderPropertiesProviderMap(@NonNull final List<ViewHeaderPropertiesProvider> providers)
{
final ArrayList<ViewHeaderPropertiesProvider> genericProviders = new ArrayList<>();
final ArrayListMultimap<String, ViewHeaderPropertiesProvider> providersByTableName = ArrayListMultimap.create();
for (final ViewHeaderPropertiesProvider provider : providers)
{
final String appliesOnlyToTableName = provider.getAppliesOnlyToTableName();
if (Check.isBlank(appliesOnlyToTableName))
{
genericProviders.add(provider);
final Set<String> tableNames = ImmutableSet.copyOf(providersByTableName.keySet());
for (final String tableName : tableNames)
{
providersByTableName.put(tableName, provider);
}
}
else
{
if (!providersByTableName.containsKey(appliesOnlyToTableName)) | {
providersByTableName.putAll(appliesOnlyToTableName, genericProviders);
}
providersByTableName.put(appliesOnlyToTableName, provider);
}
}
this.genericProviders = CompositeViewHeaderPropertiesProvider.of(genericProviders);
this.providersByTableName = providersByTableName.keySet()
.stream()
.collect(ImmutableMap.toImmutableMap(
tableName -> tableName,
tableName -> CompositeViewHeaderPropertiesProvider.of(providersByTableName.get(tableName))));
}
public ViewHeaderPropertiesProvider getProvidersByTableName(@Nullable final String tableName)
{
return tableName != null
? providersByTableName.getOrDefault(tableName, genericProviders)
: genericProviders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewHeaderPropertiesProviderMap.java | 1 |
请完成以下Java代码 | public void validate() {
Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present");
}
public Duration getFirstBackoff() {
return firstBackoff;
}
public void setFirstBackoff(Duration firstBackoff) {
this.firstBackoff = firstBackoff;
}
public @Nullable Duration getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Duration maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getFactor() {
return factor;
}
public void setFactor(int factor) {
this.factor = factor;
}
public boolean isBasedOnPreviousValue() {
return basedOnPreviousValue;
}
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) {
this.basedOnPreviousValue = basedOnPreviousValue;
}
@Override
public String toString() {
return new ToStringCreator(this).append("firstBackoff", firstBackoff)
.append("maxBackoff", maxBackoff)
.append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue) | .toString();
}
}
public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)");
}
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor;
}
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java | 1 |
请完成以下Java代码 | protected boolean equals(int errorCode, String sqlState) {
return this.getErrorCode() == errorCode && this.getSqlState().equals(sqlState);
}
}
public static boolean checkDeadlockException(SQLException sqlException) {
String sqlState = sqlException.getSQLState();
if (sqlState != null) {
sqlState = sqlState.toUpperCase();
} else {
return false;
}
int errorCode = sqlException.getErrorCode();
return MYSQL.equals(errorCode, sqlState) ||
MSSQL.equals(errorCode, sqlState) ||
DB2.equals(errorCode, sqlState) ||
ORACLE.equals(errorCode, sqlState) ||
POSTGRES.equals(errorCode, sqlState) ||
H2.equals(errorCode, sqlState);
}
public static BatchExecutorException findBatchExecutorException(PersistenceException exception) {
Throwable cause = exception;
do {
if (cause instanceof BatchExecutorException) {
return (BatchExecutorException) cause;
}
cause = cause.getCause();
} while (cause != null);
return null;
}
/**
* Pass logic, which directly calls MyBatis API. In case a MyBatis exception is thrown, it is
* wrapped into a {@link ProcessEngineException} and never propagated directly to an Engine API
* call. In some cases, the top-level exception and its message are shown as a response body in
* the REST API. Wrapping all MyBatis API calls in our codebase makes sure that the top-level
* exception is always a {@link ProcessEngineException} with a generic message. Like this, SQL | * details are never disclosed to potential attackers.
*
* @param supplier which calls MyBatis API
* @param <T> is the type of the return value
* @return the value returned by the supplier
* @throws ProcessEngineException which wraps the actual exception
*/
public static <T> T doWithExceptionWrapper(Supplier<T> supplier) {
try {
return supplier.get();
} catch (Exception ex) {
throw wrapPersistenceException(ex);
}
}
public static ProcessEnginePersistenceException wrapPersistenceException(Exception ex) {
return new ProcessEnginePersistenceException(PERSISTENCE_EXCEPTION_MESSAGE, ex);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ExceptionUtil.java | 1 |
请完成以下Java代码 | public int size() {
this.lock.readLock().lock();
try {
return doublyLinkedList.size();
} finally {
this.lock.readLock().unlock();
}
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public void clear() {
this.lock.writeLock().lock();
try {
linkedListNodeMap.clear();
doublyLinkedList.clear();
} finally { | this.lock.writeLock().unlock();
}
}
private boolean evictElement() {
this.lock.writeLock().lock();
try {
LinkedListNode<CacheElement<K, V>> linkedListNode = doublyLinkedList.removeTail();
if (linkedListNode.isEmpty()) {
return false;
}
linkedListNodeMap.remove(linkedListNode.getElement().getKey());
return true;
} finally {
this.lock.writeLock().unlock();
}
}
} | repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\LRUCache.java | 1 |
请完成以下Java代码 | public void setReference (String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Reference.
@return Reference for this record
*/
public String getReference ()
{
return (String)get_Value(COLUMNNAME_Reference);
}
/** Set Release No.
@param ReleaseNo
Internal Release Number
*/
public void setReleaseNo (String ReleaseNo)
{
set_Value (COLUMNNAME_ReleaseNo, ReleaseNo);
}
/** Get Release No.
@return Internal Release Number
*/
public String getReleaseNo ()
{
return (String)get_Value(COLUMNNAME_ReleaseNo);
}
/** Set Script.
@param Script
Dynamic Java Language Script to calculate result
*/
public void setScript (byte[] Script)
{
set_ValueNoCheck (COLUMNNAME_Script, Script);
}
/** Get Script.
@return Dynamic Java Language Script to calculate result
*/
public byte[] getScript ()
{
return (byte[])get_Value(COLUMNNAME_Script);
}
/** Set Roll the Script.
@param ScriptRoll Roll the Script */
public void setScriptRoll (String ScriptRoll)
{
set_Value (COLUMNNAME_ScriptRoll, ScriptRoll);
}
/** Get Roll the Script.
@return Roll the Script */
public String getScriptRoll ()
{
return (String)get_Value(COLUMNNAME_ScriptRoll);
}
/** Status AD_Reference_ID=53239 */
public static final int STATUS_AD_Reference_ID=53239;
/** In Progress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */ | public static final String STATUS_Completed = "CO";
/** Error = ER */
public static final String STATUS_Error = "ER";
/** Set Status.
@param Status
Status of the currently running check
*/
public void setStatus (String Status)
{
set_ValueNoCheck (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationScript.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: server-provider1
zipkin:
base-url: http://localhost:9100
sleuth:
sampler:
percentage: 1
server:
port: 9000
eureka:
client:
serviceUrl:
def | aultZone: http://mrbird:123456@peer1:8080/eureka/,http://mrbird:123456@peer2:8081/eureka/ | repos\SpringAll-master\43.Spring-Cloud-Sleuth\Server-Provider1\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public <T extends ReferenceListAwareEnum> T getValueAsRefListOrNull(@NonNull final Function<String, T> mapper)
{
final String value = StringUtils.trimBlankToNull(getValueAsString());
if (value == null)
{
return null;
}
return mapper.apply(value);
}
public boolean isNullValues()
{
return value == null
&& (!isRangeOperator() || valueTo == null)
&& sqlWhereClause == null;
}
private boolean isRangeOperator() {return operator != null && operator.isRangeOperator();}
//
//
// ------------------
//
//
public static final class Builder
{
private boolean joinAnd = true;
private String fieldName;
private Operator operator = Operator.EQUAL;
@Nullable private Object value;
@Nullable private Object valueTo;
private Builder()
{
super();
}
public DocumentFilterParam build()
{ | return new DocumentFilterParam(this);
}
public Builder setJoinAnd(final boolean joinAnd)
{
this.joinAnd = joinAnd;
return this;
}
public Builder setFieldName(final String fieldName)
{
this.fieldName = fieldName;
return this;
}
public Builder setOperator(@NonNull final Operator operator)
{
this.operator = operator;
return this;
}
public Builder setOperator()
{
operator = valueTo != null ? Operator.BETWEEN : Operator.EQUAL;
return this;
}
public Builder setValue(@Nullable final Object value)
{
this.value = value;
return this;
}
public Builder setValueTo(@Nullable final Object valueTo)
{
this.valueTo = valueTo;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParam.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void removeAssignment(@NonNull final I_M_HU_QRCode qrCode, @NonNull final ImmutableSet<HuId> huIdsToRemove)
{
streamAssignmentForQrAndHuIds(ImmutableSet.of(HUQRCodeRepoId.ofRepoId(qrCode.getM_HU_QRCode_ID())), huIdsToRemove)
.forEach(InterfaceWrapperHelper::delete);
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_QRCode_ID, huQrCodeIds)
.create()
.stream();
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrAndHuIds(
@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds,
@NonNull final ImmutableSet<HuId> huIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class) | .addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_QRCode_ID, huQrCodeIds)
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_ID, huIds)
.create()
.stream();
}
private static HUQRCode toHUQRCode(final I_M_HU_QRCode record)
{
return HUQRCode.fromGlobalQRCodeJsonString(record.getRenderedQRCode());
}
public Stream<HUQRCode> streamQRCodesLike(@NonNull final String like)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode.class)
.addOnlyActiveRecordsFilter()
.addStringLikeFilter(I_M_HU_QRCode.COLUMNNAME_RenderedQRCode, like, false)
.orderBy(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID)
.create()
.stream()
.map(HUQRCodesRepository::toHUQRCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public <T> T convert(@Nullable Object value, @Nullable Class<T> target) {
if (value == null || target == null || ClassUtils.isAssignableValue(target, value)) {
return (T) value;
}
if (conversions.hasCustomReadTarget(value.getClass(), target)) {
return conversionService.convert(value, target);
}
if (Enum.class.isAssignableFrom(target)) {
return (T) Enum.valueOf((Class<Enum>) target, value.toString());
}
return conversionService.convert(value, target);
}
/** | * Convert a value from the {@link Row} to a type - throws an exception, if it's impossible.
* @param row which contains the column values.
* @param target class.
* @param columnName the name of the column which to convert.
* @param <T> the parameter for the intended type.
* @return the value which can be constructed from the input.
*/
public <T> T fromRow(Row row, String columnName, Class<T> target) {
try {
// try, directly the driver
return row.get(columnName, target);
} catch (Exception e) {
Object obj = row.get(columnName);
return convert(obj, target);
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\rowmapper\ColumnConverter.java | 2 |
请完成以下Java代码 | private MaterialCockpitRowsData createRowsData(
@NonNull final DocumentFilterList filters,
@NonNull final MaterialCockpitRowsLoader materialCockpitRowsLoader)
{
final LocalDate date = materialCockpitFilters.getFilterByDate(filters);
final MaterialCockpitDetailsRowAggregation detailsRowAggregation = retrieveDetailsRowAggregation();
if (date == null)
{
return new MaterialCockpitRowsData(detailsRowAggregation, materialCockpitRowFactory,qtyDemandSupplyRepository, ImmutableList.of());
}
final List<MaterialCockpitRow> rows = materialCockpitRowsLoader.getMaterialCockpitRows(filters, date, detailsRowAggregation);
return new MaterialCockpitRowsData(detailsRowAggregation, materialCockpitRowFactory,qtyDemandSupplyRepository, rows);
}
@Override
public ViewLayout getViewLayout(
@NonNull final WindowId windowId,
@NonNull final JSONViewDataType viewDataType,
@Nullable final ViewProfileId profileId)
{
Check.errorUnless(MaterialCockpitUtil.WINDOWID_MaterialCockpitView.equals(windowId),
"The parameter windowId needs to be {}, but is {} instead; viewDataType={}; ",
MaterialCockpitUtil.WINDOWID_MaterialCockpitView, windowId, viewDataType);
final String commaSeparatedFieldNames = sysConfigBL.getValue(SYSCFG_Layout, (String)null);
final boolean displayIncludedRows = sysConfigBL.getBooleanValue(SYSCFG_DisplayIncludedRows, true);
final ViewLayout.Builder viewlayOutBuilder = ViewLayout.builder()
.setWindowId(windowId)
.setHasTreeSupport(displayIncludedRows)
.setTreeCollapsible(true)
.setTreeExpandedDepth(ViewLayout.TreeExpandedDepth_AllCollapsed)
.setAllowOpeningRowDetails(false)
.addElementsFromViewRowClass(MaterialCockpitRow.class, viewDataType, commaSeparatedFieldNames)
.setFilters(materialCockpitFilters.getFilterDescriptors().getAll());
return viewlayOutBuilder.build();
}
private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final AdProcessId processId = processDAO.retrieveProcessIdByClass(processClass); | if (processId == null)
{
throw new AdempiereException("No processId found for " + processClass);
}
return RelatedProcessDescriptor.builder()
.processId(processId)
.anyTable().anyWindow()
.displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions)
.build();
}
private boolean retrieveIsIncludePerPlantDetailRows()
{
return Services.get(ISysConfigBL.class).getBooleanValue(
MaterialCockpitUtil.SYSCONFIG_INCLUDE_PER_PLANT_DETAIL_ROWS,
false,
Env.getAD_Client_ID(),
Env.getAD_Org_ID(Env.getCtx()));
}
private MaterialCockpitDetailsRowAggregation retrieveDetailsRowAggregation()
{
if (retrieveIsIncludePerPlantDetailRows())
{
return MaterialCockpitDetailsRowAggregation.PLANT;
}
return MaterialCockpitDetailsRowAggregation.getDefault();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitViewFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private MaterialDescriptorBuilder initCommonDescriptorBuilder(final DDOrderLine ddOrderLine)
{
return MaterialDescriptor.builder()
.productDescriptor(ddOrderLine.getProductDescriptor())
// .customerId(ddOrderLine.getBPartnerId()) // the ddOrder line's bpartner is not the customer, but probably the shipper
.quantity(ddOrderLine.getQtyToMove());
}
protected abstract CandidatesQuery createPreExistingCandidatesQuery(
AbstractDDOrderEvent ddOrderEvent,
DDOrderLine ddOrderLine,
CandidateType candidateType);
private DistributionDetail createCandidateDetailFromDDOrderAndLine(
@NonNull final DDOrder ddOrder,
@NonNull final DDOrderLine ddOrderLine)
{
return DistributionDetail.builder()
.ddOrderDocStatus(ddOrder.getDocStatus())
.ddOrderRef(DDOrderRef.ofNullableDDOrderAndLineId(ddOrder.getDdOrderId(), ddOrderLine.getDdOrderLineId()))
.forwardPPOrderRef(ddOrder.getForwardPPOrderRef())
.distributionNetworkAndLineId(ddOrderLine.getDistributionNetworkAndLineId())
.qty(ddOrderLine.getQtyToMove())
.plantId(ddOrder.getPlantId())
.productPlanningId(ddOrder.getProductPlanningId())
.shipperId(ddOrder.getShipperId())
.build();
}
private void handleMainDataUpdates(@NonNull final DDOrderCreatedEvent ddOrderCreatedEvent, @NonNull final DDOrderLine ddOrderLine)
{
if (ddOrderCreatedEvent.getDdOrder().isSimulated())
{ | return;
}
final OrgId orgId = ddOrderCreatedEvent.getOrgId();
final ZoneId timeZone = orgDAO.getTimeZone(orgId);
final DDOrderMainDataHandler mainDataUpdater = DDOrderMainDataHandler.builder()
.ddOrderDetailRequestHandler(ddOrderDetailRequestHandler)
.mainDataRequestHandler(mainDataRequestHandler)
.abstractDDOrderEvent(ddOrderCreatedEvent)
.ddOrderLine(ddOrderLine)
.orgZone(timeZone)
.build();
mainDataUpdater.handleUpdate();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderAdvisedOrCreatedHandler.java | 2 |
请完成以下Java代码 | private Mono<Void> updateIndexes(Map<String, String> indexToDelete, Map<String, String> indexToAdd,
String sessionId) {
// @formatter:off
return Flux.fromIterable(indexToDelete.entrySet())
.flatMap((entry) -> {
String indexKey = getIndexKey(entry.getKey(), entry.getValue());
return removeSessionFromIndex(indexKey, sessionId).thenReturn(indexKey);
})
.flatMap((indexKey) -> this.sessionRedisOperations.opsForSet().remove(getSessionIndexesKey(sessionId), indexKey))
.thenMany(Flux.fromIterable(indexToAdd.entrySet()))
.flatMap((entry) -> {
String indexKey = getIndexKey(entry.getKey(), entry.getValue());
return this.sessionRedisOperations.opsForSet().add(indexKey, sessionId).thenReturn(indexKey);
})
.flatMap((indexKey) -> this.sessionRedisOperations.opsForSet().add(getSessionIndexesKey(sessionId), indexKey))
.then();
// @formatter:on
}
Mono<Void> delete(String sessionId) {
String sessionIndexesKey = getSessionIndexesKey(sessionId);
return this.sessionRedisOperations.opsForSet()
.members(sessionIndexesKey)
.flatMap((indexKey) -> removeSessionFromIndex((String) indexKey, sessionId))
.then(this.sessionRedisOperations.delete(sessionIndexesKey))
.then();
}
private Mono<Void> removeSessionFromIndex(String indexKey, String sessionId) {
return this.sessionRedisOperations.opsForSet().remove(indexKey, sessionId).then();
}
Mono<Map<String, String>> getIndexes(String sessionId) {
String sessionIndexesKey = getSessionIndexesKey(sessionId);
return this.sessionRedisOperations.opsForSet()
.members(sessionIndexesKey)
.cast(String.class)
.collectMap((indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[0], | (indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[1]);
}
Flux<String> getSessionIds(String indexName, String indexValue) {
String indexKey = getIndexKey(indexName, indexValue);
return this.sessionRedisOperations.opsForSet().members(indexKey).cast(String.class);
}
private void updateIndexKeyPrefix() {
this.indexKeyPrefix = this.namespace + "sessions:index:";
}
private String getSessionIndexesKey(String sessionId) {
return this.namespace + "sessions:" + sessionId + ":idx";
}
private String getIndexKey(String indexName, String indexValue) {
return this.indexKeyPrefix + indexName + ":" + indexValue;
}
void setNamespace(String namespace) {
Assert.hasText(namespace, "namespace cannot be empty");
this.namespace = namespace;
updateIndexKeyPrefix();
}
void setIndexResolver(IndexResolver<Session> indexResolver) {
Assert.notNull(indexResolver, "indexResolver cannot be null");
this.indexResolver = indexResolver;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionIndexer.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_BusinessRule_Trigger getAD_BusinessRule_Trigger()
{
return get_ValueAsPO(COLUMNNAME_AD_BusinessRule_Trigger_ID, org.compiere.model.I_AD_BusinessRule_Trigger.class);
}
@Override
public void setAD_BusinessRule_Trigger(final org.compiere.model.I_AD_BusinessRule_Trigger AD_BusinessRule_Trigger)
{
set_ValueFromPO(COLUMNNAME_AD_BusinessRule_Trigger_ID, org.compiere.model.I_AD_BusinessRule_Trigger.class, AD_BusinessRule_Trigger);
}
@Override
public void setAD_BusinessRule_Trigger_ID (final int AD_BusinessRule_Trigger_ID)
{
if (AD_BusinessRule_Trigger_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, AD_BusinessRule_Trigger_ID);
}
@Override
public int getAD_BusinessRule_Trigger_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID);
}
@Override
public void setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag) | {
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setSource_Record_ID (final int Source_Record_ID)
{
if (Source_Record_ID < 1)
set_ValueNoCheck (COLUMNNAME_Source_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Source_Record_ID, Source_Record_ID);
}
@Override
public int getSource_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Record_ID);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_Source_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTriggering_User_ID (final int Triggering_User_ID)
{
if (Triggering_User_ID < 1)
set_Value (COLUMNNAME_Triggering_User_ID, null);
else
set_Value (COLUMNNAME_Triggering_User_ID, Triggering_User_ID);
}
@Override
public int getTriggering_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Triggering_User_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Event.java | 1 |
请完成以下Java代码 | public void setValue(Bindings bindings, ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", getStructuralId(bindings)));
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return null;
}
public boolean isLeftValue() {
return false;
}
public boolean isMethodInvocation() {
return true;
}
public final ValueReference getValueReference(Bindings bindings, ELContext context) {
return null;
}
@Override
public void appendStructure(StringBuilder builder, Bindings bindings) {
property.appendStructure(builder, bindings);
params.appendStructure(builder, bindings);
}
@Override
public Object eval(Bindings bindings, ELContext context) {
return invoke(bindings, context, null, null, null);
}
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) {
Object base = property.getPrefix().eval(bindings, context);
if (base == null) {
throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", property.getPrefix()));
}
Object method = property.getProperty(bindings, context);
if (method == null) {
throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base)); | }
String name = bindings.convert(method, String.class);
paramValues = params.eval(bindings, context);
context.setPropertyResolved(false);
Object result = context.getELResolver().invoke(context, base, name, paramTypes, paramValues);
if (!context.isPropertyResolved()) {
throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, base.getClass()));
}
// if (returnType != null && !returnType.isInstance(result)) { // should we check returnType for method invocations?
// throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, base.getClass()));
// }
return result;
}
public int getCardinality() {
return 2;
}
public Node getChild(int i) {
return i == 0 ? property : i == 1 ? params : null;
}
@Override
public String toString() {
return "<method>";
}
} | repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstMethod.java | 1 |
请完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
return activityId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
} | public Boolean getRetriesLeft() {
return retriesLeft;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ClientCacheProperties {
private static final boolean DEFAULT_KEEP_ALIVE = false;
private static final int DEFAULT_DURABLE_CLIENT_TIMEOUT_IN_SECONDS = 300;
private boolean keepAlive = DEFAULT_KEEP_ALIVE;
private int durableClientTimeout = DEFAULT_DURABLE_CLIENT_TIMEOUT_IN_SECONDS;
private String durableClientId;
public String getDurableClientId() {
return this.durableClientId;
}
public void setDurableClientId(String durableClientId) {
this.durableClientId = durableClientId;
}
public int getDurableClientTimeout() { | return this.durableClientTimeout;
}
public void setDurableClientTimeout(int durableClientTimeout) {
this.durableClientTimeout = durableClientTimeout;
}
public boolean isKeepAlive() {
return this.keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ClientCacheProperties.java | 2 |
请完成以下Java代码 | public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID)
{
if (API_Request_Audit_ID < 1)
set_Value (COLUMNNAME_API_Request_Audit_ID, null);
else
set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID);
}
@Override
public int getAPI_Request_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID);
}
@Override
public void setAPI_Response_Audit_ID (final int API_Response_Audit_ID)
{
if (API_Response_Audit_ID < 1)
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, API_Response_Audit_ID);
}
@Override
public int getAPI_Response_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID);
}
@Override
public void setBody (final @Nullable java.lang.String Body)
{
set_Value (COLUMNNAME_Body, Body);
}
@Override
public java.lang.String getBody()
{
return get_ValueAsString(COLUMNNAME_Body);
}
@Override
public void setHttpCode (final @Nullable java.lang.String HttpCode)
{
set_Value (COLUMNNAME_HttpCode, HttpCode);
}
@Override
public java.lang.String getHttpCode()
{
return get_ValueAsString(COLUMNNAME_HttpCode); | }
@Override
public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders)
{
set_Value (COLUMNNAME_HttpHeaders, HttpHeaders);
}
@Override
public java.lang.String getHttpHeaders()
{
return get_ValueAsString(COLUMNNAME_HttpHeaders);
}
@Override
public void setTime (final @Nullable java.sql.Timestamp Time)
{
set_Value (COLUMNNAME_Time, Time);
}
@Override
public java.sql.Timestamp getTime()
{
return get_ValueAsTimestamp(COLUMNNAME_Time);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public org.compiere.model.I_C_Order getQuotation_Order()
{
return get_ValueAsPO(COLUMNNAME_Quotation_Order_ID, org.compiere.model.I_C_Order.class);
}
@Override
public void setQuotation_Order(final org.compiere.model.I_C_Order Quotation_Order)
{
set_ValueFromPO(COLUMNNAME_Quotation_Order_ID, org.compiere.model.I_C_Order.class, Quotation_Order);
}
@Override
public void setQuotation_Order_ID (final int Quotation_Order_ID)
{
if (Quotation_Order_ID < 1)
set_Value (COLUMNNAME_Quotation_Order_ID, null);
else
set_Value (COLUMNNAME_Quotation_Order_ID, Quotation_Order_ID);
}
@Override
public int getQuotation_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_Quotation_Order_ID);
}
@Override
public org.compiere.model.I_C_OrderLine getQuotation_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_Quotation_OrderLine_ID, org.compiere.model.I_C_OrderLine.class);
}
@Override
public void setQuotation_OrderLine(final org.compiere.model.I_C_OrderLine Quotation_OrderLine)
{
set_ValueFromPO(COLUMNNAME_Quotation_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, Quotation_OrderLine);
}
@Override
public void setQuotation_OrderLine_ID (final int Quotation_OrderLine_ID)
{
if (Quotation_OrderLine_ID < 1)
set_Value (COLUMNNAME_Quotation_OrderLine_ID, null);
else
set_Value (COLUMNNAME_Quotation_OrderLine_ID, Quotation_OrderLine_ID);
}
@Override
public int getQuotation_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Quotation_OrderLine_ID);
}
/**
* Type AD_Reference_ID=541251
* Reference name: C_Project_Repair_CostCollector_Type
*/ | public static final int TYPE_AD_Reference_ID=541251;
/** SparePartsToBeInvoiced = SP+ */
public static final String TYPE_SparePartsToBeInvoiced = "SP+";
/** SparePartsOwnedByCustomer = SPC */
public static final String TYPE_SparePartsOwnedByCustomer = "SPC";
/** RepairProductToReturn = RPC */
public static final String TYPE_RepairProductToReturn = "RPC";
/** RepairingConsumption = RP+ */
public static final String TYPE_RepairingConsumption = "RP+";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_ValueNoCheck (COLUMNNAME_VHU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_CostCollector.java | 2 |
请完成以下Java代码 | public ImmutableList<DDOrderMoveSchedule> execute()
{
return trxManager.callInThreadInheritedTrx(this::executeInTrx);
}
private ImmutableList<DDOrderMoveSchedule> executeInTrx()
{
return ddOrderMoveScheduleRepository.updateByIds(scheduleIds, this::processSchedule);
}
private void processSchedule(final DDOrderMoveSchedule schedule)
{
schedule.assertInTransit();
//
// generate movement InTransit -> DropTo Locator
final LocatorId dropToLocatorId = this.dropToLocatorId != null ? this.dropToLocatorId : schedule.getDropToLocatorId();
final MovementId dropToMovementId = createDropToMovement(schedule, dropToLocatorId);
//
// update the schedule
schedule.markAsDroppedTo(dropToLocatorId, dropToMovementId);
}
private MovementId createDropToMovement(@NonNull final DDOrderMoveSchedule schedule, @NonNull final LocatorId dropToLocatorId)
{
final I_DD_Order ddOrder = ddOrderLowLevelDAO.getById(schedule.getDdOrderId());
final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId())
.movementDate(movementDate)
.fromLocatorId(schedule.getInTransitLocatorId().orElseThrow()) | .toLocatorId(dropToLocatorId)
.huIdsToMove(schedule.getPickedHUIds())
.build();
final HUMovementGeneratorResult result = new HUMovementGenerator(request).createMovement();
final PPOrderId forwardPPOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID());
if (forwardPPOrderId != null)
{
reserveHUsForManufacturing(forwardPPOrderId, result);
}
return result.getSingleMovementLineId().getMovementId();
}
private void reserveHUsForManufacturing(@NonNull final PPOrderId ppOrderId, @NonNull final HUMovementGeneratorResult result)
{
ppOrderSourceHUService.addSourceHUs(ppOrderId, result.getMovedHUIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\drop_to\DDOrderDropToCommand.java | 1 |
请完成以下Java代码 | public String getFirstName() {
return firstName;
}
@Override
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getPassword() {
return password; | }
@Override
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean isPictureSet() {
return pictureByteArrayRef != null && pictureByteArrayRef.getId() != null;
}
@Override
public ByteArrayRef getPictureByteArrayRef() {
return pictureByteArrayRef;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityImpl.java | 1 |
请完成以下Java代码 | public static final class OrderItemBuilder
{
private final PurchaseCandidate parent;
private final PurchaseOrderItemBuilder innerBuilder;
private OrderItemBuilder(@NonNull final PurchaseCandidate parent)
{
this.parent = parent;
innerBuilder = PurchaseOrderItem.builder().purchaseCandidate(parent);
}
public OrderItemBuilder datePromised(@NonNull final ZonedDateTime datePromised)
{
innerBuilder.datePromised(datePromised);
return this;
}
public OrderItemBuilder dateOrdered(@Nullable final ZonedDateTime dateOrdered)
{
innerBuilder.dateOrdered(dateOrdered);
return this;
}
public OrderItemBuilder purchasedQty(@NonNull final Quantity purchasedQty)
{
innerBuilder.purchasedQty(purchasedQty);
return this;
}
public OrderItemBuilder remotePurchaseOrderId(final String remotePurchaseOrderId)
{
innerBuilder.remotePurchaseOrderId(remotePurchaseOrderId);
return this;
}
public OrderItemBuilder transactionReference(final ITableRecordReference transactionReference)
{
innerBuilder.transactionReference(transactionReference);
return this;
}
public OrderItemBuilder dimension(final Dimension dimension)
{
innerBuilder.dimension(dimension);
return this;
}
public PurchaseOrderItem buildAndAddToParent()
{
final PurchaseOrderItem newItem = innerBuilder.build();
parent.purchaseOrderItems.add(newItem);
return newItem;
}
}
public OrderItemBuilder createOrderItem()
{
return new OrderItemBuilder(this);
}
/**
* Intended to be used by the persistence layer | */
public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem)
{
final PurchaseCandidateId id = getId();
Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this);
Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(),
"The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}",
purchaseOrderItem, this);
purchaseOrderItems.add(purchaseOrderItem);
}
public Quantity getPurchasedQty()
{
return purchaseOrderItems.stream()
.map(PurchaseOrderItem::getPurchasedQty)
.reduce(Quantity::add)
.orElseGet(() -> getQtyToPurchase().toZero());
}
public List<PurchaseOrderItem> getPurchaseOrderItems()
{
return ImmutableList.copyOf(purchaseOrderItems);
}
public List<PurchaseErrorItem> getPurchaseErrorItems()
{
return ImmutableList.copyOf(purchaseErrorItems);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Set<String> getExclusions(AnnotationMetadata metadata, @Nullable AnnotationAttributes attributes) {
Set<String> exclusions = new LinkedHashSet<>();
Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader());
for (String annotationName : ANNOTATION_NAMES) {
AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName);
Class<?>[] exclude = (merged != null) ? merged.getClassArray("exclude") : null;
if (exclude != null) {
for (Class<?> excludeClass : exclude) {
exclusions.add(excludeClass.getName());
}
}
}
for (List<Annotation> annotations : getAnnotations(metadata).values()) {
for (Annotation annotation : annotations) {
String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude");
if (!ObjectUtils.isEmpty(exclude)) {
exclusions.addAll(Arrays.asList(exclude));
}
}
}
exclusions.addAll(getExcludeAutoConfigurationsProperty());
return exclusions;
}
protected final Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) {
MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<>();
Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader());
collectAnnotations(source, annotations, new HashSet<>());
return Collections.unmodifiableMap(annotations);
}
private void collectAnnotations(@Nullable Class<?> source, MultiValueMap<Class<?>, Annotation> annotations,
HashSet<Class<?>> seen) {
if (source != null && seen.add(source)) {
for (Annotation annotation : source.getDeclaredAnnotations()) {
if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) {
if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { | annotations.add(source, annotation);
}
collectAnnotations(annotation.annotationType(), annotations, seen);
}
}
collectAnnotations(source.getSuperclass(), annotations, seen);
}
}
@Override
public int getOrder() {
return super.getOrder() - 1;
}
@Override
protected void handleInvalidExcludes(List<String> invalidExcludes) {
// Ignore for test
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ImportAutoConfigurationImportSelector.java | 2 |
请完成以下Java代码 | protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
feed.setTitle("Baeldung RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.baeldung.com");
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
// Builds the single entries.
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("donatohan.rimenti@gmail.com");
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
Item entryTwo = new Item();
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
entryTwo.setAuthor("donatohan.rimenti@gmail.com");
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
Item entryThree = new Item();
entryThree.setTitle("Flyweight Pattern in Java");
entryThree.setAuthor("donatohan.rimenti@gmail.com");
entryThree.setLink("http://www.baeldung.com/java-flyweight");
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
Item entryFour = new Item();
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
entryFour.setAuthor("donatohan.rimenti@gmail.com");
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z"))); | Item entryFive = new Item();
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
entryFive.setAuthor("donatohan.rimenti@gmail.com");
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item();
entrySix.setTitle("Double-Checked Locking with Singleton");
entrySix.setAuthor("donatohan.rimenti@gmail.com");
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
Item entrySeven = new Item();
entrySeven.setTitle("Introduction to Dagger 2");
entrySeven.setAuthor("donatohan.rimenti@gmail.com");
entrySeven.setLink("http://www.baeldung.com/dagger-2");
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
// Creates the feed.
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-5\src\main\java\com\baeldung\rss\RssFeedView.java | 1 |
请完成以下Java代码 | public void setTaxblBaseAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.taxblBaseAmt = value;
}
/**
* Gets the value of the ttlAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTtlAmt() {
return ttlAmt;
}
/**
* Sets the value of the ttlAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlAmt = value;
}
/**
* Gets the value of the dtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dtls property.
*
* <p> | * For example, to add a new item, do as follows:
* <pre>
* getDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TaxRecordDetails1 }
*
*
*/
public List<TaxRecordDetails1> getDtls() {
if (dtls == null) {
dtls = new ArrayList<TaxRecordDetails1>();
}
return this.dtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxAmount1.java | 1 |
请完成以下Java代码 | public void setS_TimeExpenseLine_ID (int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, Integer.valueOf(S_TimeExpenseLine_ID));
}
/** Get Expense Line.
@return Time and Expense Report Line
*/
public int getS_TimeExpenseLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpenseLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_TimeType getS_TimeType() throws RuntimeException
{
return (I_S_TimeType)MTable.get(getCtx(), I_S_TimeType.Table_Name)
.getPO(getS_TimeType_ID(), get_TrxName()); }
/** Set Time Type.
@param S_TimeType_ID
Type of time recorded
*/
public void setS_TimeType_ID (int S_TimeType_ID)
{ | if (S_TimeType_ID < 1)
set_Value (COLUMNNAME_S_TimeType_ID, null);
else
set_Value (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID));
}
/** Get Time Type.
@return Type of time recorded
*/
public int getS_TimeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeExpenseLine.java | 1 |
请完成以下Java代码 | public static PatternedDateTimeFormatter ofPattern(@NonNull final String pattern)
{
return new PatternedDateTimeFormatter(pattern);
}
@Nullable
public static PatternedDateTimeFormatter ofNullablePattern(@Nullable final String pattern)
{
final String patternNorm = StringUtils.trimBlankToNull(pattern);
if (patternNorm == null)
{
return null;
}
return new PatternedDateTimeFormatter(patternNorm);
} | @Override
@Deprecated
public String toString() {return toPattern();}
public String toPattern() {return pattern;}
@Nullable
public static String toPattern(@Nullable final PatternedDateTimeFormatter obj) {return obj != null ? obj.toPattern() : null;}
@NonNull
public LocalDate parseLocalDate(@NonNull final String valueStr)
{
return LocalDate.parse(valueStr, formatter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\PatternedDateTimeFormatter.java | 1 |
请完成以下Java代码 | private static ADUIElementGroupNameFQ retrieve(final ResultSet rs) throws SQLException
{
return ADUIElementGroupNameFQ.builder()
.uiElementGroupId(AdUIElementGroupId.ofRepoId(rs.getInt(PREFIX + "AD_UI_ElementGroup_ID")))
.name(rs.getString(PREFIX + "Name"))
.uiColumnName(ADUIColumnNameFQ_Loader.retrieve(rs))
.build();
}
}
public static final class ADProcessName_Loader
{
private static final String PREFIX = "process_";
public static ADProcessName retrieve(final AdProcessId adProcessId)
{
final ADProcessName name = DB.retrieveFirstRowOrNull(
"SELECT " + ADProcessName_Loader.sqlSelect("p")
+ " FROM AD_Process p"
+ " WHERE p.AD_Process_ID=?",
Collections.singletonList(adProcessId),
ADProcessName_Loader::retrieve
);
return name != null
? name
: ADProcessName.missing(adProcessId);
}
@SuppressWarnings("SameParameterValue")
private static String sqlSelect(final String tableAlias)
{
return sqlSelectColumn(tableAlias, "Value", PREFIX)
+ ", " + sqlSelectColumn(tableAlias, "Classname", PREFIX);
}
private static ADProcessName retrieve(final ResultSet rs) throws SQLException
{
return ADProcessName.builder()
.value(rs.getString(PREFIX + "Value")) | .classname(rs.getString(PREFIX + "Classname"))
.build();
}
}
public static final class ADElementName_Loader
{
public static String retrieveColumnName(@NonNull final AdElementId adElementId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT ColumnName FROM AD_Element WHERE AD_Element_ID=?",
adElementId);
}
}
public static final class ADMessageName_Loader
{
public static String retrieveValue(@NonNull final AdMessageId adMessageId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT Value FROM AD_Message WHERE AD_Message_ID=?",
adMessageId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\Names.java | 1 |
请完成以下Java代码 | public boolean isEmpty()
{
return documents.isEmpty();
}
public int size()
{
return documents.size();
}
public TableRecordReferenceSet getRootRecords()
{
return TableRecordReferenceSet.of(documents.keySet());
}
public Collection<DocumentToInvalidate> toCollection()
{
return documents.values();
}
DocumentToInvalidateMap combine(@NonNull final DocumentToInvalidateMap other)
{
if (isEmpty())
{
return other;
}
else if (other.isEmpty())
{
return other;
}
else
{
for (final Map.Entry<TableRecordReference, DocumentToInvalidate> e : other.documents.entrySet())
{
this.documents.merge(
e.getKey(),
e.getValue(),
(item1, item2) -> item1.combine(item2));
} | return this;
}
}
public static DocumentToInvalidateMap combine(@NonNull final List<DocumentToInvalidateMap> list)
{
if (list.isEmpty())
{
return new DocumentToInvalidateMap();
}
else if (list.size() == 1)
{
return list.get(0);
}
else
{
return list.stream().reduce(DocumentToInvalidateMap::combine).get();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentToInvalidateMap.java | 1 |
请完成以下Java代码 | public class DDOrderCreatedEvent extends AbstractDDOrderEvent
{
public static final String TYPE = "DDOrderCreatedEvent";
@JsonCreator
@Builder
public DDOrderCreatedEvent(
@JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor,
@JsonProperty("ddOrder") @NonNull final DDOrder ddOrder,
@JsonProperty("supplyRequiredDescriptor") @Nullable final SupplyRequiredDescriptor supplyRequiredDescriptor)
{
super(
eventDescriptor,
ddOrder,
supplyRequiredDescriptor);
}
public static DDOrderCreatedEvent of(@NonNull final DDOrder ddOrder,
@NonNull final EventDescriptor eventDescriptor)
{ | return builder()
.eventDescriptor(eventDescriptor.withClientAndOrg(ddOrder.getClientAndOrgId()))
.ddOrder(ddOrder)
.build();
}
public static DDOrderCreatedEvent cast(@NonNull final AbstractDDOrderEvent ddOrderEvent)
{
return (DDOrderCreatedEvent)ddOrderEvent;
}
@Override
public String getEventName() {return TYPE;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddorder\DDOrderCreatedEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class TeacherController {
@ApiOperation(value = "xxx")
@GetMapping("/xxx")
public String xxx() {
return "xxx";
}
}
@Api(tags = {"2-学生管理"})
@RestController
@RequestMapping(value = "/student")
static class StudentController {
@ApiOperation(value = "获取学生清单", tags = "3-教学管理")
@GetMapping("/list")
public String bbb() {
return "bbb"; | }
@ApiOperation("获取教某个学生的老师清单")
@GetMapping("/his-teachers")
public String ccc() {
return "ccc";
}
@ApiOperation("创建一个学生")
@PostMapping("/aaa")
public String aaa() {
return "aaa";
}
}
} | repos\SpringBoot-Learning-master\2.x\chapter2-4\src\main\java\com\didispace\chapter24\Chapter24Application.java | 2 |
请完成以下Java代码 | public GatewayFilter apply(NameValueConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange).then(Mono.fromRunnable(() -> addHeader(exchange, config)));
}
@Override
public String toString() {
String name = config.getName();
String value = config.getValue();
if (config instanceof Config) {
return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this)
.append(GatewayFilter.NAME_KEY, name != null ? name : "")
.append(GatewayFilter.VALUE_KEY, value != null ? value : "")
.append(OVERRIDE_KEY, ((Config) config).isOverride())
.toString();
}
return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this)
.append(name != null ? name : "", value != null ? value : "")
.toString();
}
};
}
void addHeader(ServerWebExchange exchange, NameValueConfig config) {
// if response has been commited, no more response headers will bee added.
if (!exchange.getResponse().isCommitted()) {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null");
final String value = ServerWebExchangeUtils.expand(exchange, rawValue);
HttpHeaders headers = exchange.getResponse().getHeaders();
boolean override = true; // default is true
if (config instanceof Config) {
override = ((Config) config).isOverride();
}
if (override) {
headers.add(name, value);
}
else {
boolean headerIsMissingOrBlank = headers.getOrEmpty(name)
.stream()
.allMatch(h -> !StringUtils.hasText(h));
if (headerIsMissingOrBlank) {
headers.add(name, value); | }
}
}
}
public static class Config extends AbstractNameValueGatewayFilterFactory.NameValueConfig {
private boolean override = true;
public boolean isOverride() {
return override;
}
public Config setOverride(boolean override) {
this.override = override;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append(NAME_KEY, name)
.append(VALUE_KEY, value)
.append(OVERRIDE_KEY, override)
.toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddResponseHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | private Inventory createAndCompleteInventory()
{
final Quantity targetWeightNet = Quantity.of(targetWeight.getWeightNet(), targetWeight.getWeightNetUOM());
final UpdateHUQtyRequest updateHUQtyRequest = UpdateHUQtyRequest.builder()
.qty(targetWeightNet)
.huId(huId)
.build();
return huQtyService.updateQty(updateHUQtyRequest);
}
private void updateHUWeights()
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IWeightable huAttributes = getHUAttributes(hu);
huAttributes.setWeightTareAdjust(targetWeight.getWeightTareAdjust());
huAttributes.setWeightGross(targetWeight.getWeightGross());
huAttributes.setWeightNet(targetWeight.getWeightNet()); | huAttributes.setWeightNetNoPropagate(targetWeight.getWeightNet());
}
private IWeightable getHUAttributes(final I_M_HU hu)
{
final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class);
final IAttributeStorage huAttributes = huContextFactory
.createMutableHUContext()
.getHUAttributeStorageFactory()
.getAttributeStorage(hu);
huAttributes.setSaveOnChange(true);
return Weightables.wrap(huAttributes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\weighting\WeightHUCommand.java | 1 |
请完成以下Java代码 | public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds);
return this;
}
public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) {
this.ctx = ctx;
return this;
}
public TbMsgBuilder callback(TbMsgCallback callback) {
this.callback = callback;
return this;
} | public TbMsg build() {
return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback);
}
public String toString() {
return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts +
", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator +
", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType +
", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId +
", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds +
", ctx=" + this.ctx + ", callback=" + this.callback + ")";
}
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java | 1 |
请完成以下Java代码 | public void cleanupExpiredSessions() {
Set<Object> sessionIds = this.redisOps.opsForZSet()
.reverseRangeByScore(this.expirationsKey, 0, this.clock.millis(), 0, this.cleanupCount);
if (CollectionUtils.isEmpty(sessionIds)) {
return;
}
for (Object sessionId : sessionIds) {
String sessionKey = getSessionKey((String) sessionId);
touch(sessionKey);
}
}
private Instant getExpirationTime(RedisIndexedSessionRepository.RedisSession session) {
return session.getLastAccessedTime().plus(session.getMaxInactiveInterval());
}
/**
* Checks if the session exists. By trying to access the session we only trigger a
* deletion if the TTL is expired. This is done to handle
* <a href="https://github.com/spring-projects/spring-session/issues/93">gh-93</a>
* @param sessionKey the key
*/
private void touch(String sessionKey) {
this.redisOps.hasKey(sessionKey);
}
private String getSessionKey(String sessionId) {
return this.namespace + ":sessions:" + sessionId;
}
/**
* Set the namespace for the keys.
* @param namespace the namespace
*/
public void setNamespace(String namespace) {
Assert.hasText(namespace, "namespace cannot be null or empty");
this.namespace = namespace;
this.expirationsKey = this.namespace + ":sessions:expirations"; | }
/**
* Configure the clock used when retrieving expired sessions for clean-up.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
/**
* Configures how many sessions will be queried at a time to be cleaned up. Defaults
* to 100.
* @param cleanupCount how many sessions to be queried, must be bigger than 0.
*/
public void setCleanupCount(int cleanupCount) {
Assert.state(cleanupCount > 0, "cleanupCount must be greater than 0");
this.cleanupCount = cleanupCount;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetRedisSessionExpirationStore.java | 1 |
请完成以下Java代码 | private static final BigDecimal add(final BigDecimal bd1, final BigDecimal bd2)
{
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.add(bd2);
}
return result;
}
/**
*
* @param bd1
* @param bd2
* @return bd1 - bd2
*/
private static final BigDecimal subtract(final BigDecimal bd1, final BigDecimal bd2) | {
BigDecimal result;
if (bd1 != null)
{
result = bd1;
}
else
{
result = BigDecimal.ZERO;
}
if (bd2 != null)
{
result = result.subtract(bd2);
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUDeliveryQuantitiesHelper.java | 1 |
请完成以下Java代码 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userId = authentication.getName();
String password = authentication.getCredentials().toString();
boolean authenticated = idmIdentityService.checkPassword(userId, password);
if (authenticated) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(1);
if (isVerifyRestApiPrivilege()) {
List<Privilege> privileges = idmIdentityService.createPrivilegeQuery().userId(userId).list();
for (Privilege privilege : privileges) {
grantedAuthorities.add(new SimpleGrantedAuthority(privilege.getName()));
}
} else {
// Always add the role when it's not verified: this makes the config easier (i.e. user needs to have it)
grantedAuthorities.add(new SimpleGrantedAuthority(SecurityConstants.PRIVILEGE_ACCESS_REST_API));
}
return new UsernamePasswordAuthenticationToken(userId, password, grantedAuthorities);
} else {
throw new BadCredentialsException("Authentication failed for this username and password"); | }
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public boolean isVerifyRestApiPrivilege() {
return verifyRestApiPrivilege;
}
public void setVerifyRestApiPrivilege(boolean verifyRestApiPrivilege) {
this.verifyRestApiPrivilege = verifyRestApiPrivilege;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\security\BasicAuthenticationProvider.java | 1 |
请完成以下Java代码 | public boolean isValid()
{
loadIfNeeded();
return notValidReasons.isEmpty();
}
public String getNotValidReasons()
{
return StringUtils.toString(notValidReasons, "; ");
}
public IAttributeSetInstanceAware getM_Product()
{
return attributeSetInstanceAware;
}
public I_C_UOM getC_UOM()
{
return uom;
}
public BigDecimal getQty()
{
return qty;
}
public Timestamp getDateOrdered()
{
return dateOrdered;
}
/**
* @return locator where Quantity currently is
*/
public I_M_Locator getM_Locator()
{
return locator;
}
public DistributionNetworkLine getDD_NetworkDistributionLine()
{
loadIfNeeded();
return networkLine;
} | public ResourceId getRawMaterialsPlantId()
{
loadIfNeeded();
return rawMaterialsPlantId;
}
public I_M_Warehouse getRawMaterialsWarehouse()
{
loadIfNeeded();
return rawMaterialsWarehouse;
}
public I_M_Locator getRawMaterialsLocator()
{
loadIfNeeded();
return rawMaterialsLocator;
}
public OrgId getOrgId()
{
loadIfNeeded();
return orgId;
}
public BPartnerLocationId getOrgBPLocationId()
{
loadIfNeeded();
return orgBPLocationId;
}
public UserId getPlannerId()
{
loadIfNeeded();
return productPlanning == null ? null : productPlanning.getPlannerId();
}
public WarehouseId getInTransitWarehouseId()
{
loadIfNeeded();
return inTransitWarehouseId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\RawMaterialsReturnDDOrderLineCandidate.java | 1 |
请完成以下Java代码 | public class MatchWords {
public static boolean containsWordsIndexOf(String inputString, String[] words) {
boolean found = true;
for (String word : words) {
if (inputString.indexOf(word) == -1) {
found = false;
break;
}
}
return found;
}
public static boolean containsWords(String inputString, String[] items) {
boolean found = true;
for (String item : items) {
if (!inputString.contains(item)) {
found = false;
break;
}
}
return found;
}
public static boolean containsWordsAhoCorasick(String inputString, String[] words) {
Trie trie = Trie.builder()
.onlyWholeWords()
.addKeywords(words)
.build();
Collection<Emit> emits = trie.parseText(inputString);
emits.forEach(System.out::println);
boolean found = true;
for(String word : words) {
boolean contains = Arrays.toString(emits.toArray()).contains(word);
if (!contains) { | found = false;
break;
}
}
return found;
}
public static boolean containsWordsPatternMatch(String inputString, String[] words) {
StringBuilder regexp = new StringBuilder();
for (String word : words) {
regexp.append("(?=.*").append(word).append(")");
}
Pattern pattern = Pattern.compile(regexp.toString());
return pattern.matcher(inputString).find();
}
public static boolean containsWordsJava8(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return wordsList.stream().allMatch(inputStringList::contains);
}
public static boolean containsWordsArray(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return inputStringList.containsAll(wordsList);
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-4\src\main\java\com\baeldung\matchwords\MatchWords.java | 1 |
请完成以下Java代码 | public static void showCenterWindowModal(final JFrame modalFrame, final JFrame parentFrame, final Runnable onCloseCallback)
{
Check.assumeNotNull(modalFrame, "modalFrame not null");
Check.assumeNotNull(parentFrame, "parentFrame not null");
modalFrame.addWindowListener(new WindowAdapter()
{
@Override
public void windowOpened(final WindowEvent e)
{
//
// Disable frame (make new frame behave like a modal frame)
parentFrame.setFocusable(false);
parentFrame.setEnabled(false);
}
@Override
public void windowActivated(final WindowEvent e)
{
windowGainedFocus(e);
}
@Override
public void windowDeactivated(final WindowEvent e)
{
// nothing
}
@Override
public void windowGainedFocus(final WindowEvent e)
{
// nothing
}
@Override
public void windowLostFocus(final WindowEvent e)
{
// nothing
}
@Override
public void windowClosed(final WindowEvent e)
{
//
// Re-enable frame
parentFrame.setFocusable(true);
parentFrame.setEnabled(true);
modalFrame.removeWindowListener(this);
if (onCloseCallback != null)
{
onCloseCallback.run();
}
parentFrame.toFront();
}
});
parentFrame.addWindowListener(new WindowAdapter()
{ | @Override
public void windowActivated(final WindowEvent e)
{
windowGainedFocus(e);
}
@Override
public void windowDeactivated(final WindowEvent e)
{
// nothing
}
@Override
public void windowGainedFocus(final WindowEvent e)
{
EventQueue.invokeLater(() -> {
if (modalFrame == null || !modalFrame.isVisible() || !modalFrame.isShowing())
{
return;
}
modalFrame.toFront();
modalFrame.repaint();
});
}
@Override
public void windowLostFocus(final WindowEvent e)
{
// nothing
}
});
if (modalFrame instanceof CFrame)
{
addToWindowManager(modalFrame);
}
showCenterWindow(parentFrame, modalFrame);
}
/**
* Create a {@link FormFrame} for the given {@link I_AD_Form}.
*
* @return formFrame which was created or null
*/
public static FormFrame createForm(final I_AD_Form form)
{
final FormFrame formFrame = new FormFrame();
if (formFrame.openForm(form))
{
formFrame.pack();
return formFrame;
}
else
{
formFrame.dispose();
return null;
}
}
} // AEnv | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AEnv.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DesadvLines
{
@NonNull
Map<Integer, EDIExpDesadvLineType> lineId2LineWithNoPacks;
@NonNull
Map<Integer, DesadvLineWithPacks> lineId2LineWithPacks;
public boolean isEmpty()
{
return lineId2LineWithNoPacks.isEmpty() && lineId2LineWithPacks.isEmpty();
}
@NonNull
public List<EDIExpDesadvLineType> getAllLines()
{
return Stream.concat(lineId2LineWithNoPacks.values().stream(),
lineId2LineWithPacks.values().stream().map(DesadvLineWithPacks::getDesadvLine))
.collect(ImmutableList.toImmutableList()); | }
@NonNull
public List<EDIExpDesadvLineType> getAllSortedByLine()
{
return Stream.concat(lineId2LineWithNoPacks.values().stream(),
lineId2LineWithPacks.values().stream().map(DesadvLineWithPacks::getDesadvLine))
.sorted(Comparator.comparing(EDIExpDesadvLineType::getLine))
.collect(ImmutableList.toImmutableList());
}
@NonNull
public List<SinglePack> getPacksForLine(@NonNull final Integer desadvLineId)
{
return Optional.ofNullable(lineId2LineWithPacks.get(desadvLineId))
.map(DesadvLineWithPacks::getSinglePacks)
.orElseGet(ImmutableList::of);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\helper\DesadvLines.java | 2 |
请完成以下Java代码 | public void createMembership(String userId, String groupId) {
getIdmIdentityService().createMembership(userId, groupId);
}
@Override
public void deleteGroup(String groupId) {
getIdmIdentityService().deleteGroup(groupId);
}
@Override
public void deleteMembership(String userId, String groupId) {
getIdmIdentityService().deleteMembership(userId, groupId);
}
@Override
public boolean checkPassword(String userId, String password) {
return getIdmIdentityService().checkPassword(userId, password);
}
@Override
public void deleteUser(String userId) {
getIdmIdentityService().deleteUser(userId);
}
@Override
public void setUserPicture(String userId, Picture picture) {
getIdmIdentityService().setUserPicture(userId, picture);
}
@Override
public Picture getUserPicture(String userId) {
return getIdmIdentityService().getUserPicture(userId);
}
@Override
public void setAuthenticatedUserId(String authenticatedUserId) {
Authentication.setAuthenticatedUserId(authenticatedUserId);
}
@Override
public String getUserInfo(String userId, String key) {
return getIdmIdentityService().getUserInfo(userId, key);
} | @Override
public List<String> getUserInfoKeys(String userId) {
return getIdmIdentityService().getUserInfoKeys(userId);
}
@Override
public void setUserInfo(String userId, String key, String value) {
getIdmIdentityService().setUserInfo(userId, key, value);
}
@Override
public void deleteUserInfo(String userId, String key) {
getIdmIdentityService().deleteUserInfo(userId, key);
}
protected IdmIdentityService getIdmIdentityService() {
IdmIdentityService idmIdentityService = EngineServiceUtil.getIdmIdentityService(configuration);
if (idmIdentityService == null) {
throw new FlowableException("Trying to use idm identity service when it is not initialized");
}
return idmIdentityService;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\IdentityServiceImpl.java | 1 |
请完成以下Java代码 | public int getExternalSystem_Config_ScriptedExportConversion_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ScriptedExportConversion_ID);
}
@Override
public void setExternalSystem_Outbound_Endpoint_ID (final int ExternalSystem_Outbound_Endpoint_ID)
{
if (ExternalSystem_Outbound_Endpoint_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, ExternalSystem_Outbound_Endpoint_ID);
}
@Override
public int getExternalSystem_Outbound_Endpoint_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID);
}
@Override
public void setExternalSystemValue (final String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
}
@Override
public String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override
public void setScriptIdentifier (final String ScriptIdentifier) | {
set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier);
}
@Override
public String getScriptIdentifier()
{
return get_ValueAsString(COLUMNNAME_ScriptIdentifier);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setWhereClause (final String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedExportConversion.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected static IndexRequest buildIndexRequest(String index, String id, Object object) {
return new IndexRequest(index).id(id).source(BeanUtil.beanToMap(object), XContentType.JSON);
}
/**
* exec updateRequest
*
* @param index elasticsearch index name
* @param id Document id
* @param object request object
* @author fxbin
*/
protected void updateRequest(String index, String id, Object object) {
try {
UpdateRequest updateRequest = new UpdateRequest(index, id).doc(BeanUtil.beanToMap(object), XContentType.JSON);
client.update(updateRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("更新索引 {" + index + "} 数据 {" + object + "} 失败");
}
}
/**
* exec deleteRequest
*
* @param index elasticsearch index name
* @param id Document id
* @author fxbin
*/
protected void deleteRequest(String index, String id) { | try {
DeleteRequest deleteRequest = new DeleteRequest(index, id);
client.delete(deleteRequest, COMMON_OPTIONS);
} catch (IOException e) {
throw new ElasticsearchException("删除索引 {" + index + "} 数据id {" + id + "} 失败");
}
}
/**
* search all
*
* @param index elasticsearch index name
* @return {@link SearchResponse}
* @author fxbin
*/
protected SearchResponse search(String index) {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest, COMMON_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
return searchResponse;
}
} | repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\service\base\BaseElasticsearchService.java | 2 |
请完成以下Java代码 | private boolean atLeastOneData(TbMsg msg) {
if (!messageNamesList.isEmpty()) {
Map<String, String> dataMap = dataToMap(msg);
return processAtLeastOne(messageNamesList, dataMap);
}
return false;
}
private boolean atLeastOneMetadata(TbMsg msg) {
if (!metadataNamesList.isEmpty()) {
Map<String, String> metadataMap = metadataToMap(msg);
return processAtLeastOne(metadataNamesList, metadataMap);
}
return false;
}
private boolean processAllKeys(List<String> data, Map<String, String> map) {
for (String field : data) {
if (!map.containsKey(field)) {
return false;
}
}
return true;
} | private boolean processAtLeastOne(List<String> data, Map<String, String> map) {
for (String field : data) {
if (map.containsKey(field)) {
return true;
}
}
return false;
}
private Map<String, String> metadataToMap(TbMsg msg) {
return msg.getMetaData().getData();
}
@SuppressWarnings("unchecked")
private Map<String, String> dataToMap(TbMsg msg) {
return (Map<String, String>) gson.fromJson(msg.getData(), Map.class);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\filter\TbCheckMessageNode.java | 1 |
请完成以下Java代码 | public EventInstance getEventInstance() {
return eventInstance;
}
public void setEventInstance(EventInstance eventInstance) {
this.eventInstance = eventInstance;
}
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type; | }
@Override
public EventInstance getEventObject() {
return eventInstance;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("type='" + type + "'")
.add("eventInstance=" + eventInstance)
.toString();
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\event\FlowableEventRegistryEvent.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the issr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssr() { | return issr;
}
/**
* Sets the value of the issr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssr(String value) {
this.issr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericIdentification3.java | 1 |
请完成以下Java代码 | @Nullable public I_C_BPartner fetchManufacturer(@NonNull final String manufacturer_IFA_Value)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_BPartner.class)
.addEqualsFilter(I_C_BPartner.COLUMNNAME_IFA_Manufacturer, manufacturer_IFA_Value)
.create()
.firstOnly(I_C_BPartner.class);
}
final public I_C_BPartner importRecord(@NonNull final I_I_Pharma_BPartner importRecord)
{
final I_C_BPartner bpartner;
if (importRecord.getC_BPartner_ID() <= 0) // Insert new BPartner
{
bpartner = createNewBPartner(importRecord);
}
else
{
bpartner = updateExistingBPartner(importRecord);
}
save(bpartner);
importRecord.setC_BPartner(bpartner);
return bpartner;
}
private I_C_BPartner createNewBPartner(@NonNull final I_I_Pharma_BPartner importRecord)
{
final I_C_BPartner bpartner = InterfaceWrapperHelper.newInstance(I_C_BPartner.class);
bpartner.setAD_Org_ID(importRecord.getAD_Org_ID());
bpartner.setCompanyName(extractCompanyName(importRecord));
bpartner.setIsCompany(true);
bpartner.setName(extractCompanyName(importRecord));
bpartner.setName2(importRecord.getb00name2());
bpartner.setName3(importRecord.getb00name3());
bpartner.setIFA_Manufacturer(importRecord.getb00adrnr());
bpartner.setDescription("IFA " + importRecord.getb00adrnr());
bpartner.setIsManufacturer(true);
bpartner.setURL(importRecord.getb00homepag());
return bpartner;
}
private String extractCompanyName(@NonNull final I_I_Pharma_BPartner importRecord)
{
if (!Check.isEmpty(importRecord.getb00name1(), true))
{
return importRecord.getb00name1();
}
if (!Check.isEmpty(importRecord.getb00email(), true)) | {
return importRecord.getb00email();
}
if (!Check.isEmpty(importRecord.getb00email2(), true))
{
return importRecord.getb00email2();
}
return importRecord.getb00adrnr();
}
private I_C_BPartner updateExistingBPartner(@NonNull final I_I_Pharma_BPartner importRecord)
{
final I_C_BPartner bpartner;
bpartner = InterfaceWrapperHelper.create(importRecord.getC_BPartner(), I_C_BPartner.class);
if (!Check.isEmpty(importRecord.getb00name1(), true))
{
bpartner.setIsCompany(true);
bpartner.setCompanyName(importRecord.getb00name1());
bpartner.setName(importRecord.getb00name1());
}
if (!Check.isEmpty(importRecord.getb00name2()))
{
bpartner.setName2(importRecord.getb00name2());
}
if (!Check.isEmpty(importRecord.getb00name3()))
{
bpartner.setName3(importRecord.getb00name3());
}
if (!Check.isEmpty(importRecord.getb00adrnr()))
{
bpartner.setIFA_Manufacturer(importRecord.getb00adrnr());
bpartner.setDescription("IFA " + importRecord.getb00adrnr());
}
bpartner.setIsManufacturer(true);
if (!Check.isEmpty(importRecord.getb00homepag()))
{
bpartner.setURL(importRecord.getb00homepag());
}
return bpartner;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerImportHelper.java | 1 |
请完成以下Java代码 | public class GetDeploymentCaseDiagramCmd implements Command<InputStream>, Serializable {
private static final long serialVersionUID = 1L;
protected String caseDefinitionId;
public GetDeploymentCaseDiagramCmd(String caseDefinitionId) {
if (caseDefinitionId == null || caseDefinitionId.length() < 1) {
throw new ProcessEngineException("The case definition id is mandatory, but '" + caseDefinitionId + "' has been provided.");
}
this.caseDefinitionId = caseDefinitionId;
}
@Override
public InputStream execute(final CommandContext commandContext) {
CaseDefinitionEntity caseDefinition = Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.findDeployedCaseDefinitionById(caseDefinitionId); | for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkReadCaseDefinition(caseDefinition);
}
final String deploymentId = caseDefinition.getDeploymentId();
final String resourceName = caseDefinition.getDiagramResourceName();
InputStream caseDiagramStream = null;
if (resourceName != null) {
caseDiagramStream = commandContext.runWithoutAuthorization(new GetDeploymentResourceCmd(deploymentId, resourceName));
}
return caseDiagramStream;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\cmd\GetDeploymentCaseDiagramCmd.java | 1 |
请完成以下Java代码 | public NotificationItem build()
{
return new NotificationItem(this);
}
/**
* @param summary detail HTML text
*/
public Builder setSummary(final String summary)
{
this.summary = summary;
return this;
}
/** | * @param detail detail HTML text
*/
public Builder setDetail(String detail)
{
this.detail = detail;
return this;
}
public Builder setSenderName(String senderName)
{
this.senderName = senderName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\NotificationItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | OtelPropagator otelPropagator(ContextPropagators contextPropagators, Tracer tracer) {
return new OtelPropagator(contextPropagators, tracer);
}
@Bean
@ConditionalOnMissingBean
EventPublisher otelTracerEventPublisher(List<EventListener> eventListeners) {
return new OTelEventPublisher(eventListeners);
}
@Bean
@ConditionalOnMissingBean
OtelCurrentTraceContext otelCurrentTraceContext() {
return new OtelCurrentTraceContext();
}
@Bean
@ConditionalOnMissingBean
Slf4JEventListener otelSlf4JEventListener() {
return new Slf4JEventListener();
}
@Bean
@ConditionalOnMissingBean(SpanCustomizer.class)
OtelSpanCustomizer otelSpanCustomizer() {
return new OtelSpanCustomizer();
}
static class OTelEventPublisher implements EventPublisher { | private final List<EventListener> listeners;
OTelEventPublisher(List<EventListener> listeners) {
this.listeners = listeners;
}
@Override
public void publishEvent(Object event) {
for (EventListener listener : this.listeners) {
listener.onEvent(event);
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingAutoConfiguration.java | 2 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_Depreciation[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Depreciation Type.
@param A_Depreciation_ID Depreciation Type */
public void setA_Depreciation_ID (int A_Depreciation_ID)
{
if (A_Depreciation_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, Integer.valueOf(A_Depreciation_ID));
}
/** Get Depreciation Type.
@return Depreciation Type */
public int getA_Depreciation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set DepreciationType.
@param DepreciationType DepreciationType */
public void setDepreciationType (String DepreciationType)
{
set_Value (COLUMNNAME_DepreciationType, DepreciationType);
}
/** Get DepreciationType.
@return DepreciationType */
public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
} | /** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java | 1 |
请完成以下Java代码 | public ILockCommand setAutoCleanup(final boolean autoCleanup)
{
this._autoCleanup = autoCleanup;
return this;
}
@Override
public final boolean isAutoCleanup()
{
if (_autoCleanup != null)
{
return _autoCleanup;
}
else if (_parentLock != null)
{
return _parentLock.isAutoCleanup();
}
else
{
return DEFAULT_AutoCleanup;
}
}
@Override
public ILockCommand setFailIfAlreadyLocked(final boolean failIfAlreadyLocked)
{
this.failIfAlreadyLocked = failIfAlreadyLocked;
return this;
}
@Override
public final boolean isFailIfAlreadyLocked()
{
return failIfAlreadyLocked;
}
@Override
public ILockCommand setFailIfNothingLocked(final boolean failIfNothingLocked)
{
this.failIfNothingLocked = failIfNothingLocked;
return this;
}
@Override
public boolean isFailIfNothingLocked()
{
return failIfNothingLocked;
}
@Override
public ILockCommand retryOnFailure(final int retryOnFailure)
{
this.retryOnFailure = Math.max(retryOnFailure, 0);
return this;
}
@Override
public int getRetryOnFailure() {return retryOnFailure;}
@Override
public ILockCommand setRecordByModel(final Object model)
{
_recordsToLock.setRecordByModel(model);
return this;
}
@Override
public ILockCommand setRecordByTableRecordId(final int tableId, final int recordId)
{ | _recordsToLock.setRecordByTableRecordId(tableId, recordId);
return this;
}
@Override
public ILockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId pinstanceId)
{
_recordsToLock.setRecordsBySelection(modelClass, pinstanceId);
return this;
}
@Override
public <T> ILockCommand setRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.setRecordsByFilter(clazz, filters);
return this;
}
@Override
public <T> ILockCommand addRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.addRecordsByFilter(clazz, filters);
return this;
}
@Override
public List<LockRecordsByFilter> getSelectionToLock_Filters()
{
return _recordsToLock.getSelection_Filters();
}
@Override
public final AdTableId getSelectionToLock_AD_Table_ID()
{
return _recordsToLock.getSelection_AD_Table_ID();
}
@Override
public final PInstanceId getSelectionToLock_AD_PInstance_ID()
{
return _recordsToLock.getSelection_PInstanceId();
}
@Override
public final Iterator<TableRecordReference> getRecordsToLockIterator()
{
return _recordsToLock.getRecordsIterator();
}
@Override
public LockCommand addRecordByModel(final Object model)
{
_recordsToLock.addRecordByModel(model);
return this;
}
@Override
public LockCommand addRecordsByModel(final Collection<?> models)
{
_recordsToLock.addRecordByModels(models);
return this;
}
@Override
public ILockCommand addRecord(@NonNull final TableRecordReference record)
{
_recordsToLock.addRecords(ImmutableSet.of(record));
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java | 1 |
请完成以下Java代码 | public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) {
getDbSqlSession().delete(
"deleteEventSubscriptionsForProcessDefinition",
processDefinitionId,
EventSubscriptionEntityImpl.class
);
}
protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList<
SignalEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) {
signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity);
} | return signalEventSubscriptionEntities;
}
protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList<
MessageEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) {
messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity);
}
return messageEventSubscriptionEntities;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisEventSubscriptionDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
if (parameter.getParameterAnnotation(TokenToUser.class) instanceof TokenToUser) {
AdminUser adminUser = null;
String token = webRequest.getHeader("token");
if (null != token && !"".equals(token) && token.length() == 32) {
adminUser = adminUserService.getAdminUserByToken(token);
}
return adminUser;
}
return null;
}
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if (contentLength < 0) { | return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength; ) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\config\handler\TokenToUserMethodArgumentResolver.java | 2 |
请完成以下Java代码 | protected boolean supportsConcurrentChildInstantiation(ScopeImpl flowScope) {
CoreActivityBehavior<?> behavior = flowScope.getActivityBehavior();
return behavior == null || !(behavior instanceof SequentialMultiInstanceActivityBehavior);
}
protected ExecutionEntity getSingleExecutionForScope(ActivityExecutionTreeMapping mapping, ScopeImpl scope) {
Set<ExecutionEntity> executions = mapping.getExecutions(scope);
if (!executions.isEmpty()) {
if (executions.size() > 1) {
throw new ProcessEngineException("Executions for activity " + scope + " ambiguous");
}
return executions.iterator().next();
}
else {
return null;
}
}
protected boolean isConcurrentStart(ActivityStartBehavior startBehavior) {
return startBehavior == ActivityStartBehavior.DEFAULT
|| startBehavior == ActivityStartBehavior.CONCURRENT_IN_FLOW_SCOPE;
}
protected void instantiate(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) {
if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, null, (PvmTransition) targetElement, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivities(parentFlowScopes, (PvmActivity) targetElement, null, variables, variablesLocal,
skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected void instantiateConcurrent(ExecutionEntity ancestorScopeExecution, List<PvmActivity> parentFlowScopes, CoreModelElement targetElement) { | if (PvmTransition.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, null, (PvmTransition) targetElement, variables,
variablesLocal, skipCustomListeners, skipIoMappings);
}
else if (PvmActivity.class.isAssignableFrom(targetElement.getClass())) {
ancestorScopeExecution.executeActivitiesConcurrent(parentFlowScopes, (PvmActivity) targetElement, null, variables,
variablesLocal, skipCustomListeners, skipIoMappings);
}
else {
throw new ProcessEngineException("Cannot instantiate element " + targetElement);
}
}
protected abstract ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition);
protected abstract CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition);
protected abstract String getTargetElementId();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractInstantiationCmd.java | 1 |
请完成以下Java代码 | public List<String> userCandidates(String taskId) {
List<IdentityLink> identityLinks = getIdentityLinks(taskId);
List<String> userCandidates = new ArrayList<>();
if (identityLinks != null) {
for (IdentityLink i : identityLinks) {
if (i.getUserId() != null) {
if (i.getType().equals(IdentityLinkType.CANDIDATE)) {
userCandidates.add(i.getUserId());
}
}
}
}
return userCandidates;
}
@Override
public List<String> groupCandidates(String taskId) {
List<IdentityLink> identityLinks = getIdentityLinks(taskId);
List<String> groupCandidates = new ArrayList<>(); | if (identityLinks != null) {
for (IdentityLink i : identityLinks) {
if (i.getGroupId() != null) {
if (i.getType().equals(IdentityLinkType.CANDIDATE)) {
groupCandidates.add(i.getGroupId());
}
}
}
}
return groupCandidates;
}
private List<IdentityLink> getIdentityLinks(String taskId) {
return taskService.getIdentityLinksForTask(taskId);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskAdminRuntimeImpl.java | 1 |
请完成以下Java代码 | protected PageData<Asset> findEntities(TenantId tenantId, CustomerId id, PageLink pageLink) {
return assetDao.findAssetsByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Asset entity) {
unassignAssetFromCustomer(tenantId, new AssetId(entity.getId().getId()));
}
};
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findAssetById(tenantId, new AssetId(entityId.getId())));
}
@Override | public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findAssetByIdAsync(tenantId, new AssetId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return assetDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\asset\BaseAssetService.java | 1 |
请完成以下Java代码 | public int getReconciledBy_SAP_GLJournalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID);
}
@Override
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
@Override
public java.lang.String getReferenceNo()
{
return get_ValueAsString(COLUMNNAME_ReferenceNo);
}
@Override
public void setStatementLineDate (final java.sql.Timestamp StatementLineDate)
{
set_Value (COLUMNNAME_StatementLineDate, StatementLineDate);
}
@Override
public java.sql.Timestamp getStatementLineDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate);
}
@Override
public void setStmtAmt (final BigDecimal StmtAmt)
{
set_Value (COLUMNNAME_StmtAmt, StmtAmt);
}
@Override
public BigDecimal getStmtAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTrxAmt (final BigDecimal TrxAmt) | {
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
@Override
public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValutaDate (final java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLine.java | 1 |
请完成以下Java代码 | public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(boolean isLeaf) {
this.isLeaf = isLeaf;
}
public String getPermsType() {
return permsType;
}
public void setPermsType(String permsType) {
this.permsType = permsType;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */ | public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
public boolean isHideTab() {
return hideTab;
}
public void setHideTab(boolean hideTab) {
this.hideTab = hideTab;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java | 1 |
请完成以下Java代码 | public void setMobilePhone (java.lang.String MobilePhone)
{
set_Value (COLUMNNAME_MobilePhone, MobilePhone);
}
/** Get Handynummer.
@return Handynummer */
@Override
public java.lang.String getMobilePhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_MobilePhone);
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Role name.
@param RoleName Role name */
@Override
public void setRoleName (java.lang.String RoleName) | {
set_Value (COLUMNNAME_RoleName, RoleName);
}
/** Get Role name.
@return Role name */
@Override
public java.lang.String getRoleName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RoleName);
}
/** Set UserValue.
@param UserValue UserValue */
@Override
public void setUserValue (java.lang.String UserValue)
{
set_Value (COLUMNNAME_UserValue, UserValue);
}
/** Get UserValue.
@return UserValue */
@Override
public java.lang.String getUserValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java | 1 |
请完成以下Java代码 | private String getCountryCode(@NonNull final I_M_PriceList priceList)
{
return Optional.ofNullable(CountryId.ofRepoIdOrNull(priceList.getC_Country_ID()))
.map(countryDAO::getById)
.map(I_C_Country::getCountryCode)
.orElse(null);
}
@NonNull
private BPartnerId getBPartnerId()
{
return jsonRetrieverService.resolveBPartnerExternalIdentifier(bpartnerIdentifier, orgId)
.orElseThrow(() -> new InvalidIdentifierException("No BPartner found for identifier")
.appendParametersToMessage()
.setParameter("ExternalIdentifier", bpartnerIdentifier));
}
@NonNull
private ProductId getProductId()
{
return externalIdentifierResolver.resolveProductExternalIdentifier(productIdentifier, orgId)
.orElseThrow(() -> new InvalidIdentifierException("Fail to resolve product external identifier")
.appendParametersToMessage()
.setParameter("ExternalIdentifier", productIdentifier));
}
@NonNull
private ZonedDateTime getTargetDateAndTime()
{
final ZonedDateTime zonedDateTime = TimeUtil.asZonedDateTime(targetDate, orgDAO.getTimeZone(orgId));
Check.assumeNotNull(zonedDateTime, "zonedDateTime is not null!");
return zonedDateTime;
}
@NonNull
private List<JsonResponsePrice> getJsonResponsePrices(
@NonNull final ProductId productId,
@NonNull final String productValue,
@NonNull final PriceListVersionId priceListVersionId)
{ | return bpartnerPriceListServicesFacade.getProductPricesByPLVAndProduct(priceListVersionId, productId)
.stream()
.map(productPrice -> JsonResponsePrice.builder()
.productId(JsonMetasfreshId.of(productId.getRepoId()))
.productCode(productValue)
.taxCategoryId(JsonMetasfreshId.of(productPrice.getC_TaxCategory_ID()))
.price(productPrice.getPriceStd())
.build())
.collect(ImmutableList.toImmutableList());
}
@NonNull
private String getCurrencyCode(@NonNull final I_M_PriceList priceList)
{
return bpartnerPriceListServicesFacade
.getCurrencyCodeById(CurrencyId.ofRepoId(priceList.getC_Currency_ID()))
.toThreeLetterCode();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\command\SearchProductPricesCommand.java | 1 |
请完成以下Java代码 | public Object getBaseObject()
{
return io;
}
@Override
public int getAD_Table_ID()
{
return io.get_Table_ID();
}
@Override
public int getRecord_ID()
{
return io.get_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final BoilerPlateContext attributesEffective = attributes.toBuilder()
.setSourceDocumentFromObject(io)
.build();
//
String message = text.getTextSnippetParsed(attributesEffective);
//
if (Check.isEmpty(message, true))
{
return null;
}
//
final StringTokenizer st = new StringTokenizer(toEmail, " ,;", false);
EMailAddress to = EMailAddress.ofString(st.nextToken());
MClient client = MClient.get(ctx, Env.getAD_Client_ID(ctx));
if (orderUser != null)
{
to = EMailAddress.ofString(orderUser.getEMail());
}
EMail email = client.createEMail(
to,
text.getName(),
message,
true);
if (email == null)
{
throw new AdempiereException("Cannot create email. Check log.");
}
while (st.hasMoreTokens()) | {
email.addTo(EMailAddress.ofString(st.nextToken()));
}
send(email);
return email;
}
}, false);
return "";
}
private void send(EMail email)
{
int maxRetries = p_SMTPRetriesNo > 0 ? p_SMTPRetriesNo : 0;
int count = 0;
do
{
final EMailSentStatus emailSentStatus = email.send();
count++;
if (emailSentStatus.isSentOK())
{
return;
}
// Timeout => retry
if (emailSentStatus.isSentConnectionError() && count < maxRetries)
{
log.warn("SMTP error: {} [ Retry {}/{} ]", emailSentStatus, count, maxRetries);
}
else
{
throw new EMailSendException(emailSentStatus);
}
}
while (true);
}
private void setNotified(I_M_PackageLine packageLine)
{
InterfaceWrapperHelper.getPO(packageLine).set_ValueOfColumn("IsSentMailNotification", true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\ShipperTransportationMailNotification.java | 1 |
请完成以下Java代码 | public void setSecurPharmService(@NonNull final SecurPharmService securPharmService)
{
this.securPharmService = securPharmService;
}
@Override
public void handleActionRequest(final SecurPharmaActionRequest request)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
try
{
trxManager.runInThreadInheritedTrx(() -> handleActionRequest0(request));
}
catch (final Exception ex)
{
logger.warn("Failed processing {}", request, AdempiereException.extractCause(ex));
}
}
private void handleActionRequest0(@NonNull final SecurPharmaActionRequest request)
{
final SecurPharmAction action = request.getAction();
final InventoryId inventoryId = request.getInventoryId();
final SecurPharmProductId productId = request.getProductId();
if (SecurPharmAction.DECOMMISSION.equals(action))
{
if (productId == null)
{
securPharmService.decommissionProductsByInventoryId(inventoryId);
} | else
{
securPharmService.decommissionProductIfEligible(productId, inventoryId);
}
}
else if (SecurPharmAction.UNDO_DECOMMISSION.equals(action))
{
if (productId == null)
{
securPharmService.undoDecommissionProductsByInventoryId(inventoryId);
}
else
{
securPharmService.undoDecommissionProductIfEligible(productId, inventoryId);
}
}
else
{
throw new AdempiereException("Unknown action: " + action)
.setParameter("event", request);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\actions\SecurPharmActionProcessor.java | 1 |
请完成以下Java代码 | public static void runIfOpened(Connection connection)
throws SQLException
{
if (connection != null && !connection.isClosed()) {
// run sql statements
}
else {
// handle closed connection
}
}
public static void runIfValid(Connection connection)
throws SQLException
{
// Try to validate connection with a 5 seconds timeout
if (connection.isValid(5)) {
// run sql statements
}
else {
// handle invalid connection
}
}
public static void runIfConnectionValid(Connection connection)
{
if (isConnectionValid(connection)) {
// run sql statements
}
else {
// handle invalid connection | }
}
public static boolean isConnectionValid(Connection connection)
{
try {
if (connection != null && !connection.isClosed()) {
// Running a simple validation query
connection.prepareStatement("SELECT 1");
return true;
}
}
catch (SQLException e) {
// log some useful data here
}
return false;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\connectionstatus\ConnectionValidation.java | 1 |
请完成以下Java代码 | public class X_DHL_ShipmentOrderRequest extends org.compiere.model.PO implements I_DHL_ShipmentOrderRequest, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -2065344209L;
/** Standard Constructor */
public X_DHL_ShipmentOrderRequest (final Properties ctx, final int DHL_ShipmentOrderRequest_ID, @Nullable final String trxName)
{
super (ctx, DHL_ShipmentOrderRequest_ID, trxName);
}
/** Load Constructor */
public X_DHL_ShipmentOrderRequest (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 setDHL_ShipmentOrderRequest_ID (final int DHL_ShipmentOrderRequest_ID)
{
if (DHL_ShipmentOrderRequest_ID < 1)
set_ValueNoCheck (COLUMNNAME_DHL_ShipmentOrderRequest_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DHL_ShipmentOrderRequest_ID, DHL_ShipmentOrderRequest_ID);
}
@Override
public int getDHL_ShipmentOrderRequest_ID()
{
return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrderRequest.java | 1 |
请完成以下Java代码 | public class C_Flatrate_DataEntry
{
public static final C_Flatrate_DataEntry instance = new C_Flatrate_DataEntry();
private C_Flatrate_DataEntry()
{
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = {
I_C_Flatrate_DataEntry.COLUMNNAME_Qty_Planned,
I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM,
I_C_Flatrate_DataEntry.COLUMNNAME_C_Currency_ID })
public void updateFlatrateAmt(final I_C_Flatrate_DataEntry dataEntry)
{
updateFlatrateAmt0(dataEntry);
}
@CalloutMethod(columnNames = {
I_C_Flatrate_DataEntry.COLUMNNAME_Qty_Planned,
I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM,
I_C_Flatrate_DataEntry.COLUMNNAME_C_Currency_ID })
public void updateFlatrateAmt(final I_C_Flatrate_DataEntry dataEntry, final ICalloutField unused)
{
updateFlatrateAmt0(dataEntry);
}
private void updateFlatrateAmt0(final I_C_Flatrate_DataEntry dataEntry)
{
// gh #770: null values in one of the two factors shall result in the product being null and not 0.
if (InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM)
|| InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_Qty_Planned))
{ | dataEntry.setFlatrateAmt(null);
return;
}
final BigDecimal product = dataEntry.getQty_Planned().multiply(dataEntry.getFlatrateAmtPerUOM());
final BigDecimal flatrateAmt;
if (dataEntry.getC_Currency_ID() > 0)
{
// round to currency precision
final CurrencyId currencyId = CurrencyId.ofRepoId(dataEntry.getC_Currency_ID());
final CurrencyPrecision precision = Services.get(ICurrencyDAO.class).getStdPrecision(currencyId);
flatrateAmt = precision.round(product);
}
else
{
flatrateAmt = product;
}
dataEntry.setFlatrateAmt(flatrateAmt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\model\interceptor\C_Flatrate_DataEntry.java | 1 |
请完成以下Java代码 | public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseScriptTask(Element scriptTaskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseSequenceFlow(Element sequenceFlowElement, ScopeImpl scopeElement, TransitionImpl transition) {
addExecutionListener(transition);
}
@Override
public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
private void addExecutionListener(final ActivityImpl activity) {
if (executionListener != null) {
for (String event : EXECUTION_EVENTS) {
addListenerOnCoreModelElement(activity, executionListener, event);
}
}
} | private void addExecutionListener(final TransitionImpl transition) {
if (executionListener != null) {
addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE);
}
}
private void addListenerOnCoreModelElement(CoreModelElement element,
DelegateListener<?> listener, String event) {
if (skippable) {
element.addListener(event, listener);
} else {
element.addBuiltInListener(event, listener);
}
}
private void addTaskListener(TaskDefinition taskDefinition) {
if (taskListener != null) {
for (String event : TASK_EVENTS) {
if (skippable) {
taskDefinition.addTaskListener(event, taskListener);
} else {
taskDefinition.addBuiltInTaskListener(event, taskListener);
}
}
}
}
/**
* Retrieves task definition.
*
* @param activity the taskActivity
* @return taskDefinition for activity
*/
private TaskDefinition taskDefinition(final ActivityImpl activity) {
final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
return activityBehavior.getTaskDefinition();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java | 1 |
请完成以下Java代码 | public class HistoryCleanupContext {
private boolean immediatelyDue;
private int minuteFrom;
private int minuteTo;
private int maxRetries;
public HistoryCleanupContext(boolean immediatelyDue, int minuteFrom, int minuteTo, int maxRetries) {
this.immediatelyDue = immediatelyDue;
this.minuteFrom = minuteFrom;
this.minuteTo = minuteTo;
this.maxRetries = maxRetries;
}
public HistoryCleanupContext(int minuteFrom, int minuteTo) {
this.minuteFrom = minuteFrom;
this.minuteTo = minuteTo;
}
public boolean isImmediatelyDue() {
return immediatelyDue;
}
public void setImmediatelyDue(boolean immediatelyDue) {
this.immediatelyDue = immediatelyDue;
}
public int getMinuteFrom() {
return minuteFrom;
}
public void setMinuteFrom(int minuteFrom) { | this.minuteFrom = minuteFrom;
}
public int getMinuteTo() {
return minuteTo;
}
public void setMinuteTo(int minuteTo) {
this.minuteTo = minuteTo;
}
public int getMaxRetries() {
return this.maxRetries;
}
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupContext.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_AttributeSetExclude[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
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 Exclude Attribute Set.
@param M_AttributeSetExclude_ID
Exclude the ability to enter Attribute Sets
*/
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{
return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name)
.getPO(getM_AttributeSet_ID(), get_TrxName()); }
/** Set Attribute Set.
@param M_AttributeSet_ID
Product Attribute Set
*/
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Attribute Set.
@return Product Attribute Set
*/
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java | 1 |
请完成以下Java代码 | public ResponseEntity handleConstraintViolationException(
HttpServletRequest request,
HttpServletResponse response,
ConstraintViolationException ex) {
String errMsg = ((ConstraintViolationException) ex).getConstraintViolations()
.iterator().next().getMessage();
return ResponseEntity.error(ARG_ERROR_CODE, errMsg);
}
/**
* ServiceException异常
*
* @param exception
* @return
*/
@ExceptionHandler({ServiceException.class})
@ResponseStatus(HttpStatus.OK)
public String processServiceException(Exception exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("rpc接口调用异常。{}", exception.getMessage());
return ERROR_500;
}
/**
* 没有权限 异常
* <p/>
* 后续根据不同的需求定制即可
* 应用到所有@RequestMapping注解的方法,在其抛出UnauthorizedException异常时执行
*
* @param request
* @param e
* @return
*/
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String processUnauthorizedException(NativeWebRequest request, Model model, UnauthorizedException e) { | model.addAttribute("exception", e.getMessage());
logger.error("权限异常。{}", e.getMessage());
return ERROR_403;
}
/**
* 运行时异常
*
* @param exception
* @return
*/
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.OK)
public String processException(RuntimeException exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
}
/**
* Exception异常
*
* @param exception
* @return
*/
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
public String processException(Exception exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
//logger.info("自定义异常处理-Exception");
//ModelAndView m = new ModelAndView();
//m.addObject("exception", exception.getMessage());
//m.setViewName("error/500");
//return m;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\exception\DefaultExceptionHandler.java | 1 |
请完成以下Java代码 | public Object evaluate(ScriptEngine engine, VariableScope variableScope, Bindings bindings) {
if (shouldBeCompiled) {
compileScript(engine);
}
if (getCompiledScript() != null) {
return super.evaluate(engine, variableScope, bindings);
}
else {
try {
return evaluateScript(engine, bindings);
} catch (ScriptException e) {
if (e.getCause() instanceof BpmnError) {
throw (BpmnError) e.getCause();
}
String activityIdMessage = getActivityIdExceptionMessage(variableScope);
throw new ScriptEvaluationException("Unable to evaluate script" + activityIdMessage + ":" + e.getMessage(), e);
}
}
}
protected void compileScript(ScriptEngine engine) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
if (processEngineConfiguration.isEnableScriptEngineCaching() && processEngineConfiguration.isEnableScriptCompilation()) {
if (getCompiledScript() == null && shouldBeCompiled) {
synchronized (this) {
if (getCompiledScript() == null && shouldBeCompiled) {
// try to compile script
compiledScript = compile(engine, language, scriptSource);
// either the script was successfully compiled or it can't be
// compiled but we won't try it again
shouldBeCompiled = false;
}
}
}
}
else {
// if script compilation is disabled abort
shouldBeCompiled = false;
}
}
public CompiledScript compile(ScriptEngine scriptEngine, String language, String src) {
if(scriptEngine instanceof Compilable && !scriptEngine.getFactory().getLanguageName().equalsIgnoreCase("ecmascript")) {
Compilable compilingEngine = (Compilable) scriptEngine;
try {
CompiledScript compiledScript = compilingEngine.compile(src);
LOG.debugCompiledScriptUsing(language);
return compiledScript;
} catch (ScriptException e) {
throw new ScriptCompilationException("Unable to compile script: " + e.getMessage(), e); | }
} else {
// engine does not support compilation
return null;
}
}
protected Object evaluateScript(ScriptEngine engine, Bindings bindings) throws ScriptException {
LOG.debugEvaluatingNonCompiledScript(scriptSource);
return engine.eval(scriptSource, bindings);
}
public String getScriptSource() {
return scriptSource;
}
/**
* Sets the script source code. And invalidates any cached compilation result.
*
* @param scriptSource
* the new script source code
*/
public void setScriptSource(String scriptSource) {
this.compiledScript = null;
shouldBeCompiled = true;
this.scriptSource = scriptSource;
}
public boolean isShouldBeCompiled() {
return shouldBeCompiled;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\SourceExecutableScript.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void pessimisticReadWrite() {
template.setPropagationBehavior(
TransactionDefinition.PROPAGATION_REQUIRES_NEW);
template.setTimeout(3); // 3 seconds
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(
TransactionStatus status) {
log.info("Starting first transaction ...");
Author author = authorRepository.findById(1L).orElseThrow();
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult( | TransactionStatus status) {
log.info("Starting second transaction ...");
Author author = authorRepository.findById(1L).orElseThrow();
author.setGenre("Horror");
log.info("Commit second transaction ...");
}
});
log.info("Resuming first transaction ...");
log.info("Commit first transaction ...");
}
});
log.info("Done!");
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootPessimisticLocks\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonCloseInvoiceCandidatesResponseItem
{
@ApiModelProperty(position = 10, dataType = "java.lang.String")
JsonExternalId externalHeaderId;
@ApiModelProperty(position = 20, dataType = "java.lang.String")
JsonExternalId externalLineId;
@ApiModelProperty(position = 30, dataType = "java.lang.Long", value = "The metasfresh-ID of the upserted record")
@NonNull
MetasfreshId metasfreshId;
@ApiModelProperty(position = 40, dataType = "java.lang.String")
CloseInvoiceCandidateStatus status;
@JsonInclude(JsonInclude.Include.NON_EMPTY) | @ApiModelProperty(position = 50, dataType = "java.lang.String")
JsonErrorItem error;
public enum CloseInvoiceCandidateStatus
{
Closed("Closed"), Error("Error)");
@Getter
private final String code;
CloseInvoiceCandidateStatus(final String code)
{
this.code = code;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\invoicecandidates\response\JsonCloseInvoiceCandidatesResponseItem.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookResolver {
@Autowired
IBookService bookService;
@GraphQLQuery(name = "getBookWithTitle")
public Book getBookWithTitle(@GraphQLArgument(name = "title") String title) {
return bookService.getBookWithTitle(title);
}
@GraphQLQuery(name = "getAllBooks", description = "Get all books")
public List<Book> getAllBooks() {
return bookService.getAllBooks();
} | @GraphQLMutation(name = "addBook")
public Book addBook(@GraphQLArgument(name = "newBook") Book book) {
return bookService.addBook(book);
}
@GraphQLMutation(name = "updateBook")
public Book updateBook(@GraphQLArgument(name = "modifiedBook") Book book) {
return bookService.updateBook(book);
}
@GraphQLMutation(name = "deleteBook")
public void deleteBook(@GraphQLArgument(name = "book") Book book) {
bookService.deleteBook(book);
}
} | repos\tutorials-master\graphql-modules\graphql-spqr\src\main\java\com\baeldung\spqr\BookResolver.java | 2 |
请完成以下Java代码 | protected Map<ConsumerSeekCallback, List<TopicPartition>> getCallbacksAndTopics() {
return Collections.unmodifiableMap(this.callbackToTopics);
}
/**
* Seek all assigned partitions to the beginning.
* @since 2.6
*/
public void seekToBeginning() {
getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToBeginning);
}
/**
* Seek all assigned partitions to the end.
* @since 2.6 | */
public void seekToEnd() {
getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToEnd);
}
/**
* Seek all assigned partitions to the offset represented by the timestamp.
* @param time the time to seek to.
* @since 2.6
*/
public void seekToTimestamp(long time) {
getCallbacksAndTopics().forEach((cb, topics) -> cb.seekToTimestamp(topics, time));
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\AbstractConsumerSeekAware.java | 1 |
请完成以下Java代码 | public Book update(Book book) {
logger.info("更新book");
return book;
}
/**
* beforeInvocation = true 意味着不管业务如何出错,缓存已清空
* beforeInvocation = false 等待方法处理完之后再清空缓存,缺点是如果逻辑出异常了,会导致缓存不会被清空
*/
@Override
@CacheEvict(cacheNames = "books", allEntries = true, beforeInvocation = true)
public void clear() {
logger.warn("清空books缓存数据");
throw new RuntimeException("测试 beforeInvocation = fasle");
} | /**
* 模拟慢查询
*/
private void simulateSlowService() {
try {
long time = 3000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
} | repos\spring-boot-quick-master\quick-cache\src\main\java\com\quick\cache\repo\SimpleBookRepository.java | 1 |
请完成以下Java代码 | public static class CachedBodyServletInputStream extends ServletInputStream
{
private final ByteArrayInputStream cachedBodyInputStream;
public CachedBodyServletInputStream(final byte[] cachedBody) {
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
}
@Override
public int read() throws IOException {
return cachedBodyInputStream.read();
}
@Override
public boolean isFinished() { | return cachedBodyInputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(final ReadListener readListener)
{
throw new AdempiereException("Not implemented");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\CachedBodyHttpServletRequest.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Quantity Invoiced. | @param ServiceLevelInvoiced
Quantity of product or service invoiced
*/
public void setServiceLevelInvoiced (BigDecimal ServiceLevelInvoiced)
{
set_ValueNoCheck (COLUMNNAME_ServiceLevelInvoiced, ServiceLevelInvoiced);
}
/** Get Quantity Invoiced.
@return Quantity of product or service invoiced
*/
public BigDecimal getServiceLevelInvoiced ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelInvoiced);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity Provided.
@param ServiceLevelProvided
Quantity of service or product provided
*/
public void setServiceLevelProvided (BigDecimal ServiceLevelProvided)
{
set_ValueNoCheck (COLUMNNAME_ServiceLevelProvided, ServiceLevelProvided);
}
/** Get Quantity Provided.
@return Quantity of service or product provided
*/
public BigDecimal getServiceLevelProvided ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelProvided);
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_ServiceLevel.java | 1 |
请完成以下Java代码 | void readTradeData() {
while (readPos.get() < writePos.get()) {
try {
final int pos = this.readOnlyBuffer.position();
final MarketData data = MarketDataUtil.readAndDecode(this.readOnlyBuffer);
readPos.addAndGet(this.readOnlyBuffer.position() - pos);
log.info("<readTradeData> client: {}, read/write gap: {}, data: {}", name, writePos.get() - readPos.get(), data);
} catch (IndexOutOfBoundsException e) {
this.readOnlyBuffer.clear(); // ring buffer
} catch (Exception e) {
log.error("<readTradeData> cannot read from buffer {}", readOnlyBuffer);
}
}
if (this.readOnlyBuffer.remaining() == 0) {
this.readOnlyBuffer.clear(); // ring buffer
}
}
void read() {
readerThreadPool.scheduleAtFixedRate(this::readTradeData, 1, 1, TimeUnit.SECONDS);
}
}
private Client newClient(String name) {
return new Client(name, buffer);
}
private void writeTradeData(MarketData data) {
try {
final int writtenBytes = MarketDataUtil.encodeAndWrite(buffer, data);
writePos.addAndGet(writtenBytes);
log.info("<writeTradeData> buffer size remaining: %{}, data: {}", 100 * buffer.remaining() / buffer.capacity(), data);
} catch (IndexOutOfBoundsException e) {
buffer.clear(); // ring buffer
writeTradeData(data);
} catch (Exception e) {
log.error("<writeTradeData> cannot write into buffer {}", buffer);
} | }
private void run(MarketDataSource source) {
writerThread.scheduleAtFixedRate(() -> {
if (source.hasNext()) {
writeTradeData(source.next());
}
}, 1, 2, TimeUnit.SECONDS);
}
public static void main(String[] args) {
MarketDataStreamServer server = new MarketDataStreamServer();
Client client1 = server.newClient("client1");
client1.read();
Client client2 = server.newClient("client2");
client2.read();
server.run(new MarketDataSource());
}
} | repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketDataStreamServer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ValRuleAutoApplierService
{
private final ConcurrentHashMap<String, ValRuleAutoApplier> tableName2Applier = new ConcurrentHashMap<>();
public void registerApplier(@NonNull final ValRuleAutoApplier valRuleAutoApplier)
{
tableName2Applier.put(valRuleAutoApplier.getTableName(), valRuleAutoApplier);
}
public void invokeApplierFor(@NonNull final Object recordModel)
{
final String tableName = InterfaceWrapperHelper.getModelTableName(recordModel);
final ValRuleAutoApplier applier = tableName2Applier.get(tableName);
if (applier == null)
{
return; // no applier registered; nothing to do
}
try | {
applier.handleRecord(recordModel);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("valRuleAutoApplier", applier)
.setParameter("recordModel", recordModel);
}
}
public void unregisterForTableName(@NonNull final String tableName)
{
tableName2Applier.remove(tableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\ValRuleAutoApplierService.java | 2 |
请完成以下Java代码 | protected void verifyResultVariableName(Process process, ServiceTask serviceTask, List<ValidationError> errors) {
if (StringUtils.isNotEmpty(serviceTask.getResultVariableName())
&& (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(serviceTask.getImplementationType()) ||
ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType()))) {
addError(errors, Problems.SERVICE_TASK_RESULT_VAR_NAME_WITH_DELEGATE, process, serviceTask, "'resultVariableName' not supported for service tasks using 'class' or 'delegateExpression");
}
if (serviceTask.isUseLocalScopeForResultVariable() && StringUtils.isEmpty(serviceTask.getResultVariableName())) {
addWarning(errors, Problems.SERVICE_TASK_USE_LOCAL_SCOPE_FOR_RESULT_VAR_WITHOUT_RESULT_VARIABLE_NAME, process, serviceTask, "'useLocalScopeForResultVariable' is set, but no 'resultVariableName' is set. The property would not be used");
}
}
protected void verifyWebservice(BpmnModel bpmnModel, Process process, ServiceTask serviceTask, List<ValidationError> errors) {
if (ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(serviceTask.getImplementationType()) && StringUtils.isNotEmpty(serviceTask.getOperationRef())) {
boolean operationFound = false;
if (bpmnModel.getInterfaces() != null && !bpmnModel.getInterfaces().isEmpty()) {
for (Interface bpmnInterface : bpmnModel.getInterfaces()) {
if (bpmnInterface.getOperations() != null && !bpmnInterface.getOperations().isEmpty()) { | for (Operation operation : bpmnInterface.getOperations()) {
if (operation.getId() != null && operation.getId().equals(serviceTask.getOperationRef())) {
operationFound = true;
break;
}
}
}
}
}
if (!operationFound) {
addError(errors, Problems.SERVICE_TASK_WEBSERVICE_INVALID_OPERATION_REF, process, serviceTask, "Invalid operation reference");
}
}
}
} | repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\ServiceTaskValidator.java | 1 |
请完成以下Java代码 | public void setStepType (java.lang.String StepType)
{
set_ValueNoCheck (COLUMNNAME_StepType, StepType);
}
/** Get Step type.
@return Migration step type
*/
@Override
public java.lang.String getStepType ()
{
return (java.lang.String)get_Value(COLUMNNAME_StepType);
}
/** Set Name der DB-Tabelle. | @param TableName Name der DB-Tabelle */
@Override
public void setTableName (java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
/** Get Name der DB-Tabelle.
@return Name der DB-Tabelle */
@Override
public java.lang.String getTableName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationStep.java | 1 |
请完成以下Java代码 | public List<User> getAll() {
return entityManager.createQuery("from User").getResultList();
}
/**
* Return the user having the passed email.
*/
public User getByEmail(String email) {
return (User) entityManager.createQuery(
"from User where email = :email")
.setParameter("email", email)
.getSingleResult();
}
/**
* Return the user having the passed id.
*/
public User getById(long id) {
return entityManager.find(User.class, id);
} | /**
* Update the passed user in the database.
*/
public void update(User user) {
entityManager.merge(user);
return;
}
// ------------------------
// PRIVATE FIELDS
// ------------------------
// An EntityManager will be automatically injected from entityManagerFactory
// setup on DatabaseConfig class.
@PersistenceContext
private EntityManager entityManager;
} // class UserDao | repos\spring-boot-samples-master\spring-boot-mysql-jpa-hibernate\src\main\java\netgloo\models\UserDao.java | 1 |
请完成以下Java代码 | public String toString() {
return (deferred ? "#" : "$") +"{...}";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(deferred ? "#{" : "${");
child.appendStructure(b, bindings);
b.append("}");
}
@Override
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return child.getMethodInfo(bindings, context, returnType, paramTypes);
}
@Override
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) {
return child.invoke(bindings, context, returnType, paramTypes, paramValues);
}
@Override
public Class<?> getType(Bindings bindings, ELContext context) {
return child.getType(bindings, context);
}
@Override
public boolean isLiteralText() {
return child.isLiteralText();
} | @Override
public boolean isReadOnly(Bindings bindings, ELContext context) {
return child.isReadOnly(bindings, context);
}
@Override
public void setValue(Bindings bindings, ELContext context, Object value) {
child.setValue(bindings, context, value);
}
@Override
public int getCardinality() {
return 1;
}
@Override
public AstNode getChild(int i) {
return i == 0 ? child : null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstEval.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimpleEnumStateMachineConfiguration extends StateMachineConfigurerAdapter<ApplicationReviewStates, ApplicationReviewEvents> {
@Override
public void configure(StateMachineConfigurationConfigurer<ApplicationReviewStates, ApplicationReviewEvents> config)
throws Exception {
config
.withConfiguration()
.autoStartup(true)
.listener(new StateMachineListener());
}
@Override
public void configure(StateMachineStateConfigurer<ApplicationReviewStates, ApplicationReviewEvents> states) throws Exception {
states
.withStates()
.initial(ApplicationReviewStates.PEER_REVIEW)
.state(ApplicationReviewStates.PRINCIPAL_REVIEW)
.end(ApplicationReviewStates.APPROVED)
.end(ApplicationReviewStates.REJECTED); | }
@Override
public void configure(StateMachineTransitionConfigurer<ApplicationReviewStates, ApplicationReviewEvents> transitions) throws Exception {
transitions.withExternal()
.source(ApplicationReviewStates.PEER_REVIEW).target(ApplicationReviewStates.PRINCIPAL_REVIEW).event(ApplicationReviewEvents.APPROVE)
.and().withExternal()
.source(ApplicationReviewStates.PRINCIPAL_REVIEW).target(ApplicationReviewStates.APPROVED).event(ApplicationReviewEvents.APPROVE)
.and().withExternal()
.source(ApplicationReviewStates.PEER_REVIEW).target(ApplicationReviewStates.REJECTED).event(ApplicationReviewEvents.REJECT)
.and().withExternal()
.source(ApplicationReviewStates.PRINCIPAL_REVIEW).target(ApplicationReviewStates.REJECTED).event(ApplicationReviewEvents.REJECT);
}
} | repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\SimpleEnumStateMachineConfiguration.java | 2 |
请完成以下Java代码 | public static final GridTabMaxRows of(final int maxRows)
{
if (maxRows == DEFAULT_MaxRows)
{
return DEFAULT;
}
if (maxRows <= 0)
{
return NO_RESTRICTION;
}
return new GridTabMaxRows(maxRows);
}
private final int maxRows;
private GridTabMaxRows(final int maxRows)
{
super();
this.maxRows = maxRows;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder(getClass().getName()).append("[");
if (isNoRestriction())
{
sb.append("NO_RESTRICTION");
}
else if (isDefault())
{
sb.append("DEFAULT");
}
else
{
sb.append(maxRows);
}
sb.append("]");
return sb.toString(); | }
/**
* Gets the maximum rows allowed.
*
* The returned number makes sense only if it's not {@link #isDefault()} or {@link #isNoRestriction()}.
*
* @return max rows allowed.
*/
public int getMaxRows()
{
return maxRows;
}
/**
* @return true if this is a "no restrictions".
*/
public boolean isNoRestriction()
{
return this == NO_RESTRICTION;
}
/**
* @return true if this restriction asks that context defaults (i.e. defined on role level, tab level etc) to be applied.
*/
public boolean isDefault()
{
return this == DEFAULT;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\GridTabMaxRows.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GuestRoom {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NaturalId
private Integer roomNumber;
@NaturalId
private Integer floor;
private String name;
private int capacity;
public GuestRoom(int roomNumber, int floor, String name, int capacity) {
this.roomNumber = roomNumber;
this.floor = floor;
this.name = name;
this.capacity = capacity;
}
protected GuestRoom() {
}
public Long getId() {
return id;
}
public Integer getRoomNumber() {
return roomNumber;
}
public Integer getFloor() {
return floor; | }
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "GuestRoom{" + "id=" + id + ", roomNumber=" + roomNumber + ", floor=" + floor + ", name=" + name + ", capacity=" + capacity + '}';
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\naturalid\entity\GuestRoom.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result<?> updateConversationTitle(@RequestBody ChatConversation updateTitleParams) {
return chatService.updateConversationTitle(updateTitleParams);
}
/**
* 获取消息
*
* @return 返回一个Result对象,包含消息的信息
* @author chenrui
* @date 2025/2/25 11:42
*/
@IgnoreAuth
@GetMapping(value = "/messages")
public Result<?> getMessages(@RequestParam(value = "conversationId", required = true) String conversationId) {
return chatService.getMessages(conversationId);
}
/**
* 清空消息
*
* @return
* @author chenrui
* @date 2025/2/25 11:42
*/
@IgnoreAuth
@GetMapping(value = "/messages/clear/{conversationId}")
public Result<?> clearMessage(@PathVariable(value = "conversationId") String conversationId) {
return chatService.clearMessage(conversationId);
}
/**
* 继续接收消息
*
* @param requestId
* @return
* @author chenrui
* @date 2025/8/11 17:49
*/
@IgnoreAuth
@GetMapping(value = "/receive/{requestId}")
public SseEmitter receiveByRequestId(@PathVariable(name = "requestId", required = true) String requestId) {
return chatService.receiveByRequestId(requestId);
}
/**
* 根据请求ID停止某个请求的处理
*
* @param requestId 请求的唯一标识符,用于识别和停止特定的请求
* @return 返回一个Result对象,表示停止请求的结果
* @author chenrui
* @date 2025/2/25 11:42 | */
@IgnoreAuth
@GetMapping(value = "/stop/{requestId}")
public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) {
return chatService.stop(requestId);
}
/**
* 上传文件
* for [QQYUN-12135]AI聊天,上传图片提示非法token
*
* @param request
* @param response
* @return
* @throws Exception
* @author chenrui
* @date 2025/4/25 11:04
*/
@IgnoreAuth
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
String bizPath = "airag";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获取上传文件对象
MultipartFile file = multipartRequest.getFile("file");
String savePath;
if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath);
} else {
savePath = CommonUtils.upload(file, bizPath, uploadType);
}
Result<?> result = new Result<>();
result.setMessage(savePath);
result.setSuccess(true);
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.