instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean isAsync(PvmExecutionImpl execution) {
return false;
}
public void execute(PvmExecutionImpl execution) {
execution.activityInstanceStarted();
execution.continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
if (execution.getActivity().isScope()) {
execution.dispatchEvent(null);
}
return null;
}
}, new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
ActivityBehavior activityBehavior = getActivityBehavior(execution);
ActivityImpl activity = execution.getActivity();
LOG.debugExecutesActivity(execution, activity, activityBehavior.getClass().getName()); | try {
activityBehavior.execute(execution);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PvmException("couldn't execute activity <" + activity.getProperty("type") + " id=\"" + activity.getId() + "\" ...>: " + e.getMessage(), e);
}
return null;
}
}, execution);
}
public String getCanonicalName() {
return "activity-execute";
}
public boolean isAsyncCapable() {
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityExecute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ApiService {
private static final Logger logger = LoggerFactory.getLogger(ApiService.class);
/**
* 保存最后一个连接上来的sessionID
*/
private String sessionId;
@Resource
private MyProperties p;
// private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
@Resource
private SocketIOServer server;
public synchronized void updateSessionId(String sid) {
sessionId = sid;
}
/**
* 服务器主动推送消息
*
* @param msgType 消息类型
* @param jsonData echarts图表数据
*/
public void pushMsg(String msgType, String jsonData) {
SocketIOClient targetClient = this.server.getClient(UUID.fromString(sessionId));
if (targetClient == null) {
logger.error("sessionId=" + sessionId + "在server中获取不到client");
} else {
targetClient.sendEvent(msgType, jsonData);
}
// queue.offer(jsonData);
}
// public String popJson() {
// try {
// return queue.poll(100L, TimeUnit.MILLISECONDS);
// } catch (InterruptedException e) {
// e.printStackTrace();
// return null;
// }
// } | /**
* 解析Base64位信息并输出到某个目录下面.
*
* @param base64Info base64串
* @return 文件地址
*/
public String saveBase64Pic(String base64Info) {
if (StringUtils.isEmpty(base64Info)) {
return "";
}
// 数据中:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABI4AAAEsCAYAAAClh/jbAAA ... 在"base64,"之后的才是图片信息
String[] arr = base64Info.split("base64,");
// 将图片输出到系统某目录.
OutputStream out = null;
String now = FastDateFormat.getInstance("yyyyMMddHHmmss").format(new Date());
String destFile = p.getImageDir() + now + ".png";
try {
// 使用了Apache commons codec的包来解析Base64
byte[] buffer = Base64.decodeBase64(arr[1]);
out = new FileOutputStream(destFile);
out.write(buffer);
} catch (IOException e) {
logger.error("解析Base64图片信息并保存到某目录下出错!", e);
return "";
} finally {
IOUtils.closeQuietly(out);
}
return destFile;
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\service\ApiService.java | 2 |
请完成以下Spring Boot application配置 | management:
endpoint:
# HttpTrace 端点配置项
httptrace:
enabled: true # 是否开启。默认为 true 开启
# HttpTrace 的具体配置项,对应 HttpTraceProperties 配置类
trace:
http:
enabled: true # 是否开启。默认为 true 开启。
include: # 包含的 trace 项的数组。默认不包含 COOKIE_HEADERS、AUTHORIZATION_HEADER 项。
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类
web:
base-path: /actuator # Actuator 提供的 A | PI 接口的根目录。默认为 /actuator
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。 | repos\SpringBoot-Labs-master\lab-34\lab-34-actuator-demo-httptrace\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | class M_CostElement
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IAcctSchemaDAO acctSchemaDAO;
public M_CostElement(@NonNull final IAcctSchemaDAO acctSchemaDAO)
{
this.acctSchemaDAO = acctSchemaDAO;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(final I_M_CostElement costElement)
{
costElement.setAD_Org_ID(OrgId.ANY.getRepoId());
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void beforeDelete(final I_M_CostElement costElement)
{
final CostElementType costElementType = CostElementType.ofCode(costElement.getCostElementType());
final CostingMethod costingMethod = CostingMethod.ofNullableCode(costElement.getCostingMethod());
final boolean isCostingMethod = costElementType.isMaterial() && costingMethod != null;
if (!isCostingMethod)
{
return;
}
// Costing Methods on AS level
final ClientId clientId = ClientId.ofRepoId(costElement.getAD_Client_ID());
for (final AcctSchema as : acctSchemaDAO.getAllByClient(clientId))
{
if (as.getCosting().getCostingMethod().equals(costingMethod))
{
throw new AdempiereException("@CannotDeleteUsed@ @C_AcctSchema_ID@");
} | }
// Costing Methods on PC level
// FIXME: this shall go in some DAO/Repository
final String productCategoriesUsingCostingMethod = queryBL
.createQueryBuilder(I_M_Product_Category_Acct.class)
.addEqualsFilter(I_M_Product_Category_Acct.COLUMNNAME_AD_Client_ID, clientId)
.addEqualsFilter(I_M_Product_Category_Acct.COLUMN_CostingMethod, costingMethod.getCode())
.andCollect(I_M_Product_Category_Acct.COLUMNNAME_M_Product_Category_ID, I_M_Product_Category.class)
.orderBy(I_M_Product_Category.COLUMNNAME_Name)
.create()
.setLimit(50)
.listDistinct(I_M_Product_Category.COLUMNNAME_Name, String.class)
.stream()
.collect(Collectors.joining(", "));
if (!Check.isEmpty(productCategoriesUsingCostingMethod, true))
{
throw new AdempiereException("@CannotDeleteUsed@ @M_Product_Category_ID@ (" + productCategoriesUsingCostingMethod + ")");
}
} // beforeDelete
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\interceptors\M_CostElement.java | 1 |
请完成以下Java代码 | public class RateType4Choice {
@XmlElement(name = "Pctg")
protected BigDecimal pctg;
@XmlElement(name = "Othr")
protected String othr;
/**
* Gets the value of the pctg property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getPctg() {
return pctg;
}
/**
* Sets the value of the pctg property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setPctg(BigDecimal value) {
this.pctg = value;
}
/** | * Gets the value of the othr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOthr(String value) {
this.othr = 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\RateType4Choice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String showNewProductPage(Model model) {
Employee employee = new Employee();
model.addAttribute("employee", employee);
return "new_employee";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(@ModelAttribute("employee") Employee employee) {
employeeService.save(employee);
return "redirect:/";
}
@RequestMapping("/edit/{id}") | public ModelAndView showEditEmployeePage(@PathVariable(name = "id") int id){
ModelAndView mav = new ModelAndView("edit_employee");
Employee employee1= employeeService.get(id);
mav.addObject("employee", employee1);
return mav;
}
@RequestMapping(value = "/delete/{id}")
public String deleteEmp(@PathVariable(name = "id") int id) {
employeeService.delete(id);
return "redirect:/";
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Employee-Salary\src\main\java\spring\project\controller\EmployeeController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Integer getSelectors() {
return this.selectors;
}
public void setSelectors(Integer selectors) {
this.selectors = selectors;
}
public void setMin(Integer min) {
this.min = min;
}
public Integer getMin() {
return this.min;
}
public void setMax(Integer max) {
this.max = max;
}
public Integer getMax() {
return this.max;
} | public @Nullable Integer getMaxQueueCapacity() {
return this.maxQueueCapacity;
}
public void setMaxQueueCapacity(@Nullable Integer maxQueueCapacity) {
this.maxQueueCapacity = maxQueueCapacity;
}
public void setIdleTimeout(Duration idleTimeout) {
this.idleTimeout = idleTimeout;
}
public Duration getIdleTimeout() {
return this.idleTimeout;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\autoconfigure\JettyServerProperties.java | 2 |
请完成以下Java代码 | public abstract class AbstractEventAtomicOperation<T extends CoreExecution> implements CoreAtomicOperation<T> {
@Override
public boolean isAsync(T execution) {
return false;
}
@Override
public void execute(T execution) {
CoreModelElement scope = getScope(execution);
List<DelegateListener<? extends BaseDelegateExecution>> listeners = execution.hasFailedOnEndListeners()
? getBuiltinListeners(scope)
: getListeners(scope, execution);
int listenerIndex = execution.getListenerIndex();
if(listenerIndex == 0) {
execution = eventNotificationsStarted(execution);
}
if(!isSkipNotifyListeners(execution)) {
if (listeners.size()>listenerIndex) {
execution.setEventName(getEventName());
execution.setEventSource(scope);
DelegateListener<? extends BaseDelegateExecution> listener = listeners.get(listenerIndex);
execution.setListenerIndex(listenerIndex+1);
try {
execution.invokeListener(listener);
} catch (Exception ex) {
eventNotificationsFailed(execution, ex);
// do not continue listener invocation once a listener has failed
return;
}
execution.performOperationSync(this);
} else {
resetListeners(execution);
eventNotificationsCompleted(execution);
}
} else {
eventNotificationsCompleted(execution);
}
}
protected void resetListeners(T execution) { | execution.setListenerIndex(0);
execution.setEventName(null);
execution.setEventSource(null);
}
protected List<DelegateListener<? extends BaseDelegateExecution>> getListeners(CoreModelElement scope, T execution) {
if(execution.isSkipCustomListeners()) {
return getBuiltinListeners(scope);
} else {
return scope.getListeners(getEventName());
}
}
protected List<DelegateListener<? extends BaseDelegateExecution>> getBuiltinListeners(CoreModelElement scope) {
return scope.getBuiltInListeners(getEventName());
}
protected boolean isSkipNotifyListeners(T execution) {
return false;
}
protected T eventNotificationsStarted(T execution) {
// do nothing
return execution;
}
protected abstract CoreModelElement getScope(T execution);
protected abstract String getEventName();
protected abstract void eventNotificationsCompleted(T execution);
protected void eventNotificationsFailed(T execution, Exception exception) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new PvmException("couldn't execute event listener : " + exception.getMessage(), exception);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\operation\AbstractEventAtomicOperation.java | 1 |
请完成以下Java代码 | public static List<I_AD_Index_Table> getAffectedIndexes(final GridTab tab, final boolean newRecord)
{
return MIndexTable.getByTableName(tab.getTableName())
.stream()
.filter(index -> index.isMatched(tab, newRecord))
.collect(ImmutableList.toImmutableList());
}
public static String getBeforeChangeWarning(final GridTab tab, final boolean newRecord)
{
final List<I_AD_Index_Table> indexes = getAffectedIndexes(tab, newRecord);
if (indexes.isEmpty())
{
return null;
}
// metas start: R.Craciunescu@metas.ro : 02280
final int rowCount = tab.getRowCount();
// metas end: R.Craciunescu@metas.ro : 02280
final StringBuilder msg = new StringBuilder();
for (final I_AD_Index_Table index : indexes)
{
if (Check.isEmpty(index.getBeforeChangeWarning()))
{
continue;
}
// metas start: R.Craciunescu@metas.ro : 02280
// if the new entry is the only row, there is nothing to be changed, so a before change warning is not needed.
if (rowCount == 1)
{
return null;
}
// metas end: R.Craciunescu@metas.ro : 02280
if (msg.length() > 0)
{
msg.append("\n");
}
msg.append(index.getBeforeChangeWarning());
}
return msg.toString();
}
private static final boolean isValueChanged(final GridTab tab, final String columnName,
final boolean newRecord)
{
final GridTable table = tab.getTableModel();
final int index = table.findColumn(columnName);
if (index == -1)
{
return false; | }
if (newRecord)
{
return true;
}
final Object valueOld = table.getOldValue(tab.getCurrentRow(), index);
if (valueOld == null)
{
return false;
}
final Object value = tab.getValue(columnName);
if (!valueOld.equals(value))
{
return true;
}
return false;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("MTableIndex[");
sb.append(get_ID()).append("-").append(getName()).append(
",AD_Table_ID=").append(getAD_Table_ID()).append("]");
return sb.toString();
}
private static class TableIndexesMap
{
private final ImmutableListMultimap<String, MIndexTable> indexesByTableName;
private final ImmutableMap<String, MIndexTable> indexesByNameUC;
public TableIndexesMap(final List<MIndexTable> indexes)
{
indexesByTableName = Multimaps.index(indexes, MIndexTable::getTableName);
indexesByNameUC = Maps.uniqueIndex(indexes, index -> index.getName().toUpperCase());
}
public ImmutableList<MIndexTable> getByTableName(@NonNull final String tableName)
{
return indexesByTableName.get(tableName);
}
public MIndexTable getByNameIgnoringCase(@NonNull final String name)
{
String nameUC = name.toUpperCase();
return indexesByNameUC.get(nameUC);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexTable.java | 1 |
请完成以下Java代码 | protected IQueryFilter<ET> createFilter()
{
return queryBL.createCompositeQueryFilter(eventTypeClass)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.addEqualsFilter(COLUMNNAME_Processed, false)
.addFilter(lockManager.getNotLockedFilter(eventTypeClass));
}
@Override
public void close()
{
// Mark this source as closed
if (_closed.getAndSet(true))
{
// already closed
return;
}
//
// Unlock all | if (_lock != null)
{
_lock.close();
_lock = null;
}
//
// Close iterator
if (_iterator != null)
{
IteratorUtils.closeQuietly(_iterator);
_iterator = null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\EventSource.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8088
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
url: jdbc:mysql:/ | /localhost:3307/demo?serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver | repos\springboot-demo-master\dynamic-datasource\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BroadcastConfig {
private static final boolean NON_DURABLE = false;
public final static String FANOUT_QUEUE_1_NAME = "com.baeldung.spring-amqp-simple.fanout.queue1";
public final static String FANOUT_QUEUE_2_NAME = "com.baeldung.spring-amqp-simple.fanout.queue2";
public final static String FANOUT_EXCHANGE_NAME = "com.baeldung.spring-amqp-simple.fanout.exchange";
public final static String TOPIC_QUEUE_1_NAME = "com.baeldung.spring-amqp-simple.topic.queue1";
public final static String TOPIC_QUEUE_2_NAME = "com.baeldung.spring-amqp-simple.topic.queue2";
public final static String TOPIC_EXCHANGE_NAME = "com.baeldung.spring-amqp-simple.topic.exchange";
public static final String BINDING_PATTERN_IMPORTANT = "*.important.*";
public static final String BINDING_PATTERN_ERROR = "#.error";
@Bean
public Declarables topicBindings() {
Queue topicQueue1 = new Queue(TOPIC_QUEUE_1_NAME, NON_DURABLE);
Queue topicQueue2 = new Queue(TOPIC_QUEUE_2_NAME, NON_DURABLE);
TopicExchange topicExchange = new TopicExchange(TOPIC_EXCHANGE_NAME, NON_DURABLE, false);
return new Declarables(topicQueue1, topicQueue2, topicExchange, BindingBuilder
.bind(topicQueue1)
.to(topicExchange)
.with(BINDING_PATTERN_IMPORTANT), BindingBuilder
.bind(topicQueue2)
.to(topicExchange) | .with(BINDING_PATTERN_ERROR));
}
@Bean
public Declarables fanoutBindings() {
Queue fanoutQueue1 = new Queue(FANOUT_QUEUE_1_NAME, NON_DURABLE);
Queue fanoutQueue2 = new Queue(FANOUT_QUEUE_2_NAME, NON_DURABLE);
FanoutExchange fanoutExchange = new FanoutExchange(FANOUT_EXCHANGE_NAME, NON_DURABLE, false);
return new Declarables(fanoutQueue1, fanoutQueue2, fanoutExchange, BindingBuilder
.bind(fanoutQueue1)
.to(fanoutExchange), BindingBuilder
.bind(fanoutQueue2)
.to(fanoutExchange));
}
} | repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\broadcast\BroadcastConfig.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_C_Phase getC_Phase()
{
return get_ValueAsPO(COLUMNNAME_C_Phase_ID, org.compiere.model.I_C_Phase.class);
}
@Override
public void setC_Phase(final org.compiere.model.I_C_Phase C_Phase)
{
set_ValueFromPO(COLUMNNAME_C_Phase_ID, org.compiere.model.I_C_Phase.class, C_Phase);
}
@Override
public void setC_Phase_ID (final int C_Phase_ID)
{
if (C_Phase_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, C_Phase_ID);
}
@Override
public int getC_Phase_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Phase_ID);
}
@Override
public void setC_Task_ID (final int C_Task_ID)
{
if (C_Task_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Task_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Task_ID, C_Task_ID);
}
@Override
public int getC_Task_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Task_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
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 setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStandardQty (final BigDecimal StandardQty)
{
set_Value (COLUMNNAME_StandardQty, StandardQty);
}
@Override
public BigDecimal getStandardQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty);
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_Task.java | 1 |
请完成以下Java代码 | private void reset(boolean clearPrimaryField) {
fQtyOrdered.removeActionListener(this);
if (clearPrimaryField) {
fProduct.setValue(null);
}
fQtyOrdered.setValue(Env.ZERO);
fQtyOrdered.setReadWrite(false);
fProduct.requestFocus();
}
private void updateData(boolean requestFocus, Component source) {
if (requestFocus) {
SwingFieldsUtil.focusNextNotEmpty(source, m_editors);
}
fQtyOrdered.setReadWrite(true);
fQtyOrdered.addActionListener(this);
}
private void commit() {
int M_Product_ID = getM_Product_ID();
if (M_Product_ID <= 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_M_Product_ID);
String productStr = fProduct.getDisplay();
if (productStr == null)
productStr = "";
BigDecimal qty = getQtyOrdered();
if (qty == null || qty.signum() == 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_QtyOrdered);
//
MOrderLine line = new MOrderLine(order);
line.setM_Product_ID(getM_Product_ID(), true);
line.setQty(qty);
line.saveEx();
//
reset(true); | changed = true;
refreshIncludedTabs();
setInfo(Msg.parseTranslation(Env.getCtx(),
"@RecordSaved@ - @M_Product_ID@:" + productStr
+ ", @QtyOrdered@:" + qty), false, null);
}
public void showCenter() {
AEnv.showCenterWindow(getOwner(), this);
}
public boolean isChanged() {
return changed;
}
public void refreshIncludedTabs() {
for (GridTab includedTab : orderTab.getIncludedTabs()) {
includedTab.dataRefreshAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\OrderLineCreate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
@ExceptionHandler(value = Exception.class)
public JSONObject defaultErrorHandler(HttpServletRequest req, Exception e) {
String errorPosition = "";
//如果错误堆栈信息存在
if (e.getStackTrace().length > 0) {
StackTraceElement element = e.getStackTrace()[0];
String fileName = element.getFileName() == null ? "未找到错误文件" : element.getFileName();
int lineNumber = element.getLineNumber();
errorPosition = fileName + ":" + lineNumber;
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", ErrorEnum.E_400.getErrorCode());
jsonObject.put("msg", ErrorEnum.E_400.getErrorMsg());
JSONObject errorObject = new JSONObject();
errorObject.put("errorLocation", e + " 错误位置:" + errorPosition);
jsonObject.put("info", errorObject);
logger.error("异常", e);
return jsonObject;
}
/**
* GET/POST请求方法错误的拦截器
* 因为开发时可能比较常见,而且发生在进入controller之前,上面的拦截器拦截不到这个错误
* 所以定义了这个拦截器
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public JSONObject httpRequestMethodHandler() {
return CommonUtil.errorJson(ErrorEnum.E_500);
}
/**
* 本系统自定义错误的拦截器
* 拦截到此错误之后,就返回这个类里面的json给前端
* 常见使用场景是参数校验失败,抛出此错,返回错误信息给前端
*/ | @ExceptionHandler(CommonJsonException.class)
public JSONObject commonJsonExceptionHandler(CommonJsonException commonJsonException) {
return commonJsonException.getResultJson();
}
/**
* 权限不足报错拦截
*/
@ExceptionHandler(UnauthorizedException.class)
public JSONObject unauthorizedExceptionHandler() {
return CommonUtil.errorJson(ErrorEnum.E_502);
}
/**
* 未登录报错拦截
* 在请求需要权限的接口,而连登录都还没登录的时候,会报此错
*/
@ExceptionHandler(UnauthenticatedException.class)
public JSONObject unauthenticatedException() {
return CommonUtil.errorJson(ErrorEnum.E_20011);
}
} | repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\exception\GlobalExceptionHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class AtlasPropertiesConfigAdapter extends PropertiesConfigAdapter<AtlasProperties> implements AtlasConfig {
AtlasPropertiesConfigAdapter(AtlasProperties properties) {
super(properties);
}
@Override
public @Nullable String get(String key) {
return null;
}
@Override
public Duration step() {
return obtain(AtlasProperties::getStep, AtlasConfig.super::step);
}
@Override
public boolean enabled() {
return obtain(AtlasProperties::isEnabled, AtlasConfig.super::enabled);
}
@Override
public Duration connectTimeout() {
return obtain(AtlasProperties::getConnectTimeout, AtlasConfig.super::connectTimeout);
}
@Override
public Duration readTimeout() {
return obtain(AtlasProperties::getReadTimeout, AtlasConfig.super::readTimeout);
}
@Override
public int numThreads() {
return obtain(AtlasProperties::getNumThreads, AtlasConfig.super::numThreads);
}
@Override
public int batchSize() {
return obtain(AtlasProperties::getBatchSize, AtlasConfig.super::batchSize);
}
@Override
public String uri() {
return obtain(AtlasProperties::getUri, AtlasConfig.super::uri);
}
@Override
public Duration meterTTL() { | return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL);
}
@Override
public boolean lwcEnabled() {
return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled);
}
@Override
public Duration lwcStep() {
return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep);
}
@Override
public boolean lwcIgnorePublishStep() {
return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep);
}
@Override
public Duration configRefreshFrequency() {
return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency);
}
@Override
public Duration configTTL() {
return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL);
}
@Override
public String configUri() {
return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri);
}
@Override
public String evalUri() {
return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public final void setSQLXML(final int parameterIndex, final SQLXML xmlObject) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, xmlObject);
getStatementImpl().setSQLXML(parameterIndex, xmlObject);
}
@Override
public final void setObject(final int parameterIndex, final Object x, final int targetSqlType, final int scaleOrLength) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
@Override
public final void setAsciiStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x, length);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x, length);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader, length);
}
@Override
public final void setAsciiStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x); | }
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader);
}
@Override
public final void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, value);
getStatementImpl().setNCharacterStream(parameterIndex, value);
}
@Override
public final void setClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setClob(parameterIndex, reader);
}
@Override
public final void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, inputStream);
getStatementImpl().setBlob(parameterIndex, inputStream);
}
@Override
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setNClob(parameterIndex, reader);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CPreparedStatementProxy.java | 1 |
请完成以下Java代码 | public void removedObserveRelation(ObserveRelation relation) {
Request request = relation.getExchange().getRequest();
String token = getTokenFromRequest(request);
clients.deregisterObserveRelation(token);
log.trace("Relation removed for token: {}", token);
}
}
private TbCoapDtlsSessionInfo getCoapDtlsSessionInfo(EndpointContext endpointContext) {
InetSocketAddress peerAddress = endpointContext.getPeerAddress();
String certPemStr = getCertPem(endpointContext);
TbCoapDtlsSessionKey tbCoapDtlsSessionKey = StringUtils.isNotBlank(certPemStr) ? new TbCoapDtlsSessionKey(peerAddress, certPemStr) : null;
TbCoapDtlsSessionInfo tbCoapDtlsSessionInfo;
if (tbCoapDtlsSessionKey != null) {
tbCoapDtlsSessionInfo = dtlsSessionsMap
.computeIfPresent(tbCoapDtlsSessionKey, (dtlsSessionIdStr, dtlsSessionInfo) -> {
dtlsSessionInfo.setLastActivityTime(System.currentTimeMillis());
return dtlsSessionInfo;
});
} else {
tbCoapDtlsSessionInfo = null; | }
return tbCoapDtlsSessionInfo;
}
private String getCertPem(EndpointContext endpointContext) {
try {
X509CertPath certPath = (X509CertPath) endpointContext.getPeerIdentity();
X509Certificate x509Certificate = (X509Certificate) certPath.getPath().getCertificates().get(0);
return Base64.getEncoder().encodeToString(x509Certificate.getEncoded());
} catch (Exception e) {
log.error("Failed to get cert PEM: [{}]", endpointContext.getPeerAddress(), e);
return null;
}
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\CoapTransportResource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<ListLineItemType> getListLineItem() {
if (listLineItem == null) {
listLineItem = new ArrayList<ListLineItemType>();
}
return this.listLineItem;
}
/**
* Represents a list line item used in a despatch advice.Gets the value of the deliveryListLineItem 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 deliveryListLineItem property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeliveryListLineItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DeliveryListLineItemType }
*
*
*/
public List<DeliveryListLineItemType> getDeliveryListLineItem() {
if (deliveryListLineItem == null) {
deliveryListLineItem = new ArrayList<DeliveryListLineItemType>();
}
return this.deliveryListLineItem;
}
/**
* Represents a list line item used in a forecast or JIT schedule.Gets the value of the forecastListLineItem 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 forecastListLineItem property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getForecastListLineItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ForecastListLineItemType }
*
*
*/
public List<ForecastListLineItemType> getForecastListLineItem() {
if (forecastListLineItem == null) {
forecastListLineItem = new ArrayList<ForecastListLineItemType>();
}
return this.forecastListLineItem;
}
/**
* A free-text description suceeding a list line item group.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFooterDescription() {
return footerDescription;
}
/**
* Sets the value of the footerDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFooterDescription(String value) {
this.footerDescription = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemListType.java | 2 |
请完成以下Java代码 | public final class NullViewHeaderPropertiesProvider implements ViewHeaderPropertiesProvider
{
public static final transient NullViewHeaderPropertiesProvider instance = new NullViewHeaderPropertiesProvider();
private NullViewHeaderPropertiesProvider()
{
}
@Override
public String getAppliesOnlyToTableName()
{
return null;
}
@Override | public @NonNull ViewHeaderProperties computeHeaderProperties(@NonNull final IView view)
{
return ViewHeaderProperties.EMPTY;
}
@Override
public ViewHeaderPropertiesIncrementalResult computeIncrementallyOnRowsChanged(
@NonNull final ViewHeaderProperties currentHeaderProperties,
@NonNull final IView view,
@NonNull final Set<DocumentId> changedRowIds,
final boolean watchedByFrontend)
{
return ViewHeaderPropertiesIncrementalResult.computedAsEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\NullViewHeaderPropertiesProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static String getPreviewType(Model model, FileAttribute fileAttribute, String officePreviewType, String pdfName, String outFilePath, FileHandlerService fileHandlerService, String officePreviewTypeImage, OtherFilePreviewImpl otherFilePreview) {
String suffix = fileAttribute.getSuffix();
boolean isPPT = suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx");
List<String> imageUrls = null;
try {
imageUrls = fileHandlerService.pdf2jpg(outFilePath,outFilePath, pdfName, fileAttribute);
} catch (Exception e) {
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
for (Throwable throwable : throwableArray) {
if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
if (e.getMessage().toLowerCase().contains(OFFICE_PASSWORD_MSG)) {
model.addAttribute("needFilePassword", true);
return EXEL_FILE_PREVIEW_PAGE;
}
} | }
}
if (imageUrls == null || imageUrls.size() < 1) {
return otherFilePreview.notSupportedFile(model, fileAttribute, "office转图片异常,请联系管理员");
}
model.addAttribute("imgUrls", imageUrls);
model.addAttribute("currentUrl", imageUrls.get(0));
if (officePreviewTypeImage.equals(officePreviewType)) {
// PPT 图片模式使用专用预览页面
return (isPPT ? PPT_FILE_PREVIEW_PAGE : OFFICE_PICTURE_FILE_PREVIEW_PAGE);
} else {
return PICTURE_FILE_PREVIEW_PAGE;
}
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\OfficeFilePreviewImpl.java | 2 |
请完成以下Java代码 | public void setIsDLM(final boolean IsDLM)
{
set_ValueNoCheck(COLUMNNAME_IsDLM, Boolean.valueOf(IsDLM));
}
/**
* Get DLM aktiviert.
*
* @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public boolean isDLM()
{
final Object oo = get_Value(COLUMNNAME_IsDLM);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/**
* Set Datensatz-ID.
*
* @param Record_ID
* Direct internal record ID
*/
@Override
public void setRecord_ID(final 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()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Name der DB-Tabelle.
*
* @param TableName Name der DB-Tabelle
*/
@Override
public void setTableName(final java.lang.String TableName)
{
set_ValueNoCheck(COLUMNNAME_TableName, TableName);
}
/**
* Get Name der DB-Tabelle.
*
* @return Name der DB-Tabelle
*/
@Override
public java.lang.String getTableName()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Record_V.java | 1 |
请完成以下Java代码 | private HUPackingMaterialsCollector getPackingMaterialsCollectorForInventory(final int inventoryId)
{
return packingMaterialsCollectorByInventoryId.get(inventoryId);
}
@Value
@Builder
private static class InventoryHeaderKey
{
@NonNull
ZonedDateTime movementDate;
@Nullable
String poReference;
}
@Value
@Builder
private static class InventoryLineKey
{
@NonNull HuId topLevelHU;
@NonNull ProductId productId;
@Nullable
InOutLineId receiptLineId;
}
@Value
@Builder
private static class InventoryLineCandidate
{
@NonNull ZonedDateTime movementDate;
@NonNull HuId topLevelHUId;
@NonNull ProductId productId;
@NonNull Quantity qty;
@Nullable | I_M_InOutLine receiptLine;
@Nullable
String poReference;
@Nullable
public InOutLineId getInOutLineId()
{
return receiptLine != null
? InOutLineId.ofRepoId(receiptLine.getM_InOutLine_ID())
: null;
}
public UomId getUomId()
{
return qty.getUomId();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\internaluse\InventoryAllocationDestination.java | 1 |
请完成以下Java代码 | public TaxCategoryId retrieveRegularTaxCategoryId()
{
final TaxCategoryId taxCategoryId = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_TaxCategory.class)
.addEqualsFilter(I_C_TaxCategory.COLUMN_VATType, X_C_TaxCategory.VATTYPE_RegularVAT)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.orderBy(I_C_TaxCategory.COLUMN_Name)
.create()
.firstId(TaxCategoryId::ofRepoIdOrNull);
if (taxCategoryId == null)
{
throw new AdempiereException("No tax category found for Regular VATType");
}
return taxCategoryId;
} | @NonNull
public Optional<TaxCategoryId> getTaxCategoryIdByInternalName(@NonNull final String internalName)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_TaxCategory.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_TaxCategory.COLUMNNAME_InternalName, internalName)
.create()
.firstOnlyOptional(I_C_TaxCategory.class)
.map(I_C_TaxCategory::getC_TaxCategory_ID)
.map(TaxCategoryId::ofRepoId);
}
@Override
public Tax getDefaultTax(final TaxCategoryId taxCategoryId)
{
return taxDAO.getDefaultTax(taxCategoryId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\impl\TaxBL.java | 1 |
请完成以下Java代码 | private String createStringFromBanner(Banner banner, Environment environment,
@Nullable Class<?> mainApplicationClass) throws UnsupportedEncodingException {
String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) {
banner.printBanner(environment, mainApplicationClass, out);
}
return byteArrayOutputStream.toString(charset);
}
/**
* Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {
private final Banner banner;
private final @Nullable Class<?> sourceClass;
PrintedBanner(Banner banner, @Nullable Class<?> sourceClass) {
this.banner = banner; | this.sourceClass = sourceClass;
}
@Override
public void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) {
sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass;
this.banner.printBanner(environment, sourceClass, out);
}
}
static class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern(DEFAULT_BANNER_LOCATION);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationBannerPrinter.java | 1 |
请完成以下Java代码 | public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
@Override
public void setScrappedQty (java.math.BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return The Quantity scrapped due to QA issues
*/
@Override
public java.math.BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge.
@param TargetQty
Target Movement Quantity
*/
@Override
public void setTargetQty (java.math.BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Target Movement Quantity
*/
@Override
public java.math.BigDecimal getTargetQty ()
{ | BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void publishProductExcludeAddedOrChanged(
final ProductId productId,
@NonNull final BPartnerId newBPartnerId,
final BPartnerId oldBPartnerId)
{
final PZN pzn = getPZNByProductId(productId);
final MSV3ProductExcludesUpdateEventBuilder eventBuilder = MSV3ProductExcludesUpdateEvent.builder();
if (oldBPartnerId != null && !Objects.equals(newBPartnerId, oldBPartnerId))
{
eventBuilder.item(MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(oldBPartnerId.getRepoId())
.delete(true)
.build());
}
eventBuilder.item(MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(newBPartnerId.getRepoId())
.build());
msv3ServerPeerService.publishProductExcludes(eventBuilder.build());
}
public void publishProductExcludeDeleted(final ProductId productId, final BPartnerId... bpartnerIds)
{
final PZN pzn = getPZNByProductId(productId); | final List<MSV3ProductExclude> eventItems = Stream.of(bpartnerIds)
.filter(Objects::nonNull)
.distinct()
.map(bpartnerId -> MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(bpartnerId.getRepoId())
.delete(true)
.build())
.collect(ImmutableList.toImmutableList());
if (eventItems.isEmpty())
{
return;
}
msv3ServerPeerService.publishProductExcludes(MSV3ProductExcludesUpdateEvent.builder()
.items(eventItems)
.build());
}
private int getPublishAllStockAvailabilityBatchSize()
{
return Services
.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_STOCK_AVAILABILITY_BATCH_SIZE, 500);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3StockAvailabilityService.java | 2 |
请完成以下Java代码 | public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Promotion Code.
@param PromotionCode
User entered promotion code at sales time
*/
public void setPromotionCode (String PromotionCode)
{
set_Value (COLUMNNAME_PromotionCode, PromotionCode);
}
/** Get Promotion Code.
@return User entered promotion code at sales time
*/
public String getPromotionCode ()
{
return (String)get_Value(COLUMNNAME_PromotionCode);
}
/** Set Usage Counter.
@param PromotionCounter
Usage counter
*/
public void setPromotionCounter (int PromotionCounter)
{
set_ValueNoCheck (COLUMNNAME_PromotionCounter, Integer.valueOf(PromotionCounter));
}
/** Get Usage Counter.
@return Usage counter
*/
public int getPromotionCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionCounter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usage Limit.
@param PromotionUsageLimit
Maximum usage limit
*/
public void setPromotionUsageLimit (int PromotionUsageLimit)
{ | set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请完成以下Java代码 | public class DbMetricsReporter {
protected MetricsRegistry metricsRegistry;
protected CommandExecutor commandExecutor;
protected String reporterId;
// log every 15 minutes...
protected long reportingIntervalInSeconds = 60 * 15;
protected MetricsCollectionTask metricsCollectionTask;
private Timer timer;
public DbMetricsReporter(MetricsRegistry metricsRegistry, CommandExecutor commandExecutor) {
this.metricsRegistry = metricsRegistry;
this.commandExecutor = commandExecutor;
initMetricsCollectionTask();
}
protected void initMetricsCollectionTask() {
metricsCollectionTask = new MetricsCollectionTask(metricsRegistry, commandExecutor);
}
public void start() {
timer = new Timer("Camunda Metrics Reporter", true);
long reportingIntervalInMillis = reportingIntervalInSeconds * 1000;
timer.scheduleAtFixedRate(metricsCollectionTask,
reportingIntervalInMillis,
reportingIntervalInMillis);
}
public void stop() {
if(timer != null) {
// cancel the timer
timer.cancel();
timer = null;
// collect and log manually for the last time
reportNow();
}
}
public void reportNow() {
if(metricsCollectionTask != null) {
metricsCollectionTask.run();
}
}
public void reportValueAtOnce(String name, long value) {
commandExecutor.execute(new ReportDbMetricsValueCmd(name, value));
}
public long getReportingIntervalInSeconds() {
return reportingIntervalInSeconds;
}
public void setReportingIntervalInSeconds(long reportingIntervalInSeconds) {
this.reportingIntervalInSeconds = reportingIntervalInSeconds;
}
public MetricsRegistry getMetricsRegistry() {
return metricsRegistry;
}
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public MetricsCollectionTask getMetricsCollectionTask() { | return metricsCollectionTask;
}
public void setMetricsCollectionTask(MetricsCollectionTask metricsCollectionTask) {
this.metricsCollectionTask = metricsCollectionTask;
}
public void setReporterId(String reporterId) {
this.reporterId = reporterId;
if (metricsCollectionTask != null) {
metricsCollectionTask.setReporter(reporterId);
}
}
protected class ReportDbMetricsValueCmd implements Command<Void> {
protected String name;
protected long value;
public ReportDbMetricsValueCmd(String name, long value) {
this.name = name;
this.value = value;
}
@Override
public Void execute(CommandContext commandContext) {
commandContext.getMeterLogManager().insert(new MeterLogEntity(name, reporterId, value, ClockUtil.getCurrentTime()));
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\DbMetricsReporter.java | 1 |
请完成以下Java代码 | public Integer getGiftPointOld() {
return giftPointOld;
}
public void setGiftPointOld(Integer giftPointOld) {
this.giftPointOld = giftPointOld;
}
public Integer getGiftPointNew() {
return giftPointNew;
}
public void setGiftPointNew(Integer giftPointNew) {
this.giftPointNew = giftPointNew;
}
public Integer getUsePointLimitOld() {
return usePointLimitOld;
}
public void setUsePointLimitOld(Integer usePointLimitOld) {
this.usePointLimitOld = usePointLimitOld;
}
public Integer getUsePointLimitNew() {
return usePointLimitNew;
}
public void setUsePointLimitNew(Integer usePointLimitNew) {
this.usePointLimitNew = usePointLimitNew;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
}
public Date getCreateTime() {
return createTime; | }
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@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(", priceOld=").append(priceOld);
sb.append(", priceNew=").append(priceNew);
sb.append(", salePriceOld=").append(salePriceOld);
sb.append(", salePriceNew=").append(salePriceNew);
sb.append(", giftPointOld=").append(giftPointOld);
sb.append(", giftPointNew=").append(giftPointNew);
sb.append(", usePointLimitOld=").append(usePointLimitOld);
sb.append(", usePointLimitNew=").append(usePointLimitNew);
sb.append(", operateMan=").append(operateMan);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductOperateLog.java | 1 |
请完成以下Java代码 | public boolean isAll()
{
return ALL.equals(this);
}
public boolean isOther()
{
return OTHER.equals(this);
}
private boolean isNone()
{
return NONE.equals(this);
}
public boolean isSpecific()
{
return !isAll() && !isOther() && !isNone();
}
public String getSqlLikeString()
{
String sqlLikeString = _sqlLikeString;
if (sqlLikeString == null)
{
sqlLikeString = _sqlLikeString = computeSqlLikeString();
}
return sqlLikeString;
}
private String computeSqlLikeString()
{
final StringBuilder sb = new StringBuilder();
sb.append("%");
boolean lastCharIsWildcard = true;
for (final AttributesKeyPartPattern partPattern : partPatterns)
{
final String partSqlLike = partPattern.getSqlLikePart();
if (lastCharIsWildcard)
{
if (partSqlLike.startsWith("%"))
{
sb.append(partSqlLike.substring(1));
}
else
{
sb.append(partSqlLike);
}
}
else
{
if (partSqlLike.startsWith("%"))
{
sb.append(partSqlLike);
}
else
{
sb.append("%").append(partSqlLike);
}
}
lastCharIsWildcard = partSqlLike.endsWith("%");
}
if (!lastCharIsWildcard)
{
sb.append("%");
} | return sb.toString();
}
public boolean matches(@NonNull final AttributesKey attributesKey)
{
for (final AttributesKeyPartPattern partPattern : partPatterns)
{
boolean partPatternMatched = false;
if (AttributesKey.NONE.getAsString().equals(attributesKey.getAsString()))
{
partPatternMatched = partPattern.matches(AttributesKeyPart.NONE);
}
else
{
for (final AttributesKeyPart part : attributesKey.getParts())
{
if (partPattern.matches(part))
{
partPatternMatched = true;
break;
}
}
}
if (!partPatternMatched)
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPattern.java | 1 |
请完成以下Java代码 | public static FieldExtension getField(DelegatePlanItemInstance planItemInstance, String fieldName) {
if (isExecutingLifecycleListener(planItemInstance)) {
return getListenerField(planItemInstance, fieldName);
} else {
return getCmmnElementField(planItemInstance, fieldName);
}
}
public static FieldExtension getCmmnElementField(DelegatePlanItemInstance planItemInstance, String fieldName) {
List<FieldExtension> fieldExtensions = getCmmnElementFields(planItemInstance);
if (fieldExtensions == null || fieldExtensions.size() == 0) {
return null;
}
for (FieldExtension fieldExtension : fieldExtensions) {
if (fieldExtension.getFieldName() != null && fieldExtension.getFieldName().equals(fieldName)) {
return fieldExtension;
}
}
return null;
}
public static FieldExtension getListenerField(DelegatePlanItemInstance planItemInstance, String fieldName) {
List<FieldExtension> fieldExtensions = getListenerFields(planItemInstance);
if (fieldExtensions == null || fieldExtensions.size() == 0) {
return null;
}
for (FieldExtension fieldExtension : fieldExtensions) {
if (fieldExtension.getFieldName() != null && fieldExtension.getFieldName().equals(fieldName)) {
return fieldExtension;
}
}
return null;
}
public static Expression createExpressionForField(FieldExtension fieldExtension) {
if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
return expressionManager.createExpression(fieldExtension.getExpression());
} else {
return new FixedValue(fieldExtension.getStringValue());
}
} | public static Expression getFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
if (isExecutingLifecycleListener(planItemInstance)) {
return getListenerFieldExpression(planItemInstance, fieldName);
} else {
return getCmmnElementFieldExpression(planItemInstance, fieldName);
}
}
public static Expression getCmmnElementFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
FieldExtension fieldExtension = getCmmnElementField(planItemInstance, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
public static Expression getListenerFieldExpression(DelegatePlanItemInstance planItemInstance, String fieldName) {
FieldExtension fieldExtension = getListenerField(planItemInstance, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\CmmnDelegateHelper.java | 1 |
请完成以下Java代码 | public void customize(InitializrMetadata metadata) {
metadata.getDependencies().merge(this.properties.getDependencies());
metadata.getTypes().merge(this.properties.getTypes());
metadata.getBootVersions().merge(this.properties.getBootVersions());
metadata.getPackagings().merge(this.properties.getPackagings());
metadata.getJavaVersions().merge(this.properties.getJavaVersions());
metadata.getLanguages().merge(this.properties.getLanguages());
metadata.getConfigurationFileFormats().merge(this.properties.getConfigurationFileFormats());
this.properties.getGroupId().apply(metadata.getGroupId());
this.properties.getArtifactId().apply(metadata.getArtifactId());
this.properties.getVersion().apply(metadata.getVersion());
this.properties.getName().apply(metadata.getName());
this.properties.getDescription().apply(metadata.getDescription());
this.properties.getPackageName().apply(metadata.getPackageName());
}
}
private static class ResourceInitializrMetadataCustomizer implements InitializrMetadataCustomizer {
private static final Log logger = LogFactory.getLog(ResourceInitializrMetadataCustomizer.class);
private static final Charset UTF_8 = StandardCharsets.UTF_8;
private final Resource resource;
ResourceInitializrMetadataCustomizer(Resource resource) { | this.resource = resource;
}
@Override
public void customize(InitializrMetadata metadata) {
logger.info("Loading initializr metadata from " + this.resource);
try (InputStream in = this.resource.getInputStream()) {
String content = StreamUtils.copyToString(in, UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
InitializrMetadata anotherMetadata = objectMapper.readValue(content, InitializrMetadata.class);
metadata.merge(anotherMetadata);
}
catch (Exception ex) {
throw new IllegalStateException("Cannot merge", ex);
}
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrMetadataBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Quantity getStorageQty(@NonNull final TU tu, @NonNull final ProductId productId)
{
final IHUStorageFactory huStorageFactory = HUContextHolder.getCurrent().getHUStorageFactory();
return huStorageFactory.getStorage(tu.toHU()).getQuantity(productId).orElseThrow(() -> new AdempiereException(NO_QTY_ERROR_MSG, tu, productId));
}
private HUQRCode getQRCode(@NonNull final LU lu) {return huService.getQRCodeByHuId(lu.getId());}
private HUQRCode getQRCode(@NonNull final TU tu) {return huService.getQRCodeByHuId(tu.getId());}
private void addToPickingSlotQueue(final LUTUResult packedHUs)
{
final PickingSlotId pickingSlotId = getPickingSlotId().orElse(null);
if (pickingSlotId == null)
{
return;
}
final CurrentPickingTarget currentPickingTarget = getPickingJob().getCurrentPickingTarget();
final LinkedHashSet<HuId> huIdsToAdd = new LinkedHashSet<>();
for (final LU lu : packedHUs.getLus())
{
if (lu.isPreExistingLU())
{
continue;
}
// do not add it if is current picking target, we will add it when closing the picking target.
if (currentPickingTarget.matches(lu.getId())) | {
continue;
}
huIdsToAdd.add(lu.getId());
}
for (final TU tu : packedHUs.getTopLevelTUs())
{
// do not add it if is current picking target, we will add it when closing the picking target.
if (currentPickingTarget.matches(tu.getId()))
{
continue;
}
huIdsToAdd.add(tu.getId());
}
if (!huIdsToAdd.isEmpty())
{
pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIdsToAdd);
}
}
private Optional<PickingSlotId> getPickingSlotId()
{
return getPickingJob().getPickingSlotIdEffective(getLineId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\pick\PickingJobPickCommand.java | 2 |
请完成以下Java代码 | private BPartnerId getBPartnerId(@Nullable final String value)
{
if (value == null)
{
return null;
}
return partnerDAO.getBPartnerIdByValue(value).orElse(null);
}
@Nullable
private ProductCategoryId getProductCategoryId(@Nullable final String value)
{
if (value == null)
{
return null; | }
return productDAO.retrieveProductCategoryIdByCategoryValue(value).orElse(null);
}
@Nullable
private ProductId getProductId(final String value)
{
return productDAO.retrieveProductIdByValue(value);
}
private List<String> readAttachmentLines() throws IOException
{
final AttachmentEntryDataResource attachment = attachmentEntryService.retrieveDataResource(p_AD_AttachmentEntry_ID);
return IOUtils.readLines(attachment.getInputStream(), StandardCharsets.UTF_8);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\process\ImportPriceListSchemaLinesFromAttachment.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getType() {
return type;
}
public int getTotalJobs() {
return totalJobs;
}
public int getBatchJobsPerSeed() {
return batchJobsPerSeed;
}
public int getInvocationsPerBatchJob() {
return invocationsPerBatchJob;
}
public String getSeedJobDefinitionId() {
return seedJobDefinitionId;
}
public String getMonitorJobDefinitionId() {
return monitorJobDefinitionId;
}
public String getBatchJobDefinitionId() {
return batchJobDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Date getRemovalTime() {
return removalTime;
} | public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) {
HistoricBatchDto dto = new HistoricBatchDto();
dto.id = historicBatch.getId();
dto.type = historicBatch.getType();
dto.totalJobs = historicBatch.getTotalJobs();
dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId();
dto.tenantId = historicBatch.getTenantId();
dto.createUserId = historicBatch.getCreateUserId();
dto.startTime = historicBatch.getStartTime();
dto.endTime = historicBatch.getEndTime();
dto.removalTime = historicBatch.getRemovalTime();
dto.executionStartTime = historicBatch.getExecutionStartTime();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchDto.java | 1 |
请完成以下Java代码 | protected String doIt()
{
helper.updateEligibleShipmentSchedules(
CarrierAdviseUpdateRequest.builder()
.query(ShipmentScheduleQuery.builder()
.shipperId(p_ShipperId)
.shipmentScheduleIds(getSelectedShipmentScheduleIds())
.build())
.isIncludeCarrierAdviseManual(p_IsIncludeCarrierAdviseManual)
.carrierProductId(p_CarrierProduct)
.carrierGoodsTypeId(p_GoodsType)
.carrierServiceIds(getCarrierServiceIds())
.build()
); | return JavaProcess.MSG_OK;
}
private ImmutableSet<ShipmentScheduleId> getSelectedShipmentScheduleIds()
{
return getSelectedIds(ShipmentScheduleId::ofRepoId, rowsLimit);
}
private ImmutableSet<CarrierServiceId> getCarrierServiceIds()
{
return Stream.of(p_CarrierProductService, p_CarrierProductService2, p_CarrierProductService3)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons.webui\src\main\java\de\metas\shipper\gateway\commons\webui\M_ShipmentSchedule_Advise_Manual.java | 1 |
请完成以下Java代码 | public class Article {
// @JsonIgnore
// @JsonProperty(access = JsonProperty.Access.READ_ONLY)
// @Schema(accessMode = AccessMode.READ_ONLY)
@Hidden
private int id;
private String title;
private int numOfWords;
public Article() {
}
public Article(int id, String title) {
this.id = id;
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getNumOfWords() {
return numOfWords;
}
public void setNumOfWords(int numOfWords) {
this.numOfWords = numOfWords;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-4\src\main\java\com\baeldung\springboot\swagger\model\Article.java | 1 |
请完成以下Java代码 | public Date getEndedTime() {
return endedTime;
}
@Override
public String getStartUserId() {
return startUserId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public boolean isCompletable() {
return completable;
}
@Override
public String getEntryCriterionId() {
return entryCriterionId;
}
@Override
public String getExitCriterionId() {
return exitCriterionId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public String getExtraValue() {
return extraValue;
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName); | }
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
return localVariables;
}
@Override
public PlanItem getPlanItem() {
return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | public String getNewState() {
return CaseInstanceState.COMPLETED;
}
@Override
public void changeStateForChildPlanItemInstance(PlanItemInstanceEntity planItemInstanceEntity) {
// terminate all child plan items not yet in an end state of the case itself (same way as with a stage for instance)
// if they would be completed, the history will contain completed plan item instances although they never "truly" completed
// specially important for cases supporting reactivation
// if the plan item implements the specific behavior interface for ending, invoke it, otherwise use the default one which is terminate, regardless,
// if the case got completed or terminated
Object behavior = planItemInstanceEntity.getPlanItem().getBehavior();
if (behavior instanceof OnParentEndDependantActivityBehavior) {
// if the specific behavior is implemented, invoke it
((OnParentEndDependantActivityBehavior) behavior).onParentEnd(commandContext, planItemInstanceEntity, PlanItemTransition.COMPLETE, null);
} else {
// use default behavior, if the interface is not implemented
CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(planItemInstanceEntity, null, null);
}
}
/**
* Overwritten in order to send a case end / completion event through the case engine dispatcher.
*/
@Override
protected void invokePostLifecycleListeners() {
super.invokePostLifecycleListeners(); | CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher()
.dispatchEvent(FlowableCmmnEventBuilder.createCaseEndedEvent(caseInstanceEntity, CaseInstanceState.COMPLETED),
EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG);
}
@Override
public String getDeleteReason() {
return "cmmn-state-transition-complete-case";
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Complete case instance] case instance ");
strb.append(caseInstanceEntity != null ? caseInstanceEntity.getId() : caseInstanceEntityId);
return strb.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\CompleteCaseInstanceOperation.java | 1 |
请完成以下Java代码 | public OAuth2TokenIntrospection build() {
validate();
return new OAuth2TokenIntrospection(this.claims);
}
private void validate() {
Assert.notNull(this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE), "active cannot be null");
Assert.isInstanceOf(Boolean.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE),
"active must be of type boolean");
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.SCOPE)) {
Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE),
"scope must be of type List");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.EXP)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.EXP),
"exp must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.IAT)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.IAT),
"iat must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.NBF)) {
Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.NBF),
"nbf must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.AUD)) {
Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.AUD),
"aud must be of type List");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.ISS)) {
validateURL(this.claims.get(OAuth2TokenIntrospectionClaimNames.ISS), "iss must be a valid URL");
}
}
@SuppressWarnings("unchecked")
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>()); | ((List<String>) this.claims.get(name)).add(value);
}
@SuppressWarnings("unchecked")
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
List<String> values = (List<String>) this.claims.get(name);
valuesConsumer.accept(values);
}
private static void validateURL(Object url, String errorMessage) {
if (URL.class.isAssignableFrom(url.getClass())) {
return;
}
try {
new URI(url.toString()).toURL();
}
catch (Exception ex) {
throw new IllegalArgumentException(errorMessage, ex);
}
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2TokenIntrospection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void addDynamicDataSource(SysDataSource sysDataSource, String dbPassword) {
DataSourceProperty dataSourceProperty = new DataSourceProperty();
dataSourceProperty.setUrl(sysDataSource.getDbUrl());
dataSourceProperty.setPassword(dbPassword);
dataSourceProperty.setDriverClassName(sysDataSource.getDbDriver());
dataSourceProperty.setUsername(sysDataSource.getDbUsername());
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
try {
ds.addDataSource(sysDataSource.getCode(), dataSource);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除数据源
* @param code
*/
private void removeDynamicDataSource(String code) { | DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
ds.removeDataSource(code);
}
/**
* 检查数据源编码是否存在
*
* @param dbCode
* @return
*/
private long checkDbCode(String dbCode) {
QueryWrapper<SysDataSource> qw = new QueryWrapper();
qw.lambda().eq(true, SysDataSource::getCode, dbCode);
return count(qw);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDataSourceServiceImpl.java | 2 |
请完成以下Java代码 | public Boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken( token );
return expiration.before( new Date() );
}
/**
* 根据token获取username
*/
public String getUsernameFromToken(String token) {
String username = getClaimsFromToken( token ).getSubject();
return username;
}
/**
* 获取token的过期时间
*/
public Date getExpirationDateFromToken(String token) {
Date expiration = getClaimsFromToken( token ).getExpiration();
return expiration; | }
/**
* 解析JWT
*/
private Claims getClaimsFromToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey( SECRET )
.parseClaimsJws( token )
.getBody();
return claims;
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\utils\JwtTokenUtil.java | 1 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start No.
@param StartNo
Starting number/position
*/
@Override
public void setStartNo (int StartNo) | {
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
@Override
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
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_ImpFormat_Row.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class UserRestController {
private final UserService userService;
private final JWTSerializer jwtSerializer;
UserRestController(UserService userService, JWTSerializer jwtSerializer) {
this.userService = userService;
this.jwtSerializer = jwtSerializer;
}
@PostMapping("/users")
public UserModel postUser(@Valid @RequestBody UserPostRequestDTO dto) {
final var userSaved = userService.signUp(dto.toSignUpRequest());
return fromUserAndToken(userSaved, jwtSerializer.jwtFromUser(userSaved));
}
@PostMapping("/users/login")
public ResponseEntity<UserModel> loginUser(@Valid @RequestBody UserLoginRequestDTO dto) {
return of(userService.login(new Email(dto.getEmail()), dto.getPassword())
.map(user -> fromUserAndToken(user, jwtSerializer.jwtFromUser(user))));
}
@GetMapping("/user") | public ResponseEntity<UserModel> getUser(@AuthenticationPrincipal UserJWTPayload jwtPayload) {
return of(userService.findById(jwtPayload.getUserId())
.map(user -> UserModel.fromUserAndToken(user, getCurrentCredential())));
}
@PutMapping("/user")
public UserModel putUser(@AuthenticationPrincipal UserJWTPayload jwtPayload,
@Valid @RequestBody UserPutRequestDTO dto) {
final var userUpdated = userService.updateUser(jwtPayload.getUserId(), dto.toUpdateRequest());
return fromUserAndToken(userUpdated, getCurrentCredential());
}
private static String getCurrentCredential() {
return SecurityContextHolder.getContext()
.getAuthentication()
.getCredentials()
.toString();
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\user\UserRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JmxManagedProcessEngine implements PlatformService<ProcessEngine>, JmxManagedProcessEngineMBean {
protected ProcessEngine processEngine;
// for subclasses
protected JmxManagedProcessEngine() {
}
public JmxManagedProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
}
public void start(PlatformServiceContainer contanier) {
// this one has no lifecycle support
}
public void stop(PlatformServiceContainer container) {
// this one has no lifecycle support
}
public String getName() {
return processEngine.getName();
}
public ProcessEngine getProcessEngine() {
return processEngine;
}
public ProcessEngine getValue() {
return processEngine;
}
public Set<String> getRegisteredDeployments() {
ManagementService managementService = processEngine.getManagementService();
return managementService.getRegisteredDeployments();
} | public void registerDeployment(String deploymentId) {
ManagementService managementService = processEngine.getManagementService();
managementService.registerDeploymentForJobExecutor(deploymentId);
}
public void unregisterDeployment(String deploymentId) {
ManagementService managementService = processEngine.getManagementService();
managementService.unregisterDeploymentForJobExecutor(deploymentId);
}
public void reportDbMetrics() {
ManagementService managementService = processEngine.getManagementService();
managementService.reportDbMetricsNow();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedProcessEngine.java | 2 |
请完成以下Java代码 | public static boolean isValueChanged(Object oldValue, Object value)
{
if (isNotNullAndIsEmpty(oldValue))
{
oldValue = null;
}
if (isNotNullAndIsEmpty(value))
{
value = null;
}
boolean bChanged = oldValue == null && value != null
|| oldValue != null && value == null;
if (!bChanged && oldValue != null)
{
if (oldValue.getClass().equals(value.getClass()))
{
if (oldValue instanceof Comparable<?>)
{
bChanged = ((Comparable<Object>)oldValue).compareTo(value) != 0;
}
else
{
bChanged = !oldValue.equals(value); | }
}
else if (value != null)
{
bChanged = !oldValue.toString().equals(value.toString());
}
}
return bChanged;
}
private static boolean isNotNullAndIsEmpty(final Object value)
{
if (value != null
&& value instanceof String
&& value.toString().equals(""))
{
return true;
}
else
{
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTableUtils.java | 1 |
请完成以下Java代码 | public void setAD_Language (java.lang.String AD_Language)
{
set_Value (COLUMNNAME_AD_Language, AD_Language);
}
/** Get Sprache.
@return Sprache für diesen Eintrag
*/
@Override
public java.lang.String getAD_Language ()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_Language);
}
@Override
public org.compiere.model.I_C_Country getC_Country() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setC_Country(org.compiere.model.I_C_Country C_Country)
{
set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country);
}
/** Set Land.
@param C_Country_ID
Land
*/
@Override
public void setC_Country_ID (int C_Country_ID)
{
if (C_Country_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Country_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID));
}
/** Get Land.
@return Land
*/
@Override
public int getC_Country_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Country Sequence.
@param C_Country_Sequence_ID Country Sequence */
@Override
public void setC_Country_Sequence_ID (int C_Country_Sequence_ID)
{
if (C_Country_Sequence_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, Integer.valueOf(C_Country_Sequence_ID));
}
/** Get Country Sequence.
@return Country Sequence */
@Override
public int getC_Country_Sequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_Sequence_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Adress-Druckformat.
@param DisplaySequence
Format for printing this Address
*/
@Override
public void setDisplaySequence (java.lang.String DisplaySequence)
{
set_Value (COLUMNNAME_DisplaySequence, DisplaySequence);
}
/** Get Adress-Druckformat.
@return Format for printing this Address
*/
@Override
public java.lang.String getDisplaySequence ()
{
return (java.lang.String)get_Value(COLUMNNAME_DisplaySequence);
}
/** Set Local Address Format.
@param DisplaySequenceLocal
Format for printing this Address locally
*/
@Override
public void setDisplaySequenceLocal (java.lang.String DisplaySequenceLocal)
{
set_Value (COLUMNNAME_DisplaySequenceLocal, DisplaySequenceLocal);
}
/** Get Local Address Format.
@return Format for printing this Address locally
*/
@Override
public java.lang.String getDisplaySequenceLocal ()
{
return (java.lang.String)get_Value(COLUMNNAME_DisplaySequenceLocal);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country_Sequence.java | 1 |
请完成以下Java代码 | public List<String> getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(List<String> tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public Boolean getIncludeExtensionProperties() {
return includeExtensionProperties;
}
public void setIncludeExtensionProperties(Boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
}
public void fromAnnotation(ExternalTaskSubscription config) {
setAutoOpen(config.autoOpen());
String topicName = config.topicName();
setTopicName(isNull(topicName) ? null : topicName);
long lockDuration = config.lockDuration();
setLockDuration(isNull(lockDuration) ? null : lockDuration);
String[] variableNames = config.variableNames();
setVariableNames(isNull(variableNames) ? null : Arrays.asList(variableNames));
setLocalVariables(config.localVariables());
String businessKey = config.businessKey();
setBusinessKey(isNull(businessKey) ? null : businessKey);
String processDefinitionId = config.processDefinitionId();
setProcessDefinitionId(isNull(processDefinitionId) ? null : processDefinitionId);
String[] processDefinitionIdIn = config.processDefinitionIdIn();
setProcessDefinitionIdIn(isNull(processDefinitionIdIn) ? null :
Arrays.asList(processDefinitionIdIn));
String processDefinitionKey = config.processDefinitionKey();
setProcessDefinitionKey(isNull(processDefinitionKey) ? null : processDefinitionKey);
String[] processDefinitionKeyIn = config.processDefinitionKeyIn();
setProcessDefinitionKeyIn(isNull(processDefinitionKeyIn) ? null :
Arrays.asList(processDefinitionKeyIn));
String processDefinitionVersionTag = config.processDefinitionVersionTag();
setProcessDefinitionVersionTag(isNull(processDefinitionVersionTag) ? null :
processDefinitionVersionTag);
ProcessVariable[] processVariables = config.processVariables();
setProcessVariables(isNull(processVariables) ? null : Arrays.stream(processVariables)
.collect(Collectors.toMap(ProcessVariable::name, ProcessVariable::value))); | setWithoutTenantId(config.withoutTenantId());
String[] tenantIdIn = config.tenantIdIn();
setTenantIdIn(isNull(tenantIdIn) ? null : Arrays.asList(tenantIdIn));
setIncludeExtensionProperties(config.includeExtensionProperties());
}
protected static boolean isNull(String[] values) {
return values.length == 1 && STRING_NULL_VALUE.equals(values[0]);
}
protected static boolean isNull(String value) {
return STRING_NULL_VALUE.equals(value);
}
protected static boolean isNull(long value) {
return LONG_NULL_VALUE == value;
}
protected static boolean isNull(ProcessVariable[] values) {
return values.length == 1 && STRING_NULL_VALUE.equals(values[0].name()) &&
STRING_NULL_VALUE.equals(values[0].value());
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SubscriptionConfiguration.java | 1 |
请完成以下Java代码 | public JSONLookupValuesPage getFieldTypeahead(
@PathVariable(PARAM_WindowId) final String windowIdStr,
@PathVariable(PARAM_ViewId) final String viewIdStr,
@PathVariable(PARAM_RowId) final String rowIdStr,
@PathVariable(PARAM_FieldName) final String fieldName,
@RequestParam("query") final String query)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
final IEditableView view = getEditableView(viewId);
final RowEditingContext editingCtx = createRowEditingContext(viewId, rowId);
return view.getFieldTypeahead(editingCtx, fieldName, query)
.transform(page -> JSONLookupValuesPage.of(page, userSession.getAD_Language()));
}
private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList)
{
return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language());
}
@GetMapping("/{fieldName}/dropdown")
public JSONLookupValuesList getFieldDropdown(
@PathVariable(PARAM_WindowId) final String windowIdStr, | @PathVariable(PARAM_ViewId) final String viewIdStr,
@PathVariable(PARAM_RowId) final String rowIdStr,
@PathVariable(PARAM_FieldName) final String fieldName)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
final IEditableView view = getEditableView(viewId);
final RowEditingContext editingCtx = createRowEditingContext(viewId, rowId);
return view.getFieldDropdown(editingCtx, fieldName)
.transform(this::toJSONLookupValuesList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowEditRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyController {
@RequestMapping("/")
public String init(Map<String, Object> model, Principal principal) {
model.put("title", "PUBLIC AREA");
model.put("message", "Any user can view this page");
model.put("username", getUserName(principal));
model.put("userroles", getUserRoles(principal));
return "home";
}
@RequestMapping("/secure")
public String secure(Map<String, Object> model, Principal principal) {
model.put("title", "SECURE AREA");
model.put("message", "Only Authorised Users Can See This Page");
model.put("username", getUserName(principal));
model.put("userroles", getUserRoles(principal));
return "home";
}
private String getUserName(Principal principal) {
if (principal == null) {
return "anonymous";
} else {
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
System.out.println(grantedAuthority.getAuthority());
} | return principal.getName();
}
}
private Collection<String> getUserRoles(Principal principal) {
if (principal == null) {
return Arrays.asList("none");
} else {
Set<String> roles = new HashSet<String>();
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
roles.add(grantedAuthority.getAuthority());
}
return roles;
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\controller\MyController.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Attributes2 AD_Reference_ID=541333
* Reference name: Attributes2
*/
public static final int ATTRIBUTES2_AD_Reference_ID=541333;
/** Test(A2T1) = A2T1 */
public static final String ATTRIBUTES2_TestA2T1 = "A2T1";
/** Test(A2T2) = A2T2 */
public static final String ATTRIBUTES2_TestA2T2 = "A2T2";
@Override
public void setAttributes2 (final java.lang.String Attributes2)
{
set_Value (COLUMNNAME_Attributes2, Attributes2);
}
@Override
public java.lang.String getAttributes2()
{
return get_ValueAsString(COLUMNNAME_Attributes2);
}
@Override
public void setC_BPartner_QuickInput_Attributes2_ID (final int C_BPartner_QuickInput_Attributes2_ID)
{
if (C_BPartner_QuickInput_Attributes2_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID, C_BPartner_QuickInput_Attributes2_ID);
}
@Override
public int getC_BPartner_QuickInput_Attributes2_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_Attributes2_ID);
} | @Override
public org.compiere.model.I_C_BPartner_QuickInput getC_BPartner_QuickInput()
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class);
}
@Override
public void setC_BPartner_QuickInput(final org.compiere.model.I_C_BPartner_QuickInput C_BPartner_QuickInput)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_QuickInput_ID, org.compiere.model.I_C_BPartner_QuickInput.class, C_BPartner_QuickInput);
}
@Override
public void setC_BPartner_QuickInput_ID (final int C_BPartner_QuickInput_ID)
{
if (C_BPartner_QuickInput_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_QuickInput_ID, C_BPartner_QuickInput_ID);
}
@Override
public int getC_BPartner_QuickInput_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_QuickInput_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput_Attributes2.java | 1 |
请完成以下Java代码 | public void setisQtyLUByMaxLoadWeight (final boolean isQtyLUByMaxLoadWeight)
{
set_Value (COLUMNNAME_isQtyLUByMaxLoadWeight, isQtyLUByMaxLoadWeight);
}
@Override
public boolean isQtyLUByMaxLoadWeight()
{
return get_ValueAsBoolean(COLUMNNAME_isQtyLUByMaxLoadWeight);
}
@Override
public void setIsInvoiceable (final boolean IsInvoiceable)
{
set_Value (COLUMNNAME_IsInvoiceable, IsInvoiceable);
}
@Override
public boolean isInvoiceable()
{
return get_ValueAsBoolean(COLUMNNAME_IsInvoiceable);
}
@Override
public void setLength (final @Nullable BigDecimal Length)
{
set_Value (COLUMNNAME_Length, Length);
}
@Override
public BigDecimal getLength()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight)
{
set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight);
}
@Override
public BigDecimal getMaxLoadWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID)
{
if (M_HU_PackingMaterial_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID);
}
@Override
public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
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 setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setStackabilityFactor (final int StackabilityFactor)
{
set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor);
}
@Override
public int getStackabilityFactor()
{
return get_ValueAsInt(COLUMNNAME_StackabilityFactor);
}
@Override
public void setWidth (final @Nullable BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java | 1 |
请完成以下Java代码 | public java.lang.String getProduct_UUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_Product_UUID);
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_ValueNoCheck (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
/** Set Old Zusagbar.
@param QtyPromised_Old Old Zusagbar */
@Override
public void setQtyPromised_Old (java.math.BigDecimal QtyPromised_Old)
{
set_Value (COLUMNNAME_QtyPromised_Old, QtyPromised_Old);
}
/** Get Old Zusagbar.
@return Old Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised_Old ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_Old);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
/** Set Zusagbar (TU).
@param QtyPromised_TU Zusagbar (TU) */
@Override
public void setQtyPromised_TU (java.math.BigDecimal QtyPromised_TU)
{
set_ValueNoCheck (COLUMNNAME_QtyPromised_TU, QtyPromised_TU);
} | /** Get Zusagbar (TU).
@return Zusagbar (TU) */
@Override
public java.math.BigDecimal getQtyPromised_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
/** Set Old Zusagbar (TU).
@param QtyPromised_TU_Old Old Zusagbar (TU) */
@Override
public void setQtyPromised_TU_Old (java.math.BigDecimal QtyPromised_TU_Old)
{
set_Value (COLUMNNAME_QtyPromised_TU_Old, QtyPromised_TU_Old);
}
/** Get Old Zusagbar (TU).
@return Old Zusagbar (TU) */
@Override
public java.math.BigDecimal getQtyPromised_TU_Old ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_Old);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_QtyReport_Event.java | 1 |
请完成以下Java代码 | public boolean hasAddedRows()
{
final HashSet<DocumentId> addedRowIds = this.addedRowIds;
return addedRowIds != null && !addedRowIds.isEmpty();
}
@Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds)
{
if (removedRowIds == null)
{
removedRowIds = new HashSet<>(rowIds);
}
else
{
removedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getRemovedRowIds()
{
final HashSet<DocumentId> removedRowIds = this.removedRowIds;
return removedRowIds != null ? removedRowIds : ImmutableSet.of();
}
@Override
public void collectChangedRowIds(final Collection<DocumentId> rowIds) | {
if (changedRowIds == null)
{
changedRowIds = new HashSet<>(rowIds);
}
else
{
changedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getChangedRowIds()
{
final HashSet<DocumentId> changedRowIds = this.changedRowIds;
return changedRowIds != null ? changedRowIds : ImmutableSet.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\AddRemoveChangedRowIdsCollector.java | 1 |
请完成以下Java代码 | public void attachState(MigratingScopeInstance owningInstance) {
ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution();
representativeExecution.addExternalTask(externalTask);
externalTask.setExecution(representativeExecution);
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
ScopeImpl targetActivity = migratingActivityInstance.getTargetScope();
ProcessDefinition targetProcessDefinition = (ProcessDefinition) targetActivity.getProcessDefinition();
externalTask.setActivityId(targetActivity.getId());
externalTask.setProcessDefinitionId(targetProcessDefinition.getId()); | externalTask.setProcessDefinitionKey(targetProcessDefinition.getKey());
}
public String getId() {
return externalTask.getId();
}
public ScopeImpl getTargetScope() {
return migratingActivityInstance.getTargetScope();
}
public void addMigratingDependentInstance(MigratingInstance migratingInstance) {
dependentInstances.add(migratingInstance);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingExternalTaskInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getPlanItemInstanceUrl() {
return planItemInstanceUrl;
}
public void setPlanItemInstanceUrl(String planItemInstanceUrl) {
this.planItemInstanceUrl = planItemInstanceUrl;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getScopeId() {
return scopeId;
} | public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResponse.java | 2 |
请完成以下Java代码 | public class StartupTimeline {
private final Instant startTime;
private final List<TimelineEvent> events;
StartupTimeline(Instant startTime, List<TimelineEvent> events) {
this.startTime = startTime;
this.events = Collections.unmodifiableList(events);
}
/**
* Return the start time of this timeline.
* @return the start time
*/
public Instant getStartTime() {
return this.startTime;
}
/**
* Return the recorded events.
* @return the events
*/
public List<TimelineEvent> getEvents() {
return this.events;
}
/**
* Event on the current {@link StartupTimeline}. Each event has a start/end time, a
* precise duration and the complete {@link StartupStep} information associated with
* it.
*/
public static class TimelineEvent {
private final BufferedStartupStep step;
private final Instant endTime;
private final Duration duration;
TimelineEvent(BufferedStartupStep step, Instant endTime) {
this.step = step;
this.endTime = endTime;
this.duration = Duration.between(step.getStartTime(), endTime);
}
/**
* Return the start time of this event. | * @return the start time
*/
public Instant getStartTime() {
return this.step.getStartTime();
}
/**
* Return the end time of this event.
* @return the end time
*/
public Instant getEndTime() {
return this.endTime;
}
/**
* Return the duration of this event, i.e. the processing time of the associated
* {@link StartupStep} with nanoseconds precision.
* @return the event duration
*/
public Duration getDuration() {
return this.duration;
}
/**
* Return the {@link StartupStep} information for this event.
* @return the step information.
*/
public StartupStep getStartupStep() {
return this.step;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\StartupTimeline.java | 1 |
请完成以下Java代码 | public void remove()
{
getCreateIterator().remove();
}
private void assertNotClosed()
{
Check.assume(!_closed.get(), "Source is not already closed");
}
private Iterator<ET> getCreateIterator()
{
assertNotClosed();
if (_iterator == null)
{
final ILock lock = getOrAcquireLock();
final Object contextProvider = PlainContextAware.newWithThreadInheritedTrx(ctx);
_iterator = queryBL.createQueryBuilder(eventTypeClass, contextProvider)
.filter(lockManager.getLockedByFilter(eventTypeClass, lock))
.addOnlyActiveRecordsFilter()
//
.orderBy()
.addColumn(InterfaceWrapperHelper.getKeyColumnName(eventTypeClass))
.endOrderBy()
//
.create()
.iterate(eventTypeClass);
}
return _iterator;
}
private ILock getOrAcquireLock()
{
assertNotClosed();
if (_lock == null)
{
final IQueryFilter<ET> filter = createFilter();
final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName());
_lock = lockManager.lock()
.setOwner(lockOwner)
.setAutoCleanup(true) | .setFailIfNothingLocked(false)
.setRecordsByFilter(eventTypeClass, filter)
.acquire();
}
return _lock;
}
protected IQueryFilter<ET> createFilter()
{
return queryBL.createCompositeQueryFilter(eventTypeClass)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.addEqualsFilter(COLUMNNAME_Processed, false)
.addFilter(lockManager.getNotLockedFilter(eventTypeClass));
}
@Override
public void close()
{
// Mark this source as closed
if (_closed.getAndSet(true))
{
// already closed
return;
}
//
// Unlock all
if (_lock != null)
{
_lock.close();
_lock = null;
}
//
// Close iterator
if (_iterator != null)
{
IteratorUtils.closeQuietly(_iterator);
_iterator = null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\EventSource.java | 1 |
请完成以下Java代码 | public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override | public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
}
@Override
public int getUpdatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions);
}
@Override
public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getUpdated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java | 1 |
请完成以下Java代码 | public static boolean validate(@Nullable final String email)
{
return validate(email, null);
}
/**
* @param clazz optional, may be {@code null}. If a class is given and the given {@code email} is not valid,
* then this method instantiates and throws an exception with message {@code "@EmailNotValid@"}.
*/
public static boolean validate(@Nullable final String email, @Nullable final Class<? extends RuntimeException> clazz)
{
final boolean emailValid = isValid(email);
if (!emailValid && clazz != null)
{
// initiate and throw our exception
try | {
throw clazz.getConstructor(String.class).newInstance("@EmailNotValid@");
}
catch (final InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
{
throw new RuntimeException("Unable to instantiate a " + clazz + " exception", e);
}
}
return emailValid;
}
public static boolean isValid(@Nullable final String email)
{
return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\email\EmailValidator.java | 1 |
请完成以下Java代码 | public LocalDate getValueAsLocalDate()
{
return value == null ? null : TimeUtil.asLocalDate(value);
}
public Object getValueAsJson()
{
if (AttributeValueType.STRING.equals(valueType))
{
return getValueAsString();
}
else if (AttributeValueType.NUMBER.equals(valueType))
{
return getValueAsBigDecimal();
}
else if (AttributeValueType.DATE.equals(valueType))
{
final LocalDate value = getValueAsLocalDate();
return value != null ? value.toString() : null;
}
else if (AttributeValueType.LIST.equals(valueType))
{
return getValueAsString();
}
else
{
throw new AdempiereException("Unknown attribute type: " + valueType);
}
}
public ITranslatableString getValueAsTranslatableString()
{
switch (valueType)
{
case STRING: | case LIST:
{
final String valueStr = getValueAsString();
return TranslatableStrings.anyLanguage(valueStr);
}
case NUMBER:
{
final BigDecimal valueBD = getValueAsBigDecimal();
return valueBD != null
? TranslatableStrings.number(valueBD, de.metas.common.util.NumberUtils.isInteger(valueBD) ? DisplayType.Integer : DisplayType.Number)
: TranslatableStrings.empty();
}
case DATE:
{
final LocalDate valueDate = getValueAsLocalDate();
return valueDate != null
? TranslatableStrings.date(valueDate, DisplayType.Date)
: TranslatableStrings.empty();
}
default:
{
return TranslatableStrings.empty();
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attribute.java | 1 |
请完成以下Java代码 | protected MessagingMessageListenerAdapter createMessageListenerInstance(@Nullable Boolean batch) {
return this.adapterProvider.getAdapter(batch == null ? isBatchListener() : batch, this.bean, this.method,
this.returnExceptions, this.errorHandler, getBatchingStrategy());
}
private @Nullable String getDefaultReplyToAddress() {
Method listenerMethod = getMethod();
if (listenerMethod != null) {
SendTo ann = AnnotationUtils.getAnnotation(listenerMethod, SendTo.class);
if (ann != null) {
String[] destinations = ann.value();
if (destinations.length > 1) {
throw new IllegalStateException("Invalid @" + SendTo.class.getSimpleName() + " annotation on '"
+ listenerMethod + "' one destination must be set (got " + Arrays.toString(destinations) + ")");
}
return destinations.length == 1 ? resolveSendTo(destinations[0]) : "";
}
}
return null;
}
private @Nullable String resolveSendTo(String value) {
BeanExpressionContext beanExpressionContext = getBeanExpressionContext();
if (beanExpressionContext != null) {
String resolvedValue = beanExpressionContext.getBeanFactory().resolveEmbeddedValue(value);
BeanExpressionResolver resolverToUse = getResolver();
if (resolverToUse != null) {
Object newValue = resolverToUse.evaluate(resolvedValue, beanExpressionContext);
Assert.isInstanceOf(String.class, newValue, "Invalid @SendTo expression");
return (String) newValue;
}
}
return value;
}
@Override
protected StringBuilder getEndpointDescription() {
return super.getEndpointDescription()
.append(" | bean='").append(this.bean).append("'")
.append(" | method='").append(this.method).append("'");
}
/**
* Provider of listener adapters.
* @since 2.4
*
*/
public interface AdapterProvider {
/**
* Get an adapter instance.
* @param batch true for a batch listener. | * @param bean the bean.
* @param method the method.
* @param returnExceptions true to return exceptions.
* @param errorHandler the error handler.
* @param batchingStrategy the batching strategy for batch listeners.
* @return the adapter.
*/
MessagingMessageListenerAdapter getAdapter(boolean batch, @Nullable Object bean, @Nullable Method method,
boolean returnExceptions, @Nullable RabbitListenerErrorHandler errorHandler,
@Nullable BatchingStrategy batchingStrategy);
}
private static final class DefaultAdapterProvider implements AdapterProvider {
@Override
public MessagingMessageListenerAdapter getAdapter(boolean batch, @Nullable Object bean, @Nullable Method method,
boolean returnExceptions, @Nullable RabbitListenerErrorHandler errorHandler,
@Nullable BatchingStrategy batchingStrategy) {
if (batch) {
return new BatchMessagingMessageListenerAdapter(bean, method, returnExceptions, errorHandler,
batchingStrategy);
}
else {
return new MessagingMessageListenerAdapter(bean, method, returnExceptions, errorHandler);
}
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MethodRabbitListenerEndpoint.java | 1 |
请完成以下Java代码 | private ImmutableList<IAccountStatementWrapper> getAccountStatementsV04(@NonNull final XMLStreamReader xmlStreamReader)
{
try
{
final JAXBContext context = JAXBContext.newInstance(de.metas.banking.camt53.jaxb.camt053_001_04.ObjectFactory.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
@SuppressWarnings("unchecked") final JAXBElement<de.metas.banking.camt53.jaxb.camt053_001_04.Document> docV04 =
(JAXBElement<de.metas.banking.camt53.jaxb.camt053_001_04.Document>)unmarshaller.unmarshal(xmlStreamReader);
return BatchBankToCustomerStatementV04Wrapper
.of(docV04.getValue().getBkToCstmrStmt())
.getAccountStatementWrappers(bankAccountService, currencyRepository, msgBL);
}
catch (final JAXBException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
@NonNull
private ImmutableList<IAccountStatementWrapper> getAccountStatementsV02(@NonNull final XMLStreamReader xmlStreamReader)
{
try
{
final JAXBContext context = JAXBContext.newInstance(de.metas.banking.camt53.jaxb.camt053_001_02.ObjectFactory.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
@SuppressWarnings("unchecked") final JAXBElement<de.metas.banking.camt53.jaxb.camt053_001_02.Document> docV02 =
(JAXBElement<de.metas.banking.camt53.jaxb.camt053_001_02.Document>)unmarshaller.unmarshal(xmlStreamReader);
return BatchBankToCustomerStatementV02Wrapper
.of(docV02.getValue().getBkToCstmrStmt())
.getAccountStatements(bankAccountService, currencyRepository, msgBL);
}
catch (final JAXBException e)
{
throw AdempiereException.wrapIfNeeded(e); | }
}
@NonNull
private OrgId getOrgId(@NonNull final BankAccountId bankAccountId)
{
return bankAccountService.getById(bankAccountId).getOrgId();
}
@Value
@Builder
private static class ImportBankStatementLineRequest
{
@NonNull
IStatementLineWrapper entryWrapper;
@NonNull
BankStatementId bankStatementId;
@NonNull
OrgId orgId;
boolean isMatchAmounts;
boolean isMultiPayment()
{
return entryWrapper.isBatchTransaction();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\BankStatementCamt53Service.java | 1 |
请完成以下Java代码 | public java.lang.String getSubProducerBPartner_Value()
{
return get_ValueAsString(COLUMNNAME_SubProducerBPartner_Value);
}
@Override
public void setTE (final @Nullable java.lang.String TE)
{
set_Value (COLUMNNAME_TE, TE);
}
@Override
public java.lang.String getTE()
{
return get_ValueAsString(COLUMNNAME_TE);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setWarehouseLocatorIdentifier (final @Nullable java.lang.String WarehouseLocatorIdentifier)
{
set_Value (COLUMNNAME_WarehouseLocatorIdentifier, WarehouseLocatorIdentifier);
}
@Override
public java.lang.String getWarehouseLocatorIdentifier()
{
return get_ValueAsString(COLUMNNAME_WarehouseLocatorIdentifier);
}
@Override
public void setWarehouseValue (final @Nullable java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
@Override
public void setX (final @Nullable java.lang.String X)
{
set_Value (COLUMNNAME_X, X); | }
@Override
public java.lang.String getX()
{
return get_ValueAsString(COLUMNNAME_X);
}
@Override
public void setX1 (final @Nullable java.lang.String X1)
{
set_Value (COLUMNNAME_X1, X1);
}
@Override
public java.lang.String getX1()
{
return get_ValueAsString(COLUMNNAME_X1);
}
@Override
public void setY (final @Nullable java.lang.String Y)
{
set_Value (COLUMNNAME_Y, Y);
}
@Override
public java.lang.String getY()
{
return get_ValueAsString(COLUMNNAME_Y);
}
@Override
public void setZ (final @Nullable java.lang.String Z)
{
set_Value (COLUMNNAME_Z, Z);
}
@Override
public java.lang.String getZ()
{
return get_ValueAsString(COLUMNNAME_Z);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class TestController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/hello")
public String hello(String name) {
// 获得服务 `demo-provider` 的一个实例
ServiceInstance instance;
if (true) {
// 获取服务 `demo-provider` 对应的实例列表
List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");
// 选择第一个
instance = instances.size() > 0 ? instances.get(0) : null;
} else { | instance = loadBalancerClient.choose("demo-provider");
}
// 发起调用
if (instance == null) {
throw new IllegalStateException("获取不到实例");
}
String targetUrl = instance.getUri() + "/echo?name=" + name;
String response = restTemplate.getForObject(targetUrl, String.class);
// 返回结果
return "consumer:" + response;
}
}
} | repos\SpringBoot-Labs-master\labx-01-spring-cloud-alibaba-nacos-discovery\labx-01-sca-nacos-discovery-demo01-consumer\src\main\java\cn\iocoder\springcloudalibaba\labx01\nacosdemo\consumer\DemoConsumerApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTextCode() {
return textCode;
}
/**
* Sets the value of the textCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTextCode(String value) {
this.textCode = value;
}
/**
* Gets the value of the text property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setText(String value) {
this.text = value;
}
/**
* Gets the value of the agencyCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAgencyCode() { | return agencyCode;
}
/**
* Sets the value of the agencyCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgencyCode(String value) {
this.agencyCode = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\FreeTextType.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setActorId (final @Nullable java.lang.String ActorId)
{
set_Value (COLUMNNAME_ActorId, ActorId);
}
@Override
public java.lang.String getActorId()
{
return get_ValueAsString(COLUMNNAME_ActorId);
}
@Override
public void setBase_url (final @Nullable java.lang.String Base_url)
{
set_Value (COLUMNNAME_Base_url, Base_url);
}
@Override
public java.lang.String getBase_url()
{
return get_ValueAsString(COLUMNNAME_Base_url);
}
@Override
public void setCarrier_Config_ID (final int Carrier_Config_ID)
{
if (Carrier_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, Carrier_Config_ID);
}
@Override
public int getCarrier_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Config_ID);
}
@Override
public void setClient_Id (final @Nullable java.lang.String Client_Id)
{
set_Value (COLUMNNAME_Client_Id, Client_Id);
}
@Override
public java.lang.String getClient_Id()
{
return get_ValueAsString(COLUMNNAME_Client_Id);
}
@Override
public void setClient_Secret (final @Nullable java.lang.String Client_Secret)
{
set_Value (COLUMNNAME_Client_Secret, Client_Secret);
}
@Override
public java.lang.String getClient_Secret()
{
return get_ValueAsString(COLUMNNAME_Client_Secret);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1) | set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setServiceLevel (final @Nullable java.lang.String ServiceLevel)
{
set_Value (COLUMNNAME_ServiceLevel, ServiceLevel);
}
@Override
public java.lang.String getServiceLevel()
{
return get_ValueAsString(COLUMNNAME_ServiceLevel);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Config.java | 1 |
请完成以下Java代码 | public class ProjectRequest {
private List<String> dependencies = new ArrayList<>();
private String name;
private String type;
private String description;
private String groupId;
private String artifactId;
private String version;
private String bootVersion;
private String packaging;
private String applicationName;
private String language;
private String configurationFileFormat;
private String packageName;
private String javaVersion;
// The base directory to create in the archive - no baseDir by default
private String baseDir;
public List<String> getDependencies() {
return this.dependencies;
}
public void setDependencies(List<String> dependencies) {
this.dependencies = dependencies;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return this.artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public String getBootVersion() {
return this.bootVersion;
}
public void setBootVersion(String bootVersion) {
this.bootVersion = bootVersion;
}
public String getPackaging() {
return this.packaging;
}
public void setPackaging(String packaging) {
this.packaging = packaging; | }
public String getApplicationName() {
return this.applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getConfigurationFileFormat() {
return this.configurationFileFormat;
}
public void setConfigurationFileFormat(String configurationFileFormat) {
this.configurationFileFormat = configurationFileFormat;
}
public String getPackageName() {
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return getGroupId() + "." + getArtifactId();
}
return null;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getJavaVersion() {
return this.javaVersion;
}
public void setJavaVersion(String javaVersion) {
this.javaVersion = javaVersion;
}
public String getBaseDir() {
return this.baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java | 1 |
请完成以下Java代码 | I_M_Attribute getIsQualityInspectionAttribute()
{
final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class);
final I_M_Attribute attribute = attributeDAO.retrieveAttributeByValue(ATTRIBUTENAME_IsQualityInspection);
Check.assumeNotNull(attribute, "attribute shall exist for {}", ATTRIBUTENAME_IsQualityInspection);
return attribute;
}
@Override
public Optional<IQualityInspectionSchedulable> asQualityInspectionSchedulable(final IContextAware context, final IAttributeStorage attributeStorage)
{
return AttributeStorageQualityInspectionSchedulable.of(this, context, attributeStorage);
} | @Override
public void updateHUAttributeRecursive(final I_M_HU hu,
final I_M_Material_Tracking materialTracking,
final String onlyHUStatus)
{
final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class);
final IHUAttributesBL huAttributesBL = Services.get(IHUAttributesBL.class);
final I_M_Attribute materialTrackingAttribute = materialTrackingAttributeBL.getMaterialTrackingAttribute();
final Object attributeValue = materialTracking == null ? null : materialTracking.getM_Material_Tracking_ID();
huAttributesBL.updateHUAttributeRecursive(hu,
materialTrackingAttribute,
attributeValue,
onlyHUStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\impl\HUMaterialTrackingBL.java | 1 |
请完成以下Java代码 | public void setM_ForecastLine_ID (int M_ForecastLine_ID)
{
if (M_ForecastLine_ID < 1)
set_Value (COLUMNNAME_M_ForecastLine_ID, null);
else
set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID));
}
@Override
public int getM_ForecastLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ForecastLine_ID);
}
@Override
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setPlannedQty (java.math.BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty); | }
@Override
public java.math.BigDecimal getPlannedQty()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Demand_Detail.java | 1 |
请完成以下Java代码 | public class C_OLCand_Validate_Selected extends JavaProcess
{
//
// services
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IMsgBL msgBL = Services.get(IMsgBL.class);
private final OLCandValidatorService olCandValidatorService = SpringContextHolder.instance.getBean(OLCandValidatorService.class);
@Override
protected void prepare()
{
// do nothing
}
@Override
protected String doIt() throws Exception
{
final IQueryFilter<I_C_OLCand> queryFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_C_OLCand> queryBuilder = queryBL.createQueryBuilder(I_C_OLCand.class, getCtx(), get_TrxName())
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false) // already processed records shall not be validated
.filter(queryFilter);
final Iterator<I_C_OLCand> selectedCands = queryBuilder
.create()
.iterate(I_C_OLCand.class); // working with a iterator, because the there might be *a lot* of C_OLCands, and the issue-solver that we use in the endcustomer.project also iterates.
olCandValidatorService.setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
try
{ | int candidatesWithError = 0;
for (final I_C_OLCand olCand : IteratorUtils.asIterable(selectedCands))
{
olCandValidatorService.validate(olCand);
if (olCand.isError())
{
candidatesWithError++;
}
InterfaceWrapperHelper.save(olCand);
}
return msgBL.getMsg(getCtx(), OLCandValidatorService.MSG_ERRORS_FOUND, new Object[] { candidatesWithError });
}
finally
{
olCandValidatorService.setValidationProcessInProgress(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCand_Validate_Selected.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<Employee> updateEmployee(
@ApiParam(value = "Employee Id to update employee object", required = true)
@PathVariable(value = "id") Long employeeId,
@ApiParam(value = "Update employee object", required = true)
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
} | @ApiOperation(value = "Delete an employee")
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(
@ApiParam(value = "Employee Id from which employee object will delete from database table", required = true)
@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot2-jpa-swagger2\src\main\java\net\alanbinu\springboot2\springboot2swagger2\controller\EmployeeController.java | 2 |
请完成以下Java代码 | protected ExpressionFactory getExpressionFactory() {
Object obj = getContext(ExpressionFactory.class);
if (obj instanceof ExpressionFactory) {
return (ExpressionFactory) obj;
}
return getDefaultExpressionFactory();
}
protected ExpressionFactory getDefaultExpressionFactory() {
return ExpressionFactory.newInstance();
}
/*
* Copied from org.apache.el.lang.ELSupport - keep in sync
*/
static boolean isFunctionalInterface(Class<?> type) {
if (!type.isInterface()) {
return false;
}
boolean foundAbstractMethod = false;
Method[] methods = type.getMethods();
for (Method method : methods) {
if (Modifier.isAbstract(method.getModifiers())) {
// Abstract methods that override one of the public methods
// of Object don't count
if (overridesObjectMethod(method)) {
continue;
}
if (foundAbstractMethod) {
// Found more than one
return false; | } else {
foundAbstractMethod = true;
}
}
}
return foundAbstractMethod;
}
/*
* Copied from org.apache.el.lang.ELSupport - keep in sync
*/
private static boolean overridesObjectMethod(Method method) {
// There are three methods that can be overridden
if ("equals".equals(method.getName())) {
if (method.getReturnType().equals(boolean.class)) {
if (method.getParameterCount() == 1) {
return method.getParameterTypes()[0].equals(Object.class);
}
}
} else if ("hashCode".equals(method.getName())) {
if (method.getReturnType().equals(int.class)) {
return method.getParameterCount() == 0;
}
} else if ("toString".equals(method.getName())) {
if (method.getReturnType().equals(String.class)) {
return method.getParameterCount() == 0;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ELContext.java | 1 |
请完成以下Java代码 | public ZonedDateTime getParameterAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter);
}
@Nullable
public Instant getParameterAsInstant()
{
return TimeUtil.asInstant(m_Parameter);
}
@Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter_To);
}
@Nullable
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null) | {
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java | 1 |
请完成以下Java代码 | public class ThingsBoardExecutors {
/** Cannot instantiate. */
private ThingsBoardExecutors(){}
/**
* Method forked from ExecutorService to provide thread pool name
*
* Creates a thread pool that maintains enough threads to support
* the given parallelism level, and may use multiple queues to
* reduce contention. The parallelism level corresponds to the
* maximum number of threads actively engaged in, or available to
* engage in, task processing. The actual number of threads may
* grow and shrink dynamically. A work-stealing pool makes no
* guarantees about the order in which submitted tasks are
* executed.
*
* @param parallelism the targeted parallelism level
* @param namePrefix used to define thread name
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code parallelism <= 0}
* @since 1.8
*/
public static ExecutorService newWorkStealingPool(int parallelism, String namePrefix) {
return new ForkJoinPool(parallelism,
new ThingsBoardForkJoinWorkerThreadFactory(namePrefix),
null, true); | }
public static ExecutorService newWorkStealingPool(int parallelism, Class clazz) {
return newWorkStealingPool(parallelism, clazz.getSimpleName());
}
/*
* executor with limited tasks queue size
* */
public static ExecutorService newLimitedTasksExecutor(int threads, int maxQueueSize, String name) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(maxQueueSize),
ThingsBoardThreadFactory.forName(name),
new ThreadPoolExecutor.CallerRunsPolicy());
executor.allowCoreThreadTimeOut(true);
return executor;
}
public static ScheduledExecutorService newSingleThreadScheduledExecutor(String name) {
return Executors.unconfigurableScheduledExecutorService(new ThingsBoardScheduledThreadPoolExecutor(1, ThingsBoardThreadFactory.forName(name)));
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String name) {
return new ThingsBoardScheduledThreadPoolExecutor(corePoolSize, ThingsBoardThreadFactory.forName(name));
}
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ThingsBoardExecutors.java | 1 |
请完成以下Java代码 | public PvmException transitCaseException(String transition, String id, CaseExecutionState currentState) {
return new PvmException(exceptionMessage(
"015",
caseStateTransitionMessage +
"Reason: Expected case execution state to be {terminatingOnTermination|terminatingOnExit} but it was '{}'.",
transition,
id,
currentState
));
}
public PvmException suspendCaseException(String id, CaseExecutionState currentState) {
return transitCaseException("suspend", id, currentState);
}
public PvmException terminateCaseException(String id, CaseExecutionState currentState) {
return transitCaseException("terminate", id, currentState);
}
public ProcessEngineException missingDelegateParentClassException(String className, String parentClass) {
return new ProcessEngineException(
exceptionMessage("016", "Class '{}' doesn't implement '{}'.", className, parentClass));
}
public UnsupportedOperationException unsupportedTransientOperationException(String className) {
return new UnsupportedOperationException(
exceptionMessage("017", "Class '{}' is not supported in transient CaseExecutionImpl", className));
}
public ProcessEngineException invokeVariableListenerException(Throwable cause) {
return new ProcessEngineException(exceptionMessage(
"018",
"Variable listener invocation failed. Reason: {}", | cause.getMessage()),
cause
);
}
public ProcessEngineException decisionDefinitionEvaluationFailed(CmmnActivityExecution execution, Exception cause) {
return new ProcessEngineException(exceptionMessage(
"019",
"Could not evaluate decision in case execution '"+execution.getId()+"'. Reason: {}",
cause.getMessage()),
cause
);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CmmnBehaviorLogger.java | 1 |
请完成以下Java代码 | public class AppEngineFactoryBean implements FactoryBean<AppEngine>, DisposableBean, ApplicationContextAware {
protected AppEngineConfiguration appEngineConfiguration;
protected ApplicationContext applicationContext;
protected AppEngine appEngine;
@Override
public void destroy() throws Exception {
if (appEngine != null) {
appEngine.close();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public AppEngine getObject() throws Exception {
configureExternallyManagedTransactions();
if (appEngineConfiguration.getBeans() == null) {
appEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext));
}
this.appEngine = appEngineConfiguration.buildAppEngine();
return this.appEngine;
}
protected void configureExternallyManagedTransactions() {
if (appEngineConfiguration instanceof SpringAppEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringAppEngineConfiguration engineConfiguration = (SpringAppEngineConfiguration) appEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
appEngineConfiguration.setTransactionsExternallyManaged(true);
}
} | }
@Override
public Class<AppEngine> getObjectType() {
return AppEngine.class;
}
@Override
public boolean isSingleton() {
return true;
}
public AppEngineConfiguration getAppEngineConfiguration() {
return appEngineConfiguration;
}
public void setAppEngineConfiguration(AppEngineConfiguration appEngineConfiguration) {
this.appEngineConfiguration = appEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\AppEngineFactoryBean.java | 1 |
请完成以下Java代码 | public int getM_AttributeSetInstance_ID()
{
return -1; // N/A
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
throw new UnsupportedOperationException();
}
@Override
public int getC_UOM_ID()
{
// TODO Auto-generated method stub
return -1;
}
@Override
public void setC_UOM_ID(final int uomId)
{
throw new UnsupportedOperationException();
}
@Override
public void setQty(final BigDecimal qty)
{
order.setQty_FastInput(qty);
}
@Override
public BigDecimal getQty()
{
return order.getQty_FastInput();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
return order.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
order.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return order.getQty_FastInput_TU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
order.setQty_FastInput_TU(qtyPacks);
}
@Override | public void setC_BPartner_ID(final int bpartnerId)
{
order.setC_BPartner_ID(bpartnerId);
}
@Override
public int getC_BPartner_ID()
{
return order.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
@Override
public String toString()
{
return String
.format("OrderHUPackingAware [order=%s, getM_Product_ID()=%s, getM_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, isInDispute()=%s]",
order, getM_Product_ID(), getM_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getQtyTU(), getC_BPartner_ID(),
getM_HU_PI_Item_Product_ID(), isInDispute());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderHUPackingAware.java | 1 |
请完成以下Java代码 | public String getIncotermLocation() {return olCandRecord.getIncotermLocation();}
// FIXME hardcoded (08691)
@Nullable
public Object getValueByColumn(@NonNull final OLCandAggregationColumn column)
{
final String olCandColumnName = column.getColumnName();
switch (olCandColumnName)
{
case I_C_OLCand.COLUMNNAME_Bill_BPartner_ID:
return getBillBPartnerInfo().getBpartnerId();
case I_C_OLCand.COLUMNNAME_Bill_Location_ID:
return getBillBPartnerInfo().getBpartnerLocationId();
case I_C_OLCand.COLUMNNAME_Bill_Location_Value_ID:
return getBillBPartnerInfo().getLocationId();
case I_C_OLCand.COLUMNNAME_Bill_User_ID:
return getBillBPartnerInfo().getContactId();
case I_C_OLCand.COLUMNNAME_DropShip_BPartner_ID:
return dropShipBPartnerInfo.orElse(bpartnerInfo).getBpartnerId();
case I_C_OLCand.COLUMNNAME_DropShip_Location_ID:
return dropShipBPartnerInfo.orElse(bpartnerInfo).getBpartnerLocationId();
case I_C_OLCand.COLUMNNAME_DropShip_Location_Value_ID:
return dropShipBPartnerInfo.orElse(bpartnerInfo).getLocationId();
case I_C_OLCand.COLUMNNAME_M_PricingSystem_ID:
return getPricingSystemId();
case I_C_OLCand.COLUMNNAME_DateOrdered:
return getDateOrdered();
case I_C_OLCand.COLUMNNAME_DatePromised_Effective:
return getDatePromised();
case I_C_OLCand.COLUMNNAME_BPartnerName:
return getBpartnerName();
case I_C_OLCand.COLUMNNAME_EMail:
return getEmail();
case I_C_OLCand.COLUMNNAME_Phone:
return getPhone();
case I_C_OLCand.COLUMNNAME_IsAutoInvoice:
return isAutoInvoice();
case I_C_OLCand.COLUMNNAME_C_Incoterms_ID:
return getIncotermsId();
case I_C_OLCand.COLUMNNAME_IncotermLocation:
return getIncotermLocation();
default:
return InterfaceWrapperHelper.getValueByColumnId(olCandRecord, column.getAdColumnId());
}
}
@Override
public int getM_ProductPrice_ID()
{
return olCandRecord.getM_ProductPrice_ID();
}
@Override | public boolean isExplicitProductPriceAttribute()
{
return olCandRecord.isExplicitProductPriceAttribute();
}
public int getFlatrateConditionsId()
{
return olCandRecord.getC_Flatrate_Conditions_ID();
}
public int getHUPIProductItemId()
{
final HUPIItemProductId packingInstructions = olCandEffectiveValuesBL.getEffectivePackingInstructions(olCandRecord);
return HUPIItemProductId.toRepoId(packingInstructions);
}
public InvoicableQtyBasedOn getInvoicableQtyBasedOn()
{
return InvoicableQtyBasedOn.ofNullableCodeOrNominal(olCandRecord.getInvoicableQtyBasedOn());
}
public BPartnerInfo getBPartnerInfo()
{
return bpartnerInfo;
}
public boolean isAssignToBatch(@NonNull final AsyncBatchId asyncBatchIdCandidate)
{
if (this.asyncBatchId == null)
{
return false;
}
return asyncBatchId.getRepoId() == asyncBatchIdCandidate.getRepoId();
}
public void setHeaderAggregationKey(@NonNull final String headerAggregationKey)
{
olCandRecord.setHeaderAggregationKey(headerAggregationKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCand.java | 1 |
请完成以下Java代码 | public void setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setDurationMillis (final int DurationMillis)
{
set_Value (COLUMNNAME_DurationMillis, DurationMillis);
}
@Override
public int getDurationMillis()
{
return get_ValueAsInt(COLUMNNAME_DurationMillis);
}
@Override
public void setLevel (final java.lang.String Level)
{
set_ValueNoCheck (COLUMNNAME_Level, Level);
}
@Override
public java.lang.String getLevel()
{
return get_ValueAsString(COLUMNNAME_Level);
}
@Override
public void setModule (final @Nullable java.lang.String Module)
{
set_Value (COLUMNNAME_Module, Module);
}
@Override
public java.lang.String getModule()
{
return get_ValueAsString(COLUMNNAME_Module);
}
@Override
public void setMsgText (final @Nullable java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setSource_Record_ID (final int Source_Record_ID)
{ | if (Source_Record_ID < 1)
set_Value (COLUMNNAME_Source_Record_ID, null);
else
set_Value (COLUMNNAME_Source_Record_ID, Source_Record_ID);
}
@Override
public int getSource_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Record_ID);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTarget_Record_ID (final int Target_Record_ID)
{
if (Target_Record_ID < 1)
set_Value (COLUMNNAME_Target_Record_ID, null);
else
set_Value (COLUMNNAME_Target_Record_ID, Target_Record_ID);
}
@Override
public int getTarget_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Target_Record_ID);
}
@Override
public void setTarget_Table_ID (final int Target_Table_ID)
{
if (Target_Table_ID < 1)
set_Value (COLUMNNAME_Target_Table_ID, null);
else
set_Value (COLUMNNAME_Target_Table_ID, Target_Table_ID);
}
@Override
public int getTarget_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Target_Table_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Log.java | 1 |
请完成以下Java代码 | public void setContent(String content) {
this.content = content;
}
public void setAuthor(User author) {
this.author = author;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false; | }
Post post = (Post) o;
return Objects.equals(id, post.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "Post(id=" + this.getId() + ", content=" + this.getContent() + ", author=" + this.getAuthor() + ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\Post.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFirstName() {
return firstName;
}
/**
* Sets the first name.
*
* @param firstName the new first name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets the last name.
*
* @return the last name
*/
public String getLastName() {
return lastName;
}
/**
* Sets the last name.
*
* @param lastName the new last name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets the user name.
*
* @return the user name
*/
public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName the new user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Gets the email address.
*
* @return the email address
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* Sets the email address.
*
* @param emailAddress the new email address
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((emailAddress == null) ? 0 : emailAddress.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode()); | result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserDTO other = (UserDTO) obj;
if (emailAddress == null) {
if (other.emailAddress != null)
return false;
} else if (!emailAddress.equals(other.emailAddress))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "UserDTO [firstName=" + firstName + ", lastName=" + lastName
+ ", userName=" + userName + ", emailAddress=" + emailAddress
+ "]";
}
} | repos\spring-boot-microservices-master\user-webservice\src\main\java\com\rohitghatol\microservices\user\dto\UserDTO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class LocationGeocodeEventHandler
{
private final ILocationDAO locationsRepo = Services.get(ILocationDAO.class);
private final ICountryDAO countryDAO = Services.get(ICountryDAO.class);
private final GeocodingService geocodingService;
private final IEventBusFactory eventBusFactory;
private final IErrorManager errorManager = Services.get(IErrorManager.class);
public LocationGeocodeEventHandler(
@NonNull final IEventBusFactory eventBusFactory,
@NonNull final GeocodingService geocodingService)
{
this.eventBusFactory = eventBusFactory;
this.geocodingService = geocodingService;
}
@PostConstruct
private void postConstruct()
{
eventBusFactory
.getEventBus(C_Location.EVENTS_TOPIC)
.subscribeOn(LocationGeocodeEventRequest.class, this::handleEvent);
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
void handleEvent(@NonNull final LocationGeocodeEventRequest request)
{
I_C_Location locationRecord = null;
try
{
locationRecord = locationsRepo.getById(request.getLocationId());
final GeoCoordinatesRequest coordinatesRequest = createGeoCoordinatesRequest(locationRecord);
final Optional<GeographicalCoordinates> xoy = geocodingService.findBestCoordinates(coordinatesRequest);
if (xoy.isPresent())
{
locationRecord.setLatitude(xoy.get().getLatitude());
locationRecord.setLongitude(xoy.get().getLongitude());
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_Resolved);
locationRecord.setGeocoding_Issue_ID(-1);
}
else
{
locationRecord.setLatitude(null);
locationRecord.setLongitude(null);
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_NotResolved);
locationRecord.setGeocoding_Issue_ID(-1);
}
}
catch (final Exception ex) | {
final AdIssueId issueId = errorManager.createIssue(ex);
if (locationRecord != null)
{
locationRecord.setGeocodingStatus(X_C_Location.GEOCODINGSTATUS_Error);
locationRecord.setGeocoding_Issue_ID(issueId.getRepoId());
}
}
finally
{
if (locationRecord != null)
{
locationsRepo.save(locationRecord);
}
}
}
private GeoCoordinatesRequest createGeoCoordinatesRequest(@NonNull final I_C_Location locationRecord)
{
final String countryCode2 = countryDAO.retrieveCountryCode2ByCountryId(CountryId.ofRepoId(locationRecord.getC_Country_ID()));
final String address = Joiner.on(" ")
.skipNulls()
.join(locationRecord.getAddress1(), locationRecord.getAddress2(), locationRecord.getAddress3(), locationRecord.getAddress4());
final String postal = locationRecord.getPostal();
final String city = locationRecord.getCity();
return GeoCoordinatesRequest.builder()
.countryCode2(countryCode2)
.address(address)
.postal(postal)
.city(city)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\asynchandler\LocationGeocodeEventHandler.java | 2 |
请完成以下Java代码 | private JeecgLlmTools grantUserRolesTool() {
ToolSpecification spec = ToolSpecification.builder()
.name("grant_user_roles")
.description("给用户授予角色,支持一次授予多个角色;如果关系已存在则跳过。返回授予结果统计。")
.parameters(
JsonObjectSchema.builder()
.addStringProperty("userId", "用户ID,必填")
.addStringProperty("roleIds", "角色ID列表,必填,使用英文逗号分隔")
.required("userId","roleIds")
.build()
)
.build();
ToolExecutor exec = (toolExecutionRequest, memoryId) -> {
JSONObject args = JSONObject.parseObject(toolExecutionRequest.arguments());
String userId = args.getString("userId");
String roleIdsStr = args.getString("roleIds");
if (org.apache.commons.lang3.StringUtils.isAnyBlank(userId, roleIdsStr)) {
return "参数缺失:userId 或 roleIds";
}
org.jeecg.modules.system.entity.SysUser user = sysUserService.getById(userId);
if (user == null) {
return "用户不存在:" + userId;
}
String[] roleIds = roleIdsStr.split(",");
int added = 0, existed = 0, invalid = 0;
for (String roleId : roleIds) {
roleId = roleId.trim();
if (roleId.isEmpty()) continue; | org.jeecg.modules.system.entity.SysRole role = sysRoleService.getById(roleId);
if (role == null) { invalid++; continue; }
com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<org.jeecg.modules.system.entity.SysUserRole> q = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
q.eq("role_id", roleId).eq("user_id", userId);
org.jeecg.modules.system.entity.SysUserRole one = sysUserRoleService.getOne(q);
if (one == null) {
org.jeecg.modules.system.entity.SysUserRole rel = new org.jeecg.modules.system.entity.SysUserRole(userId, roleId);
boolean ok = sysUserRoleService.save(rel);
if (ok) { added++; } else { invalid++; }
} else {
existed++;
}
}
return String.format("授予完成:新增%d,已存在%d,无效/失败%d", added, existed, invalid);
};
return new JeecgLlmTools(spec, exec);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\airag\JeecgBizToolsProvider.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Process getAD_Process() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process(org.compiere.model.I_AD_Process AD_Process)
{
set_ValueFromPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class, AD_Process);
}
/** Set Prozess.
@param AD_Process_ID
Prozess oder Bericht
*/
@Override
public void setAD_Process_ID (int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID));
}
/** Get Prozess.
@return Prozess oder Bericht
*/
@Override
public int getAD_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Statistics.
@param AD_Process_Stats_ID Process Statistics */
@Override
public void setAD_Process_Stats_ID (int AD_Process_Stats_ID)
{
if (AD_Process_Stats_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, Integer.valueOf(AD_Process_Stats_ID));
}
/** Get Process Statistics.
@return Process Statistics */
@Override
public int getAD_Process_Stats_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Stats_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Count.
@param Statistic_Count
Internal statistics how often the entity was used
*/
@Override
public void setStatistic_Count (int Statistic_Count)
{
set_Value (COLUMNNAME_Statistic_Count, Integer.valueOf(Statistic_Count));
}
/** Get Statistic Count.
@return Internal statistics how often the entity was used
*/
@Override
public int getStatistic_Count ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Count);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Milliseconds.
@param Statistic_Millis
Internal statistics how many milliseconds a process took
*/
@Override
public void setStatistic_Millis (int Statistic_Millis)
{
set_Value (COLUMNNAME_Statistic_Millis, Integer.valueOf(Statistic_Millis));
}
/** Get Statistic Milliseconds.
@return Internal statistics how many milliseconds a process took
*/
@Override
public int getStatistic_Millis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Millis);
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_Process_Stats.java | 1 |
请完成以下Java代码 | private static String getFileName(@Nullable File file) {
Assert.state(file != null, "'file' must not be null");
return file.getName();
}
/**
* Return the name of file as it should be written.
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Return the library file.
* @return the file
*/
public @Nullable File getFile() {
return this.file;
}
/**
* Open a stream that provides the content of the source file.
* @return the file content
* @throws IOException on error
*/
InputStream openStream() throws IOException {
Assert.state(this.file != null, "'file' must not be null");
return new FileInputStream(this.file);
}
/**
* Return the scope of the library.
* @return the scope
*/
public @Nullable LibraryScope getScope() {
return this.scope;
}
/**
* Return the {@linkplain LibraryCoordinates coordinates} of the library.
* @return the coordinates
*/
public @Nullable LibraryCoordinates getCoordinates() {
return this.coordinates;
} | /**
* Return if the file cannot be used directly as a nested jar and needs to be
* unpacked.
* @return if unpack is required
*/
public boolean isUnpackRequired() {
return this.unpackRequired;
}
long getLastModified() {
Assert.state(this.file != null, "'file' must not be null");
return this.file.lastModified();
}
/**
* Return if the library is local (part of the same build) to the application that is
* being packaged.
* @return if the library is local
*/
public boolean isLocal() {
return this.local;
}
/**
* Return if the library is included in the uber jar.
* @return if the library is included
*/
public boolean isIncluded() {
return this.included;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Library.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation Rule Depends On.
@param AD_Val_Rule_Dep_ID Validation Rule Depends On */
@Override
public void setAD_Val_Rule_Dep_ID (int AD_Val_Rule_Dep_ID)
{
if (AD_Val_Rule_Dep_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, Integer.valueOf(AD_Val_Rule_Dep_ID));
}
/** Get Validation Rule Depends On.
@return Validation Rule Depends On */
@Override
public int getAD_Val_Rule_Dep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_Dep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
}
@Override
public void setAD_Val_Rule(org.compiere.model.I_AD_Val_Rule AD_Val_Rule)
{
set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule);
}
/** Set Dynamische Validierung.
@param AD_Val_Rule_ID
Regel für die dynamische Validierung
*/
@Override
public void setAD_Val_Rule_ID (int AD_Val_Rule_ID)
{
if (AD_Val_Rule_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, Integer.valueOf(AD_Val_Rule_ID));
} | /** Get Dynamische Validierung.
@return Regel für die dynamische Validierung
*/
@Override
public int getAD_Val_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Technical note.
@param TechnicalNote
A note that is not indended for the user documentation, but for developers, customizers etc
*/
@Override
public void setTechnicalNote (java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
}
/** Get Technical note.
@return A note that is not indended for the user documentation, but for developers, customizers etc
*/
@Override
public java.lang.String getTechnicalNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_TechnicalNote);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule_Dep.java | 1 |
请完成以下Java代码 | protected Resource getResourceByPath(String path) {
if (getServletContext() == null) {
return new ClassPathContextResource(path, getClassLoader());
}
return new ServletContextResource(getServletContext(), path);
}
@Override
public @Nullable String getServerNamespace() {
return this.serverNamespace;
}
@Override
public void setServerNamespace(@Nullable String serverNamespace) {
this.serverNamespace = serverNamespace;
}
@Override
public void setServletConfig(@Nullable ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
@Override
public @Nullable ServletConfig getServletConfig() {
return this.servletConfig;
}
/**
* Returns the {@link WebServer} that was created by the context or {@code null} if
* the server has not yet been created.
* @return the embedded web server
*/
@Override
public @Nullable WebServer getWebServer() {
return this.webServer;
}
/**
* Utility class to store and restore any user defined scopes. This allows scopes to
* be registered in an ApplicationContextInitializer in the same way as they would in
* a classic non-embedded web application context.
*/
public static class ExistingWebApplicationScopes {
private static final Set<String> SCOPES;
static {
Set<String> scopes = new LinkedHashSet<>(); | scopes.add(WebApplicationContext.SCOPE_REQUEST);
scopes.add(WebApplicationContext.SCOPE_SESSION);
SCOPES = Collections.unmodifiableSet(scopes);
}
private final ConfigurableListableBeanFactory beanFactory;
private final Map<String, Scope> scopes = new HashMap<>();
public ExistingWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
for (String scopeName : SCOPES) {
Scope scope = beanFactory.getRegisteredScope(scopeName);
if (scope != null) {
this.scopes.put(scopeName, scope);
}
}
}
public void restore() {
this.scopes.forEach((key, value) -> {
if (logger.isInfoEnabled()) {
logger.info("Restoring user defined scope " + key);
}
this.beanFactory.registerScope(key, value);
});
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContext.java | 1 |
请完成以下Java代码 | public class SetDeploymentCategoryCmd implements Command<Void> {
protected String deploymentId;
protected String category;
public SetDeploymentCategoryCmd(String deploymentId, String category) {
this.deploymentId = deploymentId;
this.category = category;
}
@Override
public Void execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new FlowableIllegalArgumentException("Deployment id is null");
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
DeploymentEntity deployment = processEngineConfiguration.getDeploymentEntityManager().findById(deploymentId);
if (deployment == null) {
throw new FlowableObjectNotFoundException("No deployment found for id = '" + deploymentId + "'", Deployment.class);
}
if (Flowable5Util.isFlowable5Deployment(deployment, commandContext)) {
processEngineConfiguration.getFlowable5CompatibilityHandler().setDeploymentCategory(deploymentId, category);
}
// Update category
deployment.setCategory(category); | FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, deployment),
processEngineConfiguration.getEngineCfgKey());
}
return null;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SetDeploymentCategoryCmd.java | 1 |
请完成以下Java代码 | public class ComparatorChain<T> implements Comparator<T>
{
private final List<Comparator<T>> comparators = new ArrayList<Comparator<T>>();
public ComparatorChain()
{
}
public ComparatorChain<T> addComparator(Comparator<T> cmp)
{
final boolean reverse = false;
return addComparator(cmp, reverse);
}
public ComparatorChain<T> addComparator(Comparator<T> cmp, boolean reverse)
{
Check.assumeNotNull(cmp, "cmp not null");
if (reverse)
{
comparators.add(new ReverseComparator<T>(cmp));
}
else
{
comparators.add(cmp);
} | return this;
}
@Override
public int compare(T o1, T o2)
{
Check.assume(!comparators.isEmpty(), "ComparatorChain contains comparators");
for (final Comparator<T> cmp : comparators)
{
final int result = cmp.compare(o1, o2);
if (result != 0)
{
return result;
}
}
// assuming that objects are equal if none of child comparators said otherwise
return 0;
}
@Override
public String toString()
{
return "ComparatorChain [comparators=" + comparators + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\ComparatorChain.java | 1 |
请完成以下Java代码 | public final class ALoginRes_pl extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Po\u0142\u0105czenie" },
{ "Defaults", "Domy\u015blne" },
{ "Login", "Logowanie" },
{ "File", "Plik" },
{ "Exit", "Zako\u0144cz" },
{ "Help", "Pomoc" },
{ "About", "O aplikacji" },
{ "Host", "Host" },
{ "Database", "Baza danych" },
{ "User", "U\u017cytkownik" },
{ "EnterUser", "Wprowad\u017a Identyfikator U\u017cytkownika Aplikacji" },
{ "Password", "Has\u0142o" },
{ "EnterPassword", "Wprowad\u017a Has\u0142o Aplikacji" },
{ "Language", "J\u0119zyk" },
{ "SelectLanguage", "Wybierz j\u0119zyk" },
{ "Role", "Funkcja" },
{ "Client", "Klient" },
{ "Organization", "Organizacja" },
{ "Date", "Data" },
{ "Warehouse", "Magazyn" },
{ "Printer", "Drukarka" },
{ "Connected", "Po\u0142\u0105czony" },
{ "NotConnected", "Nie Po\u0142\u0105czony" },
{ "DatabaseNotFound", "Nie znaleziono bazy danych" },
{ "UserPwdError", "Has\u0142o nie odpowiada U\u017cytkownikowi" }, | { "RoleNotFound", "Nie znaleziono zasady" },
{ "Authorized", "Autoryzowany" },
{ "Ok", "Ok" },
{ "Cancel", "Anuluj" },
{ "VersionConflict", "Konflikt wersji:" },
{ "VersionInfo", "Serwer <> Klienta" },
{ "PleaseUpgrade", "Uruchom now\u0105 wersj\u0119 programu !" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_pl.java | 1 |
请完成以下Java代码 | protected List<IFacet<I_PMM_PurchaseCandidate>> collectFacets(final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder)
{
final List<Map<String, Object>> bpartners = queryBuilder
.andCollect(I_PMM_PurchaseCandidate.COLUMN_M_Product_ID)
.create()
.listDistinct(I_M_Product.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_Name, I_M_Product.COLUMNNAME_Value);
final List<IFacet<I_PMM_PurchaseCandidate>> facets = new ArrayList<>(bpartners.size());
for (final Map<String, Object> row : bpartners)
{
final IFacet<I_PMM_PurchaseCandidate> facet = createFacet(row);
facets.add(facet);
}
return facets;
}
private IFacet<I_PMM_PurchaseCandidate> createFacet(final Map<String, Object> row)
{
final IFacetCategory facetCategoryBPartners = getFacetCategory(); | final int bpartnerId = (int)row.get(I_M_Product.COLUMNNAME_M_Product_ID);
final String bpartnerName = new StringBuilder()
.append(row.get(I_M_Product.COLUMNNAME_Value))
.append(" - ")
.append(row.get(I_M_Product.COLUMNNAME_Name))
.toString();
final Facet<I_PMM_PurchaseCandidate> facet = Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(facetCategoryBPartners)
.setDisplayName(bpartnerName)
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_M_Product_ID + "=" + bpartnerId))
.build();
return facet;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\facet\impl\PMM_PurchaseCandidate_Product_FacetCollector.java | 1 |
请完成以下Java代码 | public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setM_Forecast_ID (final int M_Forecast_ID)
{
if (M_Forecast_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, M_Forecast_ID);
}
@Override
public int getM_Forecast_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Forecast_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override | public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java | 1 |
请完成以下Java代码 | public static int usingSorting(int num) {
String numStr = String.valueOf(num);
char[] numChars = numStr.toCharArray();
int pivotIndex;
for (pivotIndex = numChars.length - 1; pivotIndex > 0; pivotIndex--) {
if (numChars[pivotIndex] > numChars[pivotIndex - 1]) {
break;
}
}
if (pivotIndex == 0) {
return -1;
}
int pivot = numChars[pivotIndex - 1];
int minIndex = pivotIndex;
for (int j = pivotIndex + 1; j < numChars.length; j++) {
if (numChars[j] > pivot && numChars[j] < numChars[minIndex]) {
minIndex = j;
}
}
// Swap the pivot with the smallest digit found
swap(numChars, pivotIndex - 1, minIndex);
// Sort the digits to the right of the pivot in ascending order
Arrays.sort(numChars, pivotIndex, numChars.length);
return Integer.parseInt(new String(numChars));
}
public static int usingTwoPointer(int num) {
char[] numChars = Integer.toString(num)
.toCharArray();
int pivotIndex = numChars.length - 2;
while (pivotIndex >= 0 && numChars[pivotIndex] >= numChars[pivotIndex + 1]) {
pivotIndex--;
}
if (pivotIndex == -1)
return -1;
int minIndex = numChars.length - 1;
while (numChars[minIndex] <= numChars[pivotIndex]) {
minIndex--; | }
swap(numChars, pivotIndex, minIndex);
reverse(numChars, pivotIndex + 1, numChars.length - 1);
return Integer.parseInt(new String(numChars));
}
private static void swap(char[] numChars, int i, int j) {
char temp = numChars[i];
numChars[i] = numChars[j];
numChars[j] = temp;
}
private static void reverse(char[] numChars, int i, int j) {
while (i < j) {
swap(numChars, i, j);
i++;
j--;
}
}
public static void main(String[] args) {
int result = usingTwoPointer(536479);
System.out.println(result);
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\nexthighestnumbersamedigit\NextHighestNumber.java | 1 |
请完成以下Java代码 | public int getK_IndexStop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{ | if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_K_IndexStop.java | 1 |
请完成以下Java代码 | public void deleteCommentsByTaskId(String taskId) {
checkHistoryEnabled();
dataManager.deleteCommentsByTaskId(taskId);
}
@Override
public void deleteCommentsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
dataManager.deleteCommentsByProcessInstanceId(processInstanceId);
}
@Override
public void bulkDeleteCommentsForTaskIds(Collection<String> taskIds) {
dataManager.bulkDeleteCommentsForTaskIds(taskIds);
}
@Override
public void bulkDeleteCommentsForProcessInstanceIds(Collection<String> processInstanceIds) {
dataManager.bulkDeleteCommentsForProcessInstanceIds(processInstanceIds);
}
@Override
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
return dataManager.findCommentsByProcessInstanceId(processInstanceId);
}
@Override
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) {
checkHistoryEnabled();
return dataManager.findCommentsByProcessInstanceId(processInstanceId, type);
}
@Override
public Comment findComment(String commentId) {
return dataManager.findComment(commentId);
}
@Override
public Event findEvent(String commentId) {
return dataManager.findEvent(commentId);
}
@Override
public void delete(CommentEntity commentEntity) {
checkHistoryEnabled(); | delete(commentEntity, false);
Comment comment = (Comment) commentEntity;
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
// Forced to fetch the process-instance to associate the right
// process definition
String processDefinitionId = null;
String processInstanceId = comment.getProcessInstanceId();
if (comment.getProcessInstanceId() != null) {
ExecutionEntity process = getExecutionEntityManager().findById(comment.getProcessInstanceId());
if (process != null) {
processDefinitionId = process.getProcessDefinitionId();
}
}
getEventDispatcher().dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED,
commentEntity, processInstanceId, processInstanceId, processDefinitionId),
engineConfiguration.getEngineCfgKey());
}
}
protected void checkHistoryEnabled() {
if (!getHistoryManager().isHistoryEnabled()) {
throw new FlowableException("In order to use comments, history should be enabled");
}
}
protected ExecutionEntityManager getExecutionEntityManager() {
return engineConfiguration.getExecutionEntityManager();
}
protected HistoryManager getHistoryManager() {
return engineConfiguration.getHistoryManager();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\CommentEntityManagerImpl.java | 1 |
请完成以下Java代码 | public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception {
if (StringUtils.isBlank(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new Exception("template not null");
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
if (file == null){ | return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new Exception("excel file not null");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return list;
}
} | repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\Util\FileUtil.java | 1 |
请完成以下Java代码 | protected void prepare()
{
// nothing
}
@Override
protected String doIt() throws Exception
{
final I_C_PeriodControl pc = getRecord(I_C_PeriodControl.class);
this.periodId = pc.getC_Period_ID();
// Permanently closed
if (X_C_PeriodControl.PERIODSTATUS_PermanentlyClosed.equals(pc.getPeriodStatus()))
{
throw new AdempiereException("@PeriodStatus@ = " + pc.getPeriodStatus());
}
// No Action => do nothing
if (X_C_PeriodControl.PERIODACTION_NoAction.equals(pc.getPeriodAction()))
{
return "@OK@";
} | //
// Update the period control
final String newPeriodStatus = Services.get(IPeriodBL.class).getPeriodStatusForAction(pc.getPeriodAction());
pc.setPeriodStatus(newPeriodStatus);
pc.setPeriodAction(X_C_PeriodControl.PERIODACTION_NoAction); // reset the action
InterfaceWrapperHelper.save(pc);
return "@OK@";
} // doIt
@Override
protected void postProcess(boolean success)
{
// Reset Cache
CacheMgt.get().reset(I_C_PeriodControl.Table_Name);
CacheMgt.get().reset(I_C_Period.Table_Name, periodId);
}
} // PeriodControlStatus | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\PeriodControlStatus.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WikiDocumentsRepository {
private final VectorStore vectorStore;
public WikiDocumentsRepository(VectorStore vectorStore) {
this.vectorStore = vectorStore;
}
public void saveWikiDocument(WikiDocument wikiDocument) {
Map<String, Object> metadata = new HashMap<>();
metadata.put("filePath", wikiDocument.getFilePath());
Document document = new Document(wikiDocument.getContent(), metadata);
List<Document> documents = new TokenTextSplitter().apply(List.of(document));
vectorStore.add(documents);
}
public List<WikiDocument> findSimilarDocuments(String searchText) { | return vectorStore
.similaritySearch(SearchRequest.builder()
.query(searchText)
.similarityThreshold(0.87)
.topK(10).build())
.stream()
.map(document -> {
WikiDocument wikiDocument = new WikiDocument();
wikiDocument.setFilePath((String) document
.getMetadata().get("filePath"));
wikiDocument.setContent(document.getText());
return wikiDocument;
})
.toList();
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\rag\mongodb\repository\WikiDocumentsRepository.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.