instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | class MailSenderPropertiesConfiguration {
@Bean
@ConditionalOnMissingBean(JavaMailSender.class)
JavaMailSenderImpl mailSender(MailProperties properties, ObjectProvider<SslBundles> sslBundles) {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
applyProperties(properties, sender, sslBundles.getIfAvailable());
return sender;
}
private void applyProperties(MailProperties properties, JavaMailSenderImpl sender,
@Nullable SslBundles sslBundles) {
sender.setHost(properties.getHost());
if (properties.getPort() != null) {
sender.setPort(properties.getPort());
}
sender.setUsername(properties.getUsername());
sender.setPassword(properties.getPassword());
sender.setProtocol(properties.getProtocol());
if (properties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(properties.getDefaultEncoding().name());
}
Properties javaMailProperties = asProperties(properties.getProperties());
String protocol = properties.getProtocol();
protocol = (!StringUtils.hasLength(protocol)) ? "smtp" : protocol;
Ssl ssl = properties.getSsl();
if (ssl.isEnabled()) {
javaMailProperties.setProperty("mail." + protocol + ".ssl.enable", "true");
}
if (ssl.getBundle() != null) { | Assert.state(sslBundles != null, "'sslBundles' must not be null");
SslBundle sslBundle = sslBundles.getBundle(ssl.getBundle());
javaMailProperties.put("mail." + protocol + ".ssl.socketFactory",
sslBundle.createSslContext().getSocketFactory());
}
if (!javaMailProperties.isEmpty()) {
sender.setJavaMailProperties(javaMailProperties);
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
} | repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailSenderPropertiesConfiguration.java | 2 |
请完成以下Java代码 | protected Result getDefaultResult()
{
return _defaultResult;
}
@Override
public void setHUIterator(final IHUIterator iterator)
{
if (this.iterator != null && iterator != null && this.iterator != iterator)
{
throw new AdempiereException("Changing the iterator from " + this.iterator + " to " + iterator + " is not allowed for " + this + "."
+ " You need to explicitelly set it to null first and then set it again.");
}
this.iterator = iterator;
}
public final IHUIterator getHUIterator()
{
return iterator;
}
@Override
public Result beforeHU(final IMutable<I_M_HU> hu)
{
return getDefaultResult();
}
@Override | public Result afterHU(final I_M_HU hu)
{
return getDefaultResult();
}
@Override
public Result beforeHUItem(final IMutable<I_M_HU_Item> item)
{
return getDefaultResult();
}
@Override
public Result afterHUItem(final I_M_HU_Item item)
{
return getDefaultResult();
}
@Override
public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage)
{
return getDefaultResult();
}
@Override
public Result afterHUItemStorage(final IHUItemStorage itemStorage)
{
return getDefaultResult();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerAdapter.java | 1 |
请完成以下Java代码 | class ReactiveWebServerApplicationContextLocalTestWebServerProvider implements LocalTestWebServer.Provider {
private final @Nullable ReactiveWebServerApplicationContext context;
ReactiveWebServerApplicationContextLocalTestWebServerProvider(ApplicationContext context) {
this.context = getWebServerApplicationContextIfPossible(context);
}
static @Nullable ReactiveWebServerApplicationContext getWebServerApplicationContextIfPossible(
ApplicationContext context) {
try {
return (ReactiveWebServerApplicationContext) context;
}
catch (NoClassDefFoundError | ClassCastException ex) {
return null;
}
}
@Override
public @Nullable LocalTestWebServer getLocalTestWebServer() {
if (this.context == null) {
return null;
}
return LocalTestWebServer.of((isSslEnabled(this.context)) ? Scheme.HTTPS : Scheme.HTTP, () -> { | int port = this.context.getEnvironment().getProperty("local.server.port", Integer.class, 8080);
String path = this.context.getEnvironment().getProperty("spring.webflux.base-path", "");
return new BaseUriDetails(port, path);
});
}
private boolean isSslEnabled(ReactiveWebServerApplicationContext context) {
try {
AbstractConfigurableWebServerFactory webServerFactory = context
.getBean(AbstractConfigurableWebServerFactory.class);
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
}
catch (NoSuchBeanDefinitionException ex) {
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\ReactiveWebServerApplicationContextLocalTestWebServerProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailServiceImpl implements EmailService {
private static final String NOREPLY_ADDRESS = "noreply@baeldung.com";
@Autowired
private JavaMailSender emailSender;
@Autowired
private SimpleMailMessage template;
public void sendSimpleMessage(String to, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(NOREPLY_ADDRESS);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (MailException exception) {
exception.printStackTrace();
}
}
@Override
public void sendMessageWithAttachment(String to,
String subject,
String text,
String pathToAttachment) {
try {
MimeMessage message = emailSender.createMimeMessage();
// pass 'true' to the constructor to create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace(); | }
}
@Override
public void sendMessageWithInputStreamAttachment(
String to, String subject, String text, String attachmentName, InputStream attachmentStream) {
try {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
// Add the attachment from InputStream
helper.addAttachment(attachmentName, new InputStreamResource(attachmentStream));
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\mail\EmailServiceImpl.java | 2 |
请完成以下Java代码 | protected final BigDecimal extractAmountFromString(final String amountString,
final List<String> collectedErrors)
{
BigDecimal amount = BigDecimal.ZERO;
try
{
amount = NumberUtils.asBigDecimal(amountString);
}
catch (final NumberFormatException e)
{
final String wrongNumberFormatAmount = msgBL.getMsg(Env.getCtx(), ERR_WRONG_NUMBER_FORMAT_AMOUNT, new Object[] { amountString });
collectedErrors.add(wrongNumberFormatAmount);
}
return amount;
}
/**
*
* @param dateStr date string in format yyMMdd
* @param collectedErrors
* @return
*/
protected final Timestamp extractTimestampFromString(final String dateStr, final AdMessageKey failMessage, final List<String> collectedErrors)
{ | final DateFormat df = new SimpleDateFormat("yyMMdd");
final Date date;
try
{
date = df.parse(dateStr);
return TimeUtil.asTimestamp(date);
}
catch (final ParseException e)
{
final String wrongDate = msgBL.getMsg(Env.getCtx(), failMessage, new Object[] { dateStr });
collectedErrors.add(wrongDate);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\spi\impl\AbstractESRPaymentStringParser.java | 1 |
请完成以下Java代码 | private ILock getOrAcquireLock()
{
assertNotClosed();
if (_lock == null)
{
final IQueryFilter<ET> filter = createFilter();
final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName());
_lock = lockManager.lock()
.setOwner(lockOwner)
.setAutoCleanup(true)
.setFailIfNothingLocked(false)
.setRecordsByFilter(eventTypeClass, filter)
.acquire();
}
return _lock;
}
protected IQueryFilter<ET> createFilter()
{
return queryBL.createCompositeQueryFilter(eventTypeClass)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.addEqualsFilter(COLUMNNAME_Processed, false)
.addFilter(lockManager.getNotLockedFilter(eventTypeClass));
}
@Override
public void close()
{
// Mark this source as closed
if (_closed.getAndSet(true)) | {
// already closed
return;
}
//
// Unlock all
if (_lock != null)
{
_lock.close();
_lock = null;
}
//
// Close iterator
if (_iterator != null)
{
IteratorUtils.closeQuietly(_iterator);
_iterator = null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\EventSource.java | 1 |
请完成以下Java代码 | protected String getXMLElementName() {
return ELEMENT_DECISION_SERVICE;
}
@Override
protected DmnElement convertXMLToElement(XMLStreamReader xtr, ConversionHelper conversionHelper) throws Exception {
DecisionService decisionService = new DecisionService();
decisionService.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID));
decisionService.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
decisionService.setLabel(xtr.getAttributeValue(null, ATTRIBUTE_LABEL));
boolean readyWithDecisionService = false;
try {
while (!readyWithDecisionService && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement() && ELEMENT_OUTPUT_DECISION.equalsIgnoreCase(xtr.getLocalName())) {
DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addOutputDecision(ref);
} if (xtr.isStartElement() && ELEMENT_ENCAPSULATED_DECISION.equalsIgnoreCase(xtr.getLocalName())) {
DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addEncapsulatedDecision(ref);
} if (xtr.isStartElement() && ELEMENT_INPUT_DATA.equalsIgnoreCase(xtr.getLocalName())) { | DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addInputData(ref);
} else if (xtr.isEndElement() && getXMLElementName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithDecisionService = true;
}
}
} catch (Exception e) {
LOGGER.warn("Error parsing output entry", e);
}
return decisionService;
}
@Override
protected void writeAdditionalAttributes(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeAdditionalChildElements(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\DecisionServiceXMLConverter.java | 1 |
请完成以下Java代码 | public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setLogoutHandlers(LogoutHandler[] handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Set list of {@link LogoutHandler}
* @param handlers list of {@link LogoutHandler}
* @since 5.2.0
*/
public void setLogoutHandlers(List<LogoutHandler> handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Sets the {@link RedirectStrategy} used with
* {@link #ConcurrentSessionFilter(SessionRegistry, String)}
* @param redirectStrategy the {@link RedirectStrategy} to use
* @deprecated use
* {@link #ConcurrentSessionFilter(SessionRegistry, SessionInformationExpiredStrategy)}
* instead.
*/
@Deprecated
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
/**
* A {@link SessionInformationExpiredStrategy} that writes an error message to the
* response body.
*
* @author Rob Winch | * @since 4.2
*/
private static final class ResponseBodySessionInformationExpiredStrategy
implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
HttpServletResponse response = event.getResponse();
response.getWriter()
.print("This session has been expired (possibly due to multiple concurrent "
+ "logins being attempted as the same user).");
response.flushBuffer();
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\ConcurrentSessionFilter.java | 1 |
请完成以下Java代码 | protected ProcessApplicationInfoImpl createProcessApplicationInfo(final AbstractProcessApplication processApplication,
final Map<String, DeployedProcessArchive> processArchiveDeploymentMap) {
// populate process application info
ProcessApplicationInfoImpl processApplicationInfo = new ProcessApplicationInfoImpl();
processApplicationInfo.setName(processApplication.getName());
processApplicationInfo.setProperties(processApplication.getProperties());
// create deployment infos
List<ProcessApplicationDeploymentInfo> deploymentInfoList = new ArrayList<ProcessApplicationDeploymentInfo>();
if(processArchiveDeploymentMap != null) {
for (Entry<String, DeployedProcessArchive> deployment : processArchiveDeploymentMap.entrySet()) {
final DeployedProcessArchive deployedProcessArchive = deployment.getValue();
for (String deploymentId : deployedProcessArchive.getAllDeploymentIds()) {
ProcessApplicationDeploymentInfoImpl deploymentInfo = new ProcessApplicationDeploymentInfoImpl();
deploymentInfo.setDeploymentId(deploymentId);
deploymentInfo.setProcessEngineName(deployedProcessArchive.getProcessEngineName());
deploymentInfoList.add(deploymentInfo);
} | }
}
processApplicationInfo.setDeploymentInfo(deploymentInfoList);
return processApplicationInfo;
}
protected void notifyBpmPlatformPlugins(PlatformServiceContainer serviceContainer, AbstractProcessApplication processApplication) {
JmxManagedBpmPlatformPlugins plugins =
serviceContainer.getService(ServiceTypes.BPM_PLATFORM, RuntimeContainerDelegateImpl.SERVICE_NAME_PLATFORM_PLUGINS);
if (plugins != null) {
for (BpmPlatformPlugin plugin : plugins.getValue().getPlugins()) {
plugin.postProcessApplicationDeploy(processApplication);
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StartProcessApplicationServiceStep.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public InstructorDetail getInstructorDetail() {
return instructorDetail;
} | public void setInstructorDetail(InstructorDetail instructorDetail) {
this.instructorDetail = instructorDetail;
}
@Override
public String toString() {
return "Instructor [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", instructorDetail=" + instructorDetail + "]";
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\model\Instructor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | IncludeExcludeEndpointFilter<ExposableJmxEndpoint> jmxIncludeExcludePropertyEndpointFilter() {
JmxEndpointProperties.Exposure exposure = this.properties.getExposure();
return new IncludeExcludeEndpointFilter<>(ExposableJmxEndpoint.class, exposure.getInclude(),
exposure.getExclude(), EndpointExposure.JMX.getDefaultIncludes());
}
@Bean
static LazyInitializationExcludeFilter eagerlyInitializeJmxEndpointExporter() {
return LazyInitializationExcludeFilter.forBeanTypes(JmxEndpointExporter.class);
}
@Bean
OperationFilter<JmxOperation> jmxAccessPropertiesOperationFilter(EndpointAccessResolver endpointAccessResolver) {
return OperationFilter.byAccess(endpointAccessResolver);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JsonMapper.class)
static class JmxJacksonEndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<JsonMapper> jsonMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper(
jsonMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper, | jmxEndpointsSupplier.getEndpoints());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
static class JmxJackson2EndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<ObjectMapper> objectMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new org.springframework.boot.actuate.endpoint.jmx.Jackson2JmxOperationResponseMapper(
objectMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\JmxEndpointAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void checkPermission(SecurityUser user, Resource resource, Operation operation) throws ThingsboardException {
PermissionChecker permissionChecker = getPermissionChecker(user.getAuthority(), resource);
if (!permissionChecker.hasPermission(user, operation)) {
permissionDenied();
}
}
@Override
@SuppressWarnings("unchecked")
public boolean hasPermission(SecurityUser user, Resource resource, Operation operation) throws ThingsboardException {
var permissionChecker = getPermissionChecker(user.getAuthority(), resource);
return permissionChecker.hasPermission(user, operation);
}
@Override
@SuppressWarnings("unchecked")
public <I extends EntityId, T extends HasTenantId> void checkPermission(SecurityUser user, Resource resource,
Operation operation, I entityId, T entity) throws ThingsboardException {
PermissionChecker permissionChecker = getPermissionChecker(user.getAuthority(), resource);
if (!permissionChecker.hasPermission(user, operation, entityId, entity)) {
permissionDenied();
}
}
@Override
@SuppressWarnings("unchecked")
public <I extends EntityId, T extends HasTenantId> boolean hasPermission(SecurityUser user, Resource resource, Operation operation, I entityId, T entity) throws ThingsboardException { | var permissionChecker = getPermissionChecker(user.getAuthority(), resource);
return permissionChecker.hasPermission(user, operation, entityId, entity);
}
private PermissionChecker getPermissionChecker(Authority authority, Resource resource) throws ThingsboardException {
Permissions permissions = authorityPermissions.get(authority);
if (permissions == null) {
permissionDenied();
}
Optional<PermissionChecker> permissionChecker = permissions.getPermissionChecker(resource);
if (permissionChecker.isEmpty()) {
permissionDenied();
}
return permissionChecker.get();
}
private void permissionDenied() throws ThingsboardException {
throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION,
ThingsboardErrorCode.PERMISSION_DENIED);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\permission\DefaultAccessControlService.java | 2 |
请完成以下Java代码 | public VerfuegbarkeitDefektgrund getGrund() {
return grund;
}
/**
* Sets the value of the grund property.
*
* @param value
* allowed object is
* {@link VerfuegbarkeitDefektgrund }
*
*/
public void setGrund(VerfuegbarkeitDefektgrund value) {
this.grund = value;
}
/**
* Gets the value of the lieferPzn property. | *
*/
public long getLieferPzn() {
return lieferPzn;
}
/**
* Sets the value of the lieferPzn property.
*
*/
public void setLieferPzn(long value) {
this.lieferPzn = 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\VerfuegbarkeitSubstitution.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getInjectionType() {
return injectionType;
}
public void setInjectionType(String injectionType) {
this.injectionType = injectionType;
}
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 String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
} | public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public boolean isJoinParallelActivitiesOnComplete() {
return joinParallelActivitiesOnComplete;
}
public void setJoinParallelActivitiesOnComplete(boolean joinParallelActivitiesOnComplete) {
this.joinParallelActivitiesOnComplete = joinParallelActivitiesOnComplete;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\InjectActivityRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List listByRoleIds(String roleIdsStr) {
List<String> roldIds = Arrays.asList(roleIdsStr.split(","));
return super.getSessionTemplate().selectList(getStatement("listByRoleIds"), roldIds);
}
/**
* 根据父菜单ID获取该菜单下的所有子孙菜单.<br/>
*
* @param parentId
* (如果为空,则为获取所有的菜单).<br/>
* @return menuList.
*/
@SuppressWarnings("rawtypes")
@Override
public List listByParent(Long parentId) {
return super.getSessionTemplate().selectList(getStatement("listByParent"), parentId);
}
/**
* 根据菜单ID查找菜单(可用于判断菜单下是否还有子菜单).
*
* @param parentId | * .
* @return menuList.
*/
@Override
public List<PmsMenu> listByParentId(Long parentId) {
return super.getSessionTemplate().selectList(getStatement("listByParentId"), parentId);
}
/***
* 根据名称和是否叶子节点查询数据
*
* @param isLeaf
* 是否是叶子节点
* @param name
* 节点名称
* @return
*/
public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) {
return super.getSessionTemplate().selectList(getStatement("listBy"), map);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsMenuDaoImpl.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Transient
public String getPasswordConfirm() {
return passwordConfirm;
} | public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
} | repos\Spring-Boot-Advanced-Projects-main\login-registration-springboot-hibernate-jsp-auth\src\main\java\net\alanbinu\springboot\loginregistrationspringbootauthjsp\model\User.java | 1 |
请完成以下Java代码 | private final MoveTo getMoveTo(TransferSupport info)
{
MoveTo move = new MoveTo();
if (info.isDrop())
{
JTree.DropLocation dl = (JTree.DropLocation)info.getDropLocation();
TreePath path = dl.getPath();
if (path == null)
return null;
move.to = (MTreeNode)path.getLastPathComponent();
if (move.to == null)
{
return null;
}
move.indexTo = dl.getChildIndex();
if (move.indexTo == -1)
move.indexTo = 0; // insert as first child
}
else
{ // it's a paste
JTree tree = (JTree)info.getComponent();
TreePath path = tree.getSelectionPath();
if (path == null)
return null;
MTreeNode selected = (MTreeNode)path.getLastPathComponent();
if (selected.isLeaf())
{
move.to = (MTreeNode)selected.getParent();
move.indexTo = move.to.getIndex(selected) + 1; // insert after selected | }
else
{
move.to = selected;
move.indexTo = 0;
}
}
return move;
}
private boolean equals(MTreeNode node1, MTreeNode node2)
{
if(node1 == null || node2 == null)
return false;
if(node1 == node2)
return true;
return node1.getAD_Tree_ID() == node2.getAD_Tree_ID()
&& node1.getAD_Table_ID() == node2.getAD_Table_ID()
&& node1.getNode_ID() == node2.getNode_ID();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreeTransferHandler.java | 1 |
请完成以下Java代码 | public void setM_ShipperTransportation_ID (int M_ShipperTransportation_ID)
{
if (M_ShipperTransportation_ID < 1)
set_Value (COLUMNNAME_M_ShipperTransportation_ID, null);
else
set_Value (COLUMNNAME_M_ShipperTransportation_ID, Integer.valueOf(M_ShipperTransportation_ID));
}
/** Get Transport Auftrag.
@return Transport Auftrag */
@Override
public int getM_ShipperTransportation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipperTransportation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override | public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_DeliveryOrder.java | 1 |
请完成以下Java代码 | public boolean containsLabel(E label)
{
return labelMap.containsKey(label);
}
public int getFrequency(E label)
{
Integer frequency = labelMap.get(label);
if (frequency == null) return 0;
return frequency;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
ArrayList<Map.Entry<E, Integer>> entries = new ArrayList<Map.Entry<E, Integer>>(labelMap.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<E, Integer>>()
{
@Override
public int compare(Map.Entry<E, Integer> o1, Map.Entry<E, Integer> o2)
{
return -o1.getValue().compareTo(o2.getValue());
}
});
for (Map.Entry<E, Integer> entry : entries)
{
sb.append(entry.getKey());
sb.append(' ');
sb.append(entry.getValue());
sb.append(' ');
}
return sb.toString();
}
public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param)
{ | if (param == null) return null;
String[] array = param.split(" ");
return create(array);
}
@SuppressWarnings("unchecked")
public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param[])
{
if (param.length % 2 == 0) return null;
int natureCount = (param.length - 1) / 2;
Map.Entry<String, Integer>[] entries = (Map.Entry<String, Integer>[]) Array.newInstance(Map.Entry.class, natureCount);
for (int i = 0; i < natureCount; ++i)
{
entries[i] = new AbstractMap.SimpleEntry<String, Integer>(param[1 + 2 * i], Integer.parseInt(param[2 + 2 * i]));
}
return new AbstractMap.SimpleEntry<String, Map.Entry<String, Integer>[]>(param[0], entries);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\EnumItem.java | 1 |
请完成以下Java代码 | public void checkReadRegisteredDeployments() {
getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM);
}
@Override
public void checkReadProcessApplicationForDeployment() {
getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM);
}
@Override
public void checkRegisterDeployment() {
getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM);
}
@Override
public void checkUnregisterDeployment() {
getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM);
}
@Override
public void checkDeleteMetrics() {
getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM);
}
@Override
public void checkDeleteTaskMetrics() {
getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM);
}
@Override
public void checkReadSchemaLog() { | getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM);
}
// helper ////////////////////////////////////////
protected AuthorizationManager getAuthorizationManager() {
return Context.getCommandContext().getAuthorizationManager();
}
protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId);
}
protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) {
return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId);
}
protected ExecutionEntity findExecutionById(String processInstanceId) {
return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\auth\AuthorizationCommandChecker.java | 1 |
请完成以下Java代码 | public class UserUpdateGenderDTO {
/**
* 用户编号
*/
@NotNull(message = "用户编号不能为空")
private Integer id;
/**
* 性别
*/
@NotNull(message = "性别不能为空")
@InEnum(value = GenderEnum.class, message = "性别必须是 {value}")
private Integer gender;
public Integer getId() {
return id;
}
public UserUpdateGenderDTO setId(Integer id) {
this.id = id;
return this;
}
public Integer getGender() {
return gender; | }
public UserUpdateGenderDTO setGender(Integer gender) {
this.gender = gender;
return this;
}
@Override
public String toString() {
return "UserUpdateGenderDTO{" +
"id=" + id +
", gender=" + gender +
'}';
}
} | repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\dto\UserUpdateGenderDTO.java | 1 |
请完成以下Java代码 | public String getIncidentMessageLike() {
return incidentMessageLike;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isRootProcessInstances() {
return isRootProcessInstances;
}
public boolean isProcessDefinitionWithoutTenantId() {
return isProcessDefinitionWithoutTenantId;
}
public boolean isLeafProcessInstances() {
return isLeafProcessInstances;
}
public String[] getTenantIds() {
return tenantIds;
} | @Override
public ProcessInstanceQuery or() {
if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public ProcessInstanceQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BOMLine
{
BOMComponentType componentType;
ProductId componentId;
AttributeSetInstanceId asiId;
@Getter(AccessLevel.PRIVATE)
Quantity qty;
Percent scrapPercent;
@Getter(AccessLevel.PACKAGE)
BOMCostPrice costPrice;
Percent coProductCostDistributionPercent;
@Builder
private BOMLine(
@NonNull final BOMComponentType componentType,
@NonNull final ProductId componentId,
@Nullable final AttributeSetInstanceId asiId,
@NonNull final Quantity qty,
@Nullable final Percent scrapPercent,
@NonNull final BOMCostPrice costPrice,
@Nullable final Percent coProductCostDistributionPercent)
{
if (!UomId.equals(qty.getUomId(), costPrice.getUomId()))
{
throw new AdempiereException("UOM not matching: " + qty + ", " + costPrice);
}
this.componentType = componentType;
this.componentId = componentId;
this.asiId = asiId != null ? asiId : AttributeSetInstanceId.NONE;
this.qty = qty;
this.scrapPercent = scrapPercent != null ? scrapPercent : Percent.ZERO;
this.costPrice = costPrice;
if (componentType.isCoProduct())
{
this.coProductCostDistributionPercent = coProductCostDistributionPercent;
if (coProductCostDistributionPercent == null || coProductCostDistributionPercent.signum() <= 0)
{
//TODO : FIXME see https://github.com/metasfresh/metasfresh/issues/4947
// throw new AdempiereException("coProductCostDistributionPercent shall be positive for " + this);
}
}
else
{
this.coProductCostDistributionPercent = null;
}
}
public boolean isInboundBOMCosts()
{
return !isCoProduct() // Skip co-product
&& !isVariant(); // Skip variants (06005)
}
public boolean isCoProduct()
{
return getComponentType().isCoProduct();
}
public boolean isByProduct()
{
return getComponentType().isByProduct();
}
public boolean isVariant()
{
return getComponentType().isVariant();
}
public Quantity getQtyIncludingScrap()
{
return getQty().add(getScrapPercent());
} | @Nullable
public CostAmount getCostAmountOrNull(final CostElementId costElementId)
{
final BOMCostElementPrice costPriceHolder = getCostPrice().getCostElementPriceOrNull(costElementId);
if (costPriceHolder == null)
{
return null;
}
final CostPrice costPrice;
if (isByProduct())
{
costPrice = costPriceHolder.getCostPrice().withZeroComponentsCostPrice();
}
else
{
costPrice = costPriceHolder.getCostPrice();
}
final Quantity qty = getQtyIncludingScrap();
return costPrice.multiply(qty);
}
void setComponentsCostPrice(
@NonNull final CostAmount elementCostPrice,
@NonNull final CostElementId costElementId)
{
getCostPrice().setComponentsCostPrice(elementCostPrice, costElementId);
}
void clearComponentsCostPrice(@NonNull final CostElementId costElementId)
{
getCostPrice().clearComponentsCostPrice(costElementId);
}
public ImmutableList<BOMCostElementPrice> getElementPrices()
{
return getCostPrice().getElementPrices();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOMLine.java | 2 |
请完成以下Java代码 | private void setServiceTypeFields(
@NonNull final RecordServiceType recordServiceType,
@NonNull final XmlRecordService recordService)
{
recordServiceType.setRecordId(recordService.getRecordId());
recordServiceType.setCode(recordService.getCode());
recordServiceType.setRefCode(recordService.getRefCode());
recordServiceType.setName(recordService.getName());
recordServiceType.setSession(recordService.getSession());
recordServiceType.setQuantity(recordService.getQuantity());
recordServiceType.setDateBegin(recordService.getDateBegin());
recordServiceType.setDateEnd(recordService.getDateEnd());
recordServiceType.setProviderId(recordService.getProviderId());
recordServiceType.setResponsibleId(recordService.getResponsibleId());
recordServiceType.setUnit(recordService.getUnit());
recordServiceType.setUnitFactor(recordService.getUnitFactor());
recordServiceType.setExternalFactor(recordService.getExternalFactor());
recordServiceType.setAmount(recordService.getAmount());
recordServiceType.setVatRate(recordService.getVatRate());
recordServiceType.setValidate(recordService.getValidate());
recordServiceType.setObligation(recordService.getObligation());
recordServiceType.setSectionCode(recordService.getSectionCode());
recordServiceType.setRemark(recordService.getRemark());
recordServiceType.setServiceAttributes(recordService.getServiceAttributes());
}
private DocumentsType createDocumentsType(@NonNull final List<XmlDocument> documents)
{
if (documents.isEmpty())
{
return null;
}
final DocumentsType documentsType = jaxbRequestObjectFactory.createDocumentsType();
documentsType.setNumber(BigInteger.valueOf(documents.size())); | for (final XmlDocument document : documents)
{
documentsType.getDocument().add(createDocumentType(document));
}
return documentsType;
}
private DocumentType createDocumentType(@NonNull final XmlDocument document)
{
final DocumentType documentType = jaxbRequestObjectFactory.createDocumentType();
documentType.setFilename(document.getFilename());
documentType.setMimeType(document.getMimeType());
documentType.setViewer(document.getViewer());
documentType.setBase64(document.getBase64());
documentType.setUrl(document.getUrl());
return documentType;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\Invoice440FromCrossVersionModelTool.java | 1 |
请完成以下Java代码 | private long getSequence(String invoker) {
AtomicLong r = this.sequences.get(invoker);
if (r == null) {
r = new AtomicLong(0);
AtomicLong previous = this.sequences.putIfAbsent(invoker, r);
if (previous != null) {
r = previous;
}
}
return r.incrementAndGet();
}
/**
* Getters & Setters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDaemon() { | return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler;
}
public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
this.uncaughtExceptionHandler = handler;
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NamingThreadFactory.java | 1 |
请完成以下Java代码 | private static class FTSFilterDescriptorsMap
{
private final ImmutableMap<String, FTSFilterDescriptor> descriptorsByTargetTableName;
private final ImmutableMap<FTSFilterDescriptorId, FTSFilterDescriptor> descriptorsById;
private FTSFilterDescriptorsMap(@NonNull final List<FTSFilterDescriptor> descriptors)
{
descriptorsByTargetTableName = Maps.uniqueIndex(descriptors, FTSFilterDescriptor::getTargetTableName);
descriptorsById = Maps.uniqueIndex(descriptors, FTSFilterDescriptor::getId);
}
public Optional<FTSFilterDescriptor> getByTargetTableName(@NonNull final String targetTableName)
{
return Optional.ofNullable(descriptorsByTargetTableName.get(targetTableName));
}
public FTSFilterDescriptor getById(final FTSFilterDescriptorId id)
{
final FTSFilterDescriptor filter = descriptorsById.get(id);
if (filter == null)
{
throw new AdempiereException("No filter found for " + id);
}
return filter;
}
}
@ToString
private static class AvailableSelectionKeyColumnNames
{
private final ArrayList<String> availableIntKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_IntKeys);
private final ArrayList<String> availableStringKeys = new ArrayList<>(I_T_ES_FTS_Search_Result.COLUMNNAME_StringKeys);
public String reserveNext(@NonNull final FTSJoinColumn.ValueType valueType)
{
final ArrayList<String> availableKeys; | if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
availableKeys = availableIntKeys;
}
else if (valueType == FTSJoinColumn.ValueType.STRING)
{
availableKeys = availableStringKeys;
}
else
{
availableKeys = new ArrayList<>();
}
if (availableKeys.isEmpty())
{
throw new AdempiereException("No more available key columns left for valueType=" + valueType + " in " + this);
}
return availableKeys.remove(0);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSFilterDescriptorRepository.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: sc-eureka-server
server:
port: 8761
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
register-with-eureka: false
fetch-registry: false
management:
endpoin | ts:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS | repos\SpringBootLearning-master (1)\springboot-admin\sc-eureka-server\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FTSDocumentFilterDescriptorsProviderFactory implements DocumentFilterDescriptorsProviderFactory
{
// services
private static final Logger logger = LogManager.getLogger(FTSDocumentFilterDescriptorsProviderFactory.class);
private final IMsgBL msgBL = Services.get(IMsgBL.class);
private final FTSConfigService ftsConfigService;
private final FTSSearchService ftsSearchService;
private static final AdMessageKey MSG_FULL_TEXT_SEARCH_CAPTION = AdMessageKey.of("Search");
static final String FILTER_ID = "full-text-search";
static final String PARAM_SearchText = "Search";
static final String PARAM_Context = "Context";
public FTSDocumentFilterDescriptorsProviderFactory(
@NonNull final FTSConfigService ftsConfigService,
@NonNull final FTSSearchService ftsSearchService)
{
this.ftsConfigService = ftsConfigService;
this.ftsSearchService = ftsSearchService;
}
@Nullable
@Override
public DocumentFilterDescriptorsProvider createFiltersProvider(@NonNull final CreateFiltersProviderContext context)
{
return StringUtils.trimBlankToOptional(context.getTableName())
.map(this::createFiltersProvider)
.orElse(null);
}
@Nullable
private DocumentFilterDescriptorsProvider createFiltersProvider(
@NonNull final String tableName)
{
final BooleanWithReason elasticsearchEnabled = ftsConfigService.getEnabled();
if (elasticsearchEnabled.isFalse())
{
logger.debug("Skip creating FTS filters because Elasticsearch is not enabled because: {}", elasticsearchEnabled.getReasonAsString());
return null;
}
final FTSFilterDescriptor ftsFilterDescriptor = ftsConfigService
.getFilterByTargetTableName(tableName)
.orElse(null);
if (ftsFilterDescriptor == null)
{ | return null;
}
final FTSFilterContext context = FTSFilterContext.builder()
.filterDescriptor(ftsFilterDescriptor)
.searchService(ftsSearchService)
.build();
final ITranslatableString caption = msgBL.getTranslatableMsgText(MSG_FULL_TEXT_SEARCH_CAPTION);
return ImmutableDocumentFilterDescriptorsProvider.of(
DocumentFilterDescriptor.builder()
.setFilterId(FILTER_ID)
.setSortNo(DocumentFilterDescriptorsConstants.SORT_NO_FULL_TEXT_SEARCH)
.setDisplayName(caption)
.setFrequentUsed(true)
.setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS)
.addParameter(DocumentFilterParamDescriptor.builder()
.fieldName(PARAM_SearchText)
.displayName(caption)
.widgetType(DocumentFieldWidgetType.Text))
.addInternalParameter(PARAM_Context, context)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\fullTextSearch\FTSDocumentFilterDescriptorsProviderFactory.java | 2 |
请完成以下Java代码 | public void C_InvoiceDoIt(final InvoiceId invoiceId, final EDIExportStatus targetExportStatus)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(invoiceId);
invoice.setEDI_ExportStatus(targetExportStatus.getCode());
invoiceDAO.save(invoice);
}
@NonNull
public LookupValuesList computeTargetExportStatusLookupValues(final EDIExportStatus fromExportStatus)
{
final List<EDIExportStatus> availableTargetStatuses = ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus);
return availableTargetStatuses.stream()
.map(s -> LookupValue.StringLookupValue.of(s.getCode(), adReferenceService.retrieveListNameTranslatableString(EDIExportStatus.AD_Reference_ID, s.getCode())))
.collect(LookupValuesList.collect());
}
@Nullable
public Object computeParameterDefaultValue(final EDIExportStatus fromExportStatus)
{
final List<EDIExportStatus> availableTargetStatuses = ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus);
if (!availableTargetStatuses.isEmpty()) | {
final String code = availableTargetStatuses.get(0).getCode();
return LookupValue.StringLookupValue.of(code, adReferenceService.retrieveListNameTranslatableString(EDIExportStatus.AD_Reference_ID, code));
}
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
public boolean checkIsNotInvoiceWithEDI(final I_C_Doc_Outbound_Log docOutboundLog)
{
final TableRecordReference recordReference = TableRecordReference.ofReferenced(docOutboundLog);
if (!I_C_Invoice.Table_Name.equals(recordReference.getTableName()))
{
return true;
}
if (Check.isBlank(docOutboundLog.getEDI_ExportStatus()))
{
return true;
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatusHelper.java | 1 |
请完成以下Java代码 | public void exportQuartzJobLog(HttpServletResponse response, JobQueryCriteria criteria) throws IOException {
quartzJobService.downloadLog(quartzJobService.queryAllLog(criteria), response);
}
@ApiOperation("查询任务执行日志")
@GetMapping(value = "/logs")
@PreAuthorize("@el.check('timing:list')")
public ResponseEntity<PageResult<QuartzLog>> queryQuartzJobLog(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
}
@Log("新增定时任务")
@ApiOperation("新增定时任务")
@PostMapping
@PreAuthorize("@el.check('timing:add')")
public ResponseEntity<Object> createQuartzJob(@Validated @RequestBody QuartzJob resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
// 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义
checkBean(resources.getBeanName());
quartzJobService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改定时任务")
@ApiOperation("修改定时任务")
@PutMapping
@PreAuthorize("@el.check('timing:edit')")
public ResponseEntity<Object> updateQuartzJob(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){
// 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义
checkBean(resources.getBeanName());
quartzJobService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("更改定时任务状态")
@ApiOperation("更改定时任务状态") | @PutMapping(value = "/{id}")
@PreAuthorize("@el.check('timing:edit')")
public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){
quartzJobService.updateIsPause(quartzJobService.findById(id));
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("执行定时任务")
@ApiOperation("执行定时任务")
@PutMapping(value = "/exec/{id}")
@PreAuthorize("@el.check('timing:edit')")
public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){
quartzJobService.execution(quartzJobService.findById(id));
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除定时任务")
@ApiOperation("删除定时任务")
@DeleteMapping
@PreAuthorize("@el.check('timing:del')")
public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){
quartzJobService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
private void checkBean(String beanName){
// 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类
// 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。
if(!SpringBeanHolder.getAllServiceBeanName().contains(beanName)){
throw new BadRequestException("非法的 Bean,请重新输入!");
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\rest\QuartzJobController.java | 1 |
请完成以下Java代码 | final class AvailableForSaleResultGroupBuilder
{
@NonNull
@Getter
private final ProductId productId;
@NonNull
@Getter
private final AttributesKey storageAttributesKey;
@NonNull
@Getter
private final WarehouseId warehouseId;
@NonNull
private BigDecimal qtyOnHandStock;
@NonNull
private BigDecimal qtyToBeShipped;
final HashSet<Util.ArrayKey> includedRequestKeys = new HashSet<>();
@Builder
private AvailableForSaleResultGroupBuilder(
@NonNull final ProductId productId,
@NonNull final AttributesKey storageAttributesKey,
@NonNull final WarehouseId warehouseId,
@Nullable final BigDecimal qtyOnHandStock,
@Nullable final BigDecimal qtyToBeShipped)
{
this.productId = productId;
this.storageAttributesKey = storageAttributesKey;
this.warehouseId = warehouseId; | this.qtyOnHandStock = CoalesceUtil.coalesce(qtyOnHandStock, ZERO);
this.qtyToBeShipped = CoalesceUtil.coalesce(qtyToBeShipped, ZERO);
}
public AvailableForSalesLookupBucketResult build()
{
return AvailableForSalesLookupBucketResult.builder()
.productId(productId)
.storageAttributesKey(storageAttributesKey)
.quantities(AvailableForSalesLookupBucketResult.Quantities.builder()
.qtyOnHandStock(qtyOnHandStock)
.qtyToBeShipped(qtyToBeShipped)
.build())
.warehouseId(warehouseId)
.build();
}
public void addQty(@NonNull final AddToResultGroupRequest request)
{
qtyOnHandStock = qtyOnHandStock.add(CoalesceUtil.coalesce(request.getQtyOnHandStock(), ZERO));
qtyToBeShipped = qtyToBeShipped.add(CoalesceUtil.coalesce(request.getQtyToBeShipped(), ZERO));
includedRequestKeys.add(request.computeKey());
}
boolean isAlreadyIncluded(@NonNull final AddToResultGroupRequest request)
{
final Util.ArrayKey key = request.computeKey();
return includedRequestKeys.contains(key);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSaleResultGroupBuilder.java | 1 |
请完成以下Java代码 | public CalloutStatisticsEntry setStatusFailed(final Throwable exception)
{
duration = duration == null ? null : duration.stop();
this.exception = exception;
status = Status.Failed;
_nodeSummary = null; // reset
return this;
}
public CalloutStatisticsEntry getCreateChild(final ICalloutField field, final ICalloutInstance callout)
{
final ArrayKey key = Util.mkKey(field.getColumnName(), callout);
return children.computeIfAbsent(key, (theKey) -> new CalloutStatisticsEntry(indexSupplier, field, callout));
}
public CalloutStatisticsEntry childSkipped(final String columnName, final String reason)
{
logger.trace("Skip executing all callouts for {} because {}", columnName, reason);
countChildFieldsSkipped++;
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final String reason) | {
logger.trace("Skip executing all callouts for {} because {}", field, reason);
countChildFieldsSkipped++;
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary)
{
final String reasonDetails = null;
return childSkipped(field, callout, reasonSummary, reasonDetails);
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary, final String reasonDetails)
{
logger.trace("Skip executing callout {} for field {} because {} ({})", callout, field, reasonSummary, reasonDetails);
getCreateChild(field, callout).setStatusSkipped(reasonSummary, reasonDetails);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutExecutor.java | 1 |
请完成以下Java代码 | public int hashCode() {
return this.files.hashCode();
}
@Override
public String toString() {
if (this.files.size() == 1) {
return this.files.get(0).getPath();
}
return this.files.stream().map(File::toString).collect(Collectors.joining(", "));
}
/**
* Find the Docker Compose file by searching in the given working directory. Files are
* considered in the same order that {@code docker compose} uses, namely:
* <ul>
* <li>{@code compose.yaml}</li>
* <li>{@code compose.yml}</li>
* <li>{@code docker-compose.yaml}</li>
* <li>{@code docker-compose.yml}</li>
* </ul>
* @param workingDirectory the working directory to search or {@code null} to use the
* current directory
* @return the located file or {@code null} if no Docker Compose file can be found
*/
public static @Nullable DockerComposeFile find(@Nullable File workingDirectory) {
File base = (workingDirectory != null) ? workingDirectory : new File(".");
if (!base.exists()) {
return null;
}
Assert.state(base.isDirectory(), () -> "'%s' is not a directory".formatted(base));
Path basePath = base.toPath();
for (String candidate : SEARCH_ORDER) {
Path resolved = basePath.resolve(candidate);
if (Files.exists(resolved)) {
return of(resolved.toAbsolutePath().toFile());
}
}
return null;
}
/** | * Create a new {@link DockerComposeFile} for the given {@link File}.
* @param file the source file
* @return the Docker Compose file
*/
public static DockerComposeFile of(File file) {
Assert.notNull(file, "'file' must not be null");
Assert.isTrue(file.exists(), () -> "'file' [%s] must exist".formatted(file));
Assert.isTrue(file.isFile(), () -> "'file' [%s] must be a normal file".formatted(file));
return new DockerComposeFile(Collections.singletonList(file));
}
/**
* Creates a new {@link DockerComposeFile} for the given {@link File files}.
* @param files the source files
* @return the Docker Compose file
* @since 3.4.0
*/
public static DockerComposeFile of(Collection<? extends File> files) {
Assert.notNull(files, "'files' must not be null");
for (File file : files) {
Assert.notNull(file, "'files' must not contain null elements");
Assert.isTrue(file.exists(), () -> "'files' content [%s] must exist".formatted(file));
Assert.isTrue(file.isFile(), () -> "'files' content [%s] must be a normal file".formatted(file));
}
return new DockerComposeFile(List.copyOf(files));
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DockerComposeFile.java | 1 |
请完成以下Java代码 | private static String dominantGenre(Centroid centroid) {
return centroid
.getCoordinates()
.keySet()
.stream()
.limit(2)
.collect(Collectors.joining(", "));
}
private static Centroid sortedCentroid(Centroid key) {
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
.getCoordinates()
.entrySet());
entries.sort((e1, e2) -> e2
.getValue()
.compareTo(e1.getValue()));
Map<String, Double> sorted = new LinkedHashMap<>();
for (Map.Entry<String, Double> entry : entries) {
sorted.put(entry.getKey(), entry.getValue());
}
return new Centroid(sorted);
}
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
List<Record> records = new ArrayList<>();
for (String artist : artists) {
Map<String, Double> tags = lastFm
.topTagsFor(artist)
.execute()
.body()
.all();
// Only keep popular tags.
tags
.entrySet()
.removeIf(e -> !topTags.contains(e.getKey())); | records.add(new Record(artist, tags));
}
return records;
}
private static Set<String> getTop100Tags() throws IOException {
return lastFm
.topTags()
.execute()
.body()
.all();
}
private static List<String> getTop100Artists() throws IOException {
List<String> artists = new ArrayList<>();
for (int i = 1; i <= 2; i++) {
artists.addAll(lastFm
.topArtists(i)
.execute()
.body()
.all());
}
return artists;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\LastFm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookResource implements Service {
private BookManager bookManager = new BookManager();
@Override
public void update(Routing.Rules rules) {
rules
.get("/", this::books)
.get("/{id}", this::bookById);
}
private void bookById(ServerRequest serverRequest, ServerResponse serverResponse) {
//get the book with the given id
String id = serverRequest.path().param("id");
Book book = bookManager.get(id);
JsonObject jsonObject = from(book);
serverResponse.send(jsonObject);
}
private void books(ServerRequest serverRequest, ServerResponse serverResponse) {
//get all books
List<Book> books = bookManager.getAll();
JsonArray jsonArray = from(books);
serverResponse.send(jsonArray);
} | private JsonObject from(Book book) {
JsonObject jsonObject = Json.createObjectBuilder()
.add("id", book.getId())
.add("isbn", book.getIsbn())
.add("name", book.getName())
.add("author", book.getAuthor())
.add("pages", book.getPages())
.build();
return jsonObject;
}
private JsonArray from(List<Book> books) {
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
books.forEach(book -> jsonArrayBuilder.add(from(book)));
return jsonArrayBuilder.build();
}
} | repos\tutorials-master\microservices-modules\helidon\helidon-se\src\main\java\com\baeldung\helidon\se\routing\BookResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String hello() {
return "hello";
}
@GetMapping("/index")
@ResponseBody
public String index() {
String wel = "hello ~ ";
// Subject subject = SecurityUtils.getSubject();
// System.out.println(subject.hasRole("admin"));
// String s = testService.vipPrint();
// wel = wel + s;
return wel;
}
@GetMapping("/login")
@ResponseBody
public String login() {
return "please login!"; | }
@GetMapping("/vip")
@ResponseBody
public String vip() {
return "hello vip";
}
@GetMapping("/common")
@ResponseBody
public String common() {
return "hello common";
}
} | repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\controller\LoginController.java | 2 |
请完成以下Java代码 | public static com.google.protobuf.Parser<AddressBook> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AddressBook> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.baeldung.protobuf.AddressBookProtos.AddressBook getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_protobuf_Person_descriptor;
private static final
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_protobuf_Person_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_protobuf_AddressBook_descriptor;
private static final
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_protobuf_AddressBook_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n$src/main/resources/addressbook.proto\022\010" +
"protobuf\"B\n\006Person\022\014\n\004name\030\001 \002(\t\022\n\n\002id\030\002" +
" \002(\005\022\r\n\005email\030\003 \001(\t\022\017\n\007numbers\030\004 \003(\t\"/\n\013" +
"AddressBook\022 \n\006people\030\001 \003(\0132\020.protobuf.P" +
"ersonB*\n\025com.baeldung.protobufB\021AddressB" +
"ookProtos" | };
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_protobuf_Person_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_protobuf_Person_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_Person_descriptor,
new java.lang.String[] { "Name", "Id", "Email", "Numbers", });
internal_static_protobuf_AddressBook_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_protobuf_AddressBook_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_AddressBook_descriptor,
new java.lang.String[] { "People", });
descriptor.resolveAllFeaturesImmutable();
}
// @@protoc_insertion_point(outer_class_scope)
} | repos\tutorials-master\google-protocol-buffer\src\main\java\com\baeldung\protobuf\AddressBookProtos.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LegacyEndpointConverter httptraceLegacyEndpointConverter() {
return LegacyEndpointConverters.httptrace();
}
@Bean
@ConditionalOnMissingBean(name = "threaddumpLegacyEndpointConverter")
public LegacyEndpointConverter threaddumpLegacyEndpointConverter() {
return LegacyEndpointConverters.threaddump();
}
@Bean
@ConditionalOnMissingBean(name = "liquibaseLegacyEndpointConverter")
public LegacyEndpointConverter liquibaseLegacyEndpointConverter() {
return LegacyEndpointConverters.liquibase();
}
@Bean
@ConditionalOnMissingBean(name = "flywayLegacyEndpointConverter")
public LegacyEndpointConverter flywayLegacyEndpointConverter() {
return LegacyEndpointConverters.flyway();
}
@Bean
@ConditionalOnMissingBean(name = "beansLegacyEndpointConverter")
public LegacyEndpointConverter beansLegacyEndpointConverter() {
return LegacyEndpointConverters.beans();
}
@Bean
@ConditionalOnMissingBean(name = "configpropsLegacyEndpointConverter")
public LegacyEndpointConverter configpropsLegacyEndpointConverter() {
return LegacyEndpointConverters.configprops();
}
@Bean
@ConditionalOnMissingBean(name = "mappingsLegacyEndpointConverter")
public LegacyEndpointConverter mappingsLegacyEndpointConverter() {
return LegacyEndpointConverters.mappings();
}
@Bean
@ConditionalOnMissingBean(name = "startupLegacyEndpointConverter")
public LegacyEndpointConverter startupLegacyEndpointConverter() {
return LegacyEndpointConverters.startup();
} | }
@Configuration(proxyBeanMethods = false)
protected static class CookieStoreConfiguration {
/**
* Creates a default {@link PerInstanceCookieStore} that should be used.
* @return the cookie store
*/
@Bean
@ConditionalOnMissingBean
public PerInstanceCookieStore cookieStore() {
return new JdkPerInstanceCookieStore(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
/**
* Creates a default trigger to cleanup the cookie store on deregistering of an
* {@link de.codecentric.boot.admin.server.domain.entities.Instance}.
* @param publisher publisher of {@link InstanceEvent}s events
* @param cookieStore the store to inform about deregistration of an
* {@link de.codecentric.boot.admin.server.domain.entities.Instance}
* @return a new trigger
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnMissingBean
public CookieStoreCleanupTrigger cookieStoreCleanupTrigger(final Publisher<InstanceEvent> publisher,
final PerInstanceCookieStore cookieStore) {
return new CookieStoreCleanupTrigger(publisher, cookieStore);
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerInstanceWebClientConfiguration.java | 2 |
请完成以下Java代码 | protected int getModelId(final I_M_HU_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_ID();
}
@Override
protected I_M_HU getModel(final I_M_HU_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU();
}
@Override
protected Map<Integer, I_M_HU_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU_Item huItem)
{
return query(I_M_HU_Snapshot.class)
.addEqualsFilter(I_M_HU_Snapshot.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID())
.addEqualsFilter(I_M_HU_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.map(I_M_HU_Snapshot.class, snapshot2ModelIdFunction);
}
@Override
protected Map<Integer, I_M_HU> retrieveModelsByParent(I_M_HU_Item huItem)
{
return query(I_M_HU.class)
.addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID())
.create()
.mapById(I_M_HU.class);
}
/**
* Recursively collect all M_HU_IDs and M_HU_Item_IDs starting from <code>startHUIds</code> to the bottom, including those too.
*
* @param startHUIds
* @param huIdsCollector
* @param huItemIdsCollector
*/
protected final void collectHUAndItemIds(final Set<Integer> startHUIds, final Set<Integer> huIdsCollector, final Set<Integer> huItemIdsCollector)
{
Set<Integer> huIdsToCheck = new HashSet<>(startHUIds);
while (!huIdsToCheck.isEmpty())
{
huIdsCollector.addAll(huIdsToCheck);
final Set<Integer> huItemIds = retrieveM_HU_Item_Ids(huIdsToCheck);
huItemIdsCollector.addAll(huItemIds); | final Set<Integer> includedHUIds = retrieveIncludedM_HUIds(huItemIds);
huIdsToCheck = new HashSet<>(includedHUIds);
huIdsToCheck.removeAll(huIdsCollector);
}
}
private final Set<Integer> retrieveM_HU_Item_Ids(final Set<Integer> huIds)
{
if (huIds.isEmpty())
{
return Collections.emptySet();
}
final List<Integer> huItemIdsList = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_Item.class, getContext())
.addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds)
.create()
.listIds();
return new HashSet<>(huItemIdsList);
}
private final Set<Integer> retrieveIncludedM_HUIds(final Set<Integer> huItemIds)
{
if (huItemIds.isEmpty())
{
return Collections.emptySet();
}
final List<Integer> huIdsList = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU.class, getContext())
.addInArrayOrAllFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItemIds)
.create()
.listIds();
return new HashSet<>(huIdsList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_SnapshotHandler.java | 1 |
请完成以下Java代码 | public @Nullable String getCause() {
return this.cause;
}
/**
* True if a returned message has been received.
* @return true if there is a return.
* @since 2.2.10
*/
public boolean isReturned() {
return this.returned;
}
/**
* Indicate that a returned message has been received.
* @param isReturned true if there is a return.
* @since 2.2.10
*/
public void setReturned(boolean isReturned) {
this.returned = isReturned;
}
/**
* Return true if a return has been passed to the listener or if no return has been
* received.
* @return false if an expected returned message has not been passed to the listener.
* @throws InterruptedException if interrupted.
* @since 2.2.10 | */
public boolean waitForReturnIfNeeded() throws InterruptedException {
return !this.returned || this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS);
}
/**
* Count down the returned message latch; call after the listener has been called.
* @since 2.2.10
*/
public void countDown() {
this.latch.countDown();
}
@Override
public String toString() {
return "PendingConfirm [correlationData=" + this.correlationData +
(this.cause == null ? "" : " cause=" + this.cause) + "]";
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\PendingConfirm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFundDirection() {
return fundDirection;
}
public void setFundDirection(String fundDirection) {
this.fundDirection = fundDirection;
}
public String getFundDirectionDesc() {
return AccountFundDirectionEnum.getEnum(this.getFundDirection()).getLabel();
}
public String getIsAllowSett() {
return isAllowSett;
}
public void setIsAllowSett(String isAllowSett) {
this.isAllowSett = isAllowSett == null ? null : isAllowSett.trim();
}
public String getIsCompleteSett() {
return isCompleteSett;
}
public void setIsCompleteSett(String isCompleteSett) {
this.isCompleteSett = isCompleteSett == null ? null : isCompleteSett.trim();
}
public String getRequestNo() {
return requestNo;
}
public void setRequestNo(String requestNo) {
this.requestNo = requestNo == null ? null : requestNo.trim();
}
public String getBankTrxNo() {
return bankTrxNo;
}
public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim();
}
public String getTrxType() {
return trxType;
}
public void setTrxType(String trxType) {
this.trxType = trxType == null ? null : trxType.trim(); | }
public String getTrxTypeDesc() {
return TrxTypeEnum.getEnum(this.getTrxType()).getDesc();
}
public Integer getRiskDay() {
return riskDay;
}
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getAmountDesc() {
if(this.getFundDirection().equals(AccountFundDirectionEnum.ADD.name())){
return "<span style=\"color: blue;\">+"+this.amount.doubleValue()+"</span>";
}else{
return "<span style=\"color: red;\">-"+this.amount.doubleValue()+"</span>";
}
}
public String getCreateTimeDesc() {
return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccountHistory.java | 2 |
请完成以下Java代码 | public class HistoricTaskInstanceQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, HistoricTaskInstanceQueryProperty> properties = new HashMap<>();
public static final HistoricTaskInstanceQueryProperty HISTORIC_TASK_INSTANCE_ID = new HistoricTaskInstanceQueryProperty("RES.ID_");
public static final HistoricTaskInstanceQueryProperty PROCESS_DEFINITION_ID = new HistoricTaskInstanceQueryProperty("RES.PROC_DEF_ID_");
public static final HistoricTaskInstanceQueryProperty PROCESS_INSTANCE_ID = new HistoricTaskInstanceQueryProperty("RES.PROC_INST_ID_");
public static final HistoricTaskInstanceQueryProperty EXECUTION_ID = new HistoricTaskInstanceQueryProperty("RES.EXECUTION_ID_");
public static final HistoricTaskInstanceQueryProperty TASK_NAME = new HistoricTaskInstanceQueryProperty("RES.NAME_");
public static final HistoricTaskInstanceQueryProperty TASK_DESCRIPTION = new HistoricTaskInstanceQueryProperty("RES.DESCRIPTION_");
public static final HistoricTaskInstanceQueryProperty TASK_ASSIGNEE = new HistoricTaskInstanceQueryProperty("RES.ASSIGNEE_");
public static final HistoricTaskInstanceQueryProperty TASK_OWNER = new HistoricTaskInstanceQueryProperty("RES.OWNER_");
public static final HistoricTaskInstanceQueryProperty TASK_DEFINITION_KEY = new HistoricTaskInstanceQueryProperty("RES.TASK_DEF_KEY_");
public static final HistoricTaskInstanceQueryProperty DELETE_REASON = new HistoricTaskInstanceQueryProperty("RES.DELETE_REASON_");
public static final HistoricTaskInstanceQueryProperty START = new HistoricTaskInstanceQueryProperty("RES.START_TIME_");
public static final HistoricTaskInstanceQueryProperty END = new HistoricTaskInstanceQueryProperty("RES.END_TIME_");
public static final HistoricTaskInstanceQueryProperty DURATION = new HistoricTaskInstanceQueryProperty("RES.DURATION_");
public static final HistoricTaskInstanceQueryProperty TASK_PRIORITY = new HistoricTaskInstanceQueryProperty("RES.PRIORITY_");
public static final HistoricTaskInstanceQueryProperty TASK_DUE_DATE = new HistoricTaskInstanceQueryProperty("RES.DUE_DATE_");
public static final HistoricTaskInstanceQueryProperty TENANT_ID_ = new HistoricTaskInstanceQueryProperty("RES.TENANT_ID_");
public static final HistoricTaskInstanceQueryProperty INCLUDED_VARIABLE_TIME = new HistoricTaskInstanceQueryProperty("VAR.LAST_UPDATED_TIME_"); | private String name;
public HistoricTaskInstanceQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
@Override
public String getName() {
return name;
}
public static HistoricTaskInstanceQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricTaskInstanceQueryProperty.java | 1 |
请完成以下Java代码 | public String getSourceTable()
{
return org.compiere.model.I_M_InOut.Table_Name;
}
@Override
public boolean isUserInChargeUserEditable()
{
return false;
}
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic) | {
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOut_Handler.java | 1 |
请完成以下Java代码 | public final boolean requestFocusInWindow()
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
if (findPanelCollapsible.isCollapsed())
{
return false;
}
return findPanel.requestFocusInWindow();
}
/**
* @return true if it's expanded and the underlying {@link FindPanel} allows focus.
*/
@Override
public boolean isFocusable()
{
if (!isExpanded())
{
return false;
}
return findPanel.isFocusable();
}
/**
* Adds a runnable to be executed when the this panel is collapsed or expanded.
*
* @param runnable
*/
@Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
findPanelCollapsible.addPropertyChangeListener("collapsed", new PropertyChangeListener()
{ | @Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
private static final class CollapsiblePanel extends JXTaskPane implements IUISubClassIDAware
{
private static final long serialVersionUID = 1L;
public CollapsiblePanel()
{
super();
}
@Override
public String getUISubClassID()
{
return AdempiereTaskPaneUI.UISUBCLASSID_VPanel_FindPanel;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_Collapsible.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public Integer getNumberOfStages() {
return numberOfStages;
}
public void setNumberOfStages(Integer numberOfStages) {
this.numberOfStages = numberOfStages;
}
@Override
public String toString() {
return "ScanPayRequestBo{" + | "payKey='" + payKey + '\'' +
", productName='" + productName + '\'' +
", orderNo='" + orderNo + '\'' +
", orderPrice=" + orderPrice +
", orderIp='" + orderIp + '\'' +
", orderDate='" + orderDate + '\'' +
", orderTime='" + orderTime + '\'' +
", orderPeriod=" + orderPeriod +
", returnUrl='" + returnUrl + '\'' +
", notifyUrl='" + notifyUrl + '\'' +
", sign='" + sign + '\'' +
", remark='" + remark + '\'' +
", payType='" + payType + '\'' +
", numberOfStages=" + numberOfStages +
'}';
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ScanPayRequestBo.java | 2 |
请完成以下Java代码 | private CommissionPoints extractInvoicedCommissionPoints(
@NonNull final I_C_Invoice invoiceRecord,
@NonNull final I_C_InvoiceLine invoiceLineRecord)
{
final Money invoicedLineAmount = Money.of(invoiceLineRecord.getLineNetAmt(), CurrencyId.ofRepoId(invoiceRecord.getC_Currency_ID()));
final CommissionPoints forecastCommissionPoints = CommissionPoints.of(invoicedLineAmount.toBigDecimal());
return deductTaxAmount(forecastCommissionPoints, invoiceLineRecord, invoiceRecord.isTaxIncluded());
}
@NonNull
private CommissionPoints deductTaxAmount(
@NonNull final CommissionPoints commissionPoints,
@NonNull final I_C_InvoiceLine invoiceLineRecord,
final boolean isTaxIncluded)
{
if (commissionPoints.isZero())
{
return commissionPoints;
}
BigDecimal taxAdjustedAmount = invoiceLineRecord.getLineNetAmt();
if (isTaxIncluded)
{
taxAdjustedAmount = taxAdjustedAmount.subtract(invoiceLineRecord.getTaxAmtInfo());
} | return CommissionPoints.of(taxAdjustedAmount);
}
@NonNull
private Optional<BPartnerId> getSalesRepId(@NonNull final I_C_Invoice invoiceRecord)
{
final BPartnerId invoiceSalesRepId = BPartnerId.ofRepoIdOrNull(invoiceRecord.getC_BPartner_SalesRep_ID());
if (invoiceSalesRepId != null)
{
return Optional.of(invoiceSalesRepId);
}
final I_C_BPartner customerBPartner = bPartnerDAO.getById(invoiceRecord.getC_BPartner_ID());
if (customerBPartner.isSalesRep())
{
return Optional.of(BPartnerId.ofRepoId(customerBPartner.getC_BPartner_ID()));
}
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\commissiontrigger\salesinvoiceline\SalesInvoiceFactory.java | 1 |
请完成以下Java代码 | public void setSuggestedPackingMaterial(final I_M_HU_PackingMaterial suggestedPackingMaterial)
{
this.suggestedPackingMaterial = suggestedPackingMaterial;
}
public void setSuggestedItemProduct(final I_M_HU_PI_Item_Product suggestedItemProduct)
{
this.suggestedItemProduct = suggestedItemProduct;
}
public I_M_HU_PackingMaterial getSuggestedPackingMaterial()
{
return suggestedPackingMaterial;
}
public I_M_HU_PI_Item_Product getSuggestedItemProduct()
{
return suggestedItemProduct;
}
public I_M_HU_PI getSuggestedPI() | {
return suggestedPI;
}
public void setSuggestedPI(final I_M_HU_PI suggestedPI)
{
this.suggestedPI = suggestedPI;
}
@Override
public int getC_BPartner_Location_ID()
{
return -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\PlainHUDocumentLine.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getDate1 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Date1);
}
/** Set Enddatum.
@param EndDate
Last effective date (inclusive)
*/
@Override
public void setEndDate (java.sql.Timestamp EndDate)
{
set_Value (COLUMNNAME_EndDate, EndDate);
}
/** Get Enddatum.
@return Last effective date (inclusive)
*/
@Override
public java.sql.Timestamp getEndDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_EndDate);
}
/**
* Frequency AD_Reference_ID=540870
* Reference name: C_NonBusinessDay_Frequency
*/
public static final int FREQUENCY_AD_Reference_ID=540870;
/** Weekly = W */
public static final String FREQUENCY_Weekly = "W";
/** Yearly = Y */
public static final String FREQUENCY_Yearly = "Y";
/** Set Häufigkeit.
@param Frequency
Häufigkeit von Ereignissen
*/
@Override
public void setFrequency (java.lang.String Frequency)
{
set_Value (COLUMNNAME_Frequency, Frequency);
}
/** Get Häufigkeit.
@return Häufigkeit von Ereignissen
*/
@Override
public java.lang.String getFrequency ()
{
return (java.lang.String)get_Value(COLUMNNAME_Frequency);
}
/** Set Repeat.
@param IsRepeat Repeat */
@Override
public void setIsRepeat (boolean IsRepeat)
{
set_Value (COLUMNNAME_IsRepeat, Boolean.valueOf(IsRepeat));
} | /** Get Repeat.
@return Repeat */
@Override
public boolean isRepeat ()
{
Object oo = get_Value(COLUMNNAME_IsRepeat);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_NonBusinessDay.java | 1 |
请完成以下Java代码 | private static IStringExpression buildSqlSelect(
@NonNull final List<SQLDatasourceFieldDescriptor> fields,
@NonNull final String sourceTableName,
@Nullable final String sqlFrom,
@Nullable final String sqlWhereClause,
@Nullable final String sqlGroupAndOrderBy)
{
Check.assumeNotEmpty(fields, "fields shall not be empty");
final StringBuilder sqlFields = new StringBuilder();
for (final SQLDatasourceFieldDescriptor field : fields)
{
final String fieldName = field.getFieldName();
final String sqlField = field.getSqlSelect();
if (sqlFields.length() > 0)
{
sqlFields.append("\n, ");
}
sqlFields.append("(").append(sqlField).append(") AS ").append(fieldName);
}
final StringBuilder sql = new StringBuilder();
sql.append("SELECT \n").append(sqlFields);
//
// FROM ....
sql.append("\n");
if (sqlFrom != null && !Check.isBlank(sqlFrom))
{
if (!sqlFrom.trim().toUpperCase().startsWith("FROM"))
{
sql.append("FROM ");
}
sql.append(sqlFrom.trim());
}
else
{
sql.append("FROM ").append(sourceTableName);
}
//
// WHERE
if (sqlWhereClause != null && !Check.isBlank(sqlWhereClause))
{
sql.append("\n");
if (!sqlWhereClause.trim().toUpperCase().startsWith("WHERE"))
{
sql.append("WHERE ");
}
sql.append(sqlWhereClause.trim());
}
//
// GROUP BY / ORDER BY
if (sqlGroupAndOrderBy != null && !Check.isBlank(sqlGroupAndOrderBy))
{
sql.append("\n").append(sqlGroupAndOrderBy.trim());
}
return StringExpressionCompiler.instance.compile(sql.toString());
} | private static IStringExpression buildSqlDetailsWhereClause(
@Nullable final String sqlDetailsWhereClause,
@Nullable final String sqlWhereClause)
{
String sqlDetailsWhereClauseNorm = CoalesceUtil.firstNotEmptyTrimmed(
sqlDetailsWhereClause,
sqlWhereClause);
if (sqlDetailsWhereClauseNorm == null || Check.isBlank(sqlDetailsWhereClauseNorm))
{
return IStringExpression.NULL;
}
if (sqlDetailsWhereClauseNorm.toUpperCase().startsWith("WHERE"))
{
sqlDetailsWhereClauseNorm = sqlDetailsWhereClauseNorm.substring("WHERE".length()).trim();
}
return StringExpressionCompiler.instance.compile(sqlDetailsWhereClauseNorm);
}
public Set<CtxName> getRequiredContextParameters()
{
return ImmutableSet.<CtxName>builder()
.addAll(sqlSelect.getParameters())
.addAll(sqlDetailsWhereClause.getParameters())
.addAll(isApplySecuritySettings() ? PERMISSION_REQUIRED_PARAMS : ImmutableSet.of())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\sql\SQLDatasourceDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static PrepareMsg getCommitPrepareMsg(User user, VersionCreateRequest request) {
return PrepareMsg.newBuilder().setCommitMsg(request.getVersionName())
.setBranchName(request.getBranch()).setAuthorName(getAuthorName(user)).setAuthorEmail(user.getEmail()).build();
}
private static String getAuthorName(User user) {
List<String> parts = new ArrayList<>();
if (StringUtils.isNotBlank(user.getFirstName())) {
parts.add(user.getFirstName());
}
if (StringUtils.isNotBlank(user.getLastName())) {
parts.add(user.getLastName());
}
if (parts.isEmpty()) {
parts.add(user.getName());
}
return String.join(" ", parts);
}
private ToVersionControlServiceMsg.Builder newRequestProto(PendingGitRequest<?> request, RepositorySettings settings) {
var tenantId = request.getTenantId();
var requestId = request.getRequestId();
var builder = ToVersionControlServiceMsg.newBuilder()
.setNodeId(serviceInfoProvider.getServiceId())
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequestIdMSB(requestId.getMostSignificantBits())
.setRequestIdLSB(requestId.getLeastSignificantBits());
RepositorySettings vcSettings = settings;
if (vcSettings == null && request.requiresSettings()) { | vcSettings = entitiesVersionControlService.getVersionControlSettings(tenantId);
}
if (vcSettings != null) {
builder.setVcSettings(ProtoUtils.toProto(vcSettings));
} else if (request.requiresSettings()) {
throw new RuntimeException("No entity version control settings provisioned!");
}
return builder;
}
private CommitRequestMsg.Builder buildCommitRequest(CommitGitRequest commit) {
return CommitRequestMsg.newBuilder().setTxId(commit.getTxId().toString());
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitVersionControlQueueService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HttpCodecsProperties {
/**
* Whether to log form data at DEBUG level, and headers at TRACE level.
*/
private boolean logRequestDetails;
/**
* Limit on the number of bytes that can be buffered whenever the input stream needs
* to be aggregated. This applies only to the auto-configured WebFlux server and
* WebClient instances. By default this is not set, in which case individual codec
* defaults apply. Most codecs are limited to 256K by default.
*/
private @Nullable DataSize maxInMemorySize;
public boolean isLogRequestDetails() { | return this.logRequestDetails;
}
public void setLogRequestDetails(boolean logRequestDetails) {
this.logRequestDetails = logRequestDetails;
}
public @Nullable DataSize getMaxInMemorySize() {
return this.maxInMemorySize;
}
public void setMaxInMemorySize(@Nullable DataSize maxInMemorySize) {
this.maxInMemorySize = maxInMemorySize;
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-codec\src\main\java\org\springframework\boot\http\codec\autoconfigure\HttpCodecsProperties.java | 2 |
请完成以下Java代码 | public DataType getDataType() {
return DataType.LONG;
}
@Override
public Optional<Long> getLongValue() {
return Optional.ofNullable(value);
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LongDataEntry)) return false;
if (!super.equals(o)) return false;
LongDataEntry that = (LongDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() { | return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "LongDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return Long.toString(value);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\LongDataEntry.java | 1 |
请完成以下Java代码 | public static TaxCategoryId ofRepoId(final int repoId)
{
if (repoId == NOT_FOUND.getRepoId())
{
return NOT_FOUND;
}
else
{
return new TaxCategoryId(repoId);
}
}
public static TaxCategoryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static TaxCategoryId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<TaxCategoryId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId)); | }
public static int toRepoId(final TaxCategoryId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(final TaxCategoryId o1, final TaxCategoryId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private TaxCategoryId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_TaxCategory_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\TaxCategoryId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void updateChildOrgCode(String newOrgCode, String oldOrgCode) {
//查询当前部门下的所有子级部门
LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
query.likeRight(SysDepart::getOrgCode, oldOrgCode);
query.orderByAsc(SysDepart::getDepartOrder);
query.orderByDesc(SysDepart::getCreateTime);
query.select(SysDepart::getId, SysDepart::getOrgCode);
List<SysDepart> childDeparts = departMapper.selectList(query);
if (CollectionUtil.isNotEmpty(childDeparts)) {
for (SysDepart depart : childDeparts) {
String orgCode = depart.getOrgCode();
if (orgCode.startsWith(oldOrgCode)) {
orgCode = newOrgCode + orgCode.substring(oldOrgCode.length());
}
depart.setOrgCode(orgCode);
}
}
this.updateBatchById(childDeparts);
}
/**
* 获取部门负责人
*
* @param departId | * @param page
* @return
*/
@Override
public IPage<SysUser> getDepartmentHead(String departId, Page<SysUser> page) {
List<SysUser> departmentHead = departMapper.getDepartmentHead(page, departId);
if(CollectionUtil.isNotEmpty(departmentHead)){
departmentHead.forEach(item->{
//兼职岗位
List<String> depPostList = sysUserDepPostMapper.getDepPostByUserId(item.getId());
if(CollectionUtil.isNotEmpty(depPostList)){
item.setOtherDepPostId(StringUtils.join(depPostList.toArray(), SymbolConstant.COMMA));
}
});
}
return page.setRecords(departmentHead);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartServiceImpl.java | 2 |
请完成以下Java代码 | public Percent getPercent()
{
assertValueType(IssuingToleranceValueType.PERCENTAGE);
return Check.assumeNotNull(percent, "percent not null");
}
@NonNull
public Quantity getQty()
{
assertValueType(IssuingToleranceValueType.QUANTITY);
return Check.assumeNotNull(qty, "qty not null");
}
public ITranslatableString toTranslatableString()
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return TranslatableStrings.builder().appendPercent(percent).build();
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build();
}
else
{
// shall not happen
return TranslatableStrings.empty();
}
}
public Quantity addTo(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.add(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.add(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public Quantity subtractFrom(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.subtract(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{ | final Quantity qty = getQty();
return qtyBase.subtract(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qtyConv = qtyConverter.apply(qty);
if (qtyConv.equals(qty))
{
return this;
}
return toBuilder().qty(qtyConv).build();
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java | 1 |
请完成以下Java代码 | public abstract class AbstractResourceReader implements ResourceReader {
/**
* @inheritDoc
*/
@Override
public @NonNull byte[] read(@NonNull Resource resource) {
return Optional.ofNullable(resource)
.filter(this::isAbleToHandle)
.map(this::preProcess)
.map(it -> {
try (InputStream in = it.getInputStream()) {
return doRead(in);
}
catch (IOException cause) {
throw new ResourceReadException(String.format("Failed to read from Resource [%s]",
it.getDescription()), cause);
}
})
.orElseThrow(() -> new UnhandledResourceException(String.format("Unable to handle Resource [%s]",
ResourceUtils.nullSafeGetDescription(resource))));
}
/**
* Determines whether this reader is able to handle and read from the target {@link Resource}.
*
* The default implementation determines that the {@link Resource} can be handled if the {@link Resource} handle
* is not {@literal null}.
*
* @param resource {@link Resource} to evaluate.
* @return a boolean value indicating whether this reader is able to handle and read from
* the target {@link Resource}.
* @see org.springframework.core.io.Resource | */
@SuppressWarnings("unused")
protected boolean isAbleToHandle(@Nullable Resource resource) {
return resource != null;
}
/**
* Reads data from the target {@link Resource} (intentionally) by using the {@link InputStream} returned by
* {@link Resource#getInputStream()}.
*
* However, other algorithm/strategy implementations are free to read from the {@link Resource} as is appropriate
* for the given context (e.g. cloud environment). In those cases, implementors should override
* the {@link #read(Resource)} method.
*
* @param resourceInputStream {@link InputStream} used to read data from the target {@link Resource}.
* @return a {@literal non-null} byte array containing the data from the target {@link Resource}.
* @throws IOException if an I/O error occurs while reading from the {@link Resource}.
* @see java.io.InputStream
* @see #read(Resource)
*/
protected abstract @NonNull byte[] doRead(@NonNull InputStream resourceInputStream) throws IOException;
/**
* Pre-processes the target {@link Resource} before reading from the {@link Resource}.
*
* @param resource {@link Resource} to pre-process; never {@literal null}.
* @return the given, target {@link Resource}.
* @see org.springframework.core.io.Resource
*/
protected @NonNull Resource preProcess(@NonNull Resource resource) {
return resource;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\AbstractResourceReader.java | 1 |
请完成以下Java代码 | protected String encodeNonNullPassword(String rawPassword) {
return digest(rawPassword, this.saltGenerator.generateKey());
}
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
return decodeAndCheckMatches(rawPassword, encodedPassword);
}
@Override
protected boolean upgradeEncodingNonNull(String encodedPassword) {
String[] parts = encodedPassword.split("\\$");
if (parts.length != 4) {
throw new IllegalArgumentException("Encoded password does not look like SCrypt: " + encodedPassword);
}
long params = Long.parseLong(parts[1], 16);
int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff);
int memoryCost = (int) params >> 8 & 0xff;
int parallelization = (int) params & 0xff;
return cpuCost < this.cpuCost || memoryCost < this.memoryCost || parallelization < this.parallelization;
}
private boolean decodeAndCheckMatches(CharSequence rawPassword, String encodedPassword) {
String[] parts = encodedPassword.split("\\$");
if (parts.length != 4) {
return false;
}
long params = Long.parseLong(parts[1], 16);
byte[] salt = decodePart(parts[2]);
byte[] derived = decodePart(parts[3]);
int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff); | int memoryCost = (int) params >> 8 & 0xff;
int parallelization = (int) params & 0xff;
byte[] generated = SCrypt.generate(Utf8.encode(rawPassword), salt, cpuCost, memoryCost, parallelization,
this.keyLength);
return MessageDigest.isEqual(derived, generated);
}
private String digest(CharSequence rawPassword, byte[] salt) {
byte[] derived = SCrypt.generate(Utf8.encode(rawPassword), salt, this.cpuCost, this.memoryCost,
this.parallelization, this.keyLength);
String params = Long.toString(
((int) (Math.log(this.cpuCost) / Math.log(2)) << 16L) | this.memoryCost << 8 | this.parallelization,
16);
StringBuilder sb = new StringBuilder((salt.length + derived.length) * 2);
sb.append("$").append(params).append('$');
sb.append(encodePart(salt)).append('$');
sb.append(encodePart(derived));
return sb.toString();
}
private byte[] decodePart(String part) {
return Base64.getDecoder().decode(Utf8.encode(part));
}
private String encodePart(byte[] part) {
return Utf8.decode(Base64.getEncoder().encode(part));
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\scrypt\SCryptPasswordEncoder.java | 1 |
请完成以下Java代码 | public int getC_Queue_WorkPackage_Param_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Param_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Date.
@param P_Date
Prozess-Parameter
*/
@Override
public void setP_Date (java.sql.Timestamp P_Date)
{
set_Value (COLUMNNAME_P_Date, P_Date);
}
/** Get Process Date.
@return Prozess-Parameter
*/
@Override
public java.sql.Timestamp getP_Date ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_P_Date);
}
/** Set Process Number.
@param P_Number
Prozess-Parameter
*/
@Override
public void setP_Number (java.math.BigDecimal P_Number)
{
set_Value (COLUMNNAME_P_Number, P_Number);
}
/** Get Process Number.
@return Prozess-Parameter
*/
@Override
public java.math.BigDecimal getP_Number () | {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Process String.
@param P_String
Prozess-Parameter
*/
@Override
public void setP_String (java.lang.String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Prozess-Parameter
*/
@Override
public java.lang.String getP_String ()
{
return (java.lang.String)get_Value(COLUMNNAME_P_String);
}
/** Set Parameter Name.
@param ParameterName Parameter Name */
@Override
public void setParameterName (java.lang.String ParameterName)
{
set_ValueNoCheck (COLUMNNAME_ParameterName, ParameterName);
}
/** Get Parameter Name.
@return Parameter Name */
@Override
public java.lang.String getParameterName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ParameterName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Param.java | 1 |
请完成以下Spring Boot application配置 | ###########【Kafka集群】###########
spring.kafka.bootstrap-servers=9.134.41.114:9092
###########【初始化生产者配置】###########
# 重试次数
spring.kafka.producer.retries=0
# 应答级别:多少个分区副本备份完成时向生产者发送ack确认(可选0、1、all/-1)
spring.kafka.producer.acks=1
# 批量大小
spring.kafka.producer.batch-size=16384
# 提交延时
spring.kafka.producer.properties.linger.ms=0
# 当生产端积累的消息达到batch-size或接收到消息linger.ms后,生产者就会将消息提交给kafka
# linger.ms为0表示每接收到一条消息就提交给kafka,这时候batch-size其实就没用了
# 生产端缓冲区大小
spring.kafka.producer.buffer-memory = 33554432
# Kafka提供的序列化和反序列化类
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
# 自定义分区器
# spring.kafka.producer.properties.partitioner.class=com.felix.kafka.producer.CustomizePartitioner
###########【初始化消费者配置】###########
# 默认的消费组ID
spring.kafka.consumer.properties.group.id=defaultConsumerGroup
# 是否自动提交offset
spring.kafka.consumer.enable-auto-commit=true
# 提交offset延时(接收到消息后多久提交offset)
spring.kafka.consumer.auto.commit.interval.ms=1000
# 当kafka中没有初始offset或offset超出范围时将自动重置offset
# earliest:重置为分区中最小的offset;
# latest:重置为分区中最新的offset(消费分区中新产生的数据);
# none:只要有一个分区不存在已提交的offset,就抛出异常;
spring.kafka.consumer.auto-offset-reset=la | test
# 消费会话超时时间(超过这个时间consumer没有发送心跳,就会触发rebalance操作)
spring.kafka.consumer.properties.session.timeout.ms=120000
# 消费请求超时时间
spring.kafka.consumer.properties.request.timeout.ms=180000
# Kafka提供的序列化和反序列化类
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
# 消费端监听的topic不存在时,项目启动会报错(关掉)
spring.kafka.listener.missing-topics-fatal=false
# 设置批量消费
# spring.kafka.listener.type=batch
# 批量消费每次最多消费多少条消息 | repos\SpringBootLearning-master\version2.x\spring-kafka-demo\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private void updateLogLineDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus)
{
final ICompositeQueryUpdater<I_C_Doc_Outbound_Log_Line> queryUpdaterLogLine = queryBL.createCompositeQueryUpdater(I_C_Doc_Outbound_Log_Line.class)
.addSetColumnValue(I_C_Doc_Outbound_Log_Line.COLUMNNAME_DocStatus, DocStatus.toCodeOrNull(docStatus));
queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId())
.addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMN_Record_ID, tableRecordReference.getRecord_ID())
.create()
.update(queryUpdaterLogLine);
}
@Override
@NonNull
public ImmutableList<LogWithLines> retrieveLogsWithLines(@NonNull final ImmutableList<I_C_Doc_Outbound_Log> logs)
{
if (logs.isEmpty())
{
return ImmutableList.of();
}
final ImmutableSet<DocOutboundLogId> ids = logs.stream()
.map(log -> DocOutboundLogId.ofRepoId(log.getC_Doc_Outbound_Log_ID()))
.collect(ImmutableSet.toImmutableSet()); | final Map<Integer, List<I_C_Doc_Outbound_Log_Line>> linesByLogId = queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class)
.addInArrayFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_C_Doc_Outbound_Log_ID, ids)
.create()
.list()
.stream()
.collect(Collectors.groupingBy(I_C_Doc_Outbound_Log_Line::getC_Doc_Outbound_Log_ID));
return logs.stream()
.map(log -> LogWithLines.builder()
.log(log)
.lines(linesByLogId.getOrDefault(log.getC_Doc_Outbound_Log_ID(), Collections.emptyList()))
.build())
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getAuthoritiesClaimDelimiter() {
return this.authoritiesClaimDelimiter;
}
public void setAuthoritiesClaimDelimiter(@Nullable String authoritiesClaimDelimiter) {
this.authoritiesClaimDelimiter = authoritiesClaimDelimiter;
}
public @Nullable String getAuthoritiesClaimName() {
return this.authoritiesClaimName;
}
public void setAuthoritiesClaimName(@Nullable String authoritiesClaimName) {
this.authoritiesClaimName = authoritiesClaimName;
}
public @Nullable String getPrincipalClaimName() {
return this.principalClaimName;
}
public void setPrincipalClaimName(@Nullable String principalClaimName) {
this.principalClaimName = principalClaimName;
}
public String readPublicKey() throws IOException {
String key = "spring.security.oauth2.resourceserver.jwt.public-key-location";
if (this.publicKeyLocation == null) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"No public key location specified");
}
if (!this.publicKeyLocation.exists()) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"Public key location does not exist");
}
try (InputStream inputStream = this.publicKeyLocation.getInputStream()) {
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
}
public static class Opaquetoken {
/**
* Client id used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientId;
/**
* Client secret used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientSecret;
/**
* OAuth 2.0 endpoint through which token introspection is accomplished.
*/
private @Nullable String introspectionUri;
public @Nullable String getClientId() { | return this.clientId;
}
public void setClientId(@Nullable String clientId) {
this.clientId = clientId;
}
public @Nullable String getClientSecret() {
return this.clientSecret;
}
public void setClientSecret(@Nullable String clientSecret) {
this.clientSecret = clientSecret;
}
public @Nullable String getIntrospectionUri() {
return this.introspectionUri;
}
public void setIntrospectionUri(@Nullable String introspectionUri) {
this.introspectionUri = introspectionUri;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\OAuth2ResourceServerProperties.java | 2 |
请完成以下Java代码 | public static URL getResource(String name) {
return getResource(name, null);
}
public static URL getResource(String name, ClassLoader classLoader) {
if(classLoader == null) {
// Try the current Thread context class loader
classLoader = Thread.currentThread().getContextClassLoader();
}
URL url = classLoader.getResource(name);
if (url == null) {
// Finally, try the class loader for this class
classLoader = ReflectUtil.class.getClassLoader();
url = classLoader.getResource(name);
}
return url;
}
public static File getResourceAsFile(String path) {
URL resource = getResource(path);
try {
return new File(resource.toURI());
} catch (URISyntaxException e) {
throw new ModelException("Exception while loading resource file " + path, e);
}
}
/** | * Create a new instance of the provided type
*
* @param type the class to create a new instance of
* @param parameters the parameters to pass to the constructor
* @return the created instance
*/
public static <T> T createInstance(Class<T> type, Object... parameters) {
// get types for parameters
Class<?>[] parameterTypes = new Class<?>[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Object parameter = parameters[i];
parameterTypes[i] = parameter.getClass();
}
try {
// create instance
Constructor<T> constructor = type.getConstructor(parameterTypes);
return constructor.newInstance(parameters);
} catch (Exception e) {
throw new ModelException("Exception while creating an instance of type "+type, e);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\ReflectUtil.java | 1 |
请完成以下Java代码 | public String getBatchJobDefinitionId() {
return batchJobDefinitionId;
}
public void setBatchJobDefinitionId(String batchJobDefinitionId) {
this.batchJobDefinitionId = batchJobDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
} | @Override
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("endTime", endTime);
persistentState.put("executionStartTime", executionStartTime);
return persistentState;
}
public void delete() {
HistoricIncidentManager historicIncidentManager = Context.getCommandContext().getHistoricIncidentManager();
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(seedJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(monitorJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(batchJobDefinitionId);
HistoricJobLogManager historicJobLogManager = Context.getCommandContext().getHistoricJobLogManager();
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(seedJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(monitorJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(batchJobDefinitionId);
Context.getCommandContext().getHistoricBatchManager().delete(this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchEntity.java | 1 |
请完成以下Java代码 | public void setLineNetAmt(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setLineNetAmt(ic);
}
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setOrderedData(ic);
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setDeliveredData(ic);
}
@Override
public void invalidateCandidatesFor(final Object model)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model);
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
final List<IInvoiceCandidateHandler> handlersForTable = retrieveImplementationsForTable(ctx, tableName);
for (final IInvoiceCandidateHandler handler : handlersForTable)
{
final OnInvalidateForModelAction onInvalidateForModelAction = handler.getOnInvalidateForModelAction();
switch (onInvalidateForModelAction)
{
case RECREATE_ASYNC:
scheduleCreateMissingCandidatesFor(model, handler);
break;
case REVALIDATE:
handler.invalidateCandidatesFor(model);
break;
default:
// nothing
logger.warn("Got no OnInvalidateForModelAction for " + model + ". Doing nothing.");
break;
}
}
}
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
return handler.calculatePriceAndTax(ic);
}
@Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setBPartnerData(ic);
} | @Override
public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate icRecord)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(icRecord);
handler.setInvoiceScheduleAndDateToInvoice(icRecord);
}
@Override
public void setPickedData(final I_C_Invoice_Candidate ic)
{
final InvoiceCandidateRecordService invoiceCandidateRecordService = SpringContextHolder.instance.getBean(InvoiceCandidateRecordService.class);
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setShipmentSchedule(ic);
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(ic.getM_ShipmentSchedule_ID());
if (shipmentScheduleId == null)
{
return;
}
final StockQtyAndUOMQty qtysPicked = invoiceCandidateRecordService.ofRecord(ic).computeQtysPicked();
ic.setQtyPicked(qtysPicked.getStockQty().toBigDecimal());
ic.setQtyPickedInUOM(qtysPicked.getUOMQtyNotNull().toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerBL.java | 1 |
请完成以下Java代码 | public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Sales Volume in 1.000.
@param SalesVolume
Total Volume of Sales in Thousands of Currency
*/
public void setSalesVolume (int SalesVolume)
{
set_Value (COLUMNNAME_SalesVolume, Integer.valueOf(SalesVolume));
}
/** Get Sales Volume in 1.000.
@return Total Volume of Sales in Thousands of Currency
*/
public int getSalesVolume ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesVolume);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Start Implementation/Production.
@param StartProductionDate
The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public void setStartProductionDate (Timestamp StartProductionDate)
{
set_Value (COLUMNNAME_StartProductionDate, StartProductionDate);
}
/** Get Start Implementation/Production.
@return The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public Timestamp getStartProductionDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartProductionDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Registration.java | 1 |
请完成以下Java代码 | public void createUOMConversion(@NonNull final CreateUOMConversionRequest request)
{
final BigDecimal fromToMultiplier = request.getFromToMultiplier();
final BigDecimal toFromMultiplier = UOMConversionRate.computeInvertedMultiplier(fromToMultiplier);
final I_C_UOM_Conversion record = newInstance(I_C_UOM_Conversion.class);
record.setM_Product_ID(ProductId.toRepoId(request.getProductId()));
record.setC_UOM_ID(request.getFromUomId().getRepoId());
record.setC_UOM_To_ID(request.getToUomId().getRepoId());
record.setMultiplyRate(fromToMultiplier);
record.setDivideRate(toFromMultiplier);
record.setIsCatchUOMForProduct(request.isCatchUOMForProduct());
saveRecord(record);
}
@Override
public void updateUOMConversion(@NonNull final UpdateUOMConversionRequest request)
{
final I_C_UOM_Conversion record = Services.get(IQueryBL.class).createQueryBuilder(I_C_UOM_Conversion.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_M_Product_ID, request.getProductId())
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_C_UOM_ID, request.getFromUomId())
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_C_UOM_To_ID, request.getToUomId())
.create()
.firstOnlyNotNull(I_C_UOM_Conversion.class);// we have a unique-constraint
final BigDecimal fromToMultiplier = request.getFromToMultiplier();
final BigDecimal toFromMultiplier = UOMConversionRate.computeInvertedMultiplier(fromToMultiplier);
record.setMultiplyRate(fromToMultiplier);
record.setDivideRate(toFromMultiplier);
record.setIsCatchUOMForProduct(request.isCatchUOMForProduct());
saveRecord(record);
}
@NonNull
private UOMConversionsMap retrieveProductConversions(@NonNull final ProductId productId) | {
final UomId productStockingUomId = Services.get(IProductBL.class).getStockUOMId(productId);
final ImmutableList<UOMConversionRate> rates = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_UOM_Conversion.class)
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_M_Product_ID, productId)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(UOMConversionDAO::toUOMConversionOrNull)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return buildUOMConversionsMap(productId,
productStockingUomId,
rates);
}
@NonNull
private static UOMConversionsMap buildUOMConversionsMap(
@NonNull final ProductId productId,
@NonNull final UomId productStockingUomId,
@NonNull final ImmutableList<UOMConversionRate> rates)
{
return UOMConversionsMap.builder()
.productId(productId)
.hasRatesForNonStockingUOMs(!rates.isEmpty())
.rates(ImmutableList.<UOMConversionRate>builder()
.add(UOMConversionRate.one(productStockingUomId)) // default conversion
.addAll(rates)
.build())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMConversionDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MustacheResourceTemplateLoader implements TemplateLoader, ResourceLoaderAware {
private String prefix = "";
private String suffix = "";
private String charSet = "UTF-8";
private ResourceLoader resourceLoader = new DefaultResourceLoader(null);
public MustacheResourceTemplateLoader() {
}
public MustacheResourceTemplateLoader(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
/**
* Set the charset.
* @param charSet the charset
*/
public void setCharset(String charSet) { | this.charSet = charSet;
}
/**
* Set the resource loader.
* @param resourceLoader the resource loader
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public Reader getTemplate(String name) throws Exception {
return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(),
this.charSet);
}
} | repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\autoconfigure\MustacheResourceTemplateLoader.java | 2 |
请完成以下Java代码 | public void startDocument() throws SAXException {
website = new Baeldung();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case ARTICLES:
website.setArticleList(new ArrayList<>());
break;
case ARTICLE:
website.getArticleList().add(new BaeldungArticle());
break;
case TITLE:
elementValue = new StringBuilder();
break;
case CONTENT:
elementValue = new StringBuilder();
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
switch (qName) {
case TITLE:
latestArticle().setTitle(elementValue.toString());
break;
case CONTENT:
latestArticle().setContent(elementValue.toString());
break;
}
}
private BaeldungArticle latestArticle() {
List<BaeldungArticle> articleList = website.getArticleList();
int latestArticleIndex = articleList.size() - 1;
return articleList.get(latestArticleIndex);
}
public Baeldung getWebsite() {
return website;
}
}
public static class Baeldung {
private List<BaeldungArticle> articleList; | public void setArticleList(List<BaeldungArticle> articleList) {
this.articleList = articleList;
}
public List<BaeldungArticle> getArticleList() {
return this.articleList;
}
}
public static class BaeldungArticle {
private String title;
private String content;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\sax\SaxParserMain.java | 1 |
请完成以下Java代码 | public Wrapper<T> code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 ,返回自身的引用.
*
* @param message
* the new 信息
*
* @return the wrapper
*/
public Wrapper<T> message(String message) {
this.setMessage(message);
return this;
}
/**
* Sets the 结果数据 ,返回自身的引用.
*
* @param result | * the new 结果数据
*
* @return the wrapper
*/
public Wrapper<T> result(T result) {
this.setData(result);
return this;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\wrapper\Wrapper.java | 1 |
请完成以下Java代码 | public I_AD_Window getPO_Window() throws RuntimeException
{
return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name)
.getPO(getPO_Window_ID(), get_TrxName()); }
/** Set PO Window.
@param PO_Window_ID
Purchase Order Window
*/
public void setPO_Window_ID (int PO_Window_ID)
{
if (PO_Window_ID < 1)
set_Value (COLUMNNAME_PO_Window_ID, null);
else
set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID));
}
/** Get PO Window.
@return Purchase Order Window
*/
public int getPO_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Query.
@param Query
SQL
*/
public void setQuery (String Query)
{
set_Value (COLUMNNAME_Query, Query);
}
/** Get Query.
@return SQL
*/
public String getQuery ()
{
return (String)get_Value(COLUMNNAME_Query);
}
/** Set Search Type.
@param SearchType
Which kind of search is used (Query or Table)
*/
public void setSearchType (String SearchType)
{
set_Value (COLUMNNAME_SearchType, SearchType);
} | /** Get Search Type.
@return Which kind of search is used (Query or Table)
*/
public String getSearchType ()
{
return (String)get_Value(COLUMNNAME_SearchType);
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
public void setTransactionCode (String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
public String getTransactionCode ()
{
return (String)get_Value(COLUMNNAME_TransactionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java | 1 |
请完成以下Java代码 | public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction)
{
final PurchaseView view = views.getIfPresent(viewId);
if (view == null || !view.isAllowClosingPerUserRequest())
{
return;
}
if (closeAction.isDone())
{
onViewClosedByUser(view);
}
views.invalidate(viewId);
views.cleanUp(); // also cleanup to prevent views cache to grow.
}
@Override
public final Stream<IView> streamAllViews()
{
return Stream.empty();
}
@Override
public final void invalidateView(final ViewId viewId)
{
final IView view = getByIdOrNull(viewId);
if (view == null)
{
return;
}
view.invalidateAll();
}
@Override
public final PurchaseView createView(@NonNull final CreateViewRequest request)
{
final ViewId viewId = newViewId();
final List<PurchaseDemand> demands = getDemands(request);
final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands);
final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList);
final PurchaseView view = PurchaseView.builder()
.viewId(viewId) | .rowsSupplier(rowsSupplier)
.additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors())
.build();
return view;
}
protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors()
{
return ImmutableList.of();
}
private final PurchaseRowsSupplier createRowsSupplier(
final ViewId viewId,
final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList)
{
final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder()
.purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList)
.viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff
.purchaseRowFactory(purchaseRowFactory)
.availabilityCheckService(availabilityCheckService)
.build()
.createPurchaseRowsSupplier();
return rowsSupplier;
}
protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass);
Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java | 1 |
请完成以下Java代码 | public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private volatile String name;
private Address address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
} | repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\serialization\Customer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setUserSearchBase(String userSearchBase) {
this.userSearchBase = userSearchBase;
}
/**
* Returns the configured {@link AuthenticationManager} that can be used to perform
* LDAP authentication.
* @return the configured {@link AuthenticationManager}
*/
public final AuthenticationManager createAuthenticationManager() {
LdapAuthenticationProvider ldapAuthenticationProvider = getProvider();
return new ProviderManager(ldapAuthenticationProvider);
}
private LdapAuthenticationProvider getProvider() {
AbstractLdapAuthenticator authenticator = getAuthenticator();
LdapAuthenticationProvider provider;
if (this.ldapAuthoritiesPopulator != null) {
provider = new LdapAuthenticationProvider(authenticator, this.ldapAuthoritiesPopulator);
}
else {
provider = new LdapAuthenticationProvider(authenticator);
}
if (this.authoritiesMapper != null) {
provider.setAuthoritiesMapper(this.authoritiesMapper);
}
if (this.userDetailsContextMapper != null) {
provider.setUserDetailsContextMapper(this.userDetailsContextMapper);
}
return provider; | }
private AbstractLdapAuthenticator getAuthenticator() {
AbstractLdapAuthenticator authenticator = createDefaultLdapAuthenticator();
if (this.userSearchFilter != null) {
authenticator.setUserSearch(
new FilterBasedLdapUserSearch(this.userSearchBase, this.userSearchFilter, this.contextSource));
}
if (this.userDnPatterns != null && this.userDnPatterns.length > 0) {
authenticator.setUserDnPatterns(this.userDnPatterns);
}
authenticator.afterPropertiesSet();
return authenticator;
}
/**
* Allows subclasses to supply the default {@link AbstractLdapAuthenticator}.
* @return the {@link AbstractLdapAuthenticator} that will be configured for LDAP
* authentication
*/
protected abstract T createDefaultLdapAuthenticator();
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\AbstractLdapAuthenticationManagerFactory.java | 2 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(groupsById)
.toString();
}
public ImmutableSet<String> getTableNames()
{
return tableNames;
}
public boolean containsTableName(final String tableName)
{
return tableNames.contains(tableName);
}
public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final String tableName)
{
return addingToDefaultGroup(ImmutableSet.of(tableName));
}
public ImmutableTableNamesGroupsIndex addingToDefaultGroup(@NonNull final Collection<String> tableNames)
{
if (tableNames.isEmpty())
{
return this;
}
final TableNamesGroup defaultGroupExisting = groupsById.get(DEFAULT_GROUP_ID);
final TableNamesGroup defaultGroupNew;
if (defaultGroupExisting != null)
{
defaultGroupNew = defaultGroupExisting.toBuilder()
.tableNames(tableNames)
.build();
}
else
{
defaultGroupNew = TableNamesGroup.builder()
.groupId(DEFAULT_GROUP_ID)
.tableNames(tableNames)
.build();
}
if (Objects.equals(defaultGroupExisting, defaultGroupNew))
{
return this;
} | return replacingGroup(defaultGroupNew);
}
public ImmutableTableNamesGroupsIndex replacingGroup(@NonNull final TableNamesGroup groupToAdd)
{
if (groupsById.isEmpty())
{
return new ImmutableTableNamesGroupsIndex(ImmutableList.of(groupToAdd));
}
final ArrayList<TableNamesGroup> newGroups = new ArrayList<>(groupsById.size() + 1);
boolean added = false;
for (final TableNamesGroup group : groupsById.values())
{
if (Objects.equals(group.getGroupId(), groupToAdd.getGroupId()))
{
newGroups.add(groupToAdd);
added = true;
}
else
{
newGroups.add(group);
}
}
if (!added)
{
newGroups.add(groupToAdd);
added = true;
}
return new ImmutableTableNamesGroupsIndex(newGroups);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\ImmutableTableNamesGroupsIndex.java | 1 |
请完成以下Java代码 | public abstract class AbstractCommonEventProcessingCacheListener<K, V> extends CacheListenerAdapter<K, V> {
@Override
public void afterCreate(EntryEvent<K, V> event) {
processEntryEvent(event, EntryEventType.CREATE);
}
@Override
public void afterDestroy(EntryEvent<K, V> event) {
processEntryEvent(event, EntryEventType.DESTROY);
}
@Override
public void afterInvalidate(EntryEvent<K, V> event) {
processEntryEvent(event, EntryEventType.INVALIDATE);
}
@Override
public void afterUpdate(EntryEvent<K, V> event) {
processEntryEvent(event, EntryEventType.UPDATE);
}
protected void processEntryEvent(EntryEvent<K, V> event, EntryEventType eventType) { }
@Override
public void afterRegionClear(RegionEvent<K, V> event) {
processRegionEvent(event, RegionEventType.CLEAR);
}
@Override
public void afterRegionCreate(RegionEvent<K, V> event) {
processRegionEvent(event, RegionEventType.CREATE);
}
@Override
public void afterRegionDestroy(RegionEvent<K, V> event) {
processRegionEvent(event, RegionEventType.DESTROY);
}
@Override
public void afterRegionInvalidate(RegionEvent<K, V> event) {
processRegionEvent(event, RegionEventType.INVALIDATE);
}
@Override
public void afterRegionLive(RegionEvent<K, V> event) { | processRegionEvent(event, RegionEventType.LIVE);
}
protected void processRegionEvent(RegionEvent<K, V> event, RegionEventType eventType) { }
public enum EntryEventType {
CREATE,
DESTROY,
INVALIDATE,
UPDATE;
}
public enum RegionEventType {
CLEAR,
CREATE,
DESTROY,
INVALIDATE,
LIVE;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\cache\AbstractCommonEventProcessingCacheListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setConsumersPerQueue(Integer consumersPerQueue) {
this.consumersPerQueue = consumersPerQueue;
}
/**
* Set the number of messages to receive before acknowledging (success).
* A failed message will short-circuit this counter.
* @param messagesPerAck the number of messages.
* @see #setAckTimeout(Long)
*/
public void setMessagesPerAck(Integer messagesPerAck) {
this.messagesPerAck = messagesPerAck;
}
/**
* An approximate timeout; when {@link #setMessagesPerAck(Integer) messagesPerAck} is
* greater than 1, and this time elapses since the last ack, the pending acks will be
* sent either when the next message arrives, or a short time later if no additional
* messages arrive. In that case, the actual time depends on the
* {@link #setMonitorInterval(long) monitorInterval}.
* @param ackTimeout the timeout in milliseconds (default 20000);
* @see #setMessagesPerAck(Integer)
*/
public void setAckTimeout(Long ackTimeout) {
this.ackTimeout = ackTimeout;
}
@Override
protected DirectMessageListenerContainer createContainerInstance() {
return new DirectMessageListenerContainer();
}
@Override
protected void initializeContainer(DirectMessageListenerContainer instance,
@Nullable RabbitListenerEndpoint endpoint) { | super.initializeContainer(instance, endpoint);
JavaUtils javaUtils = JavaUtils.INSTANCE.acceptIfNotNull(this.taskScheduler, instance::setTaskScheduler)
.acceptIfNotNull(this.monitorInterval, instance::setMonitorInterval)
.acceptIfNotNull(this.messagesPerAck, instance::setMessagesPerAck)
.acceptIfNotNull(this.ackTimeout, instance::setAckTimeout);
if (endpoint != null && endpoint.getConcurrency() != null) {
try {
instance.setConsumersPerQueue(Integer.parseInt(endpoint.getConcurrency()));
}
catch (NumberFormatException e) {
throw new IllegalStateException("Failed to parse concurrency: " + e.getMessage(), e);
}
}
else {
javaUtils.acceptIfNotNull(this.consumersPerQueue, instance::setConsumersPerQueue);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\DirectRabbitListenerContainerFactory.java | 2 |
请完成以下Java代码 | public static <R> Singleton<R> from(final Supplier<R> original) {
return new Singleton<>(original);
}
/**
* <p>from.</p>
*
* @param original a {@link java.util.function.Function} object
* @param arg0 a T object
* @param <T> a T class
* @param <R> a R class
* @return a {@link com.ulisesbocchio.jasyptspringboot.util.Singleton} object
*/
public static <T, R> Singleton<R> from(final Function<T, R> original, T arg0) {
return fromLazy(original, () -> arg0);
}
/**
* <p>from.</p>
*
* @param original a {@link java.util.function.BiFunction} object
* @param arg0 a T object
* @param arg1 a U object
* @param <T> a T class
* @param <U> a U class
* @param <R> a R class
* @return a {@link com.ulisesbocchio.jasyptspringboot.util.Singleton} object
*/
public static <T, U, R> Singleton<R> from(final BiFunction<T, U, R> original, T arg0, U arg1) {
return fromLazy(original, () -> arg0, () -> arg1);
}
/**
* <p>fromLazy.</p>
*
* @param original a {@link java.util.function.Function} object
* @param arg0Supplier a {@link java.util.function.Supplier} object
* @param <T> a T class
* @param <R> a R class
* @return a {@link com.ulisesbocchio.jasyptspringboot.util.Singleton} object
*/
public static <T, R> Singleton<R> fromLazy(final Function<T, R> original, Supplier<T> arg0Supplier) { | return from(() -> original.apply(arg0Supplier.get()));
}
/**
* <p>fromLazy.</p>
*
* @param original a {@link java.util.function.BiFunction} object
* @param arg0Supplier a {@link java.util.function.Supplier} object
* @param arg1Supplier a {@link java.util.function.Supplier} object
* @param <T> a T class
* @param <U> a U class
* @param <R> a R class
* @return a {@link com.ulisesbocchio.jasyptspringboot.util.Singleton} object
*/
public static <T, U, R> Singleton<R> fromLazy(final BiFunction<T, U, R> original, Supplier<T> arg0Supplier, Supplier<U> arg1Supplier) {
return from(() -> original.apply(arg0Supplier.get(), arg1Supplier.get()));
}
/**
* <p>Constructor for Singleton.</p>
*
* @param original a {@link java.util.function.Supplier} object
*/
public Singleton(final Supplier<R> original) {
instanceSupplier = () -> {
synchronized (original) {
if (!initialized) {
final R singletonInstance = original.get();
instanceSupplier = () -> singletonInstance;
initialized = true;
}
return instanceSupplier.get();
}
};
}
/** {@inheritDoc} */
@Override
public R get() {
return instanceSupplier.get();
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\Singleton.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
} | @Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")";
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java | 2 |
请完成以下Java代码 | public class User {
private Long id;
private String firstName;
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() { | return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
} | repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\deserialization\jsongeneric\User.java | 1 |
请完成以下Java代码 | class Employee {
@Id
private String id;
private String name;
@DBRef(lazy = true) // lazy to avoid stackoverflow on load
private Manager manager;
public Employee() {
}
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
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 Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
} | repos\spring-data-examples-main\mongodb\linking\src\main\java\example\springdata\mongodb\linking\dbref\Employee.java | 1 |
请完成以下Java代码 | public void save(@NonNull final AttachmentEntry attachmentEntry)
{
attachmentEntryRepository.save(attachmentEntry);
}
@Value
public static class AttachmentEntryQuery
{
List<String> tagsSetToTrue;
List<String> tagsSetToAnyValue;
Object referencedRecord;
String mimeType;
@Builder | private AttachmentEntryQuery(
@Singular("tagSetToTrue") final List<String> tagsSetToTrue,
@Singular("tagSetToAnyValue") final List<String> tagsSetToAnyValue,
@Nullable final String mimeType,
@NonNull final Object referencedRecord)
{
this.referencedRecord = referencedRecord;
this.mimeType = mimeType;
this.tagsSetToTrue = tagsSetToTrue;
this.tagsSetToAnyValue = tagsSetToAnyValue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ResourceService
{
private final ResourceRepository resourceRepository;
public ResourceService(
@NonNull final ResourceRepository resourceRepository)
{
this.resourceRepository = resourceRepository;
}
public static ResourceService newInstanceForUnitTesting()
{
Adempiere.assertUnitTestMode();
return new ResourceService(
new ResourceRepository());
}
public ImmutableSet<ResourceId> getActivePlantIds() {return resourceRepository.getActivePlantIds();} | //
//
// ------------------------------------------------------------------------
//
//
@UtilityClass
@Deprecated
public static class Legacy
{
public static String getResourceName(@NonNull final ResourceId resourceId)
{
final I_S_Resource resourceRecord = ResourceRepository.retrieveRecordById(resourceId);
return resourceRecord.getName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\ResourceService.java | 2 |
请完成以下Java代码 | public class SpringCacheBasedAclCache implements AclCache {
private final Cache cache;
private PermissionGrantingStrategy permissionGrantingStrategy;
private AclAuthorizationStrategy aclAuthorizationStrategy;
public SpringCacheBasedAclCache(Cache cache, PermissionGrantingStrategy permissionGrantingStrategy,
AclAuthorizationStrategy aclAuthorizationStrategy) {
Assert.notNull(cache, "Cache required");
Assert.notNull(permissionGrantingStrategy, "PermissionGrantingStrategy required");
Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required");
this.cache = cache;
this.permissionGrantingStrategy = permissionGrantingStrategy;
this.aclAuthorizationStrategy = aclAuthorizationStrategy;
}
@Override
public void evictFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
MutableAcl acl = getFromCache(pk);
if (acl != null) {
this.cache.evict(acl.getId());
this.cache.evict(acl.getObjectIdentity());
}
}
@Override
public void evictFromCache(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
MutableAcl acl = getFromCache(objectIdentity);
if (acl != null) {
this.cache.evict(acl.getId());
this.cache.evict(acl.getObjectIdentity());
}
}
@Override
public MutableAcl getFromCache(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
return getFromCache((Object) objectIdentity);
}
@Override | public MutableAcl getFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
return getFromCache((Object) pk);
}
@Override
public void putInCache(MutableAcl acl) {
Assert.notNull(acl, "Acl required");
Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required");
Assert.notNull(acl.getId(), "ID required");
if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) {
putInCache((MutableAcl) acl.getParentAcl());
}
this.cache.put(acl.getObjectIdentity(), acl);
this.cache.put(acl.getId(), acl);
}
private MutableAcl getFromCache(Object key) {
Cache.ValueWrapper element = this.cache.get(key);
if (element == null) {
return null;
}
return initializeTransientFields((MutableAcl) element.get());
}
private MutableAcl initializeTransientFields(MutableAcl value) {
if (value instanceof AclImpl) {
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy);
}
if (value.getParentAcl() != null) {
initializeTransientFields((MutableAcl) value.getParentAcl());
}
return value;
}
@Override
public void clearCache() {
this.cache.clear();
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\SpringCacheBasedAclCache.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setBinaryData (final @Nullable java.lang.String BinaryData)
{
set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData);
}
@Override
public java.lang.String getBinaryData()
{
return get_ValueAsString(COLUMNNAME_BinaryData);
}
@Override
public void setContentType (final @Nullable java.lang.String ContentType)
{
set_ValueNoCheck (COLUMNNAME_ContentType, ContentType);
}
@Override
public java.lang.String getContentType()
{
return get_ValueAsString(COLUMNNAME_ContentType);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_ValueNoCheck (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setFileName (final @Nullable java.lang.String FileName)
{
set_ValueNoCheck (COLUMNNAME_FileName, FileName);
}
@Override
public java.lang.String getFileName()
{
return get_ValueAsString(COLUMNNAME_FileName);
}
@Override
public void setM_Product_AttachmentEntry_ReferencedRecord_v_ID (final int M_Product_AttachmentEntry_ReferencedRecord_v_ID)
{
if (M_Product_AttachmentEntry_ReferencedRecord_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, M_Product_AttachmentEntry_ReferencedRecord_v_ID);
}
@Override
public int getM_Product_AttachmentEntry_ReferencedRecord_v_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_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 setType (final boolean Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public boolean isType()
{
return get_ValueAsBoolean(COLUMNNAME_Type);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_ValueNoCheck (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_AttachmentEntry_ReferencedRecord_v.java | 1 |
请完成以下Java代码 | final class UpdateASIAttributeFromModelCommand
{
@NonNull private final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService;
@NonNull private final IAttributeDAO attributeDAO;
@NonNull private final IAttributeSetInstanceBL attributeSetInstanceBL;
@NonNull private final AttributeCode attributeCode;
@NonNull private final Object sourceModel;
@SuppressWarnings("unused")
public static class UpdateASIAttributeFromModelCommandBuilder
{
public void execute()
{
build().execute();
}
}
public void execute()
{
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel);
if (asiAware == null)
{
return;
}
final ProductId productId = ProductId.ofRepoIdOrNull(asiAware.getM_Product_ID());
if (productId == null)
{ | return;
}
final AttributeId attributeId = attributeDAO.retrieveActiveAttributeIdByValueOrNull(attributeCode);
if (attributeId == null)
{
return;
}
attributeSetInstanceBL.getCreateASI(asiAware);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID());
final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, attributeId);
if (ai != null)
{
// If it was set, just leave it as it is
return;
}
attributeSetInstanceBL.getCreateAttributeInstance(asiId, attributeId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\UpdateASIAttributeFromModelCommand.java | 1 |
请完成以下Java代码 | public void onReverse(final I_M_InOut inout)
{
if (isMaterialReturn(inout))
{
return;
}
final boolean reversal = true;
eventSender.send(createInOutChangedEvent(inout, reversal));
}
private InOutChangedEvent createInOutChangedEvent(final I_M_InOut inout, final boolean reversal)
{
return InOutChangedEvent.builder()
.bpartnerId(BPartnerId.ofRepoId(inout.getC_BPartner_ID()))
.movementDate(TimeUtil.asInstant(inout.getMovementDate()))
.soTrx(SOTrx.ofBoolean(inout.isSOTrx()))
.productIds(extractProductIds(inout))
.reversal(reversal)
.build();
}
private boolean isMaterialReturn(final I_M_InOut inout)
{ | final String movementType = inout.getMovementType();
return Services.get(IInOutBL.class).isReturnMovementType(movementType);
}
private Set<ProductId> extractProductIds(final I_M_InOut inout)
{
final IInOutDAO inoutsRepo = Services.get(IInOutDAO.class);
return inoutsRepo.retrieveLines(inout)
.stream()
.map(I_M_InOutLine::getM_Product_ID)
.map(ProductId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\interceptor\M_InOut.java | 1 |
请完成以下Java代码 | public class CalloutProductCategory extends CalloutEngine
{
/**
* Loop detection of product category tree.
*
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return "" or error message
*/
public String testForLoop (final ICalloutField calloutField)
{
final I_M_Product_Category productCategory = calloutField.getModel(I_M_Product_Category.class); | final int productCategoryParentId = productCategory.getM_Product_Category_Parent_ID();
if (productCategoryParentId <= 0)
{
return NO_ERROR;
}
if(productCategory.getM_Product_Category_ID() > 0)
{
MProductCategory.assertNoLoopInTree(productCategory);
}
return NO_ERROR;
}
} // CalloutProductCategory | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutProductCategory.java | 1 |
请完成以下Java代码 | public class Author {
@Id
private String id;
@ArangoId
private String arangoId;
private String name;
public Author() {
super();
}
public Author(String name) {
this.name = name;
}
public String getId() {
return id;
} | public void setId(String id) {
this.id = id;
}
public String getArangoId() {
return arangoId;
}
public void setArangoId(String arangoId) {
this.arangoId = arangoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | repos\tutorials-master\persistence-modules\spring-data-arangodb\src\main\java\com\baeldung\arangodb\model\Author.java | 1 |
请完成以下Java代码 | private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
if (jsonValue.isBoolean())
return jsonValue.getAsBoolean();
else if (jsonValue.isString())
return jsonValue.getAsString();
else {
BigDecimal bigDec = jsonValue.getAsBigDecimal();
Long l;
Integer i;
if ((i = toInteger(bigDec)) != null) {
return i;
} else if ((l = toLong(bigDec)) != null) {
return l;
} else {
return bigDec.doubleValue();
}
}
}
private Long toLong(BigDecimal val) {
try { | return val.toBigIntegerExact().longValue();
} catch (ArithmeticException e) {
return null;
}
}
private Integer toInteger(BigDecimal val) {
try {
return val.intValueExact();
} catch (ArithmeticException e) {
return null;
}
}
} | repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\serialization\MapDeserializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Resource
{
@NonNull ResourceId resourceId;
@NonNull String name;
@Nullable ManufacturingResourceType manufacturingResourceType;
@Nullable WorkplaceId workplaceId;
@Nullable Integer externalSystemParentConfigId;
boolean isManufacturingResource;
public boolean isWorkstation()
{
return isManufacturingResource
&& ManufacturingResourceType.WorkStation == manufacturingResourceType;
}
public boolean isExternalSystem() | {
return isManufacturingResource
&& ManufacturingResourceType.ExternalSystem == manufacturingResourceType;
}
@NonNull
public ResourceQRCode toQrCode()
{
return ResourceQRCode.builder()
.resourceId(resourceId)
.resourceType(ManufacturingResourceType.toCodeOrNull(manufacturingResourceType))
.caption(name)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\Resource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isRetained(VariableInstanceEntity entity, Object param) {
return isRetained(entity, (InternalVariableInstanceQueryImpl) param);
}
public boolean isRetained(VariableInstanceEntity entity, InternalVariableInstanceQueryImpl param) {
if (param.executionId != null && !param.executionId.equals(entity.getExecutionId())) {
return false;
}
if (param.scopeId != null && !param.scopeId.equals(entity.getScopeId())) {
return false;
}
if (param.scopeIds != null && !param.scopeIds.contains(entity.getScopeId())) {
return false;
}
if (param.taskId != null && !param.taskId.equals(entity.getTaskId())) {
return false;
}
if (param.processInstanceId != null && !param.processInstanceId.equals(entity.getProcessInstanceId())) {
return false;
}
if (param.withoutTaskId && entity.getTaskId() != null) {
return false;
}
if (param.subScopeId != null && !param.subScopeId.equals(entity.getSubScopeId())) {
return false;
}
if (param.subScopeIds != null && !param.subScopeIds.contains(entity.getSubScopeId())) {
return false;
}
if (param.withoutSubScopeId && entity.getSubScopeId() != null) {
return false;
}
if (param.scopeType != null && !param.scopeType.equals(entity.getScopeType())) {
return false;
}
if (param.scopeTypes != null && !param.scopeTypes.isEmpty() && !param.scopeTypes.contains(entity.getScopeType())) {
return false;
} | if (param.id != null && !param.id.equals(entity.getId())) {
return false;
}
if (param.taskIds != null && !param.taskIds.contains(entity.getTaskId())) {
return false;
}
if (param.executionIds != null && !param.executionIds.contains(entity.getExecutionId())) {
return false;
}
if (param.name != null && !param.name.equals(entity.getName())) {
return false;
}
if (param.names != null && !param.names.isEmpty() && !param.names.contains(entity.getName())) {
return false;
}
return true;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\InternalVariableInstanceQueryImpl.java | 2 |
请完成以下Java代码 | public boolean reActivateIt()
{
log.info(toString());
// Before reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE);
if (m_processMsg != null)
return false;
setProcessed(false);
setDocAction(DOCACTION_Complete);
// After reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE);
if (m_processMsg != null)
return false;
return true;
} // reActivateIt
@Override
public boolean rejectIt()
{
return true;
}
@Override
public boolean reverseAccrualIt()
{
log.info(toString());
// Before reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL);
if (m_processMsg != null)
return false;
// After reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL);
if (m_processMsg != null)
return false;
return true;
} // reverseAccrualIt
@Override
public boolean reverseCorrectIt()
{
log.info(toString());
// Before reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT);
if (m_processMsg != null)
return false;
// After reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT);
if (m_processMsg != null)
return false;
return true;
} | /**
* Unlock Document.
*
* @return true if success
*/
@Override
public boolean unlockIt()
{
log.info(toString());
setProcessing(false);
return true;
} // unlockIt
@Override
public boolean voidIt()
{
return false;
}
@Override
public int getC_Currency_ID()
{
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateConditions.java | 1 |
请完成以下Java代码 | public void beforeFlatrateTermReactivate(final I_C_Flatrate_Term term)
{
deleteFlatrateTermDataEntriesOnReactivate(term);
deleteC_Invoice_Clearing_AllocsOnReactivate(term);
deleteInvoiceCandidates(term);
}
/**
* Deletes {@link I_C_Flatrate_DataEntry} records for given term.
*
* @throws AdempiereException if any data entry record is completed
*/
protected void deleteFlatrateTermDataEntriesOnReactivate(final I_C_Flatrate_Term term)
{
final List<I_C_Flatrate_DataEntry> entries = flatrateDAO.retrieveDataEntries(term, null, null);
for (final I_C_Flatrate_DataEntry entry : entries)
{
// note: The system will prevent the deletion of a completed entry
// However, we want to give a user-friendly explanation to the user.
if (X_C_Flatrate_DataEntry.DOCSTATUS_Completed.equals(entry.getDocStatus()))
{
final ITranslatableString uomName = uomDAO.getName(UomId.ofRepoId(entry.getC_UOM_ID()));
throw new AdempiereException(
MSG_TERM_ERROR_ENTRY_ALREADY_CO_2P,
uomName, entry.getC_Period().getName());
}
InterfaceWrapperHelper.delete(entry);
}
}
/**
* Deletes {@link I_C_Invoice_Clearing_Alloc}s for given term.
*/
protected void deleteC_Invoice_Clearing_AllocsOnReactivate(final I_C_Flatrate_Term term)
{
// note: we assume that invoice candidate validator will take care of the invoice candidate's IsToClear flag
final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class);
final List<I_C_Invoice_Clearing_Alloc> icas = flatrateDAO.retrieveClearingAllocs(term);
for (final I_C_Invoice_Clearing_Alloc ica : icas)
{
InterfaceWrapperHelper.delete(ica);
}
} | /**
* When a term is reactivated, its invoice candidate needs to be deleted.
* Note that we assume the deletion will fail with a meaningful error message if the invoice candidate has already been invoiced.
*/
public void deleteInvoiceCandidates(@NonNull final I_C_Flatrate_Term term)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(term);
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterFlatrateTermEnded(final I_C_Flatrate_Term term)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void beforeSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\spi\FallbackFlatrateTermEventListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void authorBatchInserts() {
Author jn = new Author();
jn.setName("Joana Nimar");
jn.setGenre("History");
jn.setAge(34);
Author mj = new Author();
mj.setName("Mark Janel");
mj.setGenre("Anthology");
mj.setAge(23);
Author og = new Author();
og.setName("Olivia Goy");
og.setGenre("Horror");
og.setAge(43);
Author qy = new Author();
qy.setName("Quartis Young");
qy.setGenre("Anthology"); | qy.setAge(51);
Author at = new Author();
at.setName("Alicia Tom");
at.setGenre("Anthology");
at.setAge(38);
Author kl = new Author();
kl.setName("Katy Loin");
kl.setGenre("Anthology");
kl.setAge(56);
List<Author> authors = Arrays.asList(jn, mj, og, qy, at, kl);
authorRepository.saveAll(authors);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchingAndSerial\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse);
}
/** Set Lager.
@param M_Warehouse_ID
Storage Warehouse and Service Point
*/
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Lager.
@return Storage Warehouse and Service Point
*/
@Override
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Priorität.
@param PriorityNo
Where inventory should be picked from first
*/
@Override
public void setPriorityNo (int PriorityNo)
{
set_Value (COLUMNNAME_PriorityNo, Integer.valueOf(PriorityNo));
}
/** Get Relative Priorität.
@return Where inventory should be picked from first
*/
@Override
public int getPriorityNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PriorityNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Gang.
@param X
X-Dimension, z.B. Gang
*/
@Override
public void setX (java.lang.String X)
{
set_Value (COLUMNNAME_X, X);
} | /** Get Gang.
@return X-Dimension, z.B. Gang
*/
@Override
public java.lang.String getX ()
{
return (java.lang.String)get_Value(COLUMNNAME_X);
}
/** Set Regal.
@param X1 Regal */
@Override
public void setX1 (java.lang.String X1)
{
set_Value (COLUMNNAME_X1, X1);
}
/** Get Regal.
@return Regal */
@Override
public java.lang.String getX1 ()
{
return (java.lang.String)get_Value(COLUMNNAME_X1);
}
/** Set Fach.
@param Y
Y-Dimension, z.B. Fach
*/
@Override
public void setY (java.lang.String Y)
{
set_Value (COLUMNNAME_Y, Y);
}
/** Get Fach.
@return Y-Dimension, z.B. Fach
*/
@Override
public java.lang.String getY ()
{
return (java.lang.String)get_Value(COLUMNNAME_Y);
}
/** Set Ebene.
@param Z
Z-Dimension, z.B. Ebene
*/
@Override
public void setZ (java.lang.String Z)
{
set_Value (COLUMNNAME_Z, Z);
}
/** Get Ebene.
@return Z-Dimension, z.B. Ebene
*/
@Override
public java.lang.String getZ ()
{
return (java.lang.String)get_Value(COLUMNNAME_Z);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java | 1 |
请完成以下Java代码 | public void setExternalSystem_Outbound_Endpoint_ID (final int ExternalSystem_Outbound_Endpoint_ID)
{
if (ExternalSystem_Outbound_Endpoint_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, ExternalSystem_Outbound_Endpoint_ID);
}
@Override
public int getExternalSystem_Outbound_Endpoint_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID);
}
@Override
public void setLoginUsername (final @Nullable String LoginUsername)
{
set_Value (COLUMNNAME_LoginUsername, LoginUsername);
}
@Override
public String getLoginUsername()
{
return get_ValueAsString(COLUMNNAME_LoginUsername);
}
@Override
public void setOutboundHttpEP (final String OutboundHttpEP)
{
set_Value (COLUMNNAME_OutboundHttpEP, OutboundHttpEP);
}
@Override
public String getOutboundHttpEP()
{
return get_ValueAsString(COLUMNNAME_OutboundHttpEP);
}
@Override
public void setOutboundHttpMethod (final String OutboundHttpMethod)
{
set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod);
}
@Override
public String getOutboundHttpMethod()
{
return get_ValueAsString(COLUMNNAME_OutboundHttpMethod);
}
@Override
public void setPassword (final @Nullable String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setSasSignature (final @Nullable String SasSignature)
{
set_Value (COLUMNNAME_SasSignature, SasSignature);
}
@Override | public String getSasSignature()
{
return get_ValueAsString(COLUMNNAME_SasSignature);
}
/**
* Type AD_Reference_ID=542016
* Reference name: ExternalSystem_Outbound_Endpoint_EndpointType
*/
public static final int TYPE_AD_Reference_ID=542016;
/** HTTP = HTTP */
public static final String TYPE_HTTP = "HTTP";
/** SFTP = SFTP */
public static final String TYPE_SFTP = "SFTP";
/** FILE = FILE */
public static final String TYPE_FILE = "FILE";
/** EMAIL = EMAIL */
public static final String TYPE_EMAIL = "EMAIL";
/** TCP = TCP */
public static final String TYPE_TCP = "TCP";
@Override
public void setType (final String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setValue (final String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setRelatedEntities(EntitiesExportCtx<?> ctx, RuleChain ruleChain, RuleChainExportData exportData) {
RuleChainMetaData metaData = ruleChainService.loadRuleChainMetaData(ctx.getTenantId(), ruleChain.getId());
Optional.ofNullable(metaData.getNodes()).orElse(Collections.emptyList())
.forEach(ruleNode -> {
ruleNode.setRuleChainId(null);
ctx.putExternalId(ruleNode.getId(), ruleNode.getExternalId());
ruleNode.setId(ctx.getExternalId(ruleNode.getId()));
ruleNode.setCreatedTime(0);
ruleNode.setExternalId(null);
replaceUuidsRecursively(ctx, ruleNode.getConfiguration(), Collections.emptySet(), PROCESSED_CONFIG_FIELDS_PATTERN);
});
Optional.ofNullable(metaData.getRuleChainConnections()).orElse(Collections.emptyList())
.forEach(ruleChainConnectionInfo -> {
ruleChainConnectionInfo.setTargetRuleChainId(getExternalIdOrElseInternal(ctx, ruleChainConnectionInfo.getTargetRuleChainId()));
});
exportData.setMetaData(metaData); | if (ruleChain.getFirstRuleNodeId() != null) {
ruleChain.setFirstRuleNodeId(ctx.getExternalId(ruleChain.getFirstRuleNodeId()));
}
}
@Override
protected RuleChainExportData newExportData() {
return new RuleChainExportData();
}
@Override
public Set<EntityType> getSupportedEntityTypes() {
return Set.of(EntityType.RULE_CHAIN);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\exporting\impl\RuleChainExportService.java | 2 |
请完成以下Java代码 | public Expression getCollectionExpression() {
return collectionExpression;
}
public void setCollectionExpression(Expression collectionExpression) {
this.collectionExpression = collectionExpression;
}
public String getCollectionVariable() {
return collectionVariable;
}
public void setCollectionVariable(String collectionVariable) {
this.collectionVariable = collectionVariable;
}
public String getCollectionElementVariable() {
return collectionElementVariable;
}
public void setCollectionElementVariable(String collectionElementVariable) {
this.collectionElementVariable = collectionElementVariable;
}
public String getCollectionElementIndexVariable() {
return collectionElementIndexVariable;
}
public void setCollectionElementIndexVariable(String collectionElementIndexVariable) {
this.collectionElementIndexVariable = collectionElementIndexVariable;
}
public void setInnerActivityBehavior(ActivityBehavior innerActivityBehavior) {
this.innerActivityBehavior = innerActivityBehavior;
if (innerActivityBehavior instanceof org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) {
((org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior) innerActivityBehavior).setV5MultiInstanceActivityBehavior(this);
} else {
((AbstractBpmnActivityBehavior) this.innerActivityBehavior).setMultiInstanceActivityBehavior(this);
} | }
public ActivityBehavior getInnerActivityBehavior() {
return innerActivityBehavior;
}
/**
* ACT-1339. Calling ActivityEndListeners within an {@link AtomicOperation} so that an executionContext is present.
*
* @author Aris Tzoumas
* @author Joram Barrez
*/
private static final class CallActivityListenersOperation implements AtomicOperation {
private List<ExecutionListener> listeners;
private CallActivityListenersOperation(List<ExecutionListener> listeners) {
this.listeners = listeners;
}
@Override
public void execute(InterpretableExecution execution) {
for (ExecutionListener executionListener : listeners) {
try {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new ExecutionListenerInvocation(executionListener, execution));
} catch (Exception e) {
throw new ActivitiException("Couldn't execute listener", e);
}
}
}
@Override
public boolean isAsync(InterpretableExecution execution) {
return false;
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java | 1 |
请完成以下Java代码 | public TypedValue transform(Object value) throws IllegalArgumentException {
if (value instanceof Number) {
int intValue = transformNumber((Number) value);
return Variables.integerValue(intValue);
} else if (value instanceof String) {
int intValue = transformString((String) value);
return Variables.integerValue(intValue);
} else {
throw new IllegalArgumentException();
}
}
protected int transformNumber(Number value) {
if(isInteger(value)){
return value.intValue(); | } else {
throw new IllegalArgumentException();
}
}
protected boolean isInteger(Number value) {
double doubleValue = value.doubleValue();
return doubleValue == (int) doubleValue;
}
protected int transformString(String value) {
return Integer.parseInt(value);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\type\IntegerDataTypeTransformer.java | 1 |
请完成以下Java代码 | public class TreeListenerSupport implements ITreeListener
{
private final WeakList<ITreeListener> listeners = new WeakList<ITreeListener>();
public void addTreeListener(ITreeListener listener, boolean isWeak)
{
if (!listeners.contains(listener))
listeners.add(listener, isWeak);
}
public void removeTreeListener(ITreeListener listener)
{
listeners.remove(listener);
}
@Override
public void onNodeInserted(PO po)
{
for (ITreeListener listener : listeners)
{
listener.onNodeInserted(po);
}
} | @Override
public void onNodeDeleted(PO po)
{
for (ITreeListener listener : listeners)
{
listener.onNodeDeleted(po);
}
}
@Override
public void onParentChanged(int AD_Table_ID, int nodeId, int newParentId, int oldParentId, String trxName)
{
if (newParentId == oldParentId)
return;
for (ITreeListener listener : listeners)
{
listener.onParentChanged(AD_Table_ID, nodeId, newParentId, oldParentId, trxName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\TreeListenerSupport.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.