instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public static synchronized void addBooks(int count) {
totalBooks += count;
}
public String getName() {
return name;
}
public int getBooks() {
return books;
}
public static class LibraryStatistics {
public static int getAverageBooks(Library[] libraries) {
int total = 0;
for (Library library : libraries) {
total += library.books;
}
return libraries.length > 0 ? total / libraries.length : 0;
}
}
public static class Book {
private final String title; | private final String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public void displayBookDetails() {
LOGGER.info("Book Title: " + title);
LOGGER.info("Book Author: " + author);
}
}
public record BookRecord(String title, String author) {
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\statickeyword\Library.java | 1 |
请完成以下Java代码 | public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) {
throw new ProcessEngineException(exceptionMessage(
"047",
"'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e);
}
public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) {
logInfo(
"048",
"Camunda Platform sucessfully started at '{}'.", serverInfo);
}
public void camundaBpmPlatformStopped(String serverInfo) {
logInfo(
"049",
"Camunda Platform stopped at '{}'", serverInfo); | }
public void paDeployed(String name) {
logInfo(
"050",
"Process application {} successfully deployed", name);
}
public void paUndeployed(String name) {
logInfo(
"051",
"Process application {} undeployed", name);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DomainUserDetailsService implements ReactiveUserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional(readOnly = true)
public Mono<UserDetails> findByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository
.findOneWithAuthoritiesByEmailIgnoreCase(login)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User with email " + login + " was not found in the database")))
.map(user -> createSpringSecurityUser(login, user));
} | String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository
.findOneWithAuthoritiesByLogin(lowercaseLogin)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")))
.map(user -> createSpringSecurityUser(lowercaseLogin, user));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.isActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<SimpleGrantedAuthority> grantedAuthorities = user
.getAuthorities()
.stream()
.map(Authority::getName)
.map(SimpleGrantedAuthority::new)
.toList();
return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\security\DomainUserDetailsService.java | 2 |
请完成以下Java代码 | private final boolean isAllowChangingTourInstanceAutomatically(final I_M_Tour_Instance tourInstance)
{
if (tourInstance == null)
{
return false;
}
// Don't allow to assign/unassign delivery days to a not saved tour instance
if (tourInstance.getM_Tour_Instance_ID() <= 0)
{
return false;
}
// Don't allow to assign/unassign delivery days to a Processed tour instance
if (tourInstance.isProcessed())
{
return false;
}
// Allow changing tour instance assignments only if it's a generic tour
return isGenericTourInstance(tourInstance);
}
@Override
public void assignToTourInstance(final I_M_DeliveryDay deliveryDay, final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
Check.assume(tourInstance.getM_Tour_Instance_ID() > 0, "tourInstance shall be saved: {}", tourInstance);
deliveryDay.setM_Tour_Instance(tourInstance);
// NOTE: please don't save it because it could be that is not the only change or we are in a before/after save model interceptor
}
private final void unassignFromTourInstance(final I_M_DeliveryDay deliveryDay)
{
deliveryDay.setM_Tour_Instance(null);
// NOTE: please don't save it because it could be that is not the only change or we are in a before/after save model interceptor
}
/**
* Checks if we need to have a tour instance assignment for our given delivery day
*
* @param deliveryDay
* @return true if an assignment is required
*/
private final boolean isTourInstanceAssignmentRequired(final I_M_DeliveryDay deliveryDay)
{
// Tour assignment (change) is not allowed if our delivery day is already processed
if (deliveryDay.isProcessed())
{ | return false;
}
//
// If Delivery Day has documents allocated to it, we really need to assign it to a tour
final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class);
final boolean tourInstanceAssignmentRequired = deliveryDayDAO.hasAllocations(deliveryDay);
return tourInstanceAssignmentRequired;
}
private ITourInstanceQueryParams createTourInstanceQueryParams(final I_M_DeliveryDay deliveryDay)
{
final ITourInstanceQueryParams tourInstanceMatchingParams = new PlainTourInstanceQueryParams();
tourInstanceMatchingParams.setM_Tour(deliveryDay.getM_Tour());
tourInstanceMatchingParams.setDeliveryDate(deliveryDay.getDeliveryDate());
return tourInstanceMatchingParams;
}
@Override
public void process(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
tourInstance.setProcessed(true);
InterfaceWrapperHelper.save(tourInstance);
}
@Override
public void unprocess(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
tourInstance.setProcessed(false);
InterfaceWrapperHelper.save(tourInstance);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourInstanceBL.java | 1 |
请完成以下Java代码 | public void start(BundleContext context) throws Exception {
callbacks.add(new Service(context, URLStreamHandlerService.class.getName(), new BpmnURLHandler(), props("url.handler.protocol", "bpmn")));
callbacks.add(new Service(context, URLStreamHandlerService.class.getName(), new BarURLHandler(), props("url.handler.protocol", "bar")));
try {
callbacks.add(new Service(context, new String[]{ArtifactUrlTransformer.class.getName(), ArtifactListener.class.getName()}, new BpmnDeploymentListener(), null));
callbacks.add(new Service(context, new String[]{ArtifactUrlTransformer.class.getName(), ArtifactListener.class.getName()}, new BarDeploymentListener(), null));
} catch (NoClassDefFoundError e) {
LOGGER.warn("FileInstall package is not available, disabling fileinstall support");
LOGGER.debug("FileInstall package is not available, disabling fileinstall support", e);
}
callbacks.add(new Tracker(new Extender(context)));
}
@Override
public void stop(BundleContext context) throws Exception {
for (Runnable r : callbacks) {
r.run();
}
}
private static Dictionary<String, String> props(String... args) {
Dictionary<String, String> props = new Hashtable<>();
for (int i = 0; i < args.length / 2; i++) {
props.put(args[2 * i], args[2 * i + 1]);
}
return props;
}
@SuppressWarnings({"rawtypes"})
private static class Service implements Runnable {
private final ServiceRegistration registration;
public Service(BundleContext context, String clazz, Object service, Dictionary props) {
this.registration = context.registerService(clazz, service, props);
}
public Service(BundleContext context, String[] clazz, Object service, Dictionary props) {
this.registration = context.registerService(clazz, service, props);
}
@Override
public void run() { | registration.unregister();
}
}
private static class Tracker implements Runnable {
private final Extender extender;
private Tracker(Extender extender) {
this.extender = extender;
this.extender.open();
}
@Override
public void run() {
extender.close();
}
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\Activator.java | 1 |
请完成以下Java代码 | public VariableDefinition getProperty(String propertyUUID) {
return properties != null ? properties.get(propertyUUID) : null;
}
public VariableDefinition getPropertyByName(String name) {
if (properties != null) {
for (Map.Entry<String, VariableDefinition> variableDefinition : properties.entrySet()) {
if (variableDefinition.getValue() != null) {
if (Objects.equals(variableDefinition.getValue().getName(), name)) {
return variableDefinition.getValue();
}
}
}
}
return null;
}
public boolean hasMapping(String taskId) {
return mappings.get(taskId) != null;
}
public boolean shouldMapAllInputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_INPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
} | public boolean shouldMapAllOutputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_OUTPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
}
public TemplatesDefinition getTemplates() {
return templates;
}
public void setTemplates(TemplatesDefinition templates) {
this.templates = templates;
}
public Map<String, AssignmentDefinition> getAssignments() {
return assignments;
}
public void setAssignments(Map<String, AssignmentDefinition> assignments) {
this.assignments = assignments;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\Extension.java | 1 |
请完成以下Java代码 | public static MBPartner[] getEmployees (MHRProcess p)
{
List<Object> params = new ArrayList<>();
StringBuffer whereClause = new StringBuffer();
whereClause.append(" C_BPartner.C_BPartner_ID IN (SELECT e.C_BPartner_ID FROM HR_Employee e WHERE e.IsActive=?");
// Just active employee
params.add(true);
// This payroll not content periods, NOT IS a Regular Payroll > ogi-cd 28Nov2007
if(p.getHR_Payroll_ID() != 0 && p.getHR_Period_ID() != 0)
{
whereClause.append(" AND (e.HR_Payroll_ID IS NULL OR e.HR_Payroll_ID=?) " );
params.add(p.getHR_Payroll_ID());
}
// HR Period
if(p.getHR_Period_ID() == 0)
{
whereClause.append(" AND e.StartDate <=? ");
params.add(p.getDateAcct());
}
else
{
whereClause.append(" AND e.StartDate <=? ");
params.add(new X_HR_Period(p.getCtx(), p.getHR_Period_ID(), null).getEndDate());
}
// Selected Department
if (p.getHR_Department_ID() != 0)
{
whereClause.append(" AND e.HR_Department_ID =? ");
params.add(p.getHR_Department_ID());
}
whereClause.append(" ) "); // end select from HR_Employee
// Selected Employee
if (p.getC_BPartner_ID() != 0)
{
whereClause.append(" AND C_BPartner_ID =? ");
params.add(p.getC_BPartner_ID());
}
//client
whereClause.append(" AND AD_Client_ID =? ");
params.add(p.getAD_Client_ID()); | List<MBPartner> list = new Query(p.getCtx(), MBPartner.Table_Name, whereClause.toString(), p.get_TrxName())
.setParameters(params)
.setOnlyActiveRecords(true)
.setOrderBy(COLUMNNAME_Name)
.list(MBPartner.class);
return list.toArray(new MBPartner[list.size()]);
} // getEmployees
public static MHREmployee getActiveEmployee(Properties ctx, int C_BPartner_ID, String trxName)
{
return new Query(ctx, Table_Name, COLUMNNAME_C_BPartner_ID+"=?", trxName)
.setOnlyActiveRecords(true)
.setParameters(new Object[]{C_BPartner_ID})
.setOrderBy(COLUMNNAME_HR_Employee_ID+" DESC") // just in case...
.first();
}
/** Cache */
private static CCache<Integer, MHREmployee> s_cache = new CCache<>(Table_Name, 1000);
/**************************************************************************
* Invoice Line Constructor
* @param ctx context
* @param HR_Employee_ID ID Employee
* @param trxName transaction name
*/
public MHREmployee (Properties ctx, int HR_Employee_ID, String trxName) //--
{
super (ctx, HR_Employee_ID, trxName);
if (HR_Employee_ID == 0)
{
setClientOrg(Env.getAD_Client_ID(Env.getCtx()), Env.getAD_Org_ID(Env.getCtx()));
}
} // MHREmployee
/**
* Load Constructor
* @param ctx context
* @param rs result set record
*/
public MHREmployee (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MHREmployee
} // MHREmployee | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHREmployee.java | 1 |
请完成以下Java代码 | public static <T> T getProperties(String property, Class<T> requiredType) {
return getProperties(property, null, requiredType);
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
}
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy() {
SpringBeanHolder.clearHolder();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringBeanHolder.applicationContext);
}
SpringBeanHolder.applicationContext = applicationContext;
if (addCallback) {
for (SpringBeanHolder.CallBack callBack : SpringBeanHolder.CALL_BACKS) {
callBack.executor();
}
CALL_BACKS.clear();
}
SpringBeanHolder.addCallback = false;
}
/**
* 获取 @Service 的所有 bean 名称
* @return / | */
public static List<String> getAllServiceBeanName() {
return new ArrayList<>(Arrays.asList(applicationContext
.getBeanNamesForAnnotation(Service.class)));
}
interface CallBack {
/**
* 回调执行方法
*/
void executor();
/**
* 本回调任务名称
* @return /
*/
default String getCallBackName() {
return Thread.currentThread().getId() + ":" + this.getClass().getName();
}
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SpringBeanHolder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMEASUREMENTUNIT() {
return measurementunit;
}
/**
* Sets the value of the measurementunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREMENTUNIT(String value) {
this.measurementunit = value;
}
/**
* Gets the value of the tamou1 property.
*
* @return
* possible object is
* {@link TAMOU1 }
*
*/
public TAMOU1 getTAMOU1() {
return tamou1;
}
/**
* Sets the value of the tamou1 property.
*
* @param value
* allowed object is
* {@link TAMOU1 }
*
*/
public void setTAMOU1(TAMOU1 value) {
this.tamou1 = value; | }
/**
* Gets the value of the ttaxi1 property.
*
* @return
* possible object is
* {@link TTAXI1 }
*
*/
public TTAXI1 getTTAXI1() {
return ttaxi1;
}
/**
* Sets the value of the ttaxi1 property.
*
* @param value
* allowed object is
* {@link TTAXI1 }
*
*/
public void setTTAXI1(TTAXI1 value) {
this.ttaxi1 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TRAILR.java | 2 |
请完成以下Java代码 | public class MultiValueMap<K, V> implements Map<K, List<V>>
{
private final HashMap<K, List<V>> map;
public MultiValueMap()
{
this.map = new HashMap<>();
}
@Override
public int size()
{
return map.size();
}
@Override
public boolean isEmpty()
{
return map.isEmpty();
}
@Override
public boolean containsKey(@Nullable final Object key)
{
return map.containsKey(key);
}
@Override
public boolean containsValue(final Object value)
{
for (final List<V> values : map.values())
{
if (values == null || values.isEmpty())
{
continue;
}
if (values.contains(value))
{
return true;
}
}
return false;
}
@Override
public List<V> get(final Object key)
{
return map.get(key);
}
@Override
public List<V> put(final K key, final List<V> value)
{
return map.put(key, value);
}
/**
* Add the given single value to the current list of values for the given key.
*
* @param key the key
* @param value the value to be added
*/
public void add(final K key, final V value)
{
List<V> values = map.get(key);
if (values == null)
{
values = newValuesList();
map.put(key, values);
}
values.add(value);
}
protected List<V> newValuesList()
{
return new ArrayList<V>();
}
/**
* Set the given single value under the given key.
*
* @param key the key
* @param value the value to set
*/
public void set(final K key, final V value)
{
List<V> values = map.get(key);
if (values == null)
{
values = new ArrayList<V>();
map.put(key, values);
}
else
{ | values.clear();
}
values.add(value);
}
@Override
public List<V> remove(final Object key)
{
return map.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends List<V>> m)
{
map.putAll(m);
}
@Override
public void clear()
{
map.clear();
}
@Override
public Set<K> keySet()
{
return map.keySet();
}
@Override
public Collection<List<V>> values()
{
return map.values();
}
@Override
public Set<Map.Entry<K, List<V>>> entrySet()
{
return map.entrySet();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MultiValueMap.java | 1 |
请完成以下Java代码 | public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override | public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_T_Letter_Spool.java | 1 |
请完成以下Java代码 | public void setTermDuration (final int TermDuration)
{
set_Value (COLUMNNAME_TermDuration, TermDuration);
}
@Override
public int getTermDuration()
{
return get_ValueAsInt(COLUMNNAME_TermDuration);
}
/**
* TermDurationUnit AD_Reference_ID=540281
* Reference name: TermDurationUnit
*/
public static final int TERMDURATIONUNIT_AD_Reference_ID=540281;
/** Monat(e) = month */
public static final String TERMDURATIONUNIT_MonatE = "month";
/** Woche(n) = week */
public static final String TERMDURATIONUNIT_WocheN = "week";
/** Tag(e) = day */
public static final String TERMDURATIONUNIT_TagE = "day";
/** Jahr(e) = year */
public static final String TERMDURATIONUNIT_JahrE = "year";
@Override
public void setTermDurationUnit (final java.lang.String TermDurationUnit)
{
set_Value (COLUMNNAME_TermDurationUnit, TermDurationUnit);
}
@Override
public java.lang.String getTermDurationUnit()
{
return get_ValueAsString(COLUMNNAME_TermDurationUnit);
}
@Override
public void setTermOfNotice (final int TermOfNotice)
{
set_Value (COLUMNNAME_TermOfNotice, TermOfNotice); | }
@Override
public int getTermOfNotice()
{
return get_ValueAsInt(COLUMNNAME_TermOfNotice);
}
/**
* TermOfNoticeUnit AD_Reference_ID=540281
* Reference name: TermDurationUnit
*/
public static final int TERMOFNOTICEUNIT_AD_Reference_ID=540281;
/** Monat(e) = month */
public static final String TERMOFNOTICEUNIT_MonatE = "month";
/** Woche(n) = week */
public static final String TERMOFNOTICEUNIT_WocheN = "week";
/** Tag(e) = day */
public static final String TERMOFNOTICEUNIT_TagE = "day";
/** Jahr(e) = year */
public static final String TERMOFNOTICEUNIT_JahrE = "year";
@Override
public void setTermOfNoticeUnit (final java.lang.String TermOfNoticeUnit)
{
set_Value (COLUMNNAME_TermOfNoticeUnit, TermOfNoticeUnit);
}
@Override
public java.lang.String getTermOfNoticeUnit()
{
return get_ValueAsString(COLUMNNAME_TermOfNoticeUnit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Transition.java | 1 |
请完成以下Java代码 | public static HistoryCleanupJobHandlerConfiguration fromJson(JsonObject jsonObject) {
HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration();
if (jsonObject.has(JOB_CONFIG_COUNT_EMPTY_RUNS)) {
config.setCountEmptyRuns(JsonUtil.getInt(jsonObject, JOB_CONFIG_COUNT_EMPTY_RUNS));
}
if (jsonObject.has(JOB_CONFIG_EXECUTE_AT_ONCE)) {
config.setImmediatelyDue(JsonUtil.getBoolean(jsonObject, JOB_CONFIG_EXECUTE_AT_ONCE));
}
config.setMinuteFrom(JsonUtil.getInt(jsonObject, JOB_CONFIG_MINUTE_FROM));
config.setMinuteTo(JsonUtil.getInt(jsonObject, JOB_CONFIG_MINUTE_TO));
return config;
}
/**
* The delay between two "empty" runs increases twice each time until it reaches {@link HistoryCleanupJobHandlerConfiguration#MAX_DELAY} value.
* @param date date to count delay from
* @return date with delay
*/
public Date getNextRunWithDelay(Date date) {
Date result = addSeconds(date, Math.min((int)(Math.pow(2., (double)countEmptyRuns) * START_DELAY), MAX_DELAY));
return result;
}
private Date addSeconds(Date date, int amount) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.SECOND, amount);
return c.getTime();
}
public int getCountEmptyRuns() {
return countEmptyRuns;
}
public void setCountEmptyRuns(int countEmptyRuns) {
this.countEmptyRuns = countEmptyRuns;
} | 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;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandlerConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void contextLoads(){
}
// @Test
// public void testGetAllDevelopers(){
// HttpHeaders headers = new HttpHeaders();
// HttpEntity<String> entity = new HttpEntity<String>(null, headers);
//
// ResponseEntity<String> response = restTemplate.exchange(getRootUrl() + "/users", HttpMethod.GET, entity, String.class);
//
// assertNotNull(response.getBody());
// }
@Test
public void testGetDeveloperById() {
//
Developer developer = restTemplate.getForObject(getRootUrl() + "/dev/1", Developer.class);
System.out.println(developer.getFirstName());
assertNotNull(developer);
}
@Test
public void testCreateDeveloper(){
Developer developer = new Developer();
developer.setEmailId("hamdamboy.urunov@gmail.com");
developer.setFirstName("Hamdamboy");
developer.setLastName("Urunov");
// developer.setCreateAt(null);
// developer.setUpdatedAt(null);
ResponseEntity<Developer> postResponse = restTemplate.postForEntity(getRootUrl() + "/devs", developer, Developer.class);
assertNotNull(postResponse);
assertNotNull(postResponse.getBody());
}
@Test
public void testUpdatePost(){
int id = 1;
Developer developer = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class);
developer.setFirstName("hamdambek");
developer.setLastName("urunov");
restTemplate.put(getRootUrl() + "/developer/" + id, developer);
Developer updateDevelop = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class); | assertNotNull(updateDevelop);
}
@Test
public void testDeletePost(){
//
int id = 2;
Developer developer = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class);
assertNotNull(developer);
restTemplate.delete(getRootUrl() + "/developers/" + id);
try {
developer = restTemplate.getForObject(getRootUrl() + "/developer/" + id, Developer.class);
} catch (final HttpClientErrorException e){
assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
}
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringMySQL\src\main\java\spring\restapi\service\SpringBootCrudRestApplicationTests.java | 2 |
请完成以下Java代码 | 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 void onBeforeChange(final I_C_OrderLine record)
{
final OrderCostDetailOrderLinePart orderLineInfo = extractOrderLineInfoIfHasChanges(record);
if (orderLineInfo != null)
{
orderCostService.updateOrderCostsOnOrderLineChanged(orderLineInfo);
}
}
@Nullable
private static OrderCostDetailOrderLinePart extractOrderLineInfoIfHasChanges(final I_C_OrderLine record)
{
final I_C_OrderLine recordBeforeChanges = InterfaceWrapperHelper.createOld(record, I_C_OrderLine.class);
final OrderCostDetailOrderLinePart lineInfoBeforeChanges = OrderCostDetailOrderLinePart.ofOrderLine(recordBeforeChanges);
final OrderCostDetailOrderLinePart lineInfo = OrderCostDetailOrderLinePart.ofOrderLine(record);
if (lineInfo.equals(lineInfoBeforeChanges))
{ | return null; // no changes
}
return lineInfo;
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void onBeforeDelete(final I_C_OrderLine record)
{
if (InterfaceWrapperHelper.isUIAction(record))
{
orderCostService.deleteByCreatedOrderLineId(extractOrderAndLineId(record));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\interceptor\C_OrderLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | 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 |
请在Spring Boot框架中完成以下Java代码 | private void getStopOnDemandRequest(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final OnDemandRoutesPCMController.StopOnDemandRouteRequest stopOnDemandRouteRequest = OnDemandRoutesPCMController.StopOnDemandRouteRequest.builder()
.routeId(getBPartnersFromLocalFileRouteId(request))
.externalSystemRequest(request)
.externalSystemService(this)
.build();
exchange.getIn().setBody(stopOnDemandRouteRequest);
}
@NonNull
private GetBPartnerFromFileRouteBuilder getBPartnersFromFileRouteBuilder(@NonNull final JsonExternalSystemRequest request, @NonNull final CamelContext camelContext)
{
return GetBPartnerFromFileRouteBuilder
.builder()
.fileEndpointConfig(PCMConfigUtil.extractLocalFileConfig(request, camelContext))
.camelContext(camelContext)
.enabledByExternalSystemRequest(request)
.processLogger(processLogger)
.routeId(getBPartnersFromLocalFileRouteId(request))
.build();
}
@NonNull
@VisibleForTesting
public static String getBPartnersFromLocalFileRouteId(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
return "GetBPartnerFromLocalFile#" + externalSystemRequest.getExternalSystemChildConfigValue();
}
@Override
public String getServiceValue()
{
return "LocalFileSyncBPartners";
}
@Override | public String getExternalSystemTypeCode()
{
return PCM_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return START_BPARTNER_SYNC_LOCAL_FILE_ROUTE;
}
@Override
public String getDisableCommand()
{
return STOP_BPARTNER_SYNC_LOCAL_FILE_ROUTE;
}
@NonNull
public String getStartBPartnerRouteId()
{
return getExternalSystemTypeCode() + "-" + getEnableCommand();
}
@NonNull
public String getStopBPartnerRouteId()
{
return getExternalSystemTypeCode() + "-" + getDisableCommand();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\LocalFileBPartnerSyncServicePCMRouteBuilder.java | 2 |
请完成以下Java代码 | public class PersonIdentificationSchemeName1Choice {
@XmlElement(name = "Cd")
protected String cd;
@XmlElement(name = "Prtry")
protected String prtry;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = 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\PersonIdentificationSchemeName1Choice.java | 1 |
请完成以下Java代码 | public void setLineWrap (boolean wrap)
{
m_textArea.setLineWrap (wrap);
}
/**
* Set Text Wrap Style Word
* @param word
*/
public void setWrapStyleWord (boolean word)
{
m_textArea.setWrapStyleWord (word);
}
/**
* Set Opaque
* @param isOpaque
*/
@Override
public void setOpaque (boolean isOpaque)
{
// JScrollPane & Viewport is always not Opaque
if (m_textArea == null) // during init of JScrollPane
super.setOpaque(isOpaque);
else
m_textArea.setOpaque(isOpaque);
} // setOpaque
/**
* Set Text Margin
* @param m insets
*/
public void setMargin (Insets m)
{
if (m_textArea != null)
m_textArea.setMargin(m);
} // setMargin
/**
* AddFocusListener
* @param l
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textArea == null) // during init
super.addFocusListener(l);
else
m_textArea.addFocusListener(l);
}
/**
* Add Text Mouse Listener | * @param l
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textArea.addMouseListener(l);
}
/**
* Add Text Key Listener
* @param l
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textArea.addKeyListener(l);
}
/**
* Add Text Input Method Listener
* @param l
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
}
/**
* Get text Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier
* @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java | 1 |
请完成以下Java代码 | public String getValue()
{
StringBuilder sb = new StringBuilder();
for (Word word : innerList)
{
sb.append(word.value);
}
return sb.toString();
}
@Override
public String getLabel()
{
return label;
}
@Override
public void setLabel(String label)
{
this.label = label;
}
@Override
public void setValue(String value)
{
innerList.clear();
innerList.add(new Word(value, label));
}
@Override
public int length()
{
return getValue().length();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('[');
int i = 1;
for (Word word : innerList)
{
sb.append(word.getValue());
String label = word.getLabel();
if (label != null)
{
sb.append('/').append(label);
}
if (i != innerList.size())
{
sb.append(' ');
}
++i; | }
sb.append("]/");
sb.append(label);
return sb.toString();
}
/**
* 转换为一个简单词
* @return
*/
public Word toWord()
{
return new Word(getValue(), getLabel());
}
public CompoundWord(List<Word> innerList, String label)
{
this.innerList = innerList;
this.label = label;
}
public static CompoundWord create(String param)
{
if (param == null) return null;
int cutIndex = param.lastIndexOf(']');
if (cutIndex <= 2 || cutIndex == param.length() - 1) return null;
String wordParam = param.substring(1, cutIndex);
List<Word> wordList = new LinkedList<Word>();
for (String single : wordParam.split("\\s+"))
{
if (single.length() == 0) continue;
Word word = Word.create(single);
if (word == null)
{
Predefine.logger.warning("使用参数" + single + "构造单词时发生错误");
return null;
}
wordList.add(word);
}
String labelParam = param.substring(cutIndex + 1);
if (labelParam.startsWith("/"))
{
labelParam = labelParam.substring(1);
}
return new CompoundWord(wordList, labelParam);
}
@Override
public Iterator<Word> iterator()
{
return innerList.iterator();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\CompoundWord.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PmsBrand> listBrand(String keyword, Integer showStatus, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
PmsBrandExample pmsBrandExample = new PmsBrandExample();
pmsBrandExample.setOrderByClause("sort desc");
PmsBrandExample.Criteria criteria = pmsBrandExample.createCriteria();
if (!StrUtil.isEmpty(keyword)) {
criteria.andNameLike("%" + keyword + "%");
}
if(showStatus!=null){
criteria.andShowStatusEqualTo(showStatus);
}
return brandMapper.selectByExample(pmsBrandExample);
}
@Override
public PmsBrand getBrand(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
@Override | public int updateShowStatus(List<Long> ids, Integer showStatus) {
PmsBrand pmsBrand = new PmsBrand();
pmsBrand.setShowStatus(showStatus);
PmsBrandExample pmsBrandExample = new PmsBrandExample();
pmsBrandExample.createCriteria().andIdIn(ids);
return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample);
}
@Override
public int updateFactoryStatus(List<Long> ids, Integer factoryStatus) {
PmsBrand pmsBrand = new PmsBrand();
pmsBrand.setFactoryStatus(factoryStatus);
PmsBrandExample pmsBrandExample = new PmsBrandExample();
pmsBrandExample.createCriteria().andIdIn(ids);
return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsBrandServiceImpl.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "Item [id=" + id + ", name=" + name + ", value=" + value + "]";
}
@Override
public int hashCode() { | return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
return Objects.equals(id, other.id);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\model\Item.java | 1 |
请完成以下Java代码 | public void setServiceFeeExternalInvoiceDocumentNo (final @Nullable java.lang.String ServiceFeeExternalInvoiceDocumentNo)
{
set_Value (COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo, ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public java.lang.String getServiceFeeExternalInvoiceDocumentNo()
{
return get_ValueAsString(COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public void setServiceFeeInvoicedDate (final @Nullable java.sql.Timestamp ServiceFeeInvoicedDate)
{
set_Value (COLUMNNAME_ServiceFeeInvoicedDate, ServiceFeeInvoicedDate);
}
@Override
public java.sql.Timestamp getServiceFeeInvoicedDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ServiceFeeInvoicedDate);
}
@Override
public void setSource_BP_BankAccount_ID (final int Source_BP_BankAccount_ID)
{
if (Source_BP_BankAccount_ID < 1)
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, null);
else
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, Source_BP_BankAccount_ID);
}
@Override
public int getSource_BP_BankAccount_ID()
{ | return get_ValueAsInt(COLUMNNAME_Source_BP_BankAccount_ID);
}
@Override
public void setSource_BPartner_ID (final int Source_BPartner_ID)
{
if (Source_BPartner_ID < 1)
set_Value (COLUMNNAME_Source_BPartner_ID, null);
else
set_Value (COLUMNNAME_Source_BPartner_ID, Source_BPartner_ID);
}
@Override
public int getSource_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice.java | 1 |
请完成以下Java代码 | public void undeclareAlternativeNamespace(String alternativeNs){
if(!alternativeNsToActual.containsKey(alternativeNs)){
return;
}
String actual = alternativeNsToActual.remove(alternativeNs);
actualNsToAlternative.remove(actual);
}
public Set<String> getAlternativeNamespaces(String actualNs) {
return actualNsToAlternative.get(actualNs);
}
@Override
public String getAlternativeNamespace(String actualNs) {
Set<String> alternatives = getAlternativeNamespaces(actualNs);
if (alternatives == null || alternatives.size() == 0) {
return null;
}
else if (alternatives.size() == 1) {
return alternatives.iterator().next();
}
else
{
throw new ModelException("There is more than one alternative namespace registered");
}
}
public String getActualNamespace(String alternativeNs) {
return alternativeNsToActual.get(alternativeNs);
}
public Collection<ModelElementType> getTypes() {
return new ArrayList<ModelElementType>(typesByName.values());
}
public ModelElementType getType(Class<? extends ModelElementInstance> instanceClass) {
return typesByClass.get(instanceClass);
}
public ModelElementType getTypeForName(String typeName) {
return getTypeForName(null, typeName);
}
public ModelElementType getTypeForName(String namespaceUri, String typeName) {
return typesByName.get(ModelUtil.getQName(namespaceUri, typeName));
}
/**
* Registers a {@link ModelElementType} in this {@link Model}.
*
* @param modelElementType the element type to register
* @param instanceType the instance class of the type to register
*/
public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) {
QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName());
typesByName.put(qName, modelElementType);
typesByClass.put(instanceType, modelElementType);
} | public String getModelName() {
return modelName;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((modelName == null) ? 0 : modelName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ModelImpl other = (ModelImpl) obj;
if (modelName == null) {
if (other.modelName != null) {
return false;
}
} else if (!modelName.equals(other.modelName)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM); | return list;
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean(name = "multipartResolver")
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\spring\web\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private QuotationLinesGroupAggregator createGroupAggregator(@NonNull final QuotationLinesGroupKey key)
{
if (key.getType() == QuotationLinesGroupKey.Type.REPAIRED_PRODUCT)
{
final ServiceRepairProjectTask task = tasksById.get(key.getTaskId());
if (task == null)
{
// shall not happen
throw new AdempiereException("No task found for " + key);
}
final int groupIndex = nextRepairingGroupIndex.getAndIncrement();
return RepairedProductAggregator.builder()
.priceCalculator(priceCalculator)
.key(key)
.groupCaption(String.valueOf(groupIndex))
.repairOrderSummary(task.getRepairOrderSummary())
.repairServicePerformedId(task.getRepairServicePerformedId())
.build();
}
else if (key.getType() == QuotationLinesGroupKey.Type.OTHERS)
{
return OtherLinesAggregator.builder()
.priceCalculator(priceCalculator)
.build();
}
else
{
throw new AdempiereException("Unknown key type: " + key);
}
}
private OrderFactory newOrderFactory()
{ | return OrderFactory.newSalesOrder()
.docType(quotationDocTypeId)
.orgId(pricingInfo.getOrgId())
.dateOrdered(extractDateOrdered(project, pricingInfo.getOrgTimeZone()))
.datePromised(pricingInfo.getDatePromised())
.shipBPartner(project.getBpartnerId(), project.getBpartnerLocationId(), project.getBpartnerContactId())
.salesRepId(project.getSalesRepId())
.pricingSystemId(pricingInfo.getPricingSystemId())
.warehouseId(project.getWarehouseId())
.paymentTermId(project.getPaymentTermId())
.campaignId(project.getCampaignId())
.projectId(project.getProjectId());
}
public final QuotationLineIdsByCostCollectorIdIndex getQuotationLineIdsIndexedByCostCollectorId()
{
Objects.requireNonNull(generatedQuotationLineIdsIndexedByCostCollectorId, "generatedQuotationLineIdsIndexedByCostCollectorId");
return generatedQuotationLineIdsIndexedByCostCollectorId;
}
public QuotationAggregator addAll(@NonNull final List<ServiceRepairProjectCostCollector> costCollectors)
{
this.costCollectorsToAggregate.addAll(costCollectors);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\QuotationAggregator.java | 2 |
请完成以下Java代码 | public class C_Dunning_Candidate_Process extends JavaProcess
{
//
// Services
private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class);
private final IAsyncBatchDAO asyncBatchDAO = Services.get(IAsyncBatchDAO.class);
public static final String PARAM_IsAutoProcess = "IsComplete";
private boolean p_isAutoProcess = true;
//
// async batch
private final String m_AsyncBatchName = "Generate dunning docs";
private final String m_AsyncBatchDesc = "Generate dunning docs ";
private final String m_asyncBatchType = Dunning_Constants.C_Async_Batch_InternalName_DunningDoc;
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
if (para.getParameter() == null)
{
// skip if no parameter value
continue;
}
final String name = para.getParameterName();
if (name.equals(PARAM_IsAutoProcess))
{
p_isAutoProcess = para.getParameterAsBoolean();
}
}
}
@Override
protected String doIt()
{
final IDunningBL dunningBL = Services.get(IDunningBL.class);
final IDunningContext context = dunningBL.createDunningContext(getCtx(),
null, // DunningDate, not needed
null, // C_DunningLevel, not needed
get_TrxName());
context.setProperty(IDunningProducer.CONTEXT_ProcessDunningDoc, p_isAutoProcess);
//
// Create Async Batch for tracking | // retrieve async batch type
final I_C_Async_Batch_Type asyncBatchType;
asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), m_asyncBatchType);
Check.assumeNotNull(asyncBatchType, "Defined Async Batch type should not be null for internal name ", m_asyncBatchType);
// Create Async Batch for tracking
final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch()
.setContext(getCtx())
.setC_Async_Batch_Type(asyncBatchType.getInternalName())
.setAD_PInstance_Creator_ID(getPinstanceId())
.setName(m_AsyncBatchName)
.setDescription(m_AsyncBatchDesc)
.buildAndEnqueue();
context.setProperty(IDunningProducer.CONTEXT_AsyncBatchIdDunningDoc, asyncBatchId);
final SelectedDunningCandidatesSource source = new SelectedDunningCandidatesSource(getProcessInfo().getWhereClause());
source.setDunningContext(context);
dunningBL.processCandidates(context, source);
return MSG_OK;
}
/**
* This dunning candidate source returns only those candidates that have been selected by the user.
*/
private static final class SelectedDunningCandidatesSource extends AbstractDunningCandidateSource
{
private final String whereClause;
public SelectedDunningCandidatesSource(final String whereClause)
{
this.whereClause = whereClause;
}
@Override
public Iterator<I_C_Dunning_Candidate> iterator()
{
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
final Iterator<I_C_Dunning_Candidate> it = dunningDAO.retrieveNotProcessedCandidatesIteratorRW(getDunningContext(), whereClause);
return it;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_Process.java | 1 |
请完成以下Java代码 | public void init() throws IOException {
String resource = "config/mybatis-config.xml";
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
// 1.读取mybatis配置文件创SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
@Test
// 面向接口编程模型
public void quickStart() throws Exception {
// 2.获取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// 3.获取对应mapper
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
JdkProxySourceClassUtil.writeClassToDisk(mapper.getClass().getSimpleName(), mapper.getClass());
// 4.执行查询语句并返回结果
Person person = mapper.selectByPrimaryKey(1L);
System.out.println(person.toString()); | }
}
@Test
// ibatis编程模型
public void quickStartIBatis() throws Exception {
// 2.获取sqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
initH2dbMybatis(sqlSession);
// ibatis编程模型(与配置文件耦合严重)
Person person = sqlSession.selectOne("com.xiaolyuh.domain.mapper.PersonMapper.selectByPrimaryKey", 1L);
System.out.println(person.toString());
}
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\mybatis\MybatisTest.java | 1 |
请完成以下Java代码 | public List<EngineDeployer> getDeployers() {
return deployers;
}
public void setDeployers(List<EngineDeployer> deployers) {
this.deployers = deployers;
}
public DeploymentCache<CaseDefinitionCacheEntry> getCaseDefinitionCache() {
return caseDefinitionCache;
}
public void setCaseDefinitionCache(DeploymentCache<CaseDefinitionCacheEntry> caseDefinitionCache) {
this.caseDefinitionCache = caseDefinitionCache;
}
public CmmnEngineConfiguration getCaseEngineConfiguration() {
return cmmnEngineConfiguration;
}
public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) {
this.cmmnEngineConfiguration = cmmnEngineConfiguration;
} | public CaseDefinitionEntityManager getCaseDefinitionEntityManager() {
return caseDefinitionEntityManager;
}
public void setCaseDefinitionEntityManager(CaseDefinitionEntityManager caseDefinitionEntityManager) {
this.caseDefinitionEntityManager = caseDefinitionEntityManager;
}
public CmmnDeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(CmmnDeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\CmmnDeploymentManager.java | 1 |
请完成以下Java代码 | private AbstractAllocationSourceDestination createSourceOrDestForReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule)
{
final IProductStorage storage = huReceiptScheduleBL.createProductStorage(receiptSchedule);
final Object trxReferencedModel = receiptSchedule;
return new GenericAllocationSourceDestination(storage, trxReferencedModel);
}
private boolean isEligible(final I_M_ReceiptSchedule_Alloc rsa)
{
if (!rsa.isActive())
{
logger.debug("Allocation not eligible because it's not active: {}", rsa);
return false;
}
// Consider only TU/VHU allocations
final int tuHU_ID = rsa.getM_TU_HU_ID();
if (tuHU_ID <= 0)
{
logger.debug("Allocation not eligible because there is no M_TU_HU_ID: {}", rsa);
return false;
}
// Make sure the RSA's LU or TU is in our scope (if any)
final int luTU_ID = rsa.getM_LU_HU_ID();
if (!isInScopeHU(tuHU_ID) && !isInScopeHU(luTU_ID))
{
logger.debug("Allocation not eligible because the LU is not in scope: {}", rsa);
logger.debug("In Scope HUs are: {}", inScopeHU_IDs);
return false;
}
return true;
}
private boolean isInScopeHU(final int huId)
{ | if (huId <= 0)
{
return false;
}
if (inScopeHU_IDs == null)
{
return true;
}
if (inScopeHU_IDs.isEmpty())
{
return true;
}
return inScopeHU_IDs.contains(HuId.ofRepoId(huId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\HUReceiptScheduleWeightNetAdjuster.java | 1 |
请完成以下Java代码 | public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set View ID.
@param ViewId View ID */
@Override
public void setViewId (java.lang.String ViewId)
{
set_Value (COLUMNNAME_ViewId, ViewId);
}
/** Get View ID.
@return View ID */
@Override
public java.lang.String getViewId ()
{
return (java.lang.String)get_Value(COLUMNNAME_ViewId);
}
/** Set Sql WHERE.
@param WhereClause | Fully qualified SQL WHERE clause
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
/**
* NotificationSeverity AD_Reference_ID=541947
* Reference name: NotificationSeverity
*/
public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947;
/** Notice = Notice */
public static final String NOTIFICATIONSEVERITY_Notice = "Notice";
/** Warning = Warning */
public static final String NOTIFICATIONSEVERITY_Warning = "Warning";
/** Error = Error */
public static final String NOTIFICATIONSEVERITY_Error = "Error";
@Override
public void setNotificationSeverity (final java.lang.String NotificationSeverity)
{
set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity);
}
@Override
public java.lang.String getNotificationSeverity()
{
return get_ValueAsString(COLUMNNAME_NotificationSeverity);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AdProcessRouteBuilder extends RouteBuilder
{
/**
* Does a POST to the app-Server's processes API.
* The exchange's header needs to contain the AD_Process.Value, the exchange-body needs to contain the process parameters (if any).
*/
@Override
public void configure() throws Exception
{
errorHandler(noErrorHandler());
from(direct(ExternalSystemCamelConstants.MF_AD_Process_ROUTE_ID))
.routeId(ExternalSystemCamelConstants.MF_AD_Process_ROUTE_ID)
.streamCache("true")
.log("Route invoked!") | .process(exchange -> {
final Object request = exchange.getIn().getBody();
if (!(request instanceof JsonAdProcessRequest))
{
throw new RuntimeCamelException("The route " + ExternalSystemCamelConstants.MF_AD_Process_ROUTE_ID + " requires the body to be instanceof JsonAdProcessRequest. "
+ "However, it is " + (request == null ? "null" : request.getClass().getName()));
}
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonAttachmentRequest.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.POST))
.toD("{{metasfresh.adprocess.v2.api.uri}}/${header." + ExternalSystemConstants.PARAM_CUSTOM_QUERY_AD_PROCESS_VALUE + "}/invoke")
.to(direct(UNPACK_V2_API_RESPONSE));
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\AdProcessRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class SalesOrderCandidate
{
@NonNull PriceListId priceListId;
@NonNull ZonedDateTime datePromised;
@NonNull I_C_Order fromQuotation;
@NonNull ImmutableList<SalesOrderLineCandidate> lines;
@NonNull ImmutableList<I_C_OrderLine> otherQuotationLinesToCopyDirectly;
}
@Data
@Builder
private static class SalesOrderLineCandidate
{
@Nullable
private ProductId bomProductId;
private boolean addProductToPriceList;
//
// Quotation info:
@NonNull
private final GroupId quotationGroupId; | @NonNull
private final String quotationGroupName;
@NonNull
final OrgId orgId;
@NonNull
final ProductId quotationTemplateProductId;
@NonNull
final BigDecimal price;
@NonNull
final BigDecimal qty;
@NonNull
final UomId uomId;
@NonNull
final TaxCategoryId taxCategoryId;
//
// Additional quotation lines to copy directly
@NonNull
@Default
private final ImmutableList<I_C_OrderLine> additionalQuotationLines = ImmutableList.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\CreateSalesOrderAndBOMsFromQuotationCommand.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public <T> T getValue(final String name, final Class<T> clazz)
{
final IUserValuePreference userValuePreference = name2value.get(name);
if (userValuePreference == null)
{
return null;
}
return userValuePreference.getValue(clazz);
}
}
private static final class UserValuePreferencesBuilder
{
public static Collector<I_AD_Preference, ?, ImmutableMap<Optional<AdWindowId>, IUserValuePreferences>> byWindowIdCollector()
{
return Collectors.collectingAndThen(
Collectors.groupingBy((I_AD_Preference adPreference) -> extractAdWindowId(adPreference), collector()) // downstream collector: AD_Window_ID->IUserValuePreferences
, ImmutableMap::copyOf // finisher
);
}
public static Collector<I_AD_Preference, UserValuePreferencesBuilder, IUserValuePreferences> collector()
{
return Collector.of(
UserValuePreferencesBuilder::new // supplier
, UserValuePreferencesBuilder::add // accumulator
, (l, r) -> l.addAll(r) // combiner
, UserValuePreferencesBuilder::build // finisher
, Collector.Characteristics.UNORDERED // characteristics
);
}
private static Optional<AdWindowId> extractAdWindowId(final I_AD_Preference adPreference)
{
return AdWindowId.optionalOfRepoId(adPreference.getAD_Window_ID());
}
private Optional<AdWindowId> adWindowIdOptional;
private final Map<String, IUserValuePreference> name2value = new HashMap<>();
private UserValuePreferencesBuilder()
{
super();
}
public UserValuePreferences build()
{
if (isEmpty())
{
return UserValuePreferences.EMPTY; | }
return new UserValuePreferences(this);
}
public boolean isEmpty()
{
return name2value.isEmpty();
}
public UserValuePreferencesBuilder add(final I_AD_Preference adPreference)
{
final Optional<AdWindowId> currentWindowId = extractAdWindowId(adPreference);
if (isEmpty())
{
adWindowIdOptional = currentWindowId;
}
else if (!adWindowIdOptional.equals(currentWindowId))
{
throw new IllegalArgumentException("Preference " + adPreference + "'s AD_Window_ID=" + currentWindowId + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
final String attributeName = adPreference.getAttribute();
final String attributeValue = adPreference.getValue();
name2value.put(attributeName, UserValuePreference.of(adWindowIdOptional, attributeName, attributeValue));
return this;
}
public UserValuePreferencesBuilder addAll(final UserValuePreferencesBuilder fromBuilder)
{
if (fromBuilder == null || fromBuilder.isEmpty())
{
return this;
}
if (!isEmpty() && !adWindowIdOptional.equals(fromBuilder.adWindowIdOptional))
{
throw new IllegalArgumentException("Builder " + fromBuilder + "'s AD_Window_ID=" + fromBuilder.adWindowIdOptional + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
name2value.putAll(fromBuilder.name2value);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceBL.java | 2 |
请完成以下Java代码 | default CookieSameSiteSupplier whenHasNameMatching(Pattern pattern) {
Assert.notNull(pattern, "'pattern' must not be null");
return when((cookie) -> pattern.matcher(cookie.getName()).matches());
}
/**
* Limit this supplier so that it's only called if the predicate accepts the Cookie.
* @param predicate the predicate used to match the cookie
* @return a new {@link CookieSameSiteSupplier} that only calls this supplier when the
* cookie matches the predicate
*/
default CookieSameSiteSupplier when(Predicate<Cookie> predicate) {
Assert.notNull(predicate, "'predicate' must not be null");
return (cookie) -> predicate.test(cookie) ? getSameSite(cookie) : null;
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#NONE}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofNone() {
return of(SameSite.NONE);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#LAX}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofLax() {
return of(SameSite.LAX);
} | /**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#STRICT}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofStrict() {
return of(SameSite.STRICT);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns the given
* {@link SameSite} value.
* @param sameSite the value to return
* @return the supplier instance
*/
static CookieSameSiteSupplier of(SameSite sameSite) {
Assert.notNull(sameSite, "'sameSite' must not be null");
return (cookie) -> sameSite;
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\CookieSameSiteSupplier.java | 1 |
请完成以下Java代码 | public Auftragsart getAuftragsart() {
return auftragsart;
}
/**
* Sets the value of the auftragsart property.
*
* @param value
* allowed object is
* {@link Auftragsart }
*
*/
public void setAuftragsart(Auftragsart value) {
this.auftragsart = value;
}
/**
* Gets the value of the auftragskennung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuftragskennung() {
return auftragskennung;
}
/**
* Sets the value of the auftragskennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuftragskennung(String value) {
this.auftragskennung = value;
} | /**
* Gets the value of the gebindeId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGebindeId() {
return gebindeId;
}
/**
* Sets the value of the gebindeId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGebindeId(String value) {
this.gebindeId = value;
}
/**
* Gets the value of the auftragsSupportID property.
*
*/
public int getAuftragsSupportID() {
return auftragsSupportID;
}
/**
* Sets the value of the auftragsSupportID property.
*
*/
public void setAuftragsSupportID(int value) {
this.auftragsSupportID = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAntwortAuftrag.java | 1 |
请完成以下Java代码 | public class SysCategory implements Serializable,Comparable<SysCategory>{
private static final long serialVersionUID = 1L;
/**主键*/
@TableId(type = IdType.ASSIGN_ID)
private java.lang.String id;
/**父级节点*/
private java.lang.String pid;
/**类型名称*/
@Excel(name = "类型名称", width = 15)
private java.lang.String name;
/**类型编码*/
@Excel(name = "类型编码", width = 15)
private java.lang.String code;
/**创建人*/
private java.lang.String createBy;
/**创建日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date createTime;
/**更新人*/
private java.lang.String updateBy;
/**更新日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date updateTime;
/**所属部门*/
private java.lang.String sysOrgCode;
/**是否有子节点*/ | @Excel(name = "是否有子节点(1:有)", width = 15)
private java.lang.String hasChild;
/**租户ID*/
private java.lang.Integer tenantId;
@Override
public int compareTo(SysCategory o) {
//比较条件我们定的是按照code的长度升序
// <0:当前对象比传入对象小。
// =0:当前对象等于传入对象。
// >0:当前对象比传入对象大。
int s = this.code.length() - o.code.length();
return s;
}
@Override
public String toString() {
return "SysCategory [code=" + code + ", name=" + name + "]";
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysCategory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setINSTITUTIONNAME(String value) {
this.institutionname = value;
}
/**
* Gets the value of the institutionlocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONLOCATION() {
return institutionlocation;
}
/**
* Sets the value of the institutionlocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONLOCATION(String value) {
this.institutionlocation = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getCOUNTRY() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOUNTRY(String value) {
this.country = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HFINI1.java | 2 |
请完成以下Java代码 | public class M_HU_PI_Item_Product
{
private static final String MSG_QUANTITY_INVALID = "de.metas.handlingunits.InvalidQuantity";
@Init
public void setupCallouts()
{
final IProgramaticCalloutProvider calloutProvider = Services.get(IProgramaticCalloutProvider.class);
calloutProvider.registerAnnotatedCallout(this);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
})
public void beforeSave_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct)
{
updateItemProduct(itemProduct);
setUOMItemProduct(itemProduct);
Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct);
// Validate the item product only if is saved.
validateItemProduct(itemProduct);
}
@CalloutMethod(columnNames = {
I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID,
I_M_HU_PI_Item_Product.COLUMNNAME_Qty,
I_M_HU_PI_Item_Product.COLUMNNAME_IsInfiniteCapacity
})
public void onManualChange_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct, final ICalloutField field)
{
updateItemProduct(itemProduct);
setUOMItemProduct(itemProduct);
Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct);
}
private void updateItemProduct(final I_M_HU_PI_Item_Product itemProduct) | {
if (itemProduct.isAllowAnyProduct())
{
itemProduct.setM_Product_ID(-1);
itemProduct.setIsInfiniteCapacity(true);
}
}
private void setUOMItemProduct(final I_M_HU_PI_Item_Product huPiItemProduct)
{
final ProductId productId = ProductId.ofRepoIdOrNull(huPiItemProduct.getM_Product_ID());
if (productId == null)
{
// nothing to do
return;
}
final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(productId);
huPiItemProduct.setC_UOM_ID(stockingUOMId.getRepoId());
}
private void validateItemProduct(final I_M_HU_PI_Item_Product itemProduct)
{
if (Services.get(IHUCapacityBL.class).isValidItemProduct(itemProduct))
{
return;
}
final String errorMsg = Services.get(IMsgBL.class).getMsg(InterfaceWrapperHelper.getCtx(itemProduct), M_HU_PI_Item_Product.MSG_QUANTITY_INVALID);
throw new AdempiereException(errorMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI_Item_Product.java | 1 |
请完成以下Java代码 | public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionRuleResult ruleResult) {
return new DmnDecisionResultException(exceptionMessage(
"007",
"Unable to get single decision rule result entry as it has more than one entry '{}'", ruleResult)
);
}
public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionTableResult decisionResult) {
return new DmnDecisionResultException(exceptionMessage(
"008",
"Unable to get single decision rule result as it has more than one rule result '{}'", decisionResult)
);
}
public DmnTransformException unableToFindAnyDecisionTable() {
return new DmnTransformException(exceptionMessage(
"009",
"Unable to find any decision table in model.")
);
}
public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionResultEntries result) {
return new DmnDecisionResultException(exceptionMessage(
"010",
"Unable to get single decision result entry as it has more than one entry '{}'", result)
);
}
public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionResult decisionResult) {
return new DmnDecisionResultException(exceptionMessage(
"011", | "Unable to get single decision result as it has more than one result '{}'", decisionResult)
);
}
public DmnEngineException decisionLogicTypeNotSupported(DmnDecisionLogic decisionLogic) {
return new DmnEngineException(exceptionMessage(
"012",
"Decision logic type '{}' not supported by DMN engine.", decisionLogic.getClass())
);
}
public DmnEngineException decisionIsNotADecisionTable(DmnDecision decision) {
return new DmnEngineException(exceptionMessage(
"013",
"The decision '{}' is not implemented as decision table.", decision)
);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnEngineLogger.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("fieldName", fieldName)
.add("groupBy", groupBy)
.add("valueType", valueType)
.toString();
}
public String getOffsetFieldName()
{
return fieldName + "_offset";
}
public String getCaption(final String adLanguage)
{
return caption.translate(adLanguage); | }
public String getOffsetCaption(final String adLanguage)
{
return offsetCaption.translate(adLanguage);
}
public String getDescription(final String adLanguage)
{
return description.translate(adLanguage);
}
public Optional<String> getUnit(final String adLanguage)
{
return unit != null
? StringUtils.trimBlankToOptional(unit.translate(adLanguage))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPIField.java | 1 |
请完成以下Java代码 | private String handleChange(final I_M_ProductScalePrice productScalePrice, final String trxName)
{
if (BigDecimal.ONE.compareTo(productScalePrice.getQty()) != 0)
{
// nothing to do
return null;
}
PreparedStatement pstmt = null;
try
{
//
// Update the M_ProductPrice record this po belongs to
pstmt = DB.prepareStatement(SQL_UPDATE_PRODUCTPRICE, trxName);
pstmt.setBigDecimal(1, productScalePrice.getPriceLimit());
pstmt.setBigDecimal(2, productScalePrice.getPriceList());
pstmt.setBigDecimal(3, productScalePrice.getPriceStd());
pstmt.setInt(4, productScalePrice.getM_ProductPrice_ID());
int no = pstmt.executeUpdate();
if (no == 1)
{
// OK, we were able to update M_Product_Price
return null;
}
throw new AdempiereException("Didn't find M_Product_Price for M_ProductSalePrice with id " + productScalePrice.getM_ProductScalePrice_ID()).markAsUserValidationError();
}
catch (SQLException e)
{
final String msg = "Unable to update M_Product_Price for M_ProductSalePrice with id " + productScalePrice.getM_ProductScalePrice_ID();
MetasfreshLastError.saveError(logger, msg, e);
throw new DBException(msg, e);
}
finally
{
DB.close(pstmt);
}
}
private boolean isAlreadyExisting(final int currentId, final int productPriceId, final BigDecimal qty, final String trxName)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(SQL_SELECT_EXISTING, trxName);
pstmt.setInt(1, productPriceId);
pstmt.setBigDecimal(2, qty);
rs = pstmt.executeQuery();
if (rs.next())
{
final int existingId = rs.getInt(1); | if (existingId == currentId)
{
// there is already a scaleprice in the DB, but it is the
// one we are currently validating.
return false;
}
// there is a different scalePrice with the same priceList and
// quantity.
return true;
}
return false;
}
catch (SQLException e)
{
final String msg = "Unable to check if a M_ProductScalePrice for M_ProductPrice with id "
+ productPriceId + " and quantity " + qty + " already exists";
MetasfreshLastError.saveError(logger, msg, e);
throw new DBException(msg, e);
}
finally
{
DB.close(pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\modelvalidator\MProductScalePriceValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GrpcClientMetricAutoConfiguration {
/**
* Creates a {@link ClientInterceptor} that collects metrics about incoming and outgoing requests and responses.
*
* @param registry The registry used to create the metrics.
* @return The newly created MetricCollectingClientInterceptor bean.
*/
@GrpcGlobalClientInterceptor
@Order(InterceptorOrder.ORDER_TRACING_METRICS)
@ConditionalOnMissingBean
public MetricCollectingClientInterceptor metricCollectingClientInterceptor(final MeterRegistry registry) {
return new MetricCollectingClientInterceptor(registry);
} | /**
* Creates a {@link ClientInterceptor} that collects metrics about client attempts and client calls.
*
* @param registry The registry used to create the metrics.
* @return The newly created MetricsClientInterceptor bean.
*/
@ConditionalOnProperty(prefix = "grpc", name = "metricsA66Enabled", matchIfMissing = true)
@GrpcGlobalClientInterceptor
@Order(InterceptorOrder.ORDER_TRACING_METRICS)
@ConditionalOnMissingBean
public MetricsClientInterceptor metricsClientInterceptor(final MeterRegistry registry) {
return new MetricsClientInterceptor(registry, Stopwatch::createUnstarted);
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\autoconfigure\GrpcClientMetricAutoConfiguration.java | 2 |
请完成以下Java代码 | public int getC_CreditLimit_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CreditLimit_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class);
}
@Override
public void setC_Currency(org.compiere.model.I_C_Currency C_Currency)
{
set_ValueFromPO(COLUMNNAME_C_Currency_ID, org.compiere.model.I_C_Currency.class, C_Currency);
}
/** Set Währung.
@param C_Currency_ID
Die Währung für diesen Eintrag
*/
@Override
public void setC_Currency_ID (int C_Currency_ID)
{
throw new IllegalArgumentException ("C_Currency_ID is virtual column"); }
/** Get Währung.
@return Die Währung für diesen Eintrag
*/
@Override
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum von.
@param DateFrom
Startdatum eines Abschnittes
*/
@Override
public void setDateFrom (java.sql.Timestamp DateFrom) | {
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Datum von.
@return Startdatum eines Abschnittes
*/
@Override
public java.sql.Timestamp getDateFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Freigegeben.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Freigegeben.
@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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_CreditLimit.java | 1 |
请完成以下Java代码 | private IHandlingUnitsDAO getHandlingUnitsDAO()
{
// FIXME: find out why if we are using the "handlingUnitsDAO" field, tests are failing
return Services.get(IHandlingUnitsDAO.class);
}
public boolean isDeveloperMode()
{
return developerModeBL.isEnabled();
}
public I_M_HU_PI getVirtualPI(final Properties ctx)
{
return getHandlingUnitsDAO().retrieveVirtualPI(ctx);
}
public I_M_HU_Item getFirstNotPureVirtualItem(@NonNull final I_M_HU_Item item)
{
final IHandlingUnitsDAO handlingUnitsDAO = getHandlingUnitsDAO();
I_M_HU_Item itemFirstNotPureVirtual = item;
while (itemFirstNotPureVirtual != null && handlingUnitsBL.isPureVirtual(itemFirstNotPureVirtual))
{
final I_M_HU parentHU = itemFirstNotPureVirtual.getM_HU();
itemFirstNotPureVirtual = handlingUnitsDAO.retrieveParentItem(parentHU);
}
// shall not happen
if (itemFirstNotPureVirtual == null)
{
throw new AdempiereException("No not pure virtual HU item found for " + item);
}
return itemFirstNotPureVirtual;
}
public boolean isVirtual(final I_M_HU_Item item) | {
return handlingUnitsBL.isVirtual(item);
}
public List<I_M_HU_Item> retrieveItems(@NonNull final I_M_HU hu)
{
return getHandlingUnitsDAO().retrieveItems(hu);
}
public HUItemType getItemType(final I_M_HU_Item item)
{
return HUItemType.ofCode(handlingUnitsBL.getItemType(item));
}
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU_Item item)
{
return getHandlingUnitsDAO().retrieveIncludedHUs(item);
}
public I_M_HU_PI getIncluded_HU_PI(@NonNull final I_M_HU_Item item)
{
return handlingUnitsBL.getIncludedPI(item);
}
public void deleteHU(final I_M_HU hu)
{
getHandlingUnitsDAO().delete(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\AllocationStrategySupportingServicesFacade.java | 1 |
请完成以下Java代码 | public @NonNull Set<FAOpenItemsHandlerMatchingKey> getMatchers()
{
return ImmutableSet.of(
FAOpenItemsHandlerMatchingKey.of(B_InTransit_Acct, I_C_BankStatement.Table_Name)
);
}
@Override
public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FAOpenItemTrxInfoComputeRequest request)
{
final AccountConceptualName accountConceptualName = request.getAccountConceptualName();
if (accountConceptualName == null)
{
return Optional.empty();
}
if (I_C_BankStatement.Table_Name.equals(request.getTableName()))
{
if (accountConceptualName.isAnyOf(B_InTransit_Acct))
{
final BankStatementId bankStatementId = BankStatementId.ofRepoId(request.getRecordId());
final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(request.getLineId());
final BankStatementLineRefId bankStatementLineRefId = BankStatementLineRefId.ofRepoIdOrNull(request.getSubLineId());
return Optional.of(FAOpenItemTrxInfo.opening(FAOpenItemKey.bankStatementLine(bankStatementId, bankStatementLineId, bankStatementLineRefId, accountConceptualName)));
}
else
{
return Optional.empty();
}
}
else
{
return Optional.empty();
}
}
@Override
public void onGLJournalLineCompleted(final SAPGLJournalLine line)
{
final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null) | {
// shall not happen
return;
}
final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName();
if (accountConceptualName == null)
{
return;
}
if (accountConceptualName.isAnyOf(B_InTransit_Acct))
{
openItemTrxInfo.getKey().getBankStatementLineId()
.ifPresent(bankStatementLineId -> bankStatementBL.markAsReconciledWithGLJournalLine(bankStatementLineId, line.getIdNotNull()));
}
}
@Override
public void onGLJournalLineReactivated(final SAPGLJournalLine line)
{
final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null)
{
// shall not happen
return;
}
final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName();
if (accountConceptualName == null)
{
return;
}
if (accountConceptualName.isAnyOf(B_InTransit_Acct))
{
openItemTrxInfo.getKey().getBankStatementLineId()
.ifPresent(bankStatementBL::unreconcile);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\open_items_handler\BankStatementOIHandler.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(annotatedObject)
.toString();
}
public String getTableName()
{
return tableName;
}
/**
* Gets a set of column names on which this callout instance is listening
*
* @return set of column names
*/
public Set<String> getColumnNames()
{
return columnNames;
}
@Override
public String getId()
{
return id;
}
@Override
public void execute(final ICalloutExecutor executor, final ICalloutField field)
{
final String columnName = field.getColumnName();
final CalloutMethodPointcutKey pointcutKey = CalloutMethodPointcutKey.of(columnName);
final List<CalloutMethodPointcut> pointcutsForKey = mapPointcuts.get(pointcutKey);
if (pointcutsForKey.isEmpty())
{
return;
}
for (final ICalloutMethodPointcut pointcut : pointcutsForKey)
{
executePointcut(pointcut, executor, field);
}
}
private void executePointcut(@NonNull final ICalloutMethodPointcut pointcut, @NonNull final ICalloutExecutor executor, @NonNull final ICalloutField field)
{
// Skip executing this callout if we were asked to skip when record copying mode is active
if (pointcut.isSkipIfCopying() && field.isRecordCopyingMode())
{
logger.info("Skip invoking callout because we are in copying mode: {}", pointcut.getMethod());
return;
} | if (pointcut.isSkipIfIndirectlyCalled() && executor.getActiveCalloutInstancesCount() > 1)
{
logger.info("Skip invoking callout because it is called via another callout: {}", pointcut.getMethod());
return;
}
try
{
final Method method = pointcut.getMethod();
final Object model = field.getModel(pointcut.getModelClass());
// make sure the method can be executed
if (!method.isAccessible())
{
method.setAccessible(true);
}
if (pointcut.isParamCalloutFieldRequired())
{
method.invoke(annotatedObject, model, field);
}
else
{
method.invoke(annotatedObject, model);
}
}
catch (final CalloutExecutionException e)
{
throw e;
}
catch (final Exception e)
{
throw CalloutExecutionException.wrapIfNeeded(e)
.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\AnnotatedCalloutInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MetasfreshEventListener
{
private static final Logger logger = LogManager.getLogger(MetasfreshEventListener.class);
private final MaterialEventHandlerRegistry materialEventHandlerRegistry;
private final MetasfreshEventBusService metasfreshEventBusService;
private final MaterialEventConverter materialEventConverter;
private final IEventListener internalListener = new IEventListener()
{
@Override
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final MaterialEvent lightWeightEvent = materialEventConverter.toMaterialEvent(event);
try (final MDCCloseable ignored = MDC.putCloseable("MaterialEventClass", lightWeightEvent.getClass().getName()))
{
logger.debug("Received MaterialEvent={}", lightWeightEvent);
// make sure that every record we create has the correct AD_Client_ID and AD_Org_ID
final Properties temporaryCtx = Env.copyCtx(Env.getCtx());
Env.setClientId(temporaryCtx, lightWeightEvent.getClientId());
Env.setOrgId(temporaryCtx, lightWeightEvent.getOrgId());
if (lightWeightEvent.getUserId().isRegularUser())
{
Env.setLoggedUserId(temporaryCtx, lightWeightEvent.getUserId());
}
try (final IAutoCloseable ignored1 = Env.switchContext(temporaryCtx))
{
invokeListenerInTrx(lightWeightEvent);
}
}
}
private void invokeListenerInTrx(@NonNull final MaterialEvent materialEvent) | {
Services.get(ITrxManager.class).runInNewTrx(() -> materialEventHandlerRegistry.onEvent(materialEvent));
}
@Override
public String toString()
{
return MetasfreshEventBusService.class.getName() + ".internalListener";
}
};
public MetasfreshEventListener(
@NonNull final MaterialEventHandlerRegistry materialEventHandlerRegistry,
@NonNull final MetasfreshEventBusService metasfreshEventBusService,
@NonNull final MaterialEventConverter materialEventConverter)
{
this.materialEventConverter = materialEventConverter;
this.materialEventHandlerRegistry = materialEventHandlerRegistry;
this.metasfreshEventBusService = metasfreshEventBusService;
this.metasfreshEventBusService.subscribe(internalListener);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\eventbus\MetasfreshEventListener.java | 2 |
请完成以下Java代码 | public class LambdaExpression {
private final List<String> formalParameters;
private final ValueExpression expression;
private final Map<String, Object> nestedArguments = new HashMap<>();
private ELContext context = null;
public LambdaExpression(List<String> formalParameters, ValueExpression expression) {
this.formalParameters = formalParameters;
this.expression = expression;
}
public void setELContext(ELContext context) {
this.context = context;
}
@SuppressWarnings("null") // args[i] can't be null due to earlier checks
public Object invoke(ELContext context, Object... args) throws ELException {
Objects.requireNonNull(context, "context is null");
int formalParamCount = 0;
if (formalParameters != null) {
formalParamCount = formalParameters.size();
}
int argCount = 0;
if (args != null) {
argCount = args.length;
}
if (formalParamCount > argCount) {
throw new ELException("Only '" + argCount + "' arguments were provided for a lambda expression that requires at least '" + formalParamCount + "''");
}
// Build the argument map
// Start with the arguments from any outer expressions so if there is
// any overlap the local arguments have priority
Map<String, Object> lambdaArguments = new HashMap<>(nestedArguments);
for (int i = 0; i < formalParamCount; i++) {
lambdaArguments.put(formalParameters.get(i), args[i]);
}
context.enterLambdaScope(lambdaArguments); | try {
Object result = expression.getValue(context);
// Make arguments from this expression available to any nested
// expression
if (result instanceof LambdaExpression) {
((LambdaExpression) result).nestedArguments.putAll(lambdaArguments);
}
return result;
} finally {
context.exitLambdaScope();
}
}
public Object invoke(Object... args) {
return invoke(context, args);
}
public List<String> getFormalParameters() {
return formalParameters;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\LambdaExpression.java | 1 |
请完成以下Java代码 | public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getSourceCaseDefinitionId() {
return sourceCaseDefinitionId;
}
public void setSourceCaseDefinitionId(String sourceCaseDefinitionId) {
this.sourceCaseDefinitionId = sourceCaseDefinitionId;
} | public String getTargetCaseDefinitionId() {
return targetCaseDefinitionId;
}
public void setTargetCaseDefinitionId(String targetCaseDefinitionId) {
this.targetCaseDefinitionId = targetCaseDefinitionId;
}
public String getMigrationMessage() {
return migrationMessage;
}
public void setMigrationMessage(String migrationMessage) {
this.migrationMessage = migrationMessage;
}
public String getMigrationStacktrace() {
return migrationStacktrace;
}
public void setMigrationStacktrace(String migrationStacktrace) {
this.migrationStacktrace = migrationStacktrace;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationPartResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderEntryIdClass {
@Id
private long orderId;
@Id
private long productId;
@ManyToOne
private User user;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
} | public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\pojo\OrderEntryIdClass.java | 2 |
请完成以下Java代码 | public int getServiceFeeAmount_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_ServiceFeeAmount_Currency_ID);
}
@Override
public void setServiceFeeExternalInvoiceDocumentNo (final @Nullable java.lang.String ServiceFeeExternalInvoiceDocumentNo)
{
set_Value (COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo, ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public java.lang.String getServiceFeeExternalInvoiceDocumentNo()
{
return get_ValueAsString(COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public void setServiceFeeInvoicedDate (final @Nullable java.sql.Timestamp ServiceFeeInvoicedDate)
{
set_Value (COLUMNNAME_ServiceFeeInvoicedDate, ServiceFeeInvoicedDate);
}
@Override
public java.sql.Timestamp getServiceFeeInvoicedDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ServiceFeeInvoicedDate);
}
@Override
public void setSource_BP_BankAccount_ID (final int Source_BP_BankAccount_ID)
{
if (Source_BP_BankAccount_ID < 1)
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, null);
else
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, Source_BP_BankAccount_ID); | }
@Override
public int getSource_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_BP_BankAccount_ID);
}
@Override
public void setSource_BPartner_ID (final int Source_BPartner_ID)
{
if (Source_BPartner_ID < 1)
set_Value (COLUMNNAME_Source_BPartner_ID, null);
else
set_Value (COLUMNNAME_Source_BPartner_ID, Source_BPartner_ID);
}
@Override
public int getSource_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice.java | 1 |
请完成以下Java代码 | AsyncImportRecordsResponse importRecordsAsync(@NonNull final ImportRecordsRequest request)
{
if (importRecordsAsyncExecutor == null)
{
throw new AdempiereException("No " + ImportRecordsAsyncExecutor.class + " defined");
}
return importRecordsAsyncExecutor.schedule(request);
}
private void notifyImportDone(
@NonNull final ActualImportRecordsResult result,
@NonNull final UserId recipientUserId)
{
try
{
final String targetTableName = result.getTargetTableName();
final String windowName = adTableDAO.retrieveWindowName(Env.getCtx(), targetTableName);
notificationBL.send(UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC) | .recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_RecordsImported)
.contentADMessageParam(result.getCountInsertsIntoTargetTableString())
.contentADMessageParam(result.getCountUpdatesIntoTargetTableString())
.contentADMessageParam(windowName)
.build());
}
catch (final Exception ex)
{
logger.warn("Failed notifying user '{}' about {}. Ignored.", recipientUserId, result, ex);
}
}
public int deleteImportRecords(@NonNull final ImportDataDeleteRequest request)
{
return importProcessFactory.newImportProcessForTableName(request.getImportTableName())
.setParameters(request.getAdditionalParameters())
.deleteImportRecords(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractSpringDataJpaService<T extends Serializable> implements IOperations<T> {
@Override
public T findOne(final long id) {
return getDao().findById(id).orElse(null);
}
@Override
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public T create(final T entity) {
return getDao().save(entity);
} | @Override
public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract CrudRepository<T, Serializable> getDao();
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\services\impl\AbstractSpringDataJpaService.java | 2 |
请完成以下Java代码 | public void init(final FilterConfig filterConfig)
{
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException
{
final HttpServletRequest httpServletRequest = (HttpServletRequest)request;
final HttpServletResponse httpServletResponse = (HttpServletResponse)response;
try
{
if (isBypassAll() || apiAuditService.bypassFilter(httpServletRequest))
{
chain.doFilter(request, response);
return;
}
final ApiRequestAuditId requestAuditId = apiAuditService.extractApiRequestAuditId(httpServletRequest).orElse(null);
final Optional<UserId> loggedUserId = Env.getLoggedUserIdIfExists();
// dev-note: this means the request was already filtered once
if (requestAuditId != null)
{
final ApiAuditLoggable apiAuditLoggable;
if (loggedUserId.isPresent())
{
apiAuditLoggable = apiAuditService.createLogger(requestAuditId, loggedUserId.get());
}
else
{
apiAuditLoggable = apiAuditService.createLogger(requestAuditId, UserId.METASFRESH);
Loggables
.withLogger(apiAuditLoggable, logger, Level.WARN)
.addLog("Request contains ApiRequestAuditId={}, but there is no logged-in user - logging with AD_User_ID=", requestAuditId.getRepoId(), UserId.METASFRESH.getRepoId());
}
try (final IAutoCloseable ignored = Loggables.temporarySetLoggable(apiAuditLoggable))
{
chain.doFilter(request, response);
return;
}
}
final ApiAuditConfig matchingAuditConfig = apiAuditService.getMatchingAuditConfig(httpServletRequest).orElse(null);
if (matchingAuditConfig == null || matchingAuditConfig.isBypassAudit())
{
chain.doFilter(request, response);
return;
} | apiAuditService.processRequest(chain, httpServletRequest, httpServletResponse, matchingAuditConfig);
}
catch (final Throwable t)
{
logger.error(t.getLocalizedMessage(), t);
ResponseHandler.writeErrorResponse(t, httpServletResponse, null, null);
}
}
@Override
public void destroy()
{
}
private boolean isBypassAll()
{
//if(true) return true;
return sysConfigBL.getBooleanValue(SYSCONFIG_BypassAll, false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\filter\ApiAuditFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomMongoRepositoryImpl<T extends UuidIdentifiedEntity> extends SimpleMongoRepository<T, UUID> implements CustomMongoRepository<T> {
public CustomMongoRepositoryImpl(MongoEntityInformation<T, UUID> metadata, MongoOperations mongoOperations) {
super(metadata, mongoOperations);
}
@Override
public <S extends T> S save(S entity) {
generateId(entity);
return super.save(entity);
}
@Override
public <S extends T> List<S> saveAll(Iterable<S> entities) {
entities.forEach(entity -> generateId(entity));
return super.saveAll(entities);
}
@Override
public <S extends T> S insert(S entity) { | generateId(entity);
return super.insert(entity);
}
@Override
public <S extends T> List<S> insert(Iterable<S> entities) {
entities.forEach(entity -> generateId(entity));
return super.insert(entities);
}
protected <S extends T> void generateId(S entity) {
if(entity != null && entity.getId() == null) {
entity.setId(UUID.randomUUID());
}
}
} | repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\uuid\repository\impl\CustomMongoRepositoryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityDataSourceConfig
{
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.security")
public DataSourceProperties securityDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource securityDataSource() {
DataSourceProperties securityDataSourceProperties = securityDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(securityDataSourceProperties.getDriverClassName())
.url(securityDataSourceProperties.getUrl())
.username(securityDataSourceProperties.getUsername())
.password(securityDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager securityTransactionManager()
{
EntityManagerFactory factory = securityEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(securityDataSource());
factory.setPackagesToScan(new String[]{"net.alanbinu.springboot.springbootmultipledatasources.security.entities"});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties(); | jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
@Bean
public DataSourceInitializer securityDataSourceInitializer()
{
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(securityDataSource());
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("security-data.sql"));
dataSourceInitializer.setDatabasePopulator(databasePopulator);
dataSourceInitializer.setEnabled(env.getProperty("datasource.security.initialize", Boolean.class, false));
return dataSourceInitializer;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\config\SecurityDataSourceConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FollowRelationJdbcRepositoryAdapter implements FollowRelationRepository {
private final FollowRelationJdbcRepository repository;
@Override
public boolean exists(FollowRelation followRelation) {
return repository.existsByFollowerIdAndFolloweeId(followRelation.followerId(), followRelation.followeeId());
}
@Override
public FollowRelation save(FollowRelation followRelation) {
repository.save(new FollowRelationJdbcEntity(0L, followRelation.followerId(), followRelation.followeeId()));
return followRelation;
}
@Override
public List<FollowRelation> findByFollowerId(long followerId) { | return repository.findByFollowerId(followerId).stream()
.map(e -> new FollowRelation(e.followerId(), e.followeeId()))
.toList();
}
@Override
public List<FollowRelation> findByFolloweeId(long followeeId) {
return repository.findByFolloweeId(followeeId).stream()
.map(e -> new FollowRelation(e.followerId(), e.followeeId()))
.toList();
}
@Override
public void delete(FollowRelation followRelation) {
repository.deleteByFollowerIdAndFolloweeId(followRelation.followerId(), followRelation.followeeId());
}
} | repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\FollowRelationJdbcRepositoryAdapter.java | 2 |
请完成以下Java代码 | public int getAD_Table_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table_Target() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_Target_ID(), get_TrxName()); }
/** Set Ziel-Tabelle.
@param AD_Table_Target_ID Ziel-Tabelle */
public void setAD_Table_Target_ID (int AD_Table_Target_ID)
{
if (AD_Table_Target_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, Integer.valueOf(AD_Table_Target_ID));
}
/** Get Ziel-Tabelle.
@return Ziel-Tabelle */
public int getAD_Table_Target_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Target_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quell-Datensatz-ID.
@param Record_Source_ID Quell-Datensatz-ID */
public void setRecord_Source_ID (int Record_Source_ID)
{
if (Record_Source_ID < 1)
set_ValueNoCheck (COLUMNNAME_Record_Source_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID));
}
/** Get Quell-Datensatz-ID.
@return Quell-Datensatz-ID */
public int getRecord_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ziel-Datensatz-ID.
@param Record_Target_ID Ziel-Datensatz-ID */
public void setRecord_Target_ID (int Record_Target_ID)
{
if (Record_Target_ID < 1)
set_ValueNoCheck (COLUMNNAME_Record_Target_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID));
}
/** Get Ziel-Datensatz-ID.
@return Ziel-Datensatz-ID */
public int getRecord_Target_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_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_AD_Relation_Explicit_v1.java | 1 |
请完成以下Java代码 | protected void tellSuccess(TbContext ctx, TbMsg tbMsg) {
if (forceAck) {
ctx.enqueueForTellNext(tbMsg.copyWithNewCtx(), TbNodeConnectionType.SUCCESS);
} else {
ctx.tellSuccess(tbMsg);
}
}
protected void tellFailure(TbContext ctx, TbMsg tbMsg, Throwable t) {
if (forceAck) {
if (t == null) {
ctx.enqueueForTellNext(tbMsg.copyWithNewCtx(), TbNodeConnectionType.FAILURE);
} else {
ctx.enqueueForTellFailure(tbMsg.copyWithNewCtx(), t);
}
} else {
if (t == null) { | ctx.tellNext(tbMsg, TbNodeConnectionType.FAILURE);
} else {
ctx.tellFailure(tbMsg, t);
}
}
}
protected TbMsg ackIfNeeded(TbContext ctx, TbMsg msg) {
if (forceAck) {
ctx.ack(msg);
return msg.copyWithNewCtx();
} else {
return msg;
}
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\external\TbAbstractExternalNode.java | 1 |
请完成以下Java代码 | public class TbCoreTransportApiService {
private final TbCoreQueueFactory tbCoreQueueFactory;
private final TransportApiService transportApiService;
private final StatsFactory statsFactory;
@Value("${queue.transport_api.max_pending_requests:10000}")
private int maxPendingRequests;
@Value("${queue.transport_api.max_requests_timeout:10000}")
private long requestTimeout;
@Value("${queue.transport_api.request_poll_interval:25}")
private int responsePollDuration;
@Value("${queue.transport_api.max_callback_threads:100}")
private int maxCallbackThreads;
private ExecutorService transportCallbackExecutor;
private TbQueueResponseTemplate<TbProtoQueueMsg<TransportApiRequestMsg>,
TbProtoQueueMsg<TransportApiResponseMsg>> transportApiTemplate;
public TbCoreTransportApiService(TbCoreQueueFactory tbCoreQueueFactory, TransportApiService transportApiService, StatsFactory statsFactory) {
this.tbCoreQueueFactory = tbCoreQueueFactory;
this.transportApiService = transportApiService;
this.statsFactory = statsFactory;
}
@PostConstruct
public void init() {
this.transportCallbackExecutor = ThingsBoardExecutors.newWorkStealingPool(maxCallbackThreads, getClass());
TbQueueProducer<TbProtoQueueMsg<TransportApiResponseMsg>> producer = tbCoreQueueFactory.createTransportApiResponseProducer();
TbQueueConsumer<TbProtoQueueMsg<TransportApiRequestMsg>> consumer = tbCoreQueueFactory.createTransportApiRequestConsumer();
String key = StatsType.TRANSPORT.getName();
MessagesStats queueStats = statsFactory.createMessagesStats(key);
DefaultTbQueueResponseTemplate.DefaultTbQueueResponseTemplateBuilder
<TbProtoQueueMsg<TransportApiRequestMsg>, TbProtoQueueMsg<TransportApiResponseMsg>> builder = DefaultTbQueueResponseTemplate.builder();
builder.requestTemplate(consumer);
builder.responseTemplate(producer);
builder.maxPendingRequests(maxPendingRequests);
builder.requestTimeout(requestTimeout);
builder.pollInterval(responsePollDuration);
builder.executor(transportCallbackExecutor);
builder.handler(transportApiService);
builder.stats(queueStats);
transportApiTemplate = builder.build(); | }
@AfterStartUp(order = AfterStartUp.REGULAR_SERVICE)
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
log.info("Received application ready event. Starting polling for events.");
transportApiTemplate.subscribe();
transportApiTemplate.launch(transportApiService);
}
@PreDestroy
public void destroy() {
if (transportApiTemplate != null) {
transportApiTemplate.stop();
}
if (transportCallbackExecutor != null) {
transportCallbackExecutor.shutdownNow();
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\transport\TbCoreTransportApiService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TransactionEventHandlerForStockRecords
implements MaterialEventHandler<AbstractTransactionEvent>
{
private final StockDataUpdateRequestHandler dataUpdateRequestHandler;
public TransactionEventHandlerForStockRecords(
@NonNull final StockDataUpdateRequestHandler dataUpdateRequestHandler)
{
this.dataUpdateRequestHandler = dataUpdateRequestHandler;
}
@Override
public Collection<Class<? extends AbstractTransactionEvent>> getHandledEventType()
{
return ImmutableList.of(TransactionCreatedEvent.class, TransactionDeletedEvent.class);
}
@Override
public void handleEvent(@NonNull final AbstractTransactionEvent event)
{
final StockDataUpdateRequest dataUpdateRequest = createDataUpdateRequestForEvent(event);
dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest);
}
private StockDataUpdateRequest createDataUpdateRequestForEvent(
@NonNull final AbstractTransactionEvent event)
{ | final MaterialDescriptor materialDescriptor = event.getMaterialDescriptor();
final StockDataRecordIdentifier identifier = StockDataRecordIdentifier.builder()
.clientId(event.getClientId())
.orgId(event.getOrgId())
.warehouseId(materialDescriptor.getWarehouseId())
.productId(ProductId.ofRepoId(materialDescriptor.getProductId()))
.storageAttributesKey(materialDescriptor.getStorageAttributesKey())
.build();
final StockChangeSourceInfo stockChangeSourceInfo = StockChangeSourceInfo.ofTransactionId(event.getTransactionId());
return StockDataUpdateRequest.builder()
.identifier(identifier)
.onHandQtyChange(event.getQuantityDelta())
.sourceInfo(stockChangeSourceInfo)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\eventhandler\TransactionEventHandlerForStockRecords.java | 2 |
请完成以下Java代码 | void updateMnemonicBindingX (AbstractButton b)
{
int m = b.getMnemonic();
if (m != 0)
{
InputMap map = SwingUtilities.getUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null)
{
map = new ComponentInputMapUIResource(b);
SwingUtilities.replaceUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW, map);
}
map.clear();
String className = b.getClass().getName();
int mask = InputEvent.ALT_MASK; // Default Buttons
if (b instanceof JCheckBox // In Tab | || className.indexOf("VButton") != -1)
mask = InputEvent.SHIFT_MASK + InputEvent.CTRL_MASK;
map.put(KeyStroke.getKeyStroke(m, mask, false), "pressed");
map.put(KeyStroke.getKeyStroke(m, mask, true), "released");
map.put(KeyStroke.getKeyStroke(m, 0, true), "released");
}
else
{
InputMap map = SwingUtilities.getUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map != null)
map.clear();
}
} // updateMnemonicBindingX
} // AdempiereButtonListener | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereButtonListener.java | 1 |
请完成以下Java代码 | public void setAD_InfoWindow_From_ID (int AD_InfoWindow_From_ID)
{
if (AD_InfoWindow_From_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_From_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_From_ID, Integer.valueOf(AD_InfoWindow_From_ID));
}
/** Get Info Window From.
@return Info Window From */
@Override
public int getAD_InfoWindow_From_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_From_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_InfoWindow getAD_InfoWindow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class);
}
@Override
public void setAD_InfoWindow(org.compiere.model.I_AD_InfoWindow AD_InfoWindow)
{
set_ValueFromPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class, AD_InfoWindow);
}
/** Set Info-Fenster.
@param AD_InfoWindow_ID
Info and search/select Window
*/
@Override
public void setAD_InfoWindow_ID (int AD_InfoWindow_ID)
{
if (AD_InfoWindow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, Integer.valueOf(AD_InfoWindow_ID));
}
/** Get Info-Fenster.
@return Info and search/select Window
*/
@Override
public int getAD_InfoWindow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause
SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LocalResponseCacheProperties {
static final String PREFIX = "spring.cloud.gateway.server.webflux.filter.local-response-cache";
private static final Log LOGGER = LogFactory.getLog(LocalResponseCacheProperties.class);
private static final Duration DEFAULT_CACHE_TTL_MINUTES = Duration.ofMinutes(5);
private @Nullable DataSize size;
private @Nullable Duration timeToLive;
private RequestOptions request = new RequestOptions();
public @Nullable DataSize getSize() {
return size;
}
public void setSize(DataSize size) {
this.size = size;
}
public Duration getTimeToLive() {
if (timeToLive == null) {
LOGGER.debug(String.format(
"No TTL configuration found. Default TTL will be applied for cache entries: %s minutes",
DEFAULT_CACHE_TTL_MINUTES));
return DEFAULT_CACHE_TTL_MINUTES;
}
else {
return timeToLive;
}
}
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
public RequestOptions getRequest() {
return request;
}
public void setRequest(RequestOptions request) {
this.request = request;
}
@Override
public String toString() {
return "LocalResponseCacheProperties{" + "size=" + size + ", timeToLive=" + timeToLive + ", request=" + request
+ '}';
}
public static class RequestOptions {
private NoCacheStrategy noCacheStrategy = NoCacheStrategy.SKIP_UPDATE_CACHE_ENTRY;
public NoCacheStrategy getNoCacheStrategy() {
return noCacheStrategy; | }
public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) {
this.noCacheStrategy = noCacheStrategy;
}
@Override
public String toString() {
return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}';
}
}
/**
* When client sends "no-cache" directive in "Cache-Control" header, the response
* should be re-validated from upstream. There are several strategies that indicates
* what to do with the new fresh response.
*/
public enum NoCacheStrategy {
/**
* Update the cache entry by the fresh response coming from upstream with a new
* time to live.
*/
UPDATE_CACHE_ENTRY,
/**
* Skip the update. The client will receive the fresh response, other clients will
* receive the old entry in cache.
*/
SKIP_UPDATE_CACHE_ENTRY
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java | 2 |
请完成以下Java代码 | public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping implements InitializingBean {
private final EndpointLinksResolver linksResolver;
/**
* Creates a new {@code WebFluxEndpointHandlerMapping} instance that provides mappings
* for the given endpoints.
* @param endpointMapping the base mapping for all endpoints
* @param endpoints the web endpoints
* @param endpointMediaTypes media types consumed and produced by the endpoints
* @param corsConfiguration the CORS configuration for the endpoints or {@code null}
* @param linksResolver resolver for determining links to available endpoints
* @param shouldRegisterLinksMapping whether the links endpoint should be registered
*/
public WebFluxEndpointHandlerMapping(EndpointMapping endpointMapping, Collection<ExposableWebEndpoint> endpoints,
EndpointMediaTypes endpointMediaTypes, @Nullable CorsConfiguration corsConfiguration,
EndpointLinksResolver linksResolver, boolean shouldRegisterLinksMapping) {
super(endpointMapping, endpoints, endpointMediaTypes, corsConfiguration, shouldRegisterLinksMapping);
this.linksResolver = linksResolver;
setOrder(-100);
}
@Override
protected LinksHandler getLinksHandler() {
return new WebFluxLinksHandler();
}
/**
* Handler for root endpoint providing links.
*/
class WebFluxLinksHandler implements LinksHandler {
@Override
@ResponseBody
@Reflective
public Map<String, Map<String, Link>> links(ServerWebExchange exchange) {
String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI())
.replaceQuery(null)
.toUriString();
Map<String, Link> links = WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri); | return OperationResponseBody.of(Collections.singletonMap("_links", links));
}
@Override
public String toString() {
return "Actuator root web endpoint";
}
}
static class WebFluxEndpointHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, WebFluxLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\endpoint\web\WebFluxEndpointHandlerMapping.java | 1 |
请完成以下Java代码 | public boolean reActivateIt()
{
// Before reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE);
if (m_processMsg != null)
{
return false;
}
// After reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE);
if (m_processMsg != null)
{
return false;
}
setDocAction(DOCACTION_Complete);
setProcessed(false);
return true;
} // reActivateIt
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append(getDocumentNo());
if (m_lines != null)
{
sb.append(" (#").append(m_lines.length).append(")");
}
// - Description
if (getDescription() != null && getDescription().length() > 0)
{
sb.append(" - ").append(getDescription());
}
return sb.toString();
} // getSummary
@Override
public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getCreated());
}
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg | @Override
public int getDoc_User_ID()
{
return getSalesRep_ID();
} // getDoc_User_ID
@Override
public BigDecimal getApprovalAmt()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getC_Currency_ID()
{
// TODO Auto-generated method stub
return 0;
}
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
public boolean isComplete()
{
final String docStatus = getDocStatus();
return DOCSTATUS_Completed.equals(docStatus)
|| DOCSTATUS_Closed.equals(docStatus)
|| DOCSTATUS_Reversed.equals(docStatus);
}
} // MDDOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrder.java | 1 |
请完成以下Java代码 | public class AbstractServletProcessApplication extends AbstractProcessApplication {
protected String servletContextName;
protected String servletContextPath;
protected ProcessApplicationReferenceImpl reference;
protected ClassLoader processApplicationClassloader;
@Override
protected String autodetectProcessApplicationName() {
String name = (servletContextName != null && !servletContextName.isEmpty()) ? servletContextName : servletContextPath;
if(name.startsWith("/")) {
name = name.substring(1);
}
return name;
}
@Override
public ProcessApplicationReference getReference() {
if(reference == null) {
reference = new ProcessApplicationReferenceImpl(this);
}
return reference;
} | @Override
public ClassLoader getProcessApplicationClassloader() {
return processApplicationClassloader;
}
@Override
public Map<String, String> getProperties() {
Map<String, String> properties = new HashMap<String, String>();
// set the servlet context path as property
properties.put(ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH, servletContextPath);
return properties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractServletProcessApplication.java | 1 |
请完成以下Java代码 | public class PgPassEntry
{
private final String host;
private final String port;
private final String dbName;
private final String user;
private final String password;
/* package */PgPassEntry(final String host, final String port, final String dbName, final String user, final String password)
{
super();
if (host == null || host.isEmpty())
{
throw new IllegalArgumentException("host is empty. Please use " + PgPassFile.ANY + " in this case");
}
this.host = host;
if (port == null || port.isEmpty())
{
throw new IllegalArgumentException("port is empty. Please use " + PgPassFile.ANY + " in this case");
}
this.port = port;
this.dbName = dbName;
if (dbName == null || dbName.isEmpty())
{
throw new IllegalArgumentException("dbName is empty. Please use " + PgPassFile.ANY + " in this case");
}
this.user = user;
if (user == null || user.isEmpty())
{
throw new IllegalArgumentException("user is empty. Please use " + PgPassFile.ANY + " in this case");
}
this.password = password;
// NOTE: we allow the password to be null in case this is a lookup
}
@Override
public String toString()
{
return "PgPassEntry [host=" + host + ", port=" + port + ", dbName=" + dbName + ", user=" + user + ", password=" + password + "]"; | }
public String getHost()
{
return host;
}
public String getPort()
{
return port;
}
public String getDbName()
{
return dbName;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
} // PgPassEntry | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgPassEntry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void syncSettlementICToCommissionInstance(
@NonNull final InvoiceCandidateId invoiceCandidateId,
final boolean candidateDeleted)
{
final I_C_Invoice_Candidate settlementICRecord = invoiceCandDAO.getById(invoiceCandidateId);
final CommissionSettlementShare settlementShare = commissionSettlementShareRepository.getByInvoiceCandidateId(invoiceCandidateId);
//
// pointsToSettle fact
final CommissionPoints newPointsToSettle = CommissionPoints.of(candidateDeleted ? ZERO : settlementICRecord.getQtyToInvoice());
final CommissionPoints pointsToSettleDelta = newPointsToSettle.subtract(settlementShare.getPointsToSettleSum());
if (!pointsToSettleDelta.isZero())
{
final CommissionSettlementFact fact = CommissionSettlementFact.builder()
.settlementInvoiceCandidateId(invoiceCandidateId)
.timestamp(TimeUtil.asInstant(settlementICRecord.getUpdated()))
.state(CommissionSettlementState.TO_SETTLE)
.points(pointsToSettleDelta)
.build();
settlementShare.addFact(fact);
}
//
// settledPoints fact | final CommissionPoints settledPoints = CommissionPoints.of(candidateDeleted ? ZERO : settlementICRecord.getQtyInvoiced());
final CommissionPoints settledPointsDelta = settledPoints.subtract(settlementShare.getSettledPointsSum());
if (!settledPointsDelta.isZero())
{
final CommissionSettlementFact fact = CommissionSettlementFact.builder()
.settlementInvoiceCandidateId(invoiceCandidateId)
.timestamp(TimeUtil.asInstant(settlementICRecord.getUpdated()))
.state(CommissionSettlementState.SETTLED)
.points(settledPointsDelta)
.build();
settlementShare.addFact(fact);
}
commissionSettlementShareRepository.save(settlementShare);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\SettlementInvoiceCandidateService.java | 2 |
请完成以下Java代码 | public int compare(Qualifier o1, Qualifier o2) {
Qualifier first = (o1 != null) ? o1 : new Qualifier(RELEASE);
Qualifier second = (o2 != null) ? o2 : new Qualifier(RELEASE);
int qualifier = compareQualifier(first, second);
return (qualifier != 0) ? qualifier : compareQualifierVersion(first, second);
}
private static int compareQualifierVersion(Qualifier first, Qualifier second) {
Integer firstVersion = (first.getVersion() != null) ? first.getVersion() : 0;
Integer secondVersion = (second.getVersion() != null) ? second.getVersion() : 0;
return firstVersion.compareTo(secondVersion);
}
private static int compareQualifier(Qualifier first, Qualifier second) {
int firstIndex = getQualifierIndex(first.getId());
int secondIndex = getQualifierIndex(second.getId());
// Unknown qualifier, alphabetic ordering | if (firstIndex == -1 && secondIndex == -1) {
return first.getId().compareTo(second.getId());
}
else {
return Integer.compare(firstIndex, secondIndex);
}
}
private static int getQualifierIndex(String qualifier) {
return (StringUtils.hasText(qualifier) ? KNOWN_QUALIFIERS.indexOf(qualifier) : 0);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\Version.java | 1 |
请完成以下Java代码 | public IAttributeStorage getAttributeStorage()
{
return attributeStorage;
}
@Override
public IHUAttributePropagator getPropagator()
{
return attributePropagator;
}
@Override
public I_M_Attribute getAttribute()
{
return attribute;
}
@Override
public AttributeCode getAttributeCode()
{
return AttributeCode.ofString(getAttribute().getValue());
}
@Override
public IHUAttributePropagationContext getParent()
{
return parent;
}
@Override
public void setUpdateStorageValue(final boolean updateStorageValue)
{
this.updateStorageValue = updateStorageValue;
}
@Override
public boolean isUpdateStorageValue()
{
return updateStorageValue;
}
@Override
public void setValueUpdateInvocation()
{
valueUpdateInvocation = true;
}
@Override
public boolean isValueUpdateInvocation()
{
return valueUpdateInvocation;
}
@Override
public boolean isValueUpdatedBefore()
{
return isValueUpdatedBefore(getAttributeCode());
}
@Override
public boolean isValueUpdatedBefore(final AttributeCode attributeCode)
{
return getLastPropagatorOrNull(attributeCode) != null;
}
@Override
public IHUAttributePropagator getLastPropagatorOrNull(@NonNull final AttributeCode attributeCode)
{
// Iterate up chain of parents, starting with the parent context. for each parent context, we check if the attribute was updated in that context
// NOTE: we are skipping current node because we want to check if that attribute was updated before
for (IHUAttributePropagationContext currentParentContext = parent; currentParentContext != null; currentParentContext = currentParentContext.getParent()) | {
if (!currentParentContext.isValueUpdateInvocation())
{
continue;
}
final IAttributeStorage currentAttributeStorage = currentParentContext.getAttributeStorage();
if (!currentAttributeStorage.equals(attributeStorage))
{
continue;
}
final AttributeCode currentAttributeCode = currentParentContext.getAttributeCode();
if (!AttributeCode.equals(currentAttributeCode, attributeCode))
{
continue;
}
return currentParentContext.getPropagator();
}
return null;
}
@Override
public IAttributeValueContext copy()
{
return cloneForPropagation(getAttributeStorage(), getAttribute(), getPropagator());
}
@Override
public IHUAttributePropagationContext cloneForPropagation(final IAttributeStorage attributeStorage, final I_M_Attribute attribute, final IHUAttributePropagator propagatorToUse)
{
final HUAttributePropagationContext propagationContextClone = new HUAttributePropagationContext(this, attributeStorage, propagatorToUse, attribute, getParameters());
return propagationContextClone;
}
@Override
public boolean isExternalInput()
{
// NOTE: we consider External Input if this is the first context created (i.e. has no parents => no previous calls)
return Util.same(getParent(), IHUAttributePropagationContext.NULL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\HUAttributePropagationContext.java | 1 |
请完成以下Java代码 | public String toString() {
return "!";
}
};
private final Operator operator;
private final AstNode child;
public AstUnary(AstNode child, Operator operator) {
this.child = child;
this.operator = operator;
}
public Operator getOperator() {
return operator;
}
@Override
public Object eval(Bindings bindings, ELContext context) throws ELException {
return operator.eval(bindings, context, child);
}
@Override
public String toString() { | return "'" + operator.toString() + "'";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(operator);
b.append(' ');
child.appendStructure(b, bindings);
}
public int getCardinality() {
return 1;
}
public AstNode getChild(int i) {
return i == 0 ? child : null;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstUnary.java | 1 |
请完成以下Java代码 | public boolean isRefunded()
{
return amount.signum() != 0 && amountRefunded.signum() != 0;
}
//
//
//
//
//
//
@Value
@Builder
@Jacksonized
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public static class CardReader
{
@NonNull SumUpCardReaderExternalId externalId;
@NonNull String name;
}
//
//
//
//
//
//
@Value
@Builder
@Jacksonized
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public static class Card
{
@NonNull String type;
@NonNull String last4Digits;
@Override
@Deprecated
public String toString() {return getAsString();}
public String getAsString() {return type + "-" + last4Digits;}
}
//
//
//
//
//
//
@RequiredArgsConstructor
@Getter
public enum LastSyncStatus implements ReferenceListAwareEnum
{
OK(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_OK),
Error(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_Error),
;
private static final ValuesIndex<LastSyncStatus> index = ReferenceListAwareEnums.index(values()); | @NonNull private final String code;
public static LastSyncStatus ofCode(@NonNull String code) {return index.ofCode(code);}
public static LastSyncStatus ofNullableCode(@Nullable String code) {return index.ofNullableCode(code);}
}
//
//
//
//
//
//
@Value
@Builder
@Jacksonized
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public static class LastSync
{
@NonNull LastSyncStatus status;
@Nullable Instant timestamp;
@Nullable AdIssueId errorId;
public static LastSync ok()
{
return builder()
.status(LastSyncStatus.OK)
.timestamp(SystemTime.asInstant())
.build();
}
public static LastSync error(@NonNull final AdIssueId errorId)
{
return builder()
.status(LastSyncStatus.Error)
.timestamp(SystemTime.asInstant())
.errorId(errorId)
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransaction.java | 1 |
请完成以下Java代码 | public void windowGainedFocus(WindowEvent e) {
if (firstBox != null)
firstBox.requestFocus();
}
@Override
public void windowLostFocus(WindowEvent e) {
}
});
card.first(cardContainer);
if (page > 1) {
JXPanel ctrl = new JXPanel();
JXButton previous = new JXButton("<");
JXButton next = new JXButton(">");
previous.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.previous(cardContainer);
}
});
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.next(cardContainer);
}
});
ctrl.add(previous);
ctrl.add(next);
dialogContent.add(ctrl, BorderLayout.NORTH); | }
dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
class PreviewMouseAdapter extends MouseAdapter {
private JDialog dialog;
private Window window;
PreviewMouseAdapter(JDialog d, Window w) {
dialog = d;
window = w;
}
@Override
public void mouseClicked(MouseEvent e) {
dialog.dispose();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AEnv.showWindow(window);
}
});
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowMenu.java | 1 |
请完成以下Java代码 | public boolean hasDesignation() {
return fieldSetFlags()[4];
}
/**
* Clears the value of the 'designation' field.
* @return This builder.
*/
public com.baeldung.schema.Employee.Builder clearDesignation() {
designation = null;
fieldSetFlags()[4] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public Employee build() {
try {
Employee record = new Employee();
record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]);
record.firstName = fieldSetFlags()[1] ? this.firstName : (java.lang.CharSequence) defaultValue(fields()[1]);
record.lastName = fieldSetFlags()[2] ? this.lastName : (java.lang.CharSequence) defaultValue(fields()[2]);
record.department = fieldSetFlags()[3] ? this.department : (java.lang.CharSequence) defaultValue(fields()[3]);
record.designation = fieldSetFlags()[4] ? this.designation : (java.lang.CharSequence) defaultValue(fields()[4]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked") | private static final org.apache.avro.io.DatumWriter<Employee>
WRITER$ = (org.apache.avro.io.DatumWriter<Employee>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<Employee>
READER$ = (org.apache.avro.io.DatumReader<Employee>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\Employee.java | 1 |
请完成以下Java代码 | public void setErrorDetails(String exception) {
EnsureUtil.ensureNotNull("exception", exception);
byte[] exceptionBytes = toByteArray(exception);
ByteArrayEntity byteArray = createExceptionByteArray(EXCEPTION_NAME, exceptionBytes, ResourceTypes.HISTORY);
byteArray.setRootProcessInstanceId(rootProcessInstanceId);
byteArray.setRemovalTime(removalTime);
errorDetailsByteArrayId = byteArray.getId();
}
protected ByteArrayEntity getErrorByteArray() {
if (errorDetailsByteArrayId != null) {
return Context
.getCommandContext()
.getDbEntityManager()
.selectById(ByteArrayEntity.class, errorDetailsByteArrayId);
}
return null;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public long getPriority() {
return priority;
}
public void setPriority(long priority) {
this.priority = priority;
}
public int getState() { | return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public boolean isCreationLog() {
return state == ExternalTaskState.CREATED.getStateCode();
}
@Override
public boolean isFailureLog() {
return state == ExternalTaskState.FAILED.getStateCode();
}
@Override
public boolean isSuccessLog() {
return state == ExternalTaskState.SUCCESSFUL.getStateCode();
}
@Override
public boolean isDeletionLog() {
return state == ExternalTaskState.DELETED.getStateCode();
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricExternalTaskLogEntity.java | 1 |
请完成以下Java代码 | public static void setFieldValue(Object object, String fieldName, Object value) {
//根据 对象和属性名通过反射 调用上面的方法获取 Field对象
Field field = getDeclaredField(object, fieldName);
//抑制Java对其的检查
field.setAccessible(true);
try {
//将 object 中 field 所代表的值 设置为 value
field.set(object, value);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
}
/**
* 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
*
* @param object : 子类对象
* @param fieldName : 父类中的属性名
* @return : 父类中的属性值
*/
public static Object getFieldValue(Object object, String fieldName) {
//根据 对象和属性名通过反射 调用上面的方法获取 Field对象
Field field = getDeclaredField(object, fieldName);
//抑制Java对其的检查
field.setAccessible(true);
try {
//获取 object 中 field 所代表的属性值
return field.get(object);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
return null;
}
/**
* 获取 目标对象
*
* @param proxy 代理对象
* @return
* @throws Exception
*/
public static Object getTarget(Object proxy) throws Exception {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;//不是代理对象 | }
if (AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { //cglib
return getCglibProxyTargetObject(proxy);
}
}
private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
}
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\utils\ReflectionUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ShippingFulfillment shippingCarrierCode(String shippingCarrierCode)
{
this.shippingCarrierCode = shippingCarrierCode;
return this;
}
/**
* The eBay code identifying the shipping carrier for this fulfillment. This field is returned if available. Note: The Trading API's ShippingCarrierCodeType enumeration type contains the most current list of eBay shipping carrier codes and the countries served by each carrier. See ShippingCarrierCodeType.
*
* @return shippingCarrierCode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The eBay code identifying the shipping carrier for this fulfillment. This field is returned if available. Note: The Trading API's ShippingCarrierCodeType enumeration type contains the most current list of eBay shipping carrier codes and the countries served by each carrier. See ShippingCarrierCodeType.")
public String getShippingCarrierCode()
{
return shippingCarrierCode;
}
public void setShippingCarrierCode(String shippingCarrierCode)
{
this.shippingCarrierCode = shippingCarrierCode;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
ShippingFulfillment shippingFulfillment = (ShippingFulfillment)o;
return Objects.equals(this.fulfillmentId, shippingFulfillment.fulfillmentId) &&
Objects.equals(this.lineItems, shippingFulfillment.lineItems) &&
Objects.equals(this.shipmentTrackingNumber, shippingFulfillment.shipmentTrackingNumber) &&
Objects.equals(this.shippedDate, shippingFulfillment.shippedDate) &&
Objects.equals(this.shippingCarrierCode, shippingFulfillment.shippingCarrierCode);
}
@Override
public int hashCode()
{
return Objects.hash(fulfillmentId, lineItems, shipmentTrackingNumber, shippedDate, shippingCarrierCode);
}
@Override
public String toString()
{ | StringBuilder sb = new StringBuilder();
sb.append("class ShippingFulfillment {\n");
sb.append(" fulfillmentId: ").append(toIndentedString(fulfillmentId)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" shipmentTrackingNumber: ").append(toIndentedString(shipmentTrackingNumber)).append("\n");
sb.append(" shippedDate: ").append(toIndentedString(shippedDate)).append("\n");
sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingFulfillment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class UOMConversionContext
{
public enum Rounding
{
/** The result is rounded to the target uom's precision. The default. */
TO_TARGET_UOM_PRECISION,
/** The result has at least the same scale as the input quantity, even if that scale is bigger than the UOM's precision. */
PRESERVE_SCALE;
}
public static UOMConversionContext of(@Nullable final ProductId productId, @Nullable final Rounding rounding)
{
return new UOMConversionContext(productId, rounding);
}
public static UOMConversionContext of(@Nullable final ProductId productId)
{
return new UOMConversionContext(productId, null/* rounding */);
}
public static UOMConversionContext of(final int productRepoId)
{
return of(ProductId.ofRepoIdOrNull(productRepoId));
} | /**
* @deprecated please use {@link #of(ProductId)}.
*/
@Deprecated
public static UOMConversionContext of(final I_M_Product product)
{
return of(product != null ? ProductId.ofRepoId(product.getM_Product_ID()) : null);
}
ProductId productId;
Rounding rounding;
private UOMConversionContext(
@Nullable final ProductId productId,
@Nullable final Rounding rounding)
{
this.productId = productId;
this.rounding = coalesce(rounding, Rounding.TO_TARGET_UOM_PRECISION);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionContext.java | 2 |
请完成以下Java代码 | public void calculate(final IPricingContext pricingCtx, final IPricingResult result)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
final I_C_OrderLine orderLine = (I_C_OrderLine)pricingCtx.getReferencedObject();
final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoId(orderLine.getC_Flatrate_Term_ID());
final I_C_Flatrate_Term callOrderContract = flatrateDAO.getById(flatrateTermId);
if (callOrderContract.getPriceActual() == null
|| callOrderContract.getC_UOM_ID() <= 0
|| callOrderContract.getM_Product_ID() <= 0
|| callOrderContract.getC_Currency_ID() <= 0)
{
loggable.addLog("Not applying because the contract doesn't hold any price information!;");
return;
}
if (!callOrderContractService.doesContractMatchOrderLine(orderLine, callOrderContract))
{
loggable.addLog("Not applying because the contract doesn't match the given order line!;");
return;
}
final ProductPrice productPrice = calculatePriceActual(orderLine, callOrderContract);
result.setPriceStd(productPrice.toBigDecimal());
result.setPriceList(productPrice.toBigDecimal());
result.setPriceLimit(productPrice.toBigDecimal());
result.setPriceUomId(productPrice.getUomId());
result.setCurrencyId(productPrice.getCurrencyId());
result.setProductId(productPrice.getProductId());
result.setTaxIncluded(callOrderContract.isTaxIncluded());
result.setTaxCategoryId(TaxCategoryId.ofRepoId(callOrderContract.getC_TaxCategory_ID()));
result.setCalculated(true);
}
@NonNull
private ProductPrice calculatePriceActual( | @NonNull final I_C_OrderLine orderLine,
@NonNull final I_C_Flatrate_Term flatrateTerm)
{
final UomId orderLinePriceUOM = orderLine.getPrice_UOM_ID() > 0
? UomId.ofRepoId(orderLine.getPrice_UOM_ID())
: UomId.ofRepoId(orderLine.getC_UOM_ID());
final ProductId productId = ProductId.ofRepoId(orderLine.getM_Product_ID());
final Currency currency = currencyRepository.getById(CurrencyId.ofRepoId(flatrateTerm.getC_Currency_ID()));
final ProductPrice contractProductPrice = ProductPrice.builder()
.productId(productId)
.uomId(UomId.ofRepoId(flatrateTerm.getC_UOM_ID()))
.money(Money.of(flatrateTerm.getPriceActual(), currency.getId()))
.build();
return conversionBL.convertProductPriceToUom(contractProductPrice, orderLinePriceUOM, currency.getPrecision());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\price\CallOrderPricingRule.java | 1 |
请完成以下Java代码 | public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set UI Style.
@param UIStyle UI Style */
@Override
public void setUIStyle (java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
/** Get UI Style.
@return UI Style */
@Override
public java.lang.String getUIStyle ()
{
return (java.lang.String)get_Value(COLUMNNAME_UIStyle);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementGroup.java | 1 |
请完成以下Java代码 | private static void updateRecord(final I_C_POS_JournalLine record, final POSCashJournalLine from)
{
record.setType(from.getType().getCode());
record.setAmount(from.getAmount().toBigDecimal());
record.setCashier_ID(from.getCashierId().getRepoId());
record.setDescription(from.getDescription());
record.setC_POS_Order_ID(from.getPosOrderAndPaymentId() != null ? from.getPosOrderAndPaymentId().getOrderId().getRepoId() : -1);
record.setC_POS_Payment_ID(from.getPosOrderAndPaymentId() != null ? from.getPosOrderAndPaymentId().getPaymentId().getRepoId() : -1);
}
public POSCashJournal changeJournalById(@NonNull final POSCashJournalId cashJournalId, @NonNull final Consumer<POSCashJournal> updater)
{
final I_C_POS_Journal record = retrieveRecordById(cashJournalId);
final List<I_C_POS_JournalLine> lineRecords = retrieveLineRecordsByJournalId(cashJournalId);
final POSCashJournal journal = fromRecord(record, lineRecords);
updater.accept(journal);
updateRecord(record, journal);
InterfaceWrapperHelper.save(record);
final ImmutableList<POSCashJournalLine> lines = journal.getLines();
for (int i = 0; i < lines.size(); i++)
{ | final POSCashJournalLine line = lines.get(i);
I_C_POS_JournalLine lineRecord = i < lineRecords.size() ? lineRecords.get(i) : null;
if (lineRecord == null)
{
lineRecord = InterfaceWrapperHelper.newInstance(I_C_POS_JournalLine.class);
lineRecord.setC_POS_Journal_ID(record.getC_POS_Journal_ID());
}
lineRecord.setAD_Org_ID(record.getAD_Org_ID());
updateRecord(lineRecord, line);
InterfaceWrapperHelper.save(lineRecord);
}
for (int i = lines.size(); i < lineRecords.size(); i++)
{
InterfaceWrapperHelper.delete(lineRecords.get(i));
}
return journal;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSCashJournalRepository.java | 1 |
请完成以下Java代码 | public class Artist {
private final String name;
private boolean associatedMajorLabels;
private List<String> majorLabels;
Artist(String name, boolean associatedMajorLabels, List<String> majorLabels) {
this.name = name;
this.associatedMajorLabels = associatedMajorLabels;
this.majorLabels = majorLabels;
}
public String getName() {
return name;
}
public boolean isAssociatedMajorLabels() {
return associatedMajorLabels;
}
public List<String> getMajorLabels() {
return majorLabels;
}
@Override
public int hashCode() {
return Objects.hash(name); | }
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Artist other = (Artist) obj;
return Objects.equals(name, other.name);
}
public String toString() {
return name;
}
} | repos\tutorials-master\core-java-modules\core-java-16\src\main\java\com\baeldung\java_16_features\mapmulti\Artist.java | 1 |
请完成以下Java代码 | public class X_MD_Stock_WarehouseAndProduct_v extends org.compiere.model.PO implements I_MD_Stock_WarehouseAndProduct_v, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -831057120L;
/** Standard Constructor */
public X_MD_Stock_WarehouseAndProduct_v (final Properties ctx, final int MD_Stock_WarehouseAndProduct_v_ID, @Nullable final String trxName)
{
super (ctx, MD_Stock_WarehouseAndProduct_v_ID, trxName);
}
/** Load Constructor */
public X_MD_Stock_WarehouseAndProduct_v (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 setLine (final int Line)
{
set_ValueNoCheck (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_WarehouseAndProduct_v.java | 1 |
请完成以下Java代码 | public java.lang.String getExclusionFromSaleReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_ExclusionFromSaleReason);
}
/** Set Banned Manufacturer .
@param M_BannedManufacturer_ID Banned Manufacturer */
@Override
public void setM_BannedManufacturer_ID (int M_BannedManufacturer_ID)
{
if (M_BannedManufacturer_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, Integer.valueOf(M_BannedManufacturer_ID));
}
/** Get Banned Manufacturer .
@return Banned Manufacturer */
@Override
public int getM_BannedManufacturer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BannedManufacturer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner getManufacturer() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class);
}
@Override
public void setManufacturer(org.compiere.model.I_C_BPartner Manufacturer)
{
set_ValueFromPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class, Manufacturer);
}
/** Set Hersteller.
@param Manufacturer_ID
Hersteller des Produktes | */
@Override
public void setManufacturer_ID (int Manufacturer_ID)
{
if (Manufacturer_ID < 1)
set_Value (COLUMNNAME_Manufacturer_ID, null);
else
set_Value (COLUMNNAME_Manufacturer_ID, Integer.valueOf(Manufacturer_ID));
}
/** Get Hersteller.
@return Hersteller des Produktes
*/
@Override
public int getManufacturer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Manufacturer_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_BannedManufacturer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Collection<String> loadFactoryNames(Class<?> source) {
return ImportCandidates.load(source, getBeanClassLoader()).getCandidates();
}
@Override
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 |
请在Spring Boot框架中完成以下Java代码 | public class PersonServiceImpl implements PersonService {
Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);
@Autowired
PersonRepository personRepository;
@Override
public Person save(Person person) {
Person p = personRepository.save(person);
logger.info("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
@Override
public void remove(Long id) {
logger.info("删除了id、key为" + id + "的数据缓存");
//这里不做实际删除操作
}
@Override
public void removeAll() { | logger.info("删除了所有缓存的数据缓存");
//这里不做实际删除操作
}
@Override
public Person findOne(Person person) throws Exception {
Thread.sleep((long) (Math.random() * 500), 1000);
Person p = personRepository.findOne(Example.of(person));
logger.info("为id、key为: {} 数据做了缓存", p.getId());
return p;
}
@Override
public Person findOne1(Person person) throws Exception {
Thread.sleep((long) (Math.random() * 500), 1000);
Person p = personRepository.findOne(Example.of(person));
logger.info("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
} | repos\spring-boot-student-master\spring-boot-student-websocket\src\main\java\com\xiaolyuh\service\impl\PersonServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintingServiceImpl other = (PrintingServiceImpl)obj;
if (isDirectPrint != other.isDirectPrint)
return false;
if (printerName == null)
{
if (other.printerName != null)
return false;
}
else if (!printerName.equals(other.printerName))
return false;
if (printerType == null)
{
if (other.printerType != null) | return false;
}
else if (!printerType.equals(other.printerType))
return false;
return true;
}
@Override
public String toString()
{
return "PrintingServiceImpl [printerName=" + printerName + ", printerType=" + printerType + ", isDirectPrint=" + isDirectPrint + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PrintingServiceImpl.java | 2 |
请完成以下Java代码 | public String getValue()
{
return m_value;
} // getValue
/**
* Get Validation Message
*
* @return Validation Message
*/
@JsonProperty("validationInformation")
@JsonInclude(JsonInclude.Include.NON_NULL)
public ValueNamePairValidationInformation getValidationInformation()
{
return m_validationInformation;
}
/**
* Get ID
*
* @return Value
*/
@Override
@JsonIgnore
public String getID()
{
return m_value; | } // getID
@Override
public boolean equals(final Object obj)
{
if (obj == this)
{
return true;
}
if (obj instanceof ValueNamePair)
{
final ValueNamePair other = (ValueNamePair)obj;
return Objects.equals(this.m_value, other.m_value)
&& Objects.equals(this.getName(), other.getName())
&& Objects.equals(this.m_validationInformation, other.m_validationInformation);
}
return false;
} // equals
@Override
public int hashCode()
{
return m_value.hashCode();
} // hashCode
} // KeyValuePair | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePair.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPermissionName() {
return permissionName;
}
/**
* 权限名称
*
* @return
*/
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
/**
* 权限标识
* | * @return
*/
public String getPermission() {
return permission;
}
/**
* 权限标识
*
* @return
*/
public void setPermission(String permission) {
this.permission = permission;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsPermission.java | 2 |
请完成以下Java代码 | public PMM_GenerateOrdersEnqueuer filter(final IQueryFilter<I_PMM_PurchaseCandidate> candidatesFilter)
{
this.candidatesFilter = candidatesFilter;
return this;
}
public PMM_GenerateOrdersEnqueuer confirmRecordsToProcess(final ConfirmationCallback confirmationCallback)
{
this.confirmationCallback = confirmationCallback;
return this;
}
/**
* @return number of records enqueued
*/
public int enqueue()
{
final IQuery<I_PMM_PurchaseCandidate> query = createRecordsToProcessQuery();
if (!confirmRecordsToProcess(query))
{
return 0;
}
final List<I_PMM_PurchaseCandidate> candidates = query.list();
if (candidates.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName());
final ILockCommand elementsLocker = lockManager.lock()
.setOwner(lockOwner)
.setAutoCleanup(false);
workPackageQueueFactory
.getQueueForEnqueuing(Env.getCtx(), PMM_GenerateOrders.class)
.newWorkPackage()
.setElementsLocker(elementsLocker)
.addElements(candidates)
.buildAndEnqueue();
return candidates.size();
}
private boolean confirmRecordsToProcess(final IQuery<I_PMM_PurchaseCandidate> query)
{
if (confirmationCallback == null)
{
return true; // OK, autoconfirmed
} | //
// Fail if there is nothing to update
final int countToProcess = query.count();
if (countToProcess <= 0)
{
throw new AdempiereException("@NoSelection@");
}
//
// Ask the callback if we shall process
return confirmationCallback.confirmRecordsToProcess(countToProcess);
}
private IQuery<I_PMM_PurchaseCandidate> createRecordsToProcessQuery()
{
final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder = queryBL.createQueryBuilder(I_PMM_PurchaseCandidate.class);
if (candidatesFilter != null)
{
queryBuilder.filter(candidatesFilter);
}
return queryBuilder
.addOnlyActiveRecordsFilter()
.filter(lockManager.getNotLockedFilter(I_PMM_PurchaseCandidate.class))
.addCompareFilter(I_PMM_PurchaseCandidate.COLUMNNAME_QtyToOrder, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO)
.orderBy()
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_AD_Org_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_Warehouse_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_BPartner_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_PricingSystem_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_Currency_ID)
.endOrderBy()
//
.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\async\PMM_GenerateOrdersEnqueuer.java | 1 |
请完成以下Java代码 | public static Timestamp toTimeStamp(final String string)
{
try
{
return new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(string).getTime());
}
catch (ParseException e)
{
throwIllegalArgumentEx(string, "string");
return null;
}
}
public static int getCalloutId(final GridTab mTab, final String colName)
{
final Integer id = (Integer)mTab.getValue(colName);
if (id == null || id <= 0)
{
return 0;
}
return id;
}
/**
* For a {@link Timestamp} representing e.g. "17.12.2009 15:14:34" this method returns a timestamp representing
* "17.12.2009 00:00:00".
*
* @param ctx
* @param ts
* @return
*/
public static Timestamp removeTime(final Timestamp ts)
{
final DateFormat fmt = DateFormat.getDateInstance(DateFormat.LONG);
final String strDate = fmt.format(ts);
java.util.Date date;
try
{
date = fmt.parse(strDate);
}
catch (ParseException e)
{
throw new AdempiereException(e);
}
final Timestamp currentDate = new Timestamp(date.getTime());
return currentDate;
}
public static GridTab getGridTabForTableAndWindow(final Properties ctx, final int windowNo, final int AD_Window_ID, final int AD_Table_ID, final boolean startWithEmptyQuery)
{
final GridWindowVO wVO = GridWindowVO.create(ctx, windowNo, AdWindowId.ofRepoId(AD_Window_ID));
if (wVO == null)
{
MWindow w = new MWindow(Env.getCtx(), AD_Window_ID, null);
throw new AdempiereException("No access to window - " + w.getName() + " (AD_Window_ID=" + AD_Window_ID + ")"); | }
final GridWindow gridWindow = new GridWindow(wVO);
//
GridTab tab = null;
int tabIndex = -1;
for (int i = 0; i < gridWindow.getTabCount(); i++)
{
GridTab t = gridWindow.getTab(i);
if (t.getAD_Table_ID() == AD_Table_ID)
{
tab = t;
tabIndex = i;
break;
}
}
if (tab == null)
{
throw new AdempiereException("No Tab found for AD_Table_ID=" + AD_Table_ID + ", Window:" + gridWindow.getName());
}
gridWindow.initTab(tabIndex);
//
if (startWithEmptyQuery)
{
tab.setQuery(MQuery.getEqualQuery("1", "2"));
tab.query(false);
}
return tab;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\MiscUtils.java | 1 |
请完成以下Java代码 | protected void setFailedJobRetryTimeCycleValue(Element element, ActivityImpl activity) {
String failedJobRetryTimeCycleConfiguration = null;
Element extensionElements = element.element(EXTENSION_ELEMENTS);
if (extensionElements != null) {
Element failedJobRetryTimeCycleElement = extensionElements.elementNS(FOX_ENGINE_NS, FAILED_JOB_RETRY_TIME_CYCLE);
if (failedJobRetryTimeCycleElement == null) {
// try to get it from the activiti namespace
failedJobRetryTimeCycleElement = extensionElements.elementNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS, FAILED_JOB_RETRY_TIME_CYCLE);
}
if (failedJobRetryTimeCycleElement != null) {
failedJobRetryTimeCycleConfiguration = failedJobRetryTimeCycleElement.getText();
}
} | if (failedJobRetryTimeCycleConfiguration == null || failedJobRetryTimeCycleConfiguration.isEmpty()) {
failedJobRetryTimeCycleConfiguration = Context.getProcessEngineConfiguration().getFailedJobRetryTimeCycle();
}
if (failedJobRetryTimeCycleConfiguration != null) {
FailedJobRetryConfiguration configuration = ParseUtil.parseRetryIntervals(failedJobRetryTimeCycleConfiguration);
activity.getProperties().set(FAILED_JOB_CONFIGURATION, configuration);
}
}
protected boolean isMultiInstance(ActivityImpl activity) {
// #isMultiInstance() don't work since the property is not set yet
ActivityImpl parent = activity.getParentFlowScopeActivity();
return parent != null && parent.getActivityBehavior() instanceof MultiInstanceActivityBehavior;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\DefaultFailedJobParseListener.java | 1 |
请完成以下Java代码 | public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
for (final Map.Entry<String, Object> e : debugProperties.entrySet())
{
putDebugProperty(e.getKey(), e.getValue());
}
}
public JSONDocumentField setViewEditorRenderMode(final ViewEditorRenderMode viewEditorRenderMode)
{ | this.viewEditorRenderMode = viewEditorRenderMode != null ? viewEditorRenderMode.toJson() : null;
return this;
}
public void setFieldWarning(@Nullable final JSONDocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public JSONDocumentField setDevices(@Nullable final List<JSONDeviceDescriptor> devices)
{
this.devices = devices;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentField.java | 1 |
请完成以下Java代码 | protected void setInternalValueDate(Date value)
{
attributeInstance.setValueDate(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDate()
{
return attributeInstance.getValueDate();
}
@Override
protected void setInternalValueDateInitial(Date value)
{
throw new UnsupportedOperationException("Setting initial value not supported"); | }
@Override
protected Date getInternalValueDateInitial()
{
return null;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
// FIXME tsa: figure out why this returns false instead of using the flag from M_HU_PI_Attribute?!
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AIWithHUPIAttributeValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ImportConfig ofRecordOrNull(@Nullable final I_HC_Forum_Datenaustausch_Config configRecord)
{
if (configRecord == null)
{
return null;
}
final ImportConfig.ImportConfigBuilder builder = ImportConfig.builder();
final BPGroupId patientBPGroupId = BPGroupId.ofRepoIdOrNull(configRecord.getImportedPartientBP_Group_ID());
if (patientBPGroupId != null)
{
final I_C_BP_Group patientBPartnerGroup = Check.assumeNotNull(
groupDAO.getById(patientBPGroupId),
"Unable to load BP_Group referenced by HC_Forum_Datenaustausch_Config.ImportedPartientBP_Group_ID={}. HC_Forum_Datenaustausch_Config={}",
patientBPGroupId.getRepoId(), configRecord);
builder.partientBPartnerGroupName(patientBPartnerGroup.getName());
}
final BPGroupId municipalityBPGroupId = BPGroupId.ofRepoIdOrNull(configRecord.getImportedMunicipalityBP_Group_ID());
if (municipalityBPGroupId != null)
{ | final I_C_BP_Group municipalityBPartnerGroup = Check.assumeNotNull(
groupDAO.getById(municipalityBPGroupId),
"Unable to load BP_Group referenced by HC_Forum_Datenaustausch_Config.ImportedMunicipalityBP_Group_ID={}. HC_Forum_Datenaustausch_Config={}",
municipalityBPGroupId.getRepoId(), configRecord);
builder.municipalityBPartnerGroupName(municipalityBPartnerGroup.getName());
}
if (Check.isNotBlank(configRecord.getImportedBPartnerLanguage()))
{
builder.languageCode(configRecord.getImportedBPartnerLanguage());
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\config\ImportConfigRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static final class ExecutionBuilder
{
private String name = "";
private int versionErrorRetryCount;
private boolean inTransaction = true;
private ExecutionBuilder()
{
}
public <T> T execute(final Callable<T> callable)
{
Callable<T> callableEffective = callable;
//
// First(important). Run in transaction
if (inTransaction)
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
final ITrxManager trxManager = Services.get(ITrxManager.class);
try
{
return trxManager.callInNewTrx(beforeCall);
}
catch (final Exception ex)
{
logger.info("Changes that will be discarded: {}", getCurrentDocumentChangesCollectorOrNull());
throw AdempiereException.wrapIfNeeded(ex);
}
};
}
//
// Retry on version error
if (versionErrorRetryCount > 0)
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
InvalidDocumentVersionException versionException = null;
for (int retry = 0; retry < versionErrorRetryCount; retry++)
{
try
{
return beforeCall.call();
}
catch (final InvalidDocumentVersionException ex)
{
versionException = ex;
logger.info("Version error on run {}/{}", retry + 1, versionErrorRetryCount, versionException);
}
}
Check.assumeNotNull(versionException, "VersionException must not be null");
throw versionException;
};
}
//
// Last, measure and log
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
boolean error = true;
final Stopwatch stopwatch = Stopwatch.createStarted();
try
{
final T result = beforeCall.call();
error = false; | return result;
}
finally
{
if (!error)
{
logger.debug("Executed {} in {} ({})", name, stopwatch, callable);
}
else
{
logger.warn("Failed executing {} (took {}) ({})", name, stopwatch, callable);
}
}
};
}
//
// Run the effective callable in a new execution
try (final Execution ignored = startExecution())
{
return callableEffective.call();
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
public ExecutionBuilder name(final String name)
{
this.name = name;
return this;
}
public ExecutionBuilder retryOnVersionError(final int retryCount)
{
Preconditions.checkArgument(retryCount > 0);
versionErrorRetryCount = retryCount;
return this;
}
public ExecutionBuilder outOfTransaction()
{
inTransaction = false;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\Execution.java | 2 |
请完成以下Java代码 | public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */ | public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Addition.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.