instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class CustomResponseWithBuilderController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Hello World!");
}
@GetMapping("/age")
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return ResponseEntity.badRequest()
.body("Year of birth cannot be in the future");
}
return ResponseEntity.status(HttpStatus.OK)
.body("Your age is " + calculateAge(yearOfBirth));
}
private int calculateAge(int yearOfBirth) {
return currentYear() - yearOfBirth;
} | private boolean isInFuture(int year) {
return currentYear() < year;
}
private int currentYear() {
return Year.now()
.getValue();
}
@GetMapping("/customHeader")
public ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set");
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\responseentity\CustomResponseWithBuilderController.java | 2 |
请完成以下Java代码 | public void collect(@NonNull HUAttributeChange change)
{
Check.assumeEquals(huId, change.getHuId(), "Invalid HuId for {}. Expected: {}", change, huId);
attributes.compute(change.getAttributeId(), (attributeId, previousChange) -> mergeChange(previousChange, change));
lastChangeDate = max(lastChangeDate, change.getDate());
}
private static Instant max(@Nullable final Instant instant1, @Nullable final Instant instant2)
{
if (instant1 == null)
{
return instant2;
}
else if (instant2 == null)
{
return null;
}
else if (instant1.isAfter(instant2))
{
return instant1;
}
else
{
return instant2;
}
}
private static HUAttributeChange mergeChange(
@Nullable final HUAttributeChange previousChange,
@NonNull final HUAttributeChange currentChange)
{
return previousChange != null | ? previousChange.mergeWithNextChange(currentChange)
: currentChange;
}
public boolean isEmpty()
{
return attributes.isEmpty();
}
public AttributesKey getOldAttributesKey()
{
return toAttributesKey(HUAttributeChange::getOldAttributeKeyPartOrNull);
}
public AttributesKey getNewAttributesKey()
{
return toAttributesKey(HUAttributeChange::getNewAttributeKeyPartOrNull);
}
private AttributesKey toAttributesKey(final Function<HUAttributeChange, AttributesKeyPart> keyPartExtractor)
{
if (attributes.isEmpty())
{
return AttributesKey.NONE;
}
final ImmutableList<AttributesKeyPart> parts = attributes.values()
.stream()
.map(keyPartExtractor)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return AttributesKey.ofParts(parts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChanges.java | 1 |
请完成以下Java代码 | protected void validateFlowElementsInContainer(
FlowElementsContainer container,
List<ValidationError> errors,
Process process
) {
for (FlowElement flowElement : container.getFlowElements()) {
if (flowElement instanceof FlowElementsContainer) {
FlowElementsContainer subProcess = (FlowElementsContainer) flowElement;
validateFlowElementsInContainer(subProcess, errors, process);
}
if ((flowElement instanceof FlowNode) && ((FlowNode) flowElement).isAsynchronous()) {
addWarning(errors, Problems.FLOW_ELEMENT_ASYNC_NOT_AVAILABLE, process, flowElement);
} | if ((flowElement instanceof Event)) {
((Event) flowElement).getEventDefinitions()
.stream()
.forEach(event -> {
if (event instanceof TimerEventDefinition) {
addWarning(errors, Problems.EVENT_TIMER_ASYNC_NOT_AVAILABLE, process, flowElement);
} else if (
(event instanceof SignalEventDefinition) && ((SignalEventDefinition) event).isAsync()
) {
addWarning(errors, Problems.SIGNAL_ASYNC_NOT_AVAILABLE, process, flowElement);
}
});
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\process\validation\AsyncPropertyValidator.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Create Single Order.
@param IsCreateSingleOrder
For all shipments create one Order
*/
public void setIsCreateSingleOrder (boolean IsCreateSingleOrder)
{
set_Value (COLUMNNAME_IsCreateSingleOrder, Boolean.valueOf(IsCreateSingleOrder));
}
/** Get Create Single Order.
@return For all shipments create one Order
*/
public boolean isCreateSingleOrder ()
{
Object oo = get_Value(COLUMNNAME_IsCreateSingleOrder);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Distribution Run.
@param M_DistributionRun_ID
Distribution Run create Orders to distribute products to a selected list of partners
*/
public void setM_DistributionRun_ID (int M_DistributionRun_ID)
{
if (M_DistributionRun_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionRun_ID, Integer.valueOf(M_DistributionRun_ID));
}
/** Get Distribution Run.
@return Distribution Run create Orders to distribute products to a selected list of partners
*/
public int getM_DistributionRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
} | /** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionRun.java | 1 |
请完成以下Java代码 | public ExternalWorkerJobAcquireBuilder createExternalWorkerJobAcquireBuilder() {
return new ExternalWorkerJobAcquireBuilderImpl(commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String externalJobId, String workerId) {
return new ExternalWorkerJobFailureBuilderImpl(externalJobId, workerId, commandExecutor, configuration.getJobServiceConfiguration());
}
@Override
public CmmnExternalWorkerTransitionBuilder createCmmnExternalWorkerTransitionBuilder(String externalJobId, String workerId) {
return new CmmnExternalWorkerTransitionBuilderImpl(commandExecutor, externalJobId, workerId);
}
@Override
public void unacquireExternalWorkerJob(String jobId, String workerId) {
commandExecutor.execute(new UnacquireExternalWorkerJobCmd(jobId, workerId, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, null, configuration.getJobServiceConfiguration()));
}
@Override
public void unacquireAllExternalWorkerJobsForWorker(String workerId, String tenantId) {
commandExecutor.execute(new UnacquireAllExternalWorkerJobsForWorkerCmd(workerId, tenantId, configuration.getJobServiceConfiguration()));
}
@Override
public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) {
return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager());
}
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null"); | }
return commandExecutor.execute(command);
}
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new FlowableIllegalArgumentException("The config is null");
}
if (command == null) {
throw new FlowableIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public LockManager getLockManager(String lockName) {
return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnManagementServiceImpl.java | 1 |
请完成以下Java代码 | public void flush()
{
List<ProcessInfoLog> logEntries = null;
try
{
//note: synchronized with addToBuffer
mainLock.lock();
logEntries = buffer;
this.buffer = null;
if (logEntries == null || logEntries.isEmpty())
{
return;
}
pInstanceDAO.saveProcessInfoLogs(pInstanceId, logEntries);
}
catch (final Exception ex)
{
// make sure flush never fails
logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries != null ? logEntries.size() : 0, logEntries, ex);
}
finally
{
mainLock.unlock();
}
}
private void addToBuffer(final ProcessInfoLog logEntry)
{
try
{ | //making sure there is no flush going on in a diff thread while adding to buffer
mainLock.lock();
List<ProcessInfoLog> buffer = this.buffer;
if (buffer == null)
{
buffer = this.buffer = new ArrayList<>(bufferSize);
}
buffer.add(logEntry);
if (buffer.size() >= bufferSize)
{
flush();
}
}
finally
{
mainLock.unlock();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADProcessLoggable.java | 1 |
请完成以下Java代码 | public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQtyShipped (final @Nullable BigDecimal QtyShipped)
{
set_Value (COLUMNNAME_QtyShipped, QtyShipped);
} | @Override
public BigDecimal getQtyShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalPrice (final BigDecimal TotalPrice)
{
set_Value (COLUMNNAME_TotalPrice, TotalPrice);
}
@Override
public BigDecimal getTotalPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalWeightInKg (final BigDecimal TotalWeightInKg)
{
set_Value (COLUMNNAME_TotalWeightInKg, TotalWeightInKg);
}
@Override
public BigDecimal getTotalWeightInKg()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalWeightInKg);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Item.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-consumer # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
server:
port: 28080 # | 服务器端口。默认为 8080
logging:
level:
cn.iocoder.springcloud.labx03.feigndemo.consumer.feign: DEBUG | repos\SpringBoot-Labs-master\labx-03-spring-cloud-feign\labx-03-sc-feign-demo02B-consumer\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public RestResponse<?> fileParam(@MultipartParam FileItem fileItem) throws Exception {
try {
byte[] fileContent = fileItem.getData();
log.debug("Saving the uploaded file");
java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
return RestResponse.ok();
} catch (Exception e) {
log.error(e.getMessage(), e);
return RestResponse.fail(e.getMessage());
}
}
@GetRoute("/params/header") | public void headerParam(@HeaderParam String customheader, Response response) {
log.info("Custom header: " + customheader);
response.text(customheader);
}
@GetRoute("/params/cookie")
public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
log.info("myCookie: " + myCookie);
response.text(myCookie);
}
@PostRoute("/params/vo")
public void voParam(@Param User user, Response response) {
log.info("user as voParam: " + user.toString());
response.html(user.toString() + "<br/><br/><a href='/'>Back</a>");
}
} | repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\ParameterInjectionExampleController.java | 1 |
请完成以下Spring Boot application配置 | # datasource config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot3_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datas | ource.username=root
spring.datasource.password=
mybatis.mapper-locations=classpath:mapper/*Dao.xml | repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-mybatis\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public StockQtyAndUOMQty computeQtysDelivered()
{
final StockQtyAndUOMQty qtysDelivered;
if (soTrx.isSales())
{
qtysDelivered = deliveredData.getShipmentData().computeInvoicableQtyDelivered(invoicableQtyBasedOn);
}
else
{
qtysDelivered = deliveredData.getReceiptData().getQtysTotal(invoicableQtyBasedOn);
}
return qtysDelivered;
}
@lombok.Value
public static class ToInvoiceExclOverride
{
enum InvoicedQtys
{
SUBTRACTED, NOT_SUBTRACTED
}
InvoicedQtys invoicedQtys; | /**
* Excluding possible receipt quantities with quality issues
*/
StockQtyAndUOMQty qtysRaw;
/**
* Computed including possible receipt quality issues, not overridden by a possible qtyToInvoice override.
*/
StockQtyAndUOMQty qtysCalc;
private ToInvoiceExclOverride(
@NonNull final InvoicedQtys invoicedQtys,
@NonNull final StockQtyAndUOMQty qtysRaw,
@NonNull final StockQtyAndUOMQty qtysCalc)
{
this.qtysRaw = qtysRaw;
this.qtysCalc = qtysCalc;
this.invoicedQtys = invoicedQtys;
StockQtyAndUOMQtys.assumeCommonProductAndUom(qtysRaw, qtysCalc);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoiceCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringController {
@GetMapping("/")
public String getIndex() {
return "comparison/index";
}
@GetMapping("/login")
public String showLoginPage() {
return "comparison/login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("error", "Invalid Credentials");
return "comparison/login";
}
@PostMapping("/login")
public String doLogin(HttpServletRequest req) {
return "redirect:/home";
}
@GetMapping("/home")
public String showHomePage(HttpServletRequest req, Model model) {
addUserAttributes(model);
return "comparison/home";
}
@GetMapping("/admin")
public String adminOnly(HttpServletRequest req, Model model) {
addUserAttributes(model);
model.addAttribute("adminContent", "only admin can view this"); | return "comparison/home";
}
private void addUserAttributes(Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null && !auth.getClass()
.equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
model.addAttribute("username", user.getUsername());
Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority()
.contains("USER")) {
model.addAttribute("role", "USER");
model.addAttribute("permission", "READ");
} else if (authority.getAuthority()
.contains("ADMIN")) {
model.addAttribute("role", "ADMIN");
model.addAttribute("permission", "READ WRITE");
}
}
}
}
} | repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\springsecurity\web\SpringController.java | 2 |
请完成以下Java代码 | public void setP_Number (BigDecimal P_Number)
{
set_Value (COLUMNNAME_P_Number, P_Number);
}
/** Get Process Number.
@return Process Parameter
*/
public BigDecimal getP_Number ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Process Number To.
@param P_Number_To
Process Parameter
*/
public void setP_Number_To (BigDecimal P_Number_To)
{
set_Value (COLUMNNAME_P_Number_To, P_Number_To);
}
/** Get Process Number To.
@return Process Parameter
*/
public BigDecimal getP_Number_To ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_P_Number_To);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Process String.
@param P_String
Process Parameter
*/
public void setP_String (String P_String)
{
set_Value (COLUMNNAME_P_String, P_String);
}
/** Get Process String.
@return Process Parameter
*/
public String getP_String ()
{
return (String)get_Value(COLUMNNAME_P_String);
}
/** Set Process String To.
@param P_String_To
Process Parameter
*/ | public void setP_String_To (String P_String_To)
{
set_Value (COLUMNNAME_P_String_To, P_String_To);
}
/** Get Process String To.
@return Process Parameter
*/
public String getP_String_To ()
{
return (String)get_Value(COLUMNNAME_P_String_To);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Para.java | 1 |
请完成以下Java代码 | public static ExternalSystemAlbertaConfigId ofRepoId(final int repoId)
{
return new ExternalSystemAlbertaConfigId(repoId);
}
@Nullable
public static ExternalSystemAlbertaConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ExternalSystemAlbertaConfigId(repoId) : null;
}
public static ExternalSystemAlbertaConfigId cast(@NonNull final IExternalSystemChildConfigId id)
{
return (ExternalSystemAlbertaConfigId)id;
}
@JsonValue
public int toJson() | {
return getRepoId();
}
private ExternalSystemAlbertaConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_Alberta_ID");
}
@Override
public ExternalSystemType getType()
{
return ExternalSystemType.Alberta;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\alberta\ExternalSystemAlbertaConfigId.java | 1 |
请完成以下Java代码 | public class StringDataEntry extends BasicKvEntry {
private static final long serialVersionUID = 1L;
private final String value;
public StringDataEntry(String key, String value) {
super(key);
this.value = value;
}
@Override
public DataType getDataType() {
return DataType.STRING;
}
@Override
public Optional<String> getStrValue() {
return Optional.ofNullable(value);
}
@Override
public Object getValue() {
return value;
}
@Override | public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StringDataEntry))
return false;
if (!super.equals(o))
return false;
StringDataEntry that = (StringDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "StringDataEntry{" + "value='" + value + '\'' + "} " + super.toString();
}
@Override
public String getValueAsString() {
return value;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\StringDataEntry.java | 1 |
请完成以下Java代码 | public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
public String getTaskIdVariableName() {
return taskIdVariableName;
}
public void setTaskIdVariableName(String taskIdVariableName) {
this.taskIdVariableName = taskIdVariableName;
}
public String getTaskCompleterVariableName() {
return taskCompleterVariableName;
}
public void setTaskCompleterVariableName(String taskCompleterVariableName) {
this.taskCompleterVariableName = taskCompleterVariableName;
}
@Override
public UserTask clone() {
UserTask clone = new UserTask();
clone.setValues(this);
return clone;
}
public void setValues(UserTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression()); | setValidateFormFields(otherElement.getValidateFormFields());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks);
formProperties = new ArrayList<>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (FlowableListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\UserTask.java | 1 |
请完成以下Java代码 | public @Nullable ConnectionFactory getTargetConnectionFactory(Object key) {
return this.targetConnectionFactories.get(key);
}
/**
* Specify whether to apply a validation enforcing all {@link ConnectionFactory#isPublisherConfirms()} and
* {@link ConnectionFactory#isPublisherReturns()} have a consistent value.
* <p>
* A consistent value means that all ConnectionFactories must have the same value between all
* {@link ConnectionFactory#isPublisherConfirms()} and the same value between all
* {@link ConnectionFactory#isPublisherReturns()}.
* </p>
* <p>
* Note that in any case the values between {@link ConnectionFactory#isPublisherConfirms()} and
* {@link ConnectionFactory#isPublisherReturns()} don't need to be equals between each other.
* </p>
* @param consistentConfirmsReturns true to validate, false to not validate.
* @since 2.4.4
*/
public void setConsistentConfirmsReturns(boolean consistentConfirmsReturns) {
this.consistentConfirmsReturns = consistentConfirmsReturns;
}
/**
* Adds the given {@link ConnectionFactory} and associates it with the given lookup key.
* @param key the lookup key.
* @param connectionFactory the {@link ConnectionFactory}.
*/
protected void addTargetConnectionFactory(Object key, ConnectionFactory connectionFactory) {
this.targetConnectionFactories.put(key, connectionFactory);
for (ConnectionListener listener : this.connectionListeners) {
connectionFactory.addConnectionListener(listener);
} | checkConfirmsAndReturns(connectionFactory);
}
/**
* Removes the {@link ConnectionFactory} associated with the given lookup key and returns it.
* @param key the lookup key
* @return the {@link ConnectionFactory} that was removed
*/
protected ConnectionFactory removeTargetConnectionFactory(Object key) {
return this.targetConnectionFactories.remove(key);
}
/**
* Determine the current lookup key. This will typically be implemented to check a thread-bound context.
*
* @return The lookup key.
*/
protected abstract @Nullable Object determineCurrentLookupKey();
@Override
public void destroy() {
resetConnection();
}
@Override
public void resetConnection() {
this.targetConnectionFactories.values().forEach(ConnectionFactory::resetConnection);
if (this.defaultTargetConnectionFactory != null) {
this.defaultTargetConnectionFactory.resetConnection();
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\AbstractRoutingConnectionFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LanguageKey
{
@Nullable
public static LanguageKey ofNullableString(@Nullable final String languageInfo)
{
return languageInfo != null && !languageInfo.isBlank()
? ofString(languageInfo)
: null;
}
public static Optional<LanguageKey> optionalOfNullableString(@Nullable final String languageInfo)
{
return Optional.ofNullable(ofNullableString(languageInfo));
}
@JsonCreator
public static LanguageKey ofString(@NonNull final String languageInfo)
{
final String separator = languageInfo.contains("-") ? "-" : "_";
final String[] localeParts = languageInfo.trim().split(separator);
if (localeParts.length == 0)
{
// shall not happen
throw new IllegalArgumentException("Invalid languageInfo: " + languageInfo);
}
else if (localeParts.length == 1)
{
final String language = localeParts[0];
final String country = "";
final String variant = "";
return new LanguageKey(language, country, variant);
}
else if (localeParts.length == 2)
{
final String language = localeParts[0];
final String country = localeParts[1];
final String variant = "";
return new LanguageKey(language, country, variant);
}
else
// if (localeParts.length >= 3)
{
final String language = localeParts[0];
final String country = localeParts[1];
final String variant = localeParts[2];
return new LanguageKey(language, country, variant);
}
}
public static LanguageKey ofLocale(@NonNull final Locale locale)
{
return new LanguageKey(locale.getLanguage(), locale.getCountry(), locale.getVariant());
}
public static LanguageKey getDefault()
{
return ofLocale(Locale.getDefault());
}
@NonNull
String language;
@NonNull
String country; | @NonNull
String variant;
public Locale toLocale()
{
return new Locale(language, country, variant);
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
final StringBuilder sb = new StringBuilder();
sb.append(language);
if (!country.isBlank())
{
sb.append("_").append(country);
}
if (!variant.isBlank())
{
sb.append("_").append(variant);
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\LanguageKey.java | 2 |
请完成以下Java代码 | public boolean isCopyVariablesToProperties() {
return copyVariablesToProperties;
}
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
this.copyVariablesToProperties = copyVariablesToProperties;
}
public boolean isCopyCamelBodyToBody() {
return copyCamelBodyToBody;
}
public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
this.copyCamelBodyToBody = copyCamelBodyToBody;
}
public boolean isCopyVariablesToBodyAsMap() {
return copyVariablesToBodyAsMap;
}
public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
}
public String getCopyVariablesFromProperties() {
return copyVariablesFromProperties;
}
public void setCopyVariablesFromProperties(String copyVariablesFromProperties) {
this.copyVariablesFromProperties = copyVariablesFromProperties;
}
public String getCopyVariablesFromHeader() {
return copyVariablesFromHeader;
}
public void setCopyVariablesFromHeader(String copyVariablesFromHeader) {
this.copyVariablesFromHeader = copyVariablesFromHeader;
}
public boolean isCopyCamelBodyToBodyAsString() {
return copyCamelBodyToBodyAsString;
}
public void setCopyCamelBodyToBodyAsString(boolean copyCamelBodyToBodyAsString) { | this.copyCamelBodyToBodyAsString = copyCamelBodyToBodyAsString;
}
public boolean isSetProcessInitiator() {
return StringUtils.isNotEmpty(getProcessInitiatorHeaderName());
}
public Map<String, Object> getReturnVarMap() {
return returnVarMap;
}
public void setReturnVarMap(Map<String, Object> returnVarMap) {
this.returnVarMap = returnVarMap;
}
public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName;
}
public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName;
}
@Override
public boolean isLenientProperties() {
return true;
}
public long getTimeout() {
return timeout;
}
public int getTimeResolution() {
return timeResolution;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java | 1 |
请完成以下Java代码 | public void addToCurrentQtyAndCumulate(
@NonNull final Quantity qtyToAdd,
@NonNull final CostAmount amt)
{
currentQty = currentQty.add(qtyToAdd).toZeroIfNegative();
addCumulatedAmtAndQty(amt, qtyToAdd);
}
public void addToCurrentQtyAndCumulate(@NonNull final CostAmountAndQty amtAndQty)
{
addToCurrentQtyAndCumulate(amtAndQty.getQty(), amtAndQty.getAmt());
}
public void setCostPrice(@NonNull final CostPrice costPrice)
{
this.costPrice = costPrice;
}
public void setOwnCostPrice(@NonNull final CostAmount ownCostPrice) | {
setCostPrice(getCostPrice().withOwnCostPrice(ownCostPrice));
}
public void clearOwnCostPrice()
{
setCostPrice(getCostPrice().withZeroOwnCostPrice());
}
public void addToOwnCostPrice(@NonNull final CostAmount ownCostPriceToAdd)
{
setCostPrice(getCostPrice().addToOwnCostPrice(ownCostPriceToAdd));
}
public void clearComponentsCostPrice()
{
setCostPrice(getCostPrice().withZeroComponentsCostPrice());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CurrentCost.java | 1 |
请完成以下Java代码 | public void setPP_Order_Report_ID (int PP_Order_Report_ID)
{
if (PP_Order_Report_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Report_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Report_ID, Integer.valueOf(PP_Order_Report_ID));
}
/** Get Summary the results of manufacturing.
@return Summary the results of manufacturing */
@Override
public int getPP_Order_Report_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Report_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ProductionMaterialType AD_Reference_ID=540506
* Reference name: PP_Order_Report_ProductionMaterialType
*/
public static final int PRODUCTIONMATERIALTYPE_AD_Reference_ID=540506;
/** RawMaterial = R */
public static final String PRODUCTIONMATERIALTYPE_RawMaterial = "R";
/** ProducedMaterial = P */
public static final String PRODUCTIONMATERIALTYPE_ProducedMaterial = "P";
/** ProducedMaterial = S */
public static final String PRODUCTIONMATERIALTYPE_Scrap = "S";
/** Set Production Material Type.
@param ProductionMaterialType Production Material Type */
@Override
public void setProductionMaterialType (java.lang.String ProductionMaterialType)
{
set_Value (COLUMNNAME_ProductionMaterialType, ProductionMaterialType);
}
/** Get Production Material Type.
@return Production Material Type */
@Override
public java.lang.String getProductionMaterialType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductionMaterialType);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty) | {
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set VariantGroup.
@param VariantGroup VariantGroup */
@Override
public void setVariantGroup (java.lang.String VariantGroup)
{
set_Value (COLUMNNAME_VariantGroup, VariantGroup);
}
/** Get VariantGroup.
@return VariantGroup */
@Override
public java.lang.String getVariantGroup ()
{
return (java.lang.String)get_Value(COLUMNNAME_VariantGroup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Report.java | 1 |
请完成以下Java代码 | private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) {
return role;
}
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
} | @Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java | 1 |
请完成以下Java代码 | public ServerTransportConfig getTransportConfig() {
return transportConfig;
}
public ClusterServerModifyRequest setTransportConfig(
ServerTransportConfig transportConfig) {
this.transportConfig = transportConfig;
return this;
}
public Set<String> getNamespaceSet() {
return namespaceSet;
}
public ClusterServerModifyRequest setNamespaceSet(Set<String> namespaceSet) {
this.namespaceSet = namespaceSet; | return this;
}
@Override
public String toString() {
return "ClusterServerModifyRequest{" +
"app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", mode=" + mode +
", flowConfig=" + flowConfig +
", transportConfig=" + transportConfig +
", namespaceSet=" + namespaceSet +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterServerModifyRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PCMContentSourceLocalFile
{
private static final AdMessageKey MSG_DUPLICATE_FILE_LOOKUP_DETAILS = AdMessageKey.of("ExternalSystemConfigPCMDuplicateFileLookupDetails");
@NonNull
String rootLocation;
@NonNull
String processedDirectory;
@NonNull
String erroredDirectory;
@NonNull
Duration pollingFrequency;
// bpartner
@Nullable
String fileNamePatternBPartner;
// product
@Nullable
String fileNamePatternProduct;
// warehouse
@Nullable
String fileNamePatternWarehouse;
// purchase order
@Nullable
String fileNamePatternPurchaseOrder;
@NonNull
public BooleanWithReason isStartServicePossible(
@NonNull final PCMExternalRequest pcmExternalRequest,
@NonNull final ExternalSystemParentConfigId parentId,
@NonNull final IMsgBL msgBL)
{
if (!pcmExternalRequest.isStartService())
{
return BooleanWithReason.TRUE;
}
final ImmutableMap<PCMExternalRequest, String> request2LookupInfo = getLookupInfoByExternalRequest();
final String targetLookupInfo = Optional.ofNullable(request2LookupInfo.get(pcmExternalRequest))
.orElseThrow(() -> new AdempiereException("Unexpected pcmExternalRequest=" + pcmExternalRequest.getCode())); | final boolean isFileLookupInfoDuplicated = CollectionUtils.hasDuplicatesForValue(request2LookupInfo.values(), targetLookupInfo);
if (isFileLookupInfoDuplicated)
{
final ITranslatableString duplicateFileLookupInfoErrorMsg = msgBL.getTranslatableMsgText(MSG_DUPLICATE_FILE_LOOKUP_DETAILS,
pcmExternalRequest.getCode(),
parentId.getRepoId());
return BooleanWithReason.falseBecause(duplicateFileLookupInfoErrorMsg);
}
return BooleanWithReason.TRUE;
}
@NonNull
private ImmutableMap<PCMExternalRequest, String> getLookupInfoByExternalRequest()
{
return ImmutableMap.of(
PCMExternalRequest.START_PRODUCT_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternProduct),
PCMExternalRequest.START_BPARTNER_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternBPartner),
PCMExternalRequest.START_WAREHOUSE_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternWarehouse),
PCMExternalRequest.START_PURCHASE_ORDER_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternPurchaseOrder)
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\pcm\source\PCMContentSourceLocalFile.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Student {
@Id
private long id;
private String name;
@ElementCollection
private List<String> tags = new ArrayList<>();
@ElementCollection
private List<SkillTag> skillTags = new ArrayList<>();
@ElementCollection
private List<KVTag> kvTags = new ArrayList<>();
public Student() {
}
public Student(long id, String name) {
super();
this.id = id;
this.name = name;
}
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 List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags.addAll(tags);
}
public List<SkillTag> getSkillTags() {
return skillTags;
}
public void setSkillTags(List<SkillTag> skillTags) {
this.skillTags.addAll(skillTags);
}
public List<KVTag> getKVTags() {
return this.kvTags;
}
public void setKVTags(List<KVTag> kvTags) {
this.kvTags.addAll(kvTags);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-filtering\src\main\java\com\baeldung\inmemory\persistence\model\Student.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CounterController {
public static final String INDEX_TEMPLATE_VIEW_NAME = "index";
private final Set<String> sessionIds = Collections.synchronizedSet(new HashSet<>());
@GetMapping("/")
@ResponseBody
public String home() {
return format("HTTP Session Caching Example");
}
@GetMapping("/ping")
@ResponseBody
public String ping() {
return format("PONG");
}
@GetMapping("/session")
public ModelAndView sessionRequestCounts(HttpSession session) {
this.sessionIds.add(session.getId());
Map<String, Object> model = new HashMap<>();
model.put("sessionType", session.getClass().getName());
model.put("sessionCount", this.sessionIds.size());
model.put("requestCount", getRequestCount(session)); | return new ModelAndView(INDEX_TEMPLATE_VIEW_NAME, model);
}
private Object getRequestCount(HttpSession session) {
Integer requestCount = (Integer) session.getAttribute("requestCount");
requestCount = requestCount != null ? requestCount : 0;
requestCount++;
session.setAttribute("requestCount", requestCount);
return requestCount;
}
private String format(String value) {
return String.format("<h1>%s</h1>", value);
}
}
//end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\http-session\src\main\java\example\app\caching\session\http\controller\CounterController.java | 2 |
请完成以下Java代码 | public List<ReportEntry2> getNtry() {
if (ntry == null) {
ntry = new ArrayList<ReportEntry2>();
}
return this.ntry;
}
/**
* Gets the value of the addtlStmtInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlStmtInf() { | return addtlStmtInf;
}
/**
* Sets the value of the addtlStmtInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlStmtInf(String value) {
this.addtlStmtInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AccountStatement2.java | 1 |
请完成以下Java代码 | public class ListAndSetApproach<E> {
private final List<E> list;
private final Set<E> set;
public ListAndSetApproach() {
this.list = new ArrayList<>();
this.set = new HashSet<>();
}
public boolean add(E element) {
if (set.add(element)) {
list.add(element);
return true;
}
return false;
}
public boolean remove(E element) {
if (set.remove(element)) {
list.remove(element);
return true;
}
return false;
}
public int indexOf(E element) {
return list.indexOf(element);
}
public E get(int index) {
return list.get(index);
}
public boolean contains(E element) {
return set.contains(element); | }
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void clear() {
list.clear();
set.clear();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\ListAndSetApproach.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_QualityInsp_LagerKonf_AdditionalFee_ID (final int M_QualityInsp_LagerKonf_AdditionalFee_ID)
{
if (M_QualityInsp_LagerKonf_AdditionalFee_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID, M_QualityInsp_LagerKonf_AdditionalFee_ID);
}
@Override
public int getM_QualityInsp_LagerKonf_AdditionalFee_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID);
}
@Override
public I_M_QualityInsp_LagerKonf_Version getM_QualityInsp_LagerKonf_Version()
{
return get_ValueAsPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class);
}
@Override
public void setM_QualityInsp_LagerKonf_Version(final I_M_QualityInsp_LagerKonf_Version M_QualityInsp_LagerKonf_Version)
{
set_ValueFromPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class, M_QualityInsp_LagerKonf_Version);
}
@Override
public void setM_QualityInsp_LagerKonf_Version_ID (final int M_QualityInsp_LagerKonf_Version_ID)
{
if (M_QualityInsp_LagerKonf_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, null);
else | set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, M_QualityInsp_LagerKonf_Version_ID);
}
@Override
public int getM_QualityInsp_LagerKonf_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_AdditionalFee.java | 1 |
请完成以下Java代码 | public void setOperation (String Operation)
{
set_Value (COLUMNNAME_Operation, Operation);
}
/** Get Operation.
@return Compare Operation
*/
public String getOperation ()
{
return (String)get_Value(COLUMNNAME_Operation);
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo | Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionDistribution.java | 1 |
请完成以下Java代码 | public ActiveOrHistoricCurrencyAndAmount getTtlTaxAmt() {
return ttlTaxAmt;
}
/**
* Sets the value of the ttlTaxAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlTaxAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlTaxAmt = value;
}
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDt(XMLGregorianCalendar value) {
this.dt = value;
}
/**
* Gets the value of the seqNb property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSeqNb() {
return seqNb;
}
/**
* Sets the value of the seqNb property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSeqNb(BigDecimal value) {
this.seqNb = value; | }
/**
* Gets the value of the rcrd property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rcrd property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRcrd().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TaxRecord1 }
*
*
*/
public List<TaxRecord1> getRcrd() {
if (rcrd == null) {
rcrd = new ArrayList<TaxRecord1>();
}
return this.rcrd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxInformation3.java | 1 |
请完成以下Java代码 | public CaseInstanceStartEventSubscriptionBuilder addCorrelationParameterValues(Map<String, Object> parameters) {
correlationParameterValues.putAll(parameters);
return this;
}
@Override
public CaseInstanceStartEventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
}
public boolean isDoNotUpdateToLatestVersionAutomatically() {
return doNotUpdateToLatestVersionAutomatically;
}
public String getTenantId() {
return tenantId;
}
@Override
public EventSubscription subscribe() { | checkValidInformation();
return cmmnRuntimeService.registerCaseInstanceStartEventSubscription(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(caseDefinitionKey)) {
throw new FlowableIllegalArgumentException("The case definition must be provided using the key for the subscription to be registered.");
}
if (correlationParameterValues.isEmpty()) {
throw new FlowableIllegalArgumentException(
"At least one correlation parameter value must be provided for a dynamic case start event subscription, "
+ "otherwise the case would get started on all events, regardless their correlation parameter values.");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionBuilderImpl.java | 1 |
请完成以下Java代码 | public String getLogFileDatePattern()
{
return logFileDatePattern;
}
private final void updateFileNamePattern()
{
final StringBuilder fileNamePatternBuilder = new StringBuilder();
final String logDir = getLogDir();
if (!Check.isEmpty(logDir, true))
{
fileNamePatternBuilder.append(logDir);
if (!logDir.endsWith("\\") && !logDir.endsWith("/"))
{
fileNamePatternBuilder.append(File.separator);
}
}
final String logFilePrefix = getLogFilePrefix();
fileNamePatternBuilder.append(logFilePrefix);
if (!Check.isEmpty(logFilePrefix))
{
fileNamePatternBuilder.append(".");
}
fileNamePatternBuilder.append(getLogFileDatePattern());
fileNamePatternBuilder.append(logFileSuffix);
final String fileNamePattern = fileNamePatternBuilder.toString();
super.setFileNamePattern(fileNamePattern);
// System.out.println("Using FileNamePattern: " + fileNamePattern);
}
@Override
public void setFileNamePattern(final String fnp)
{
throw new UnsupportedOperationException("Setting FileNamePattern directly is not allowed");
}
public File getLogDirAsFile()
{
if (logDir == null)
{
return null;
}
return new File(logDir);
}
public File getActiveFileOrNull()
{
try
{
final String filename = getActiveFileName();
if (filename == null)
{
return null;
}
final File file = new File(filename).getAbsoluteFile();
return file;
}
catch (Exception e)
{
addError("Failed fetching active file name", e);
return null; | }
}
public List<File> getLogFiles()
{
final File logDir = getLogDirAsFile();
if (logDir != null && logDir.isDirectory())
{
final File[] logs = logDir.listFiles(logFileNameFilter);
for (int i = 0; i < logs.length; i++)
{
try
{
logs[i] = logs[i].getCanonicalFile();
}
catch (Exception e)
{
}
}
return ImmutableList.copyOf(logs);
}
return ImmutableList.of();
}
public void flush()
{
// TODO
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshTimeBasedRollingPolicy.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionVersionTag() {
return subscriptionConfiguration.getProcessDefinitionVersionTag();
}
@Override
public Map<String, Object> getProcessVariables() {
return subscriptionConfiguration.getProcessVariables();
}
@Override
public boolean isWithoutTenantId() {
return subscriptionConfiguration.getWithoutTenantId();
}
@Override
public List<String> getTenantIdIn() { | return subscriptionConfiguration.getTenantIdIn();
}
@Override
public boolean isIncludeExtensionProperties() {
return subscriptionConfiguration.getIncludeExtensionProperties();
}
protected String[] toArray(List<String> list) {
return list.toArray(new String[0]);
}
@Override
public void afterPropertiesSet() throws Exception {
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SpringTopicSubscriptionImpl.java | 1 |
请完成以下Java代码 | public Object getRawEvent() {
return consumerRecord;
}
@Override
public Object getBody() {
return consumerRecord.value();
}
@Override
public Map<String, Object> getHeaders() {
if (headers == null) {
headers = retrieveHeaders();
}
return headers;
}
@SuppressWarnings("unchecked")
protected Map<String, Object> retrieveHeaders() {
Map<String, Object> headers = new HashMap<>();
Headers consumerRecordHeaders = consumerRecord.headers(); | for (Header consumerRecordHeader : consumerRecordHeaders) {
headers.put(consumerRecordHeader.key(), consumerRecordHeader.value());
}
return headers;
}
@Override
public String toString() {
return "KafkaConsumerRecordInboundEvent{" +
"consumerRecord=" + consumerRecord +
", headers=" + headers +
'}';
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\KafkaConsumerRecordInboundEvent.java | 1 |
请完成以下Java代码 | public List<CommentData> findByArticleId(String articleId, User user) {
List<CommentData> comments = commentReadService.findByArticleId(articleId);
if (comments.size() > 0 && user != null) {
Set<String> followingAuthors =
userRelationshipQueryService.followingAuthors(
user.getId(),
comments.stream()
.map(commentData -> commentData.getProfileData().getId())
.collect(Collectors.toList()));
comments.forEach(
commentData -> {
if (followingAuthors.contains(commentData.getProfileData().getId())) {
commentData.getProfileData().setFollowing(true);
}
});
}
return comments;
}
public CursorPager<CommentData> findByArticleIdWithCursor(
String articleId, User user, CursorPageParameter<DateTime> page) {
List<CommentData> comments = commentReadService.findByArticleIdWithCursor(articleId, page);
if (comments.isEmpty()) {
return new CursorPager<>(new ArrayList<>(), page.getDirection(), false);
}
if (user != null) { | Set<String> followingAuthors =
userRelationshipQueryService.followingAuthors(
user.getId(),
comments.stream()
.map(commentData -> commentData.getProfileData().getId())
.collect(Collectors.toList()));
comments.forEach(
commentData -> {
if (followingAuthors.contains(commentData.getProfileData().getId())) {
commentData.getProfileData().setFollowing(true);
}
});
}
boolean hasExtra = comments.size() > page.getLimit();
if (hasExtra) {
comments.remove(page.getLimit());
}
if (!page.isNext()) {
Collections.reverse(comments);
}
return new CursorPager<>(comments, page.getDirection(), hasExtra);
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\CommentQueryService.java | 1 |
请完成以下Java代码 | public boolean isParentDocumentProcessed()
{
return parentDocument.isProcessed();
}
@Override
public boolean isParentDocumentActive()
{
return parentDocument.isActive();
}
@Override
public boolean isParentDocumentNew()
{
return parentDocument.isNew();
}
@Override
public boolean isParentDocumentInvalid()
{
return !parentDocument.getValidStatus().isValid();
}
@Override
public Collection<Document> getIncludedDocuments() | {
return getChangedDocuments();
}
@Override
public Evaluatee toEvaluatee()
{
return parentDocument.asEvaluatee();
}
@Override
public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | public void setTotalOpenBalance (final BigDecimal TotalOpenBalance)
{
set_Value (COLUMNNAME_TotalOpenBalance, TotalOpenBalance);
}
/** Get Offener Saldo.
@return Gesamt der offenen Beträge in primärer Buchführungswährung
*/
@Override
public BigDecimal getTotalOpenBalance ()
{
final BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalOpenBalance);
if (bd == null)
{
return BigDecimal.ZERO;
}
return bd;
}
/** Set V_BPartnerCockpit_ID.
@param V_BPartnerCockpit_ID V_BPartnerCockpit_ID */
@Override
public void setV_BPartnerCockpit_ID (final int V_BPartnerCockpit_ID)
{
if (V_BPartnerCockpit_ID < 1)
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, null);
}
else
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, Integer.valueOf(V_BPartnerCockpit_ID));
}
}
/** Get V_BPartnerCockpit_ID.
@return V_BPartnerCockpit_ID */
@Override
public int getV_BPartnerCockpit_ID ()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_V_BPartnerCockpit_ID);
if (ii == null)
{ | return 0;
}
return ii.intValue();
}
/** Set Suchschlüssel.
@param value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setvalue (final java.lang.String value)
{
set_Value (COLUMNNAME_value, value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getvalue ()
{
return (java.lang.String)get_Value(COLUMNNAME_value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_V_BPartnerCockpit.java | 1 |
请完成以下Java代码 | protected void setC_Activity_ID(final I_C_Invoice_Candidate invoiceCandidate)
{
final ActivityId activityId = productAcctDAO.retrieveActivityForAcct(
ClientId.ofRepoId(invoiceCandidate.getAD_Client_ID()),
OrgId.ofRepoId(invoiceCandidate.getAD_Org_ID()),
ProductId.ofRepoId(invoiceCandidate.getM_Product_ID()));
invoiceCandidate.setC_Activity_ID(ActivityId.toRepoId(activityId));
}
@VisibleForTesting
protected void setC_Tax_ID(final I_C_Invoice_Candidate ic, final IPricingResult pricingResult, final Timestamp date)
{
final IContextAware contextProvider = getContext();
final TaxCategoryId taxCategoryId = pricingResult.getTaxCategoryId(); | // TODO: we should use shipPartnerLocation
final BPartnerLocationAndCaptureId billToLocation = InvoiceCandidateLocationAdapterFactory
.billLocationAdapter(ic)
.getBPartnerLocationAndCaptureId();
final TaxId taxID = taxBL.getTaxNotNull(
ic,
taxCategoryId,
ic.getM_Product_ID(),
date, // ship date
OrgId.ofRepoId(ic.getAD_Org_ID()),
(WarehouseId)null,
billToLocation, // shipPartnerLocation TODO
SOTrx.PURCHASE);
ic.setC_Tax_ID(taxID.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\InvoiceCandidateWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getBrandLogoUrl() {
return brandLogoUrl;
}
public void setBrandLogoUrl(String brandLogoUrl) {
this.brandLogoUrl = brandLogoUrl;
} | public UserEntity getCompanyEntity() {
return companyEntity;
}
public void setCompanyEntity(UserEntity companyEntity) {
this.companyEntity = companyEntity;
}
@Override
public String toString() {
return "BrandEntity{" +
"id='" + id + '\'' +
", brand='" + brand + '\'' +
", brandLogo=" + brandLogoUrl +
", companyEntity=" + companyEntity +
", sort=" + sort +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\BrandEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private ReportResult exportAsJasperPrint(final JasperPrint jasperPrint) throws IOException
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(jasperPrint);
return ReportResult.builder()
.outputType(OutputType.JasperPrint)
.reportFilename(buildReportFilename(jasperPrint, OutputType.JasperPrint))
.reportContentBase64(Util.encodeBase64(out.toByteArray()))
.build();
}
private ReportResult exportAsExcel(final JasperPrint jasperPrint) throws JRException
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final MetasJRXlsExporter exporter = new MetasJRXlsExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out); // Output
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); // Input
// Make sure our cells will be locked by default
// and assume that cells which shall not be locked are particularly specified.
jasperPrint.setProperty(XlsReportConfiguration.PROPERTY_CELL_LOCKED, "true");
// there are cases when we don't want the cells to be blocked by password
// in those cases we put in jrxml the password property with empty value, which will indicate we don't want password
// if there is no such property we take default password. If empty we set no password and if set, we use that password from the report
//noinspection StatementWithEmptyBody | if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD) == null)
{
// do nothing;
}
else if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD).isEmpty())
{
exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, null);
}
else
{
exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD));
}
exporter.exportReport();
return ReportResult.builder()
.outputType(OutputType.XLS)
.reportContentBase64(Util.encodeBase64(out.toByteArray()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JasperEngine.java | 2 |
请完成以下Java代码 | private DeliveryOrderParcel updateDeliveryOrderLine(@NonNull final DeliveryOrderParcel line, @NonNull final JsonDeliveryResponseItem jsonDeliveryResponseItem)
{
final String awb = jsonDeliveryResponseItem.getAwb();
final byte[] labelData = Base64.getDecoder().decode(jsonDeliveryResponseItem.getLabelPdfBase64());
final String trackingUrl = jsonDeliveryResponseItem.getTrackingUrl();
return line.toBuilder()
.awb(awb)
.trackingUrl(trackingUrl)
.labelPdfBase64(labelData)
.build();
}
@NonNull
@Override
public List<PackageLabels> getPackageLabelsList(@NonNull final DeliveryOrder deliveryOrder) throws ShipperGatewayException
{
final String orderIdAsString = String.valueOf(deliveryOrder.getId());
return deliveryOrder.getDeliveryOrderParcels()
.stream()
.map(line -> createPackageLabel(line.getLabelPdfBase64(), line.getAwb(), orderIdAsString))
.collect(Collectors.toList());
}
@Override
public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request)
{
return shipAdvisorService.advise(request);
}
@NonNull
private static PackageLabels createPackageLabel(final byte[] labelData, @NonNull final String awb, @NonNull final String deliveryOrderIdAsString)
{
return PackageLabels.builder() | .orderId(OrderId.of(NShiftConstants.SHIPPER_GATEWAY_ID, deliveryOrderIdAsString))
.defaultLabelType(NShiftPackageLabelType.DEFAULT)
.label(PackageLabel.builder()
.type(NShiftPackageLabelType.DEFAULT)
.labelData(labelData)
.contentType(PackageLabel.CONTENTTYPE_PDF)
.fileName(awb)
.build())
.build();
}
public JsonShipperConfig getJsonShipperConfig()
{
return jsonConverter.toJsonShipperConfig(shipperConfig);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.nshift\src\main\java\de\metas\shipper\gateway\nshift\client\NShiftShipperGatewayClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setFormat(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, java.sql.Date date) throws IOException
{
if (date == null)
{
out.nullValue();
}
else
{
String value;
if (dateFormat != null)
{
value = dateFormat.format(date);
}
else
{
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException
{
switch (in.peek())
{
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try
{
if (dateFormat != null)
{
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
}
catch (ParseException e)
{
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type
* If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date>
{
private DateFormat dateFormat;
public DateTypeAdapter()
{
}
public DateTypeAdapter(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException
{
if (date == null)
{
out.nullValue();
}
else
{
String value;
if (dateFormat != null)
{
value = dateFormat.format(date);
}
else
{
value = ISO8601Utils.format(date, true);
}
out.value(value); | }
}
@Override
public Date read(JsonReader in) throws IOException
{
try
{
switch (in.peek())
{
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try
{
if (dateFormat != null)
{
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
}
catch (ParseException e)
{
throw new JsonParseException(e);
}
}
}
catch (IllegalArgumentException e)
{
throw new JsonParseException(e);
}
}
}
public JSON setDateFormat(DateFormat dateFormat)
{
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat)
{
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\invoker\JSON.java | 2 |
请完成以下Java代码 | static ClientHttpRequestFactoryBuilder<? extends ClientHttpRequestFactory> detect() {
return detect(null);
}
/**
* Detect the most suitable {@link ClientHttpRequestFactoryBuilder} based on the
* classpath. The method favors builders in the following order:
* <ol>
* <li>{@link #httpComponents()}</li>
* <li>{@link #jetty()}</li>
* <li>{@link #reactor()}</li>
* <li>{@link #jdk()}</li>
* <li>{@link #simple()}</li>
* </ol>
* @param classLoader the class loader to use for detection
* @return the most suitable {@link ClientHttpRequestFactoryBuilder} for the classpath
* @since 3.5.0
*/
static ClientHttpRequestFactoryBuilder<? extends ClientHttpRequestFactory> detect( | @Nullable ClassLoader classLoader) {
if (HttpComponentsClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return httpComponents();
}
if (JettyClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return jetty();
}
if (ReactorClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return reactor();
}
if (JdkClientHttpRequestFactoryBuilder.Classes.present(classLoader)) {
return jdk();
}
return simple();
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ClientHttpRequestFactoryBuilder.java | 1 |
请完成以下Java代码 | public void addOnPart(CmmnOnPartDeclaration onPart) {
CmmnActivity source = onPart.getSource();
if (source == null) {
// do nothing: ignore onPart
return;
}
String sourceId = source.getId();
List<CmmnOnPartDeclaration> onPartDeclarations = onPartMap.get(sourceId);
if (onPartDeclarations == null) {
onPartDeclarations = new ArrayList<CmmnOnPartDeclaration>();
onPartMap.put(sourceId, onPartDeclarations);
}
for (CmmnOnPartDeclaration onPartDeclaration : onPartDeclarations) {
if (onPart.getStandardEvent().equals(onPartDeclaration.getStandardEvent())) {
// if there already exists an onPartDeclaration which has the
// same defined standardEvent then ignore this onPartDeclaration.
if (onPartDeclaration.getSentry() == onPart.getSentry()) {
return;
}
// but merge the sentryRef into the already existing onPartDeclaration
if (onPartDeclaration.getSentry() == null && onPart.getSentry() != null) {
// According to the specification, when "sentryRef" is specified,
// "standardEvent" must have value "exit" (page 39, Table 23).
// But there is no further check necessary.
onPartDeclaration.setSentry(onPart.getSentry());
return;
}
}
}
onPartDeclarations.add(onPart);
onParts.add(onPart); | }
// variableOnParts
public void addVariableOnParts(CmmnVariableOnPartDeclaration variableOnPartDeclaration) {
variableOnParts.add(variableOnPartDeclaration);
}
public boolean hasVariableOnPart(String variableEventName, String variableName) {
for(CmmnVariableOnPartDeclaration variableOnPartDeclaration: variableOnParts) {
if(variableOnPartDeclaration.getVariableEvent().equals(variableEventName) &&
variableOnPartDeclaration.getVariableName().equals(variableName)) {
return true;
}
}
return false;
}
public List<CmmnVariableOnPartDeclaration> getVariableOnParts() {
return variableOnParts;
}
// ifPart //////////////////////////////////////////////////////////////////
public CmmnIfPartDeclaration getIfPart() {
return ifPart;
}
public void setIfPart(CmmnIfPartDeclaration ifPart) {
this.ifPart = ifPart;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnSentryDeclaration.java | 1 |
请完成以下Java代码 | protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
StartEvent startEvent = new StartEvent();
startEvent.setInitiator(getPropertyValueAsString(PROPERTY_NONE_STARTEVENT_INITIATOR, elementNode));
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_START_NONE.equals(stencilId)) {
String formKey = getPropertyValueAsString(PROPERTY_FORMKEY, elementNode);
if (StringUtils.isNotEmpty(formKey)) {
startEvent.setFormKey(formKey);
} else {
JsonNode formReferenceNode = getProperty(PROPERTY_FORM_REFERENCE, elementNode);
if (formReferenceNode != null && formReferenceNode.get("id") != null) {
if (formMap != null && formMap.containsKey(formReferenceNode.get("id").asText())) {
startEvent.setFormKey(formMap.get(formReferenceNode.get("id").asText()));
}
}
}
convertJsonToFormProperties(elementNode, startEvent);
} else if (STENCIL_EVENT_START_TIMER.equals(stencilId)) {
convertJsonToTimerDefinition(elementNode, startEvent);
} else if (STENCIL_EVENT_START_ERROR.equals(stencilId)) {
convertJsonToErrorDefinition(elementNode, startEvent);
} else if (STENCIL_EVENT_START_MESSAGE.equals(stencilId)) {
convertJsonToMessageDefinition(elementNode, startEvent); | } else if (STENCIL_EVENT_START_SIGNAL.equals(stencilId)) {
convertJsonToSignalDefinition(elementNode, startEvent);
}
return startEvent;
}
protected void addExtensionElement(String name, String elementText, Event event) {
ExtensionElement extensionElement = new ExtensionElement();
extensionElement.setNamespace(NAMESPACE);
extensionElement.setNamespacePrefix("modeler");
extensionElement.setName(name);
extensionElement.setElementText(elementText);
event.addExtensionElement(extensionElement);
}
@Override
public void setFormMap(Map<String, String> formMap) {
this.formMap = formMap;
}
@Override
public void setFormKeyMap(Map<String, ModelInfo> formKeyMap) {
this.formKeyMap = formKeyMap;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\StartEventJsonConverter.java | 1 |
请完成以下Java代码 | public final class AdminSettingsEntity extends BaseSqlEntity<AdminSettings> implements BaseEntity<AdminSettings> {
@Column(name = ModelConstants.ADMIN_SETTINGS_TENANT_ID_PROPERTY)
private UUID tenantId;
@Column(name = ADMIN_SETTINGS_KEY_PROPERTY)
private String key;
@Convert(converter = JsonConverter.class)
@Column(name = ADMIN_SETTINGS_JSON_VALUE_PROPERTY)
private JsonNode jsonValue;
public AdminSettingsEntity() {
super();
}
public AdminSettingsEntity(AdminSettings adminSettings) {
if (adminSettings.getId() != null) {
this.setUuid(adminSettings.getId().getId());
}
this.setCreatedTime(adminSettings.getCreatedTime()); | this.tenantId = adminSettings.getTenantId().getId();
this.key = adminSettings.getKey();
this.jsonValue = adminSettings.getJsonValue();
}
@Override
public AdminSettings toData() {
AdminSettings adminSettings = new AdminSettings(new AdminSettingsId(id));
adminSettings.setCreatedTime(createdTime);
adminSettings.setTenantId(TenantId.fromUUID(tenantId));
adminSettings.setKey(key);
adminSettings.setJsonValue(jsonValue);
return adminSettings;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AdminSettingsEntity.java | 1 |
请完成以下Java代码 | public static EAN13HUQRCode fromScannedCodeOrNullIfNotHandled(@NonNull final ScannedCode scannedCode)
{
return fromStringOrNullIfNotHandled(scannedCode.getAsString());
}
@Nullable
public static EAN13HUQRCode fromStringOrNullIfNotHandled(@NonNull final String barcode)
{
return fromString(barcode).orElse(null);
}
public static ExplainedOptional<EAN13HUQRCode> fromString(@NonNull final String barcode)
{
return EAN13.ofString(barcode).map(EAN13HUQRCode::ofEAN13);
}
@Override
@Deprecated
public String toString() {return getAsString();} | public ScannedCode toScannedCode() {return ScannedCode.ofString(getAsString());}
@Override
public String getAsString() {return ean13.getAsString();}
@Override
public Optional<BigDecimal> getWeightInKg() {return ean13.getWeightInKg();}
@Override
public Optional<LocalDate> getBestBeforeDate() {return Optional.empty();}
@Override
public Optional<String> getLotNumber() {return Optional.empty();}
@NonNull
public EAN13 unbox() {return ean13;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\ean13\EAN13HUQRCode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersonRepositoryService implements PersonService {
private PersonRepository repo;
@Autowired
public void setPersonRepository(PersonRepository repo) {
this.repo = repo;
}
public Optional<Person> findOne(String id) {
return repo.findById(id);
}
public List<Person> findAll() {
List<Person> people = new ArrayList<>();
Iterator<Person> it = repo.findAll().iterator();
while (it.hasNext()) {
people.add(it.next());
}
return people;
}
public List<Person> findByFirstName(String firstName) {
return repo.findByFirstName(firstName);
} | public List<Person> findByLastName(String lastName) {
return repo.findByLastName(lastName);
}
public void create(Person person) {
person.setCreated(DateTime.now());
repo.save(person);
}
public void update(Person person) {
person.setUpdated(DateTime.now());
repo.save(person);
}
public void delete(Person person) {
repo.delete(person);
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\PersonRepositoryService.java | 2 |
请完成以下Java代码 | public void setPA_SLA_Measure_ID (int PA_SLA_Measure_ID)
{
if (PA_SLA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, Integer.valueOf(PA_SLA_Measure_ID));
}
/** Get SLA Measure.
@return Service Level Agreement Measure
*/
public int getPA_SLA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing) | {
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Measure.java | 1 |
请完成以下Java代码 | protected Optional<HistoricPlanItemInstance> getPlanItemInstance(List<HistoricPlanItemInstance> planItemInstances, PlanItemDefinition planItemDefinition) {
HistoricPlanItemInstance planItemInstance = null;
for (HistoricPlanItemInstance p : planItemInstances) {
if (p.getPlanItemDefinitionId().equals(planItemDefinition.getId())) {
if (p.getEndedTime() == null) {
planItemInstance = p; // one that's not ended yet has precedence
} else if (planItemInstance == null) {
planItemInstance = p;
}
}
}
return Optional.ofNullable(planItemInstance);
}
protected class OverviewElement {
protected String id;
protected String name;
protected Integer displayOrder;
protected String includeInStageOverview;
protected PlanItemDefinition planItemDefinition;
public OverviewElement(String id, String name, Integer displayOrder, String includeInStageOverview, PlanItemDefinition planItemDefinition) {
this.id = id;
this.name = name;
this.displayOrder = displayOrder;
this.includeInStageOverview = includeInStageOverview;
this.planItemDefinition = planItemDefinition;
}
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 Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
}
public PlanItemDefinition getPlanItemDefinition() {
return planItemDefinition;
}
public void setPlanItemDefinition(PlanItemDefinition planItemDefinition) {
this.planItemDefinition = planItemDefinition;
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetHistoricStageOverviewCmd.java | 1 |
请完成以下Java代码 | public class PrintingSegment
{
private Integer pageFrom;
private Integer pageTo;
private final int initialPageFrom;
private final int initialPageTo;
@Getter
private final int lastPages;
private final String routingType;
@Getter
private final PrinterRoutingId printerRoutingId;
@Getter
private final HardwarePrinter printer;
@Getter
private final HardwareTrayId trayId;
@Getter
private final int copies;
@Builder
private PrintingSegment(
final int initialPageFrom,
final int initialPageTo,
final int lastPages,
@Nullable final String routingType,
@Nullable final PrinterRoutingId printerRoutingId,
@NonNull final HardwarePrinter printer,
@Nullable final HardwareTrayId trayId,
final int copies)
{
this.initialPageFrom = initialPageFrom;
this.initialPageTo = initialPageTo;
this.lastPages = lastPages;
this.routingType = routingType;
this.printerRoutingId = printerRoutingId;
this.printer = printer;
this.trayId = trayId;
this.copies = CoalesceUtil.firstGreaterThanZero(copies, 1);
Check.assume(initialPageFrom <= initialPageTo, "initialPageFrom={} is less or equal to initialPageTo={}", initialPageFrom, initialPageTo);
}
public void setPageFrom(final int pageFrom)
{ | this.pageFrom = pageFrom;
}
public int getPageFrom()
{
if (pageFrom != null)
{
return pageFrom;
}
return initialPageFrom;
}
public void setPageTo(final int pageTo)
{
this.pageTo = pageTo;
}
public int getPageTo()
{
if (pageTo != null)
{
return pageTo;
}
return initialPageTo;
}
public boolean isPageRange()
{
return I_AD_PrinterRouting.ROUTINGTYPE_PageRange.equals(routingType);
}
public boolean isLastPages()
{
return I_AD_PrinterRouting.ROUTINGTYPE_LastPages.equals(routingType);
}
public boolean isQueuedForExternalSystems()
{
return isMatchingOutputType(OutputType.Queue)
&& printer.getExternalSystemParentConfigId() != null;
}
public boolean isMatchingOutputType(@NonNull OutputType outputType)
{
return OutputType.equals(printer.getOutputType(), outputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingSegment.java | 1 |
请完成以下Java代码 | public String listUsers(Model model, UserForm userForm) {
model.addAttribute("userForm", userForm);
return "users";
}
/**
* An interface to represent the form to be used
*
* @author Oliver Gierke
*/
interface UserForm {
String getUsername();
String getPassword();
String getRepeatedPassword();
/**
* Validates the {@link UserForm}.
*
* @param errors
* @param userManagement
*/
default void validate(BindingResult errors, UserManagement userManagement) {
rejectIfEmptyOrWhitespace(errors, "username", "user.username.empty"); | rejectIfEmptyOrWhitespace(errors, "password", "user.password.empty");
rejectIfEmptyOrWhitespace(errors, "repeatedPassword", "user.repeatedPassword.empty");
if (!getPassword().equals(getRepeatedPassword())) {
errors.rejectValue("repeatedPassword", "user.password.no-match");
}
try {
userManagement.findByUsername(new Username(getUsername())).ifPresent(
user -> errors.rejectValue("username", "user.username.exists"));
} catch (IllegalArgumentException o_O) {
errors.rejectValue("username", "user.username.invalidFormat");
}
}
}
} | repos\spring-data-examples-main\web\example\src\main\java\example\users\web\UserController.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public BigDecimal getFullPrice() {
return fullPrice;
}
public void setFullPrice(BigDecimal fullPrice) {
this.fullPrice = fullPrice;
} | public BigDecimal getReducePrice() {
return reducePrice;
}
public void setReducePrice(BigDecimal reducePrice) {
this.reducePrice = reducePrice;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", fullPrice=").append(fullPrice);
sb.append(", reducePrice=").append(reducePrice);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductFullReduction.java | 1 |
请完成以下Java代码 | public void setPriority (final int Priority)
{
set_Value (COLUMNNAME_Priority, Priority);
}
@Override
public int getPriority()
{
return get_ValueAsInt(COLUMNNAME_Priority);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
} | @Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State
*/
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */
public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */
public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Activity.java | 1 |
请完成以下Java代码 | public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A)
{
set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A);
}
@Override
public void setPJ_Asset_Acct (final int PJ_Asset_Acct)
{
set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct);
}
@Override
public int getPJ_Asset_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_WIP_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override | public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A)
{
set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A);
}
@Override
public void setPJ_WIP_Acct (final int PJ_WIP_Acct)
{
set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct);
}
@Override
public int getPJ_WIP_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public R<List<MenuVO>> routes(BladeUser user, Long topMenuId) {
List<MenuVO> list = menuService.routes((user == null || user.getUserId() == 0L) ? null : user.getRoleId(), topMenuId);
return R.data(list);
}
/**
* 前端按钮数据
*/
@GetMapping("/buttons")
@ApiOperationSupport(order = 8)
@Operation(summary = "前端按钮数据", description = "前端按钮数据")
public R<List<MenuVO>> buttons(BladeUser user) {
List<MenuVO> list = menuService.buttons(user.getRoleId());
return R.data(list);
}
/**
* 获取菜单树形结构
*/
@GetMapping("/tree")
@ApiOperationSupport(order = 9)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<MenuVO>> tree() {
List<MenuVO> tree = menuService.tree();
return R.data(tree);
}
/**
* 获取权限分配树形结构
*/
@GetMapping("/grant-tree")
@ApiOperationSupport(order = 10)
@Operation(summary = "权限分配树形结构", description = "权限分配树形结构")
public R<GrantTreeVO> grantTree(BladeUser user) {
GrantTreeVO vo = new GrantTreeVO();
vo.setMenu(menuService.grantTree(user));
vo.setDataScope(menuService.grantDataScopeTree(user));
return R.data(vo);
}
/**
* 获取权限分配树形结构
*/
@GetMapping("/role-tree-keys")
@ApiOperationSupport(order = 11)
@Operation(summary = "角色所分配的树", description = "角色所分配的树")
public R<CheckedTreeVO> roleTreeKeys(String roleIds) {
CheckedTreeVO vo = new CheckedTreeVO();
vo.setMenu(menuService.roleTreeKeys(roleIds));
vo.setDataScope(menuService.dataScopeTreeKeys(roleIds));
return R.data(vo);
}
/**
* 获取配置的角色权限
*/
@GetMapping("auth-routes")
@ApiOperationSupport(order = 12)
@Operation(summary = "菜单的角色权限")
public R<List<Kv>> authRoutes(BladeUser user) {
if (Func.isEmpty(user) || user.getUserId() == 0L) {
return null;
}
return R.data(menuService.authRoutes(user));
}
/** | * 顶部菜单数据
*/
@GetMapping("/top-menu")
@ApiOperationSupport(order = 13)
@Operation(summary = "顶部菜单数据", description = "顶部菜单数据")
public R<List<TopMenu>> topMenu(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<TopMenu> list = topMenuService.list(Wrappers.<TopMenu>query().lambda().orderByAsc(TopMenu::getSort));
return R.data(list);
}
/**
* 获取顶部菜单树形结构
*/
@GetMapping("/grant-top-tree")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@ApiOperationSupport(order = 14)
@Operation(summary = "顶部菜单树形结构", description = "顶部菜单树形结构")
public R<GrantTreeVO> grantTopTree(BladeUser user) {
GrantTreeVO vo = new GrantTreeVO();
vo.setMenu(menuService.grantTopTree(user));
return R.data(vo);
}
/**
* 获取顶部菜单树形结构
*/
@GetMapping("/top-tree-keys")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@ApiOperationSupport(order = 15)
@Operation(summary = "顶部菜单所分配的树", description = "顶部菜单所分配的树")
public R<CheckedTreeVO> topTreeKeys(String topMenuIds) {
CheckedTreeVO vo = new CheckedTreeVO();
vo.setMenu(menuService.topTreeKeys(topMenuIds));
return R.data(vo);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\MenuController.java | 2 |
请完成以下Java代码 | public void setCSVFieldDelimiter (java.lang.String CSVFieldDelimiter)
{
set_Value (COLUMNNAME_CSVFieldDelimiter, CSVFieldDelimiter);
}
/** Get CSV Field Delimiter.
@return CSV Field Delimiter */
@Override
public java.lang.String getCSVFieldDelimiter ()
{
return (java.lang.String)get_Value(COLUMNNAME_CSVFieldDelimiter);
}
/** Set CSV Field Quote.
@param CSVFieldQuote CSV Field Quote */
@Override
public void setCSVFieldQuote (java.lang.String CSVFieldQuote)
{
set_Value (COLUMNNAME_CSVFieldQuote, CSVFieldQuote);
}
/** Get CSV Field Quote.
@return CSV Field Quote */
@Override
public java.lang.String getCSVFieldQuote ()
{
return (java.lang.String)get_Value(COLUMNNAME_CSVFieldQuote);
}
/** Set DATEV Export Format.
@param DATEV_ExportFormat_ID DATEV Export Format */
@Override
public void setDATEV_ExportFormat_ID (int DATEV_ExportFormat_ID)
{
if (DATEV_ExportFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DATEV_ExportFormat_ID, Integer.valueOf(DATEV_ExportFormat_ID));
}
/** Get DATEV Export Format.
@return DATEV Export Format */
@Override
public int getDATEV_ExportFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DATEV_ExportFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Decimal Separator.
@param DecimalSeparator Decimal Separator */
@Override
public void setDecimalSeparator (java.lang.String DecimalSeparator)
{
set_Value (COLUMNNAME_DecimalSeparator, DecimalSeparator);
}
/** Get Decimal Separator.
@return Decimal Separator */ | @Override
public java.lang.String getDecimalSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_DecimalSeparator);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set 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);
}
/** Set Number Grouping Separator.
@param NumberGroupingSeparator Number Grouping Separator */
@Override
public void setNumberGroupingSeparator (java.lang.String NumberGroupingSeparator)
{
set_Value (COLUMNNAME_NumberGroupingSeparator, NumberGroupingSeparator);
}
/** Get Number Grouping Separator.
@return Number Grouping Separator */
@Override
public java.lang.String getNumberGroupingSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_NumberGroupingSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormat.java | 1 |
请完成以下Java代码 | public OrgId getOrgId()
{
return OrgId.ofRepoId(getMandatoryPropertyAsInt(Env.CTXNAME_AD_Org_ID));
}
public void setWarehouse(final WarehouseId warehouseId, final String warehouseName)
{
setProperty(Env.CTXNAME_M_Warehouse_ID, WarehouseId.toRepoId(warehouseId));
Ini.setProperty(Ini.P_WAREHOUSE, warehouseName);
}
@Nullable
public WarehouseId getWarehouseId()
{
return WarehouseId.ofRepoIdOrNull(getPropertyAsInt(Env.CTXNAME_M_Warehouse_ID));
}
public void setPrinterName(final String printerName)
{
setProperty(Env.CTXNAME_Printer, printerName == null ? "" : printerName); | Ini.setProperty(Ini.P_PRINTER, printerName);
}
public void setAcctSchema(final AcctSchema acctSchema)
{
setProperty("$C_AcctSchema_ID", acctSchema.getId().getRepoId());
setProperty("$C_Currency_ID", acctSchema.getCurrencyId().getRepoId());
setProperty("$HasAlias", acctSchema.getValidCombinationOptions().isUseAccountAlias());
}
@Nullable
public AcctSchemaId getAcctSchemaId()
{
return AcctSchemaId.ofRepoIdOrNull(getPropertyAsInt("$C_AcctSchema_ID"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\LoginContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ParcelShopDelivery {
protected long parcelShopId;
@XmlElement(required = true)
protected Notification parcelShopNotification;
/**
* Gets the value of the parcelShopId property.
*
*/
public long getParcelShopId() {
return parcelShopId;
}
/**
* Sets the value of the parcelShopId property.
*
*/
public void setParcelShopId(long value) {
this.parcelShopId = value;
}
/**
* Gets the value of the parcelShopNotification property.
*
* @return
* possible object is
* {@link Notification }
*
*/
public Notification getParcelShopNotification() {
return parcelShopNotification; | }
/**
* Sets the value of the parcelShopNotification property.
*
* @param value
* allowed object is
* {@link Notification }
*
*/
public void setParcelShopNotification(Notification value) {
this.parcelShopNotification = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ParcelShopDelivery.java | 2 |
请完成以下Java代码 | public abstract class ToggableSideAction extends AbstractSideAction
{
private boolean toggled;
public ToggableSideAction()
{
super();
}
public ToggableSideAction(final String id)
{
super(id);
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public SideActionType getType()
{
return SideActionType.Toggle;
} | @Override
public final void setToggled(boolean toggled)
{
this.toggled = toggled;
}
@Override
public final boolean isToggled()
{
return toggled;
}
@Override
public abstract String getDisplayName();
@Override
public abstract void execute();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\ToggableSideAction.java | 1 |
请完成以下Java代码 | public Execution getExecution() {
return businessProcess.getExecution();
}
/**
* @see BusinessProcess#getExecution()
*/
/* Makes the id of the current Execution available for injection */
@Produces
@Named
@ExecutionId
public String getExecutionId() {
return businessProcess.getExecutionId();
}
/**
* Returns the currently associated {@link Task} or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Task} is associated. Use
* {@link BusinessProcess#isTaskAssociated()} to check whether an | * association exists.
*/
/* Makes the current Task available for injection */
@Produces
@Named
public Task getTask() {
return businessProcess.getTask();
}
/**
* Returns the id of the task associated with the current conversation or
* 'null'.
*/
/* Makes the taskId available for injection */
@Produces
@Named
@TaskId
public String getTaskId() {
return businessProcess.getTaskId();
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\CurrentProcessInstance.java | 1 |
请完成以下Java代码 | public void setId() {
this.isIdAttribute = true;
}
/**
* @return the attributeName
*/
public String getAttributeName() {
return attributeName;
}
/**
* @param attributeName the attributeName to set
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public void removeAttribute(ModelElementInstance modelElement) {
if (namespaceUri == null) {
modelElement.removeAttribute(attributeName);
}
else {
modelElement.removeAttributeNs(namespaceUri, attributeName);
}
}
public void unlinkReference(ModelElementInstance modelElement, Object referenceIdentifier) {
if (!incomingReferences.isEmpty()) {
for (Reference<?> incomingReference : incomingReferences) {
((ReferenceImpl<?>) incomingReference).referencedElementRemoved(modelElement, referenceIdentifier);
}
}
}
/**
* @return the incomingReferences
*/
public List<Reference<?>> getIncomingReferences() { | return incomingReferences;
}
/**
* @return the outgoingReferences
*/
public List<Reference<?>> getOutgoingReferences() {
return outgoingReferences;
}
public void registerOutgoingReference(Reference<?> ref) {
outgoingReferences.add(ref);
}
public void registerIncoming(Reference<?> ref) {
incomingReferences.add(ref);
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\AttributeImpl.java | 1 |
请完成以下Java代码 | public class ClassicPhone {
private final String dialpad;
private final String ringer;
private String otherParts;
@AutoFactory
public ClassicPhone(@Provided String dialpad, @Provided String ringer) {
this.dialpad = dialpad;
this.ringer = ringer;
}
@AutoFactory
public ClassicPhone(String otherParts) {
this("defaultDialPad", "defaultRinger"); | this.otherParts = otherParts;
}
public String getDialpad() {
return dialpad;
}
public String getRinger() {
return ringer;
}
public String getOtherParts() {
return otherParts;
}
} | repos\tutorials-master\google-auto-project\src\main\java\com\baeldung\autofactory\model\ClassicPhone.java | 1 |
请完成以下Java代码 | public class PP_Product_BOMLine
{
/**
* Validates and them updates the BOM line fields from selected product, if any.
*/
@CalloutMethod(columnNames = I_PP_Product_BOMLine.COLUMNNAME_M_Product_ID)
public void onProductChanged(final I_PP_Product_BOMLine bomLine)
{
final int M_Product_ID = bomLine.getM_Product_ID();
if (M_Product_ID <= 0)
{
return;
}
final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM();
if (bom.getM_Product_ID() == bomLine.getM_Product_ID())
{
throw new AdempiereException("@ValidComponent@ - selected product cannot be a BOM component because it's actually the BOM product");
}
// Set BOM Line defaults
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final I_M_Product product = Services.get(IProductBL.class).getById(productId); | bomLine.setDescription(product.getDescription());
bomLine.setHelp(product.getHelp());
bomLine.setC_UOM_ID(product.getC_UOM_ID());
}
@CalloutMethod(columnNames = { I_PP_Product_BOMLine.COLUMNNAME_VariantGroup})
public void validateVariantGroup(final I_PP_Product_BOMLine bomLine)
{
final boolean valid = Services.get(IProductBOMBL.class).isValidVariantGroup(bomLine);
if (!valid)
{
throw new LiberoException("@NoSuchVariantGroup@");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Product_BOMLine.java | 1 |
请完成以下Java代码 | private int getPrecedenceScore(char ch) {
switch (ch) {
case '^':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
}
return -1;
}
private boolean isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
}
private char associativity(char ch) {
if (ch == '^')
return 'R';
return 'L';
}
public String infixToPostfix(String infix) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>(); | for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
if (isOperand(ch)) {
result.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
stack.pop();
} else {
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) {
result.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
}
} | repos\tutorials-master\core-java-modules\core-java-lang-operators-3\src\main\java\com\baeldung\infixpostfix\InfixToPostFixExpressionConversion.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
@Autowired
private UserDao userDao;
public List<User> getByMap(Map<String,Object> map) {
return userDao.getByMap(map);
}
public User getById(Integer id) {
return userDao.getById(id);
}
public User create(User user) {
userDao.create(user);
return user; | }
public User update(User user) {
userDao.update(user);
return user;
}
public int delete(Integer id) {
return userDao.delete(id);
}
public User getByUserName(String userName) {
return userDao.getByUserName(userName);
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\service\UserService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private @Nullable String getGridFsDatabase() {
return this.properties.getGridfs().getDatabase();
}
@Override
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return this.delegate.getMongoDatabase(dbName);
}
@Override
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type);
}
@Override
public PersistenceExceptionTranslator getExceptionTranslator() {
return this.delegate.getExceptionTranslator();
}
@Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
} | @Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java | 2 |
请完成以下Java代码 | public class ExecuteActivityForAdhocSubProcessCmd implements Command<Execution>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
protected String activityId;
public ExecuteActivityForAdhocSubProcessCmd(String executionId, String activityId) {
this.executionId = executionId;
this.activityId = activityId;
}
public Execution execute(CommandContext commandContext) {
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId);
if (execution == null) {
throw new ActivitiObjectNotFoundException(
"No execution found for id '" + executionId + "'",
ExecutionEntity.class
);
}
if (!(execution.getCurrentFlowElement() instanceof AdhocSubProcess)) {
throw new ActivitiException(
"The current flow element of the requested execution is not an ad-hoc sub process"
);
}
FlowNode foundNode = null;
AdhocSubProcess adhocSubProcess = (AdhocSubProcess) execution.getCurrentFlowElement();
// if sequential ordering, only one child execution can be active
if (adhocSubProcess.hasSequentialOrdering()) {
if (execution.getExecutions().size() > 0) {
throw new ActivitiException("Sequential ad-hoc sub process already has an active execution");
}
}
for (FlowElement flowElement : adhocSubProcess.getFlowElements()) {
if (activityId.equals(flowElement.getId()) && flowElement instanceof FlowNode) {
FlowNode flowNode = (FlowNode) flowElement;
if (flowNode.getIncomingFlows().size() == 0) { | foundNode = flowNode;
}
}
}
if (foundNode == null) {
throw new ActivitiException("The requested activity with id " + activityId + " can not be enabled");
}
ExecutionEntity activityExecution = Context.getCommandContext()
.getExecutionEntityManager()
.createChildExecution(execution);
activityExecution.setCurrentFlowElement(foundNode);
Context.getAgenda().planContinueProcessOperation(activityExecution);
return activityExecution;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ExecuteActivityForAdhocSubProcessCmd.java | 1 |
请完成以下Java代码 | public class ImmutablePair<L, R> implements Entry<L, R>, Serializable, Comparable<ImmutablePair<L, R>> {
/** Serialization version */
private static final long serialVersionUID = -7043970803192830955L;
protected L left;
protected R right;
/**
* @return the left element
*/
public L getLeft() {
return left;
}
/**
* @return the right element
*/
public R getRight() {
return right;
}
/**
* Create a pair of elements.
*
* @param left
* the left element
* @param right
* the right element
*/
public ImmutablePair(L left, R right) {
this.left = left;
this.right = right;
}
@Override
public final L getKey() {
return this.getLeft();
}
@Override
public R getValue() {
return this.getRight();
}
/**
* This is not allowed since the pair itself is immutable.
*
* @return never
* @throws UnsupportedOperationException
*/
@Override
public R setValue(R value) {
throw new UnsupportedOperationException("setValue not allowed for an ImmutablePair");
}
/**
* Compares the pair based on the left element followed by the right element.
* The types must be {@code Comparable}.
*
* @param other
* the other pair, not null | * @return negative if this is less, zero if equal, positive if greater
*/
@Override
@SuppressWarnings("unchecked")
public int compareTo(ImmutablePair<L, R> o) {
if (o == null) {
throw new IllegalArgumentException("Pair to compare to must not be null");
}
try {
int leftComparison = compare((Comparable<L>) getLeft(), (Comparable<L>) o.getLeft());
return leftComparison == 0 ? compare((Comparable<R>) getRight(), (Comparable<R>) o.getRight()) : leftComparison;
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Please provide comparable elements", cce);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected int compare(Comparable original, Comparable other) {
if (original == other) {
return 0;
}
if (original == null) {
return -1;
}
if (other == null) {
return 1;
}
return original.compareTo(other);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Entry)) {
return false;
} else {
Entry<?, ?> other = (Entry<?, ?>) obj;
return Objects.equals(this.getKey(), other.getKey()) &&
Objects.equals(this.getValue(), other.getValue());
}
}
@Override
public int hashCode() {
return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^
(this.getValue() == null ? 0 : this.getValue().hashCode());
}
@Override
public String toString() {
return "(" + this.getLeft() + ',' + this.getRight() + ')';
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ImmutablePair.java | 1 |
请完成以下Java代码 | public String getStructure() {
return structureAttribute.getValue(this);
}
public void setStructure(String structureRef) {
structureAttribute.setValue(this, structureRef);
}
// public Import getImport() {
// return importRefAttribute.getReferenceTargetElement(this);
// }
//
// public void setImport(Import importRef) {
// importRefAttribute.setReferenceTargetElement(this, importRef);
// }
public Collection<Property> getProperties() {
return propertyCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItemDefinition.class, CMMN_ELEMENT_CASE_FILE_ITEM_DEFINITION)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<CaseFileItemDefinition>() {
public CaseFileItemDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileItemDefinitionImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build(); | definitionTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_TYPE)
.defaultValue("http://www.omg.org/spec/CMMN/DefinitionType/Unspecified")
.build();
structureAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_STRUCTURE_REF)
.build();
// TODO: The Import does not have an id attribute!
// importRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPORT_REF)
// .qNameAttributeReference(Import.class)
// .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
propertyCollection = sequenceBuilder.elementCollection(Property.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemDefinitionImpl.java | 1 |
请完成以下Java代码 | class ByteArrayDataBlock implements CloseableDataBlock {
private final byte[] bytes;
private final int maxReadSize;
/**
* Create a new {@link ByteArrayDataBlock} backed by the given bytes.
* @param bytes the bytes to use
*/
ByteArrayDataBlock(byte... bytes) {
this(bytes, -1);
}
ByteArrayDataBlock(byte[] bytes, int maxReadSize) {
this.bytes = bytes;
this.maxReadSize = maxReadSize;
}
@Override
public long size() throws IOException {
return this.bytes.length;
} | @Override
public int read(ByteBuffer dst, long pos) throws IOException {
return read(dst, (int) pos);
}
private int read(ByteBuffer dst, int pos) {
int remaining = dst.remaining();
int length = Math.min(this.bytes.length - pos, remaining);
if (this.maxReadSize > 0 && length > this.maxReadSize) {
length = this.maxReadSize;
}
dst.put(this.bytes, pos, length);
return length;
}
@Override
public void close() throws IOException {
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\ByteArrayDataBlock.java | 1 |
请完成以下Java代码 | public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurrent Payment.
@param C_RecurrentPayment_ID Recurrent Payment */
@Override
public void setC_RecurrentPayment_ID (int C_RecurrentPayment_ID)
{
if (C_RecurrentPayment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, null); | else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, Integer.valueOf(C_RecurrentPayment_ID));
}
/** Get Recurrent Payment.
@return Recurrent Payment */
@Override
public int getC_RecurrentPayment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPayment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPayment.java | 1 |
请完成以下Java代码 | class OperationMethodParameters implements OperationParameters {
private final List<OperationParameter> operationParameters;
/**
* Create a new {@link OperationMethodParameters} instance.
* @param method the source method
* @param parameterNameDiscoverer the parameter name discoverer
*/
OperationMethodParameters(Method method, ParameterNameDiscoverer parameterNameDiscoverer) {
Assert.notNull(method, "'method' must not be null");
Assert.notNull(parameterNameDiscoverer, "'parameterNameDiscoverer' must not be null");
@Nullable String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);
Parameter[] parameters = method.getParameters();
Assert.state(parameterNames != null, () -> "Failed to extract parameter names for " + method);
this.operationParameters = getOperationParameters(parameters, parameterNames);
}
private List<OperationParameter> getOperationParameters(Parameter[] parameters, @Nullable String[] names) {
List<OperationParameter> operationParameters = new ArrayList<>(parameters.length);
for (int i = 0; i < names.length; i++) {
String name = names[i];
Assert.state(name != null, "'name' must not be null");
operationParameters.add(new OperationMethodParameter(name, parameters[i]));
}
return Collections.unmodifiableList(operationParameters);
}
@Override
public int getParameterCount() {
return this.operationParameters.size();
}
@Override | public OperationParameter get(int index) {
return this.operationParameters.get(index);
}
@Override
public Iterator<OperationParameter> iterator() {
return this.operationParameters.iterator();
}
@Override
public Stream<OperationParameter> stream() {
return this.operationParameters.stream();
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\reflect\OperationMethodParameters.java | 1 |
请完成以下Java代码 | public class LoginResponse implements Serializable
{
private static final long serialVersionUID = 6515589439074746845L;
private String username;
private String sessionId;
private String hostKey = null;
@Override
public String toString()
{
return "LoginResponse [username=" + username
+ ", sessionId=" + sessionId
+ ", hostKey=" + hostKey
+ "]";
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getSessionId()
{ | return sessionId;
}
public void setSessionId(String sessionId)
{
this.sessionId = sessionId;
}
public String getHostKey()
{
return hostKey;
}
public void setHostKey(String hostKey)
{
this.hostKey = hostKey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\LoginResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", ":x-requested-with,content-type");
filterChain.doFilter(servletRequest,servletResponse);
if (!request.getRequestURI().equals("/oauth/token")) {
invoke(fi);
}
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器 | fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
} | repos\SpringBootLearning-master (1)\springboot-security-oauth2\src\main\java\com\gf\config\MyFilterSecurityInterceptor.java | 2 |
请完成以下Java代码 | public java.lang.String getConfidentialType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* ModerationType AD_Reference_ID=395
* Reference name: CM_Chat ModerationType
*/
public static final int MODERATIONTYPE_AD_Reference_ID=395;
/** Not moderated = N */
public static final String MODERATIONTYPE_NotModerated = "N";
/** Before Publishing = B */
public static final String MODERATIONTYPE_BeforePublishing = "B";
/** After Publishing = A */
public static final String MODERATIONTYPE_AfterPublishing = "A";
/** Set Moderation Type.
@param ModerationType
Type of moderation
*/
@Override
public void setModerationType (java.lang.String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
}
/** Get Moderation Type. | @return Type of moderation
*/
@Override
public java.lang.String getModerationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Chat.java | 1 |
请完成以下Java代码 | public AdWindowId getAdWindowId()
{
return gridTab.getAdWindowId();
}
@Override
public AdTabId getAdTabId()
{
return AdTabId.ofRepoId(gridTab.getAD_Tab_ID());
}
@Override
public String getTableName()
{
return gridTab.getTableName();
}
@Override
public <T> T getSelectedModel(final Class<T> modelClass)
{
return gridTab.getModel(modelClass);
}
@Override
public <T> List<T> getSelectedModels(final Class<T> modelClass)
{
// backward compatibility
return streamSelectedModels(modelClass)
.collect(ImmutableList.toImmutableList());
}
@NonNull
@Override
public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass)
{
return Stream.of(getSelectedModel(modelClass));
}
@Override | public int getSingleSelectedRecordId()
{
return gridTab.getRecord_ID();
}
@Override
public SelectionSize getSelectionSize()
{
// backward compatibility
return SelectionSize.ofSize(1);
}
@Override
public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass)
{
return gridTab.createCurrentRecordsQueryFilter(recordClass);
}
}
} // GridTab | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java | 1 |
请完成以下Java代码 | public DocumentId getId()
{
return documentId;
}
@Override
public IViewRowType getType()
{
return rowType;
}
@Override
public DocumentPath getDocumentPath()
{
return documentPath;
}
/**
* Return false, because with true, all rows are "grayed" out. This does not mean that the rows are editable.
*/
@Override
public boolean isProcessed()
{
return false;
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
} | @Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
public DocumentZoomIntoInfo getZoomIntoInfo(@NonNull final String fieldName)
{
if (FIELDNAME_M_Product_ID.equals(fieldName))
{
return lookups.getZoomInto(productId);
}
else
{
throw new AdempiereException("Field " + fieldName + " does not support zoom info");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRow.java | 1 |
请完成以下Java代码 | private ConfigurableEnvironment createEnvironment(Class<? extends ConfigurableEnvironment> type) {
try {
Constructor<? extends ConfigurableEnvironment> constructor = type.getDeclaredConstructor();
ReflectionUtils.makeAccessible(constructor);
return constructor.newInstance();
}
catch (Exception ex) {
return new ApplicationEnvironment();
}
}
private void copyPropertySources(ConfigurableEnvironment source, ConfigurableEnvironment target) {
removePropertySources(target.getPropertySources(), isServletEnvironment(target.getClass(), this.classLoader));
for (PropertySource<?> propertySource : source.getPropertySources()) {
if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) {
target.getPropertySources().addLast(propertySource);
}
}
}
private boolean isServletEnvironment(Class<?> conversionType, ClassLoader classLoader) {
try {
Class<?> webEnvironmentClass = ClassUtils.forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader);
return webEnvironmentClass.isAssignableFrom(conversionType);
}
catch (Throwable ex) { | return false;
}
}
private void removePropertySources(MutablePropertySources propertySources, boolean isServletEnvironment) {
Set<String> names = new HashSet<>();
for (PropertySource<?> propertySource : propertySources) {
names.add(propertySource.getName());
}
for (String name : names) {
if (!isServletEnvironment || !SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(name)) {
propertySources.remove(name);
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\EnvironmentConverter.java | 1 |
请完成以下Java代码 | public void setLongValue(Long longValue) {
throw new UnsupportedOperationException("Not supported to set long value");
}
@Override
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue();
}
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
throw new UnsupportedOperationException("Not supported to set double value");
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes"); | }
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java | 1 |
请完成以下Java代码 | public final void setErrorParametersConverter(
Converter<OAuth2Error, Map<String, String>> errorParametersConverter) {
Assert.notNull(errorParametersConverter, "errorParametersConverter cannot be null");
this.errorParametersConverter = errorParametersConverter;
}
/**
* A {@link Converter} that converts the provided OAuth 2.0 Error parameters to an
* {@link OAuth2Error}.
*/
private static class OAuth2ErrorConverter implements Converter<Map<String, String>, OAuth2Error> {
@Override
public OAuth2Error convert(Map<String, String> parameters) {
String errorCode = parameters.get(OAuth2ParameterNames.ERROR);
String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI);
return new OAuth2Error(errorCode, errorDescription, errorUri);
}
}
/**
* A {@link Converter} that converts the provided {@link OAuth2Error} to a {@code Map}
* representation of OAuth 2.0 Error parameters. | */
private static class OAuth2ErrorParametersConverter implements Converter<OAuth2Error, Map<String, String>> {
@Override
public Map<String, String> convert(OAuth2Error oauth2Error) {
Map<String, String> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.ERROR, oauth2Error.getErrorCode());
if (StringUtils.hasText(oauth2Error.getDescription())) {
parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, oauth2Error.getDescription());
}
if (StringUtils.hasText(oauth2Error.getUri())) {
parameters.put(OAuth2ParameterNames.ERROR_URI, oauth2Error.getUri());
}
return parameters;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QueryVariable {
private String name;
private String operation;
private Object value;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(hidden = true)
public QueryVariableOperation getVariableOperation() {
if (operation == null) {
return null;
}
return QueryVariableOperation.forFriendlyName(operation);
}
@ApiModelProperty(allowableValues = "equals, notEquals, equalsIgnoreCase, notEqualsIgnoreCase, like, likeIgnoreCase, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals")
public void setOperation(String operation) {
this.operation = operation;
}
public String getOperation() {
return operation;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
} | public enum QueryVariableOperation {
EQUALS("equals"), NOT_EQUALS("notEquals"), EQUALS_IGNORE_CASE("equalsIgnoreCase"), NOT_EQUALS_IGNORE_CASE("notEqualsIgnoreCase"), LIKE("like"), LIKE_IGNORE_CASE("likeIgnoreCase"), GREATER_THAN("greaterThan"), GREATER_THAN_OR_EQUALS(
"greaterThanOrEquals"), LESS_THAN("lessThan"), LESS_THAN_OR_EQUALS("lessThanOrEquals");
private final String friendlyName;
private QueryVariableOperation(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getFriendlyName() {
return friendlyName;
}
public static QueryVariableOperation forFriendlyName(String friendlyName) {
for (QueryVariableOperation type : values()) {
if (type.friendlyName.equals(friendlyName)) {
return type;
}
}
throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + friendlyName);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\variable\QueryVariable.java | 2 |
请完成以下Java代码 | public PrintingData onlyWithType(@NonNull final OutputType outputType)
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(segment -> segment.isMatchingOutputType(outputType))
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public PrintingData onlyQueuedForExternalSystems()
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(PrintingSegment::isQueuedForExternalSystems)
.collect(ImmutableList.toImmutableList());
return toBuilder() | .clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public boolean hasSegments() {return !getSegments().isEmpty();}
public int getSegmentsCount() {return getSegments().size();}
public ImmutableSet<String> getPrinterNames()
{
return segments.stream()
.map(segment -> segment.getPrinter().getName())
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8088
spring:
redis:
database: 0
port: 6379
host: 127.0.0.1
password: 123456
timeout=3000:
jedis:
pool:
max-active: 8
max-idle: 8
max-wait: -1
min-idle: 0
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
#schema: database/import.sql
#sql-script-encoding: utf-8
driver-class-name: com.mysql.cj.jdbc.Dri | ver
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
thymeleaf:
cache: false
mode: HTML | repos\springboot-demo-master\shiro\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public CalculateTaxResult calculateTax(final BigDecimal amount, final boolean taxIncluded, final int scale)
{
// Null Tax
if (rate.signum() == 0)
{
return CalculateTaxResult.ZERO;
}
BigDecimal multiplier = rate.divide(Env.ONEHUNDRED, 12, RoundingMode.HALF_UP);
final BigDecimal taxAmt;
final BigDecimal reverseChargeAmt;
if (isWholeTax)
{
Check.assume(taxIncluded, "TaxIncluded shall be set when IsWholeTax is set");
taxAmt = amount;
reverseChargeAmt = BigDecimal.ZERO;
}
else if (isReverseCharge)
{
Check.assume(!taxIncluded, "TaxIncluded shall NOT be set when IsReverseCharge is set");
taxAmt = BigDecimal.ZERO;
reverseChargeAmt = amount.multiply(multiplier);
}
else if (!taxIncluded) // $100 * 6 / 100 == $6 == $100 * 0.06
{
taxAmt = amount.multiply(multiplier);
reverseChargeAmt = BigDecimal.ZERO;
}
else
// $106 - ($106 / (100+6)/100) == $6 == $106 - ($106/1.06)
{
multiplier = multiplier.add(BigDecimal.ONE);
final BigDecimal base = amount.divide(multiplier, 12, RoundingMode.HALF_UP);
taxAmt = amount.subtract(base); | reverseChargeAmt = BigDecimal.ZERO;
}
final BigDecimal taxAmtFinal = taxAmt.setScale(scale, RoundingMode.HALF_UP);
final BigDecimal reverseChargeTaxAmtFinal = reverseChargeAmt.setScale(scale, RoundingMode.HALF_UP);
log.debug("calculateTax: amount={} (incl={}, multiplier={}, scale={}) = {} [{}] / reverse charge = {} [{}]",
amount, taxIncluded, multiplier, scale, taxAmtFinal, taxAmt, reverseChargeAmt, reverseChargeTaxAmtFinal);
return CalculateTaxResult.builder()
.taxAmount(taxAmtFinal)
.reverseChargeAmt(reverseChargeTaxAmtFinal)
.build();
} // calculateTax
@NonNull
public BigDecimal calculateGross(@NonNull final BigDecimal netAmount, final int scale)
{
return netAmount.add(calculateTax(netAmount, false, scale).getTaxAmount());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\Tax.java | 1 |
请完成以下Java代码 | public static MigrationPlanDto from(MigrationPlan migrationPlan) {
MigrationPlanDto dto = new MigrationPlanDto();
VariableMap variables = migrationPlan.getVariables();
if (variables != null) {
dto.setVariables(VariableValueDto.fromMap(variables));
}
dto.setSourceProcessDefinitionId(migrationPlan.getSourceProcessDefinitionId());
dto.setTargetProcessDefinitionId(migrationPlan.getTargetProcessDefinitionId());
ArrayList<MigrationInstructionDto> instructionDtos = new ArrayList<MigrationInstructionDto>();
if (migrationPlan.getInstructions() != null) {
for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) {
MigrationInstructionDto migrationInstructionDto = MigrationInstructionDto.from(migrationInstruction);
instructionDtos.add(migrationInstructionDto);
}
}
dto.setInstructions(instructionDtos);
return dto;
}
public static MigrationPlan toMigrationPlan(ProcessEngine processEngine,
ObjectMapper objectMapper,
MigrationPlanDto migrationPlanDto) {
MigrationPlanBuilder migrationPlanBuilder = processEngine.getRuntimeService().createMigrationPlan(migrationPlanDto.getSourceProcessDefinitionId(), migrationPlanDto.getTargetProcessDefinitionId());
Map<String, VariableValueDto> variableDtos = migrationPlanDto.getVariables();
if (variableDtos != null) {
Map<String, Object> variables =
VariableValueDto.toMap(variableDtos, processEngine, objectMapper);
migrationPlanBuilder.setVariables(variables);
} | if (migrationPlanDto.getInstructions() != null) {
for (MigrationInstructionDto migrationInstructionDto : migrationPlanDto.getInstructions()) {
MigrationInstructionBuilder migrationInstructionBuilder = migrationPlanBuilder.mapActivities(migrationInstructionDto.getSourceActivityIds().get(0), migrationInstructionDto.getTargetActivityIds().get(0));
if (Boolean.TRUE.equals(migrationInstructionDto.isUpdateEventTrigger())) {
migrationInstructionBuilder = migrationInstructionBuilder.updateEventTrigger();
}
migrationPlanBuilder = migrationInstructionBuilder;
}
}
return migrationPlanBuilder.build();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\migration\MigrationPlanDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FactAcctLogService
{
private static final String SYSCONFIG_IsUseLegacyProcessor = "FactAcctLogService.useLegacyProcessor";
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
private final ITrxManager trxManager = Services.get(ITrxManager.class);
public FactAcctLogProcessResult processAll(final QueryLimit limit)
{
return trxManager.callInNewTrx(() -> processAllInTrx(limit));
}
private FactAcctLogProcessResult processAllInTrx(final QueryLimit limit)
{
if (isUseLegacyProcessor())
{
return new LegacyFactAcctLogProcessor().processAll(limit); | }
else
{
final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, "SELECT de_metas_acct.fact_acct_log_process(?)", limit.toInt());
return FactAcctLogProcessResult.builder()
.iterations(1)
.processedLogRecordsCount(count)
.build();
}
}
private boolean isUseLegacyProcessor()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_IsUseLegacyProcessor, true); // default to true for backwards compatibility
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\FactAcctLogService.java | 2 |
请完成以下Java代码 | public class UpdateProcessInstancesSuspensionStateBuilderImpl implements UpdateProcessInstancesSuspensionStateBuilder {
protected List<String> processInstanceIds;
protected ProcessInstanceQuery processInstanceQuery;
protected HistoricProcessInstanceQuery historicProcessInstanceQuery;
protected CommandExecutor commandExecutor;
protected String processDefinitionId;
public UpdateProcessInstancesSuspensionStateBuilderImpl(CommandExecutor commandExecutor) {
this.processInstanceIds = new ArrayList<String>();
this.commandExecutor = commandExecutor;
}
public UpdateProcessInstancesSuspensionStateBuilderImpl(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
@Override
public UpdateProcessInstancesSuspensionStateBuilder byProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds.addAll(processInstanceIds);
return this;
}
@Override
public UpdateProcessInstancesSuspensionStateBuilder byProcessInstanceIds(String... processInstanceIds) {
this.processInstanceIds.addAll(Arrays.asList(processInstanceIds));
return this;
}
@Override
public UpdateProcessInstancesSuspensionStateBuilder byProcessInstanceQuery(ProcessInstanceQuery processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
return this;
}
@Override
public UpdateProcessInstancesSuspensionStateBuilder byHistoricProcessInstanceQuery(HistoricProcessInstanceQuery historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
return this;
}
@Override
public void suspend() {
commandExecutor.execute(new UpdateProcessInstancesSuspendStateCmd(commandExecutor, this, true));
}
@Override | public void activate() {
commandExecutor.execute(new UpdateProcessInstancesSuspendStateCmd(commandExecutor, this, false));
}
@Override
public Batch suspendAsync() {
return commandExecutor.execute(new UpdateProcessInstancesSuspendStateBatchCmd(commandExecutor, this, true));
}
@Override
public Batch activateAsync() {
return commandExecutor.execute(new UpdateProcessInstancesSuspendStateBatchCmd(commandExecutor, this, false));
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UpdateProcessInstancesSuspensionStateBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void run(String... args) throws Exception {
UserDTO user = userRpcService.get(1);
logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user);
}
}
@Component
public class UserRpcServiceTest02 implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private UserRpcService userRpcService;
@Override
public void run(String... args) throws Exception {
// 获得用户
try {
// 发起调用
UserDTO user = userRpcService.get(null); // 故意传入空的编号,为了校验编号不通过
logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user);
} catch (Exception e) {
logger.error("[run][获得用户发生异常,信息为:[{}]", e.getMessage());
}
// 添加用户
try {
// 创建 UserAddDTO
UserAddDTO addDTO = new UserAddDTO();
addDTO.setName("yudaoyuanmayudaoyuanma"); // 故意把名字打的特别长,为了校验名字不通过
addDTO.setGender(null); // 不传递性别,为了校验性别不通过
// 发起调用
userRpcService.add(addDTO);
logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO);
} catch (Exception e) {
logger.error("[run][添加用户发生异常,信息为:[{}]", e.getMessage());
}
} | }
@Component
public class UserRpcServiceTest03 implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private UserRpcService userRpcService;
@Override
public void run(String... args) {
// 添加用户
try {
// 创建 UserAddDTO
UserAddDTO addDTO = new UserAddDTO();
addDTO.setName("yudaoyuanma"); // 设置为 yudaoyuanma ,触发 ServiceException 异常
addDTO.setGender(1);
// 发起调用
userRpcService.add(addDTO);
logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO);
} catch (Exception e) {
logger.error("[run][添加用户发生异常({}),信息为:[{}]", e.getClass().getSimpleName(), e.getMessage());
}
}
}
} | repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-xml-demo\user-rpc-service-consumer\src\main\java\cn\iocoder\springboot\lab30\rpc\ConsumerApplication.java | 2 |
请完成以下Java代码 | public long findTaskCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectTaskCountByNativeQuery", parameterMap);
}
@SuppressWarnings("unchecked")
public List<Task> findTasksByParentTaskId(String parentTaskId) {
return getDbSqlSession().selectList("selectTasksByParentTaskId", parentTaskId);
}
public void deleteTask(String taskId, String deleteReason, boolean cascade) {
TaskEntity task = Context
.getCommandContext()
.getTaskEntityManager()
.findTaskById(taskId);
if (task != null) {
if (task.getExecutionId() != null) {
throw new ActivitiException("The task cannot be deleted because is part of a running process");
}
String reason = (deleteReason == null || deleteReason.length() == 0) ? TaskEntity.DELETE_REASON_DELETED : deleteReason;
deleteTask(task, reason, cascade); | } else if (cascade) {
Context
.getCommandContext()
.getHistoricTaskInstanceEntityManager()
.deleteHistoricTaskInstanceById(taskId);
}
}
public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateTaskTenantIdForDeployment", params);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityManager.java | 1 |
请完成以下Java代码 | public class SimpleUuidConsumer {
private static final Logger log = LoggerFactory.getLogger(SimpleUuidConsumer.class);
private final Channel channel;
private final String queue;
public SimpleUuidConsumer(Channel channel, String queue) {
this.channel = channel;
this.queue = queue;
}
public void consume() throws IOException {
log.debug("starting consumer");
channel.basicConsume(queue, true, (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
long deliveryTag = delivery.getEnvelope() | .getDeliveryTag();
process(message, deliveryTag);
}, cancelledTag -> {
log.warn("cancelled: #{}", cancelledTag);
});
}
private void process(String message, long deliveryTag) {
try {
UUID.fromString(message);
log.debug("* [#{}] processed: {}", deliveryTag, message);
} catch (IllegalArgumentException e) {
log.warn("* [#{}] invalid: {}", deliveryTag, message);
}
}
} | repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\consumerackspubconfirms\SimpleUuidConsumer.java | 1 |
请完成以下Java代码 | public String getApplicationPath() {
return applicationPath;
}
public void setApplicationPath(String applicationPath) {
this.applicationPath = sanitizeApplicationPath(applicationPath);
}
protected String sanitizeApplicationPath(String applicationPath) {
if (applicationPath == null || applicationPath.isEmpty()) {
return "";
}
if (!applicationPath.startsWith("/")) {
applicationPath = "/" + applicationPath;
}
if (applicationPath.endsWith("/")) {
applicationPath = applicationPath.substring(0, applicationPath.length() - 1);
}
return applicationPath;
}
public CsrfProperties getCsrf() {
return csrf;
}
public void setCsrf(CsrfProperties csrf) {
this.csrf = csrf;
}
public SessionCookieProperties getSessionCookie() {
return sessionCookie;
}
public void setSessionCookie(SessionCookieProperties sessionCookie) {
this.sessionCookie = sessionCookie;
} | public HeaderSecurityProperties getHeaderSecurity() {
return headerSecurity;
}
public void setHeaderSecurity(HeaderSecurityProperties headerSecurity) {
this.headerSecurity = headerSecurity;
}
public AuthenticationProperties getAuth() {
return auth;
}
public void setAuth(AuthenticationProperties authentication) {
this.auth = authentication;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("indexRedirectEnabled=" + indexRedirectEnabled)
.add("webjarClasspath='" + webjarClasspath + '\'')
.add("securityConfigFile='" + securityConfigFile + '\'')
.add("webappPath='" + applicationPath + '\'')
.add("csrf='" + csrf + '\'')
.add("headerSecurityProperties='" + headerSecurity + '\'')
.add("sessionCookie='" + sessionCookie + '\'')
.add("auth='" + auth + '\'')
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\WebappProperty.java | 1 |
请完成以下Java代码 | public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setVoiceAuthCode (final @Nullable java.lang.String VoiceAuthCode)
{
set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode);
}
@Override
public java.lang.String getVoiceAuthCode()
{
return get_ValueAsString(COLUMNNAME_VoiceAuthCode); | }
@Override
public void setWriteOffAmt (final @Nullable BigDecimal WriteOffAmt)
{
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
@Override
public BigDecimal getWriteOffAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WriteOffAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment.java | 1 |
请完成以下Java代码 | public User ofRecord(@NonNull final I_AD_User userRecord)
{
final IUserBL userBL = Services.get(IUserBL.class);
final IBPartnerBL bPartnerBL = Services.get(IBPartnerBL.class);
final Language userLanguage = Language.asLanguage(userRecord.getAD_Language());
final Language bpartnerLanguage = bPartnerBL.getLanguageForModel(userRecord).orElse(null);
final Language language = userBL.getUserLanguage(userRecord);
return User.builder()
.bpartnerId(BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID()))
.id(UserId.ofRepoId(userRecord.getAD_User_ID()))
.externalId(ExternalId.ofOrNull(userRecord.getExternalId()))
.name(userRecord.getName())
.firstName(userRecord.getFirstname())
.lastName(userRecord.getLastname())
.birthday(TimeUtil.asLocalDate(userRecord.getBirthday()))
.emailAddress(userRecord.getEMail())
.userLanguage(userLanguage)
.bPartnerLanguage(bpartnerLanguage)
.language(language)
.isInvoiceEmailEnabled(OptionalBoolean.ofNullableString(userRecord.getIsInvoiceEmailEnabled()))
.build();
}
public User save(@NonNull final User user)
{
final I_AD_User userRecord;
if (user.getId() == null) | {
userRecord = newInstance(I_AD_User.class);
}
else
{
userRecord = load(user.getId().getRepoId(), I_AD_User.class);
}
userRecord.setC_BPartner_ID(BPartnerId.toRepoId(user.getBpartnerId()));
userRecord.setName(user.getName());
userRecord.setFirstname(user.getFirstName());
userRecord.setLastname(user.getLastName());
userRecord.setBirthday(TimeUtil.asTimestamp(user.getBirthday()));
userRecord.setEMail(user.getEmailAddress());
userRecord.setAD_Language(Language.asLanguageStringOrNull(user.getUserLanguage()));
saveRecord(userRecord);
return user
.toBuilder()
.id(UserId.ofRepoId(userRecord.getAD_User_ID()))
.build();
}
@NonNull
public Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId)
{
return queryBL.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, bPartnerId)
.addEqualsFilter(I_AD_User.COLUMNNAME_IsDunningContact, true)
.create()
.firstIdOnlyOptional(UserId::ofRepoIdOrNull);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserRepository.java | 1 |
请完成以下Java代码 | protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public URI getUrl() {
return url;
}
public void setUrl(URI url) {
this.url = url;
}
@Nullable | public String getAuthToken() {
return authToken;
}
public void setAuthToken(@Nullable String authToken) {
this.authToken = authToken;
}
@Nullable
public String getRoomId() {
return roomId;
}
public void setRoomId(@Nullable String roomId) {
this.roomId = roomId;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\WebexNotifier.java | 1 |
请完成以下Java代码 | public String getSectionCode() {
return sectionCode;
}
/**
* Sets the value of the sectionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSectionCode(String value) {
this.sectionCode = value;
}
/**
* Gets the value of the remark property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
}
/**
* Gets the value of the serviceAttributes property.
* | * @return
* possible object is
* {@link Long }
*
*/
public long getServiceAttributes() {
if (serviceAttributes == null) {
return 0L;
} else {
return serviceAttributes;
}
}
/**
* Sets the value of the serviceAttributes property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setServiceAttributes(Long value) {
this.serviceAttributes = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordServiceType.java | 1 |
请完成以下Java代码 | public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Error Msg.
@param ErrorMsg Error Msg */
public void setErrorMsg (String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
/** Get Error Msg.
@return Error Msg */
public String getErrorMsg ()
{
return (String)get_Value(COLUMNNAME_ErrorMsg);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Unique.
@param IsUnique Unique */
public void setIsUnique (boolean IsUnique)
{
set_Value (COLUMNNAME_IsUnique, Boolean.valueOf(IsUnique));
}
/** Get Unique.
@return Unique */
public boolean isUnique ()
{
Object oo = get_Value(COLUMNNAME_IsUnique);
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
*/
public void setName (String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */ | public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
@Override
public String getBeforeChangeWarning()
{
return (String)get_Value(COLUMNNAME_BeforeChangeWarning);
}
@Override
public void setBeforeChangeWarning(String BeforeChangeWarning)
{
set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java | 1 |
请完成以下Java代码 | protected final PickingSlotView getView()
{
return PickingSlotView.cast(super.getView());
}
protected PickingSlotView getPickingSlotView()
{
return getView();
}
@Override
protected final PickingSlotRow getSingleSelectedRow()
{
return PickingSlotRow.cast(super.getSingleSelectedRow());
}
protected final PickingSlotRow getSingleSelectedPickingSlotRow()
{
return getSingleSelectedRow();
}
protected final void invalidatePickingSlotsView()
{
invalidateView();
}
protected final ShipmentScheduleId getCurrentShipmentScheduleId()
{
return getPickingSlotView().getCurrentShipmentScheduleId();
}
protected final I_M_ShipmentSchedule getCurrentShipmentSchedule()
{
I_M_ShipmentSchedule shipmentSchedule = _shipmentSchedule;
if (shipmentSchedule == null)
{
final ShipmentScheduleId shipmentScheduleId = getCurrentShipmentScheduleId(); | _shipmentSchedule = shipmentSchedule = shipmentSchedulesRepo.getById(shipmentScheduleId, I_M_ShipmentSchedule.class);
}
return shipmentSchedule;
}
protected final I_C_UOM getCurrentShipmentScheuduleUOM()
{
final I_M_ShipmentSchedule shipmentSchedule = getCurrentShipmentSchedule();
return shipmentScheduleBL.getUomOfProduct(shipmentSchedule);
}
protected PackageableView getPackageableView()
{
final ViewId packageableViewId = getPickingSlotView().getParentViewId();
return PackageableView.cast(getViewsRepo().getView(packageableViewId));
}
protected final void invalidatePackablesView()
{
invalidateParentView();
}
protected Optional<ProductBarcodeFilterData> getBarcodeFilterData()
{
return Optional.ofNullable(getPackageableView().getBarcodeFilterData());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\PickingSlotViewBasedProcess.java | 1 |
请完成以下Java代码 | public class MyCustomConvertor implements CustomConverter {
@Override
public Object convert(Object dest, Object source, Class<?> arg2, Class<?> arg3) {
if (source == null) {
return null;
}
if (source instanceof Personne3) {
Personne3 person = (Personne3) source;
Date date = new Date(person.getDtob());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String isoDate = format.format(date);
return new Person3(person.getName(), isoDate);
} else if (source instanceof Person3) {
Person3 person = (Person3) source;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null; | try {
date = format.parse(person.getDtob());
} catch (ParseException e) {
throw new MappingException("Converter MyCustomConvertor " + "used incorrectly:" + e.getMessage());
}
long timestamp = date.getTime();
return new Personne3(person.getName(), timestamp);
} else {
throw new MappingException("Converter MyCustomConvertor " + "used incorrectly. Arguments passed in were:" + dest + " and " + source);
}
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\MyCustomConvertor.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.