instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setRed_1 (int Red_1)
{
set_Value (COLUMNNAME_Red_1, Integer.valueOf(Red_1));
}
/** Get 2nd Red.
@return RGB value for second color
*/
public int getRed_1 ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Red_1);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Repeat Distance.
@param RepeatDistance
Distance in points to repeat gradient color - or zero
*/
public void setRepeatDistance (int RepeatDistance)
{
set_Value (COLUMNNAME_RepeatDistance, Integer.valueOf(RepeatDistance));
}
/** Get Repeat Distance.
@return Distance in points to repeat gradient color - or zero
*/
public int getRepeatDistance ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RepeatDistance);
if (ii == null)
return 0;
return ii.intValue();
}
/** StartPoint AD_Reference_ID=248 */
public static final int STARTPOINT_AD_Reference_ID=248;
/** North = 1 */
public static final String STARTPOINT_North = "1";
/** North East = 2 */
public static final String STARTPOINT_NorthEast = "2";
/** East = 3 */
public static final String STARTPOINT_East = "3"; | /** South East = 4 */
public static final String STARTPOINT_SouthEast = "4";
/** South = 5 */
public static final String STARTPOINT_South = "5";
/** South West = 6 */
public static final String STARTPOINT_SouthWest = "6";
/** West = 7 */
public static final String STARTPOINT_West = "7";
/** North West = 8 */
public static final String STARTPOINT_NorthWest = "8";
/** Set Start Point.
@param StartPoint
Start point of the gradient colors
*/
public void setStartPoint (String StartPoint)
{
set_Value (COLUMNNAME_StartPoint, StartPoint);
}
/** Get Start Point.
@return Start point of the gradient colors
*/
public String getStartPoint ()
{
return (String)get_Value(COLUMNNAME_StartPoint);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Color.java | 1 |
请完成以下Java代码 | public static ProjectAndLineId ofRepoIdOrNull(final int projectRepoId, final int projectLineRepoId)
{
if (projectLineRepoId <= 0)
{
return null;
}
final ProjectId projectId = ProjectId.ofRepoIdOrNull(projectRepoId);
if (projectId == null)
{
return null;
}
return new ProjectAndLineId(projectId, projectLineRepoId);
}
ProjectId projectId;
int projectLineRepoId;
private ProjectAndLineId(
@NonNull final ProjectId projectId,
final int projectLineRepoId)
{
Check.assumeGreaterThanZero(projectLineRepoId, "C_ProjectLine_ID");
this.projectId = projectId; | this.projectLineRepoId = projectLineRepoId;
}
public int getRepoId()
{
return getProjectLineRepoId();
}
public static int toRepoId(@Nullable final ProjectAndLineId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final ProjectAndLineId id1, @Nullable final ProjectAndLineId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectAndLineId.java | 1 |
请完成以下Java代码 | public void deleteWithRelatedData() {
delete();
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
public String getActivityType() {
return activityType;
}
public Set<String> getActivityTypes() {
return activityTypes;
}
public String getAssignee() {
return assignee;
}
public String getCompletedBy() {
return completedBy;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getDeleteReason() {
return deleteReason;
}
public String getDeleteReasonLike() {
return deleteReasonLike;
}
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public Date getFinishedAfter() {
return finishedAfter;
} | public Date getFinishedBefore() {
return finishedBefore;
}
public List<String> getTenantIds() {
return tenantIds;
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getProcessInstanceIds() {
return processInstanceIds;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
public List<List<String>> getSafeCalledProcessInstanceIds() {
return safeCalledProcessInstanceIds;
}
public void setSafeCalledProcessInstanceIds(List<List<String>> safeCalledProcessInstanceIds) {
this.safeCalledProcessInstanceIds = safeCalledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricActivityInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void setLastProcessed_WorkPackage(final de.metas.async.model.I_C_Queue_WorkPackage LastProcessed_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, LastProcessed_WorkPackage);
}
@Override
public void setLastProcessed_WorkPackage_ID (final int LastProcessed_WorkPackage_ID)
{
if (LastProcessed_WorkPackage_ID < 1)
set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, null);
else
set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, LastProcessed_WorkPackage_ID);
}
@Override
public int getLastProcessed_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_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 de.metas.async.model.I_C_Async_Batch getParent_Async_Batch()
{
return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class);
} | @Override
public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch)
{
set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch);
}
@Override
public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID)
{
if (Parent_Async_Batch_ID < 1)
set_Value (COLUMNNAME_Parent_Async_Batch_ID, null);
else
set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID);
}
@Override
public int getParent_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java | 1 |
请完成以下Java代码 | public KPIField getGroupByField()
{
final KPIField groupByField = getGroupByFieldOrNull();
if (groupByField == null)
{
throw new IllegalStateException("KPI has no group by field defined");
}
return groupByField;
}
@Nullable
public KPIField getGroupByFieldOrNull()
{
return groupByField;
}
public boolean hasCompareOffset()
{
return compareOffset != null;
}
public Set<CtxName> getRequiredContextParameters()
{
if (elasticsearchDatasource != null)
{
return elasticsearchDatasource.getRequiredContextParameters();
}
else if (sqlDatasource != null)
{ | return sqlDatasource.getRequiredContextParameters();
}
else
{
throw new AdempiereException("Unknown datasource type: " + datasourceType);
}
}
public boolean isZoomToDetailsAvailable()
{
return sqlDatasource != null;
}
@NonNull
public SQLDatasourceDescriptor getSqlDatasourceNotNull()
{
return Check.assumeNotNull(getSqlDatasource(), "Not an SQL data source: {}", this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPI.java | 1 |
请完成以下Java代码 | public class X_AD_PrintFont extends PO implements I_AD_PrintFont, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_AD_PrintFont (Properties ctx, int AD_PrintFont_ID, String trxName)
{
super (ctx, AD_PrintFont_ID, trxName);
/** if (AD_PrintFont_ID == 0)
{
setAD_PrintFont_ID (0);
setCode (null);
setIsDefault (false);
setName (null);
} */
}
/** Load Constructor */
public X_AD_PrintFont (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_PrintFont[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Print Font.
@param AD_PrintFont_ID
Maintain Print Font
*/
public void setAD_PrintFont_ID (int AD_PrintFont_ID)
{
if (AD_PrintFont_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, Integer.valueOf(AD_PrintFont_ID));
}
/** Get Print Font.
@return Maintain Print Font
*/
public int getAD_PrintFont_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintFont_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
public void setCode (String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
}
/** Set Default.
@param IsDefault | Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFont.java | 1 |
请完成以下Spring Boot application配置 | spring:
# RabbitMQ 配置项,对应 RabbitProperties 配置类
rabbitmq:
host: 127.0.0.1 # RabbitMQ 服务的地址
port: 5672 # RabbitMQ 服务的端口
username: guest # RabbitMQ 服务的账号
password: guest # RabbitMQ 服务的密码
listener:
type: simple # 选择的 ListenerContainer 的类型。默认为 direct 类型
simple:
concurrency: 2 # 每个 @ListenerContainer 的并发消费的线程数
| max-concurrency: 10 # 每个 @ListenerCon 允许的并发消费的线程数
# direct:
# consumers-per-queue: 2 # 对于每一个 @RabbitListener ,一个 Queue ,对应创建几个 Consumer 。 | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-concurrency\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getParentIds() {
return parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
public Boolean getAvailable() { | return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
} | repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysPermission.java | 1 |
请完成以下Java代码 | private String asUserUsernameProperty(String userProperty) {
return String.format("%s.username", userProperty);
}
@Nullable
@Override
public Object getProperty(String name) {
return getSource().getProperty(name);
}
@NonNull
protected Predicate<String> getVcapServicePredicate() {
return this.vcapServicePredicate != null
? this.vcapServicePredicate
: propertyName -> true;
}
@Override
public Iterator<String> iterator() {
return Collections.unmodifiableList(Arrays.asList(getSource().getPropertyNames())).iterator();
}
@NonNull
public VcapPropertySource withVcapServiceName(@NonNull String serviceName) {
Assert.hasText(serviceName, "Service name is required"); | String resolvedServiceName = StringUtils.trimAllWhitespace(serviceName);
Predicate<String> vcapServiceNamePredicate = propertyName ->
propertyName.startsWith(String.format("%1$s%2$s.", VCAP_SERVICES_PROPERTY, resolvedServiceName));
return withVcapServicePredicate(vcapServiceNamePredicate);
}
@NonNull
public VcapPropertySource withVcapServicePredicate(@Nullable Predicate<String> vcapServicePredicate) {
this.vcapServicePredicate = vcapServicePredicate;
return this;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\VcapPropertySource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String edit(Model model, RpPayWay rpPayWay, DwzAjax dwz) {
RpPayWay rpPayWayOld = rpPayWayService.getDataById(rpPayWay.getId());
rpPayWayOld.setEditTime(new Date());
rpPayWayOld.setPayRate(rpPayWay.getPayRate());
RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(rpPayWay.getPayProductCode(), null);
if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法删除!");
}
rpPayWayService.updateData(rpPayWayOld);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 : 删除
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("pay:way:delete")
@RequestMapping(value = "/delete", method ={RequestMethod.POST, RequestMethod.GET})
public String delete(Model model, DwzAjax dwz, @RequestParam("id") String id) {
RpPayWay rpPayWay = rpPayWayService.getDataById(id);
RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(rpPayWay.getPayProductCode(), null);
if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法删除!");
}
rpPayWay.setStatus(PublicStatusEnum.UNACTIVE.name());
rpPayWayService.updateData(rpPayWay);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 :根据支付方式获取支付类型
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/getPayType", method = RequestMethod.GET) | @ResponseBody
public List getPayType(@RequestParam("payWayCode") String payWayCode) {
return PayTypeEnum.getWayList(payWayCode);
}
/**
* 函数功能说明 :根据支付产品获取支付方式
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/getPayWay", method = RequestMethod.GET)
@ResponseBody
public List getPayWay(@RequestParam("productCode") String productCode) {
List<RpPayWay> payWayList = rpPayWayService.listByProductCode(productCode);
Map<String, String> map = new HashMap<String, String>();
//过滤重复数据
for(RpPayWay payWay : payWayList){
map.put(payWay.getPayWayCode(), payWay.getPayWayName());
}
//转换json
List list = new ArrayList();
for (String key : map.keySet()) {
Map<String, String> mapJson = new HashMap<String, String>();
mapJson.put("desc", map.get(key));
mapJson.put("name", key);
list.add(mapJson);
}
return list;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\PayWayController.java | 2 |
请完成以下Java代码 | public class ExcelFormats
{
public static final ExcelFormat EXCEL_OPEN_XML = new ExcelOpenXMLFormat();
public static final ExcelFormat EXCEL97 = new Excel97Format();
private static final ImmutableList<ExcelFormat> ALL_FORMATS = ImmutableList.of(EXCEL_OPEN_XML, EXCEL97);
private static final String SYSCONFIG_DefaultExcelFileExtension = "de.metas.excel.DefaultFileExtension";
public static String getDefaultFileExtension()
{
final ISysConfigBL sysconfigs = Services.get(ISysConfigBL.class);
return sysconfigs.getValue(SYSCONFIG_DefaultExcelFileExtension, ExcelOpenXMLFormat.FILE_EXTENSION);
}
public static ExcelFormat getDefaultFormat()
{
return getFormatByFileExtension(getDefaultFileExtension());
}
public static Set<String> getFileExtensionsDefaultFirst()
{
return ImmutableSet.<String> builder()
.add(getDefaultFileExtension()) // default one first
.addAll(getFileExtensions())
.build();
}
public static Set<String> getFileExtensions()
{
return ALL_FORMATS.stream()
.map(ExcelFormat::getFileExtension) | .collect(ImmutableSet.toImmutableSet());
}
public static ExcelFormat getFormatByFile(@NonNull final File file)
{
final String fileExtension = Files.getFileExtension(file.getPath());
return getFormatByFileExtension(fileExtension);
}
public static ExcelFormat getFormatByFileExtension(@NonNull final String fileExtension)
{
return ALL_FORMATS
.stream()
.filter(format -> fileExtension.equals(format.getFileExtension()))
.findFirst()
.orElseThrow(() -> new AdempiereException(
"No " + ExcelFormat.class.getSimpleName() + " found for file extension '" + fileExtension + "'."
+ "\n Supported extensions are: " + getFileExtensions()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelFormats.java | 1 |
请完成以下Java代码 | public class ManufacturingOrderReportAudit
{
@Getter
private final APITransactionId transactionId;
private String jsonRequest;
private String jsonResponse;
public enum ImportStatus
{
SUCCESS, FAILED,
}
@Setter(AccessLevel.NONE)
private ImportStatus importStatus;
@Setter(AccessLevel.NONE)
private String errorMsg;
@Setter(AccessLevel.NONE)
private AdIssueId adIssueId;
@Setter(AccessLevel.NONE)
private final ArrayList<ManufacturingOrderReportAuditItem> items;
public static ManufacturingOrderReportAudit newInstance(@NonNull final APITransactionId transactionId)
{
return ManufacturingOrderReportAudit.builder()
.transactionId(transactionId)
.build();
}
@Builder
private ManufacturingOrderReportAudit(
final APITransactionId transactionId,
final String jsonRequest,
final String jsonResponse,
final ImportStatus importStatus,
final String errorMsg,
final AdIssueId adIssueId,
@Singular final List<ManufacturingOrderReportAuditItem> items)
{
this.transactionId = transactionId; | this.jsonRequest = jsonRequest;
this.jsonResponse = jsonResponse;
this.importStatus = importStatus;
this.errorMsg = errorMsg;
this.adIssueId = adIssueId;
this.items = items != null ? new ArrayList<>(items) : new ArrayList<>();
}
public void addItem(@NonNull final ManufacturingOrderReportAuditItem item)
{
items.add(item);
}
public ImmutableList<ManufacturingOrderReportAuditItem> getItems()
{
return ImmutableList.copyOf(items);
}
public void markAsSuccess()
{
this.importStatus = ImportStatus.SUCCESS;
this.errorMsg = null;
this.adIssueId = null;
}
public void markAsFailure(@NonNull final String errorMsg, @NonNull final AdIssueId adIssueId)
{
this.importStatus = ImportStatus.FAILED;
this.errorMsg = errorMsg;
this.adIssueId = adIssueId;
items.forEach(ManufacturingOrderReportAuditItem::markAsRolledBackIfSuccess);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\importaudit\ManufacturingOrderReportAudit.java | 1 |
请完成以下Java代码 | public void reverseIterative(TreeNode treeNode) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if (treeNode != null) {
queue.add(treeNode);
}
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.getLeftChild() != null)
queue.add(node.getLeftChild());
if (node.getRightChild() != null)
queue.add(node.getRightChild());
TreeNode temp = node.getLeftChild();
node.setLeftChild(node.getRightChild());
node.setRightChild(temp);
} | }
public String toString(TreeNode root) {
if (root == null) {
return "";
}
StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
buffer.append(toString(root.getLeftChild()));
buffer.append(toString(root.getRightChild()));
return buffer.toString();
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\reversingtree\TreeReverser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class CompositeHandlerMapping implements HandlerMapping {
@Autowired
private ListableBeanFactory beanFactory;
private @Nullable List<HandlerMapping> mappings;
@Override
public @Nullable HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
for (HandlerMapping mapping : getMappings()) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
return null;
}
@Override
public boolean usesPathPatterns() {
for (HandlerMapping mapping : getMappings()) {
if (mapping.usesPathPatterns()) {
return true; | }
}
return false;
}
private List<HandlerMapping> getMappings() {
if (this.mappings == null) {
this.mappings = extractMappings();
}
return this.mappings;
}
private List<HandlerMapping> extractMappings() {
List<HandlerMapping> list = new ArrayList<>(this.beanFactory.getBeansOfType(HandlerMapping.class).values());
list.remove(this);
AnnotationAwareOrderComparator.sort(list);
return list;
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\CompositeHandlerMapping.java | 2 |
请完成以下Java代码 | public void run(String... args) throws Exception {
logger.info(".... Fetching books");
logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
logger.info("以上两个查询一定从数据库查询,再根据cacheenable中的条件确定是否缓存");
logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
logger.info("获取缓存中的数据,有的不需要查数据库");
Book book = new Book("isbn-4567", "更新过的book","");
bookRepository.update(book);
logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567")); | try {
bookRepository.clear();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
}
} | repos\spring-boot-quick-master\quick-cache\src\main\java\com\quick\cache\AppRunner.java | 1 |
请完成以下Java代码 | public static void removeFactLinesIfEqual(
final Fact fact,
final FactLine dr,
final FactLine cr,
final Predicate<AcctSchema> isInterOrg)
{
final AcctSchema as = fact.getAcctSchema();
if (as.isPostIfSameClearingAccounts())
{
return;
}
if (dr == null || cr == null)
{
return;
}
if (isInterOrg.test(as))
{
return; | }
final ElementValueId debitAccountId = dr.getAccountId();
final ElementValueId creditAccountId = cr.getAccountId();
if (!ElementValueId.equals(debitAccountId, creditAccountId))
{
return;
}
BigDecimal debit = dr.getAmtAcctDr();
BigDecimal credit = cr.getAmtAcctCr();
if (debit.compareTo(credit) != 0)
{
return;
}
fact.remove(dr);
fact.remove(cr);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\PostingEqualClearingAccontsUtils.java | 1 |
请完成以下Java代码 | public static JSch setUpJsch() throws JSchException {
JSch jsch = new JSch();
jsch.addIdentity(PRIVATE_KEY);
return jsch;
}
public static Session createSession(JSch jsch) throws JSchException {
Session session = jsch.getSession(USER, HOST, PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
public static ChannelSftp createSftpChannel(Session session) throws JSchException {
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
return channelSftp; | }
public static Vector<ChannelSftp.LsEntry> listFiles(ChannelSftp channelSftp, String remoteDir) throws SftpException {
return channelSftp.ls(remoteDir);
}
public static void printFiles(Vector<ChannelSftp.LsEntry> files) {
for (ChannelSftp.LsEntry entry : files) {
LOGGER.info(entry.getLongname());
}
}
public static void disconnect(ChannelSftp channelSftp, Session session) {
channelSftp.disconnect();
session.disconnect();
}
} | repos\tutorials-master\libraries-security\src\main\java\com\baeldung\listfilesremoteserver\RemoteServerJsch.java | 1 |
请完成以下Java代码 | public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportCountByCriteria(this);
}
@Override
public List<CleanableHistoricCaseInstanceReportResult> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportByCriteria(this, page);
}
public String[] getCaseDefinitionIdIn() {
return caseDefinitionIdIn;
}
public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn;
}
public String[] getCaseDefinitionKeyIn() {
return caseDefinitionKeyIn;
}
public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) {
this.caseDefinitionKeyIn = caseDefinitionKeyIn;
}
public Date getCurrentTimestamp() {
return currentTimestamp; | }
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
public String[] getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isCompact() {
return isCompact;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java | 1 |
请完成以下Java代码 | protected Object evaluateOutputEntry(DmnExpressionImpl conclusion, VariableContext variableContext) {
String expressionLanguage = conclusion.getExpressionLanguage();
if (expressionLanguage == null) {
expressionLanguage = outputEntryExpressionLanguage;
}
return expressionEvaluationHandler.evaluateExpression(expressionLanguage, conclusion, variableContext);
}
protected Object evaluateFeelSimpleUnaryTests(DmnDecisionTableInputImpl input, DmnExpressionImpl condition, VariableContext variableContext) {
String expressionText = condition.getExpression();
if (expressionText != null) {
return feelEngine.evaluateSimpleUnaryTests(expressionText, input.getInputVariable(), variableContext);
}
else {
return null;
}
}
@Override
public DmnDecisionResult generateDecisionResult(DmnDecisionLogicEvaluationEvent event) {
DmnDecisionTableEvaluationEvent evaluationResult = (DmnDecisionTableEvaluationEvent) event; | List<DmnDecisionResultEntries> ruleResults = new ArrayList<DmnDecisionResultEntries>();
if (evaluationResult.getCollectResultName() != null || evaluationResult.getCollectResultValue() != null) {
DmnDecisionResultEntriesImpl ruleResult = new DmnDecisionResultEntriesImpl();
ruleResult.putValue(evaluationResult.getCollectResultName(), evaluationResult.getCollectResultValue());
ruleResults.add(ruleResult);
}
else {
for (DmnEvaluatedDecisionRule evaluatedRule : evaluationResult.getMatchingRules()) {
DmnDecisionResultEntriesImpl ruleResult = new DmnDecisionResultEntriesImpl();
for (DmnEvaluatedOutput evaluatedOutput : evaluatedRule.getOutputEntries().values()) {
ruleResult.putValue(evaluatedOutput.getOutputName(), evaluatedOutput.getValue());
}
ruleResults.add(ruleResult);
}
}
return new DmnDecisionResultImpl(ruleResults);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\DecisionTableEvaluationHandler.java | 1 |
请完成以下Java代码 | public class Student {
//
private String name;
private String cls;
private String country;
public void setName(String name) {
this.name = name;
}
public String getCls() {
return cls;
}
public void setCls(String cls) {
this.cls = cls;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCounty() {
return country;
}
@Override
public String toString() {
return "Student{" + | "name='" + name + '\'' +
", cls='" + cls + '\'' +
", country='" + country + '\'' +
'}';
}
public Student (String name, String cls, String country){
super();
this.name = name;
this.cls = cls;
this.country = country;
}
public String getName() {
return name;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwagger2Project\src\main\java\spring\swagger2\Student.java | 1 |
请完成以下Java代码 | public abstract class AbstractDiscoveredEndpoint<O extends Operation> extends AbstractExposableEndpoint<O>
implements DiscoveredEndpoint<O> {
private final EndpointDiscoverer<?, ?> discoverer;
private final Object endpointBean;
/**
* Create a new {@link AbstractDiscoveredEndpoint} instance.
* @param discoverer the discoverer that discovered the endpoint
* @param endpointBean the primary source bean
* @param id the ID of the endpoint
* @param defaultAccess access to the endpoint that is permitted by default
* @param operations the endpoint operations
* @since 3.4.0
*/
public AbstractDiscoveredEndpoint(EndpointDiscoverer<?, ?> discoverer, Object endpointBean, EndpointId id,
Access defaultAccess, Collection<? extends O> operations) {
super(id, defaultAccess, operations);
Assert.notNull(discoverer, "'discoverer' must not be null");
Assert.notNull(endpointBean, "'endpointBean' must not be null");
this.discoverer = discoverer;
this.endpointBean = endpointBean;
}
@Override
public Object getEndpointBean() {
return this.endpointBean;
} | @Override
public boolean wasDiscoveredBy(Class<? extends EndpointDiscoverer<?, ?>> discoverer) {
return discoverer.isInstance(this.discoverer);
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this).append("discoverer", this.discoverer.getClass().getName())
.append("endpointBean", this.endpointBean.getClass().getName());
appendFields(creator);
return creator.toString();
}
protected void appendFields(ToStringCreator creator) {
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\annotation\AbstractDiscoveredEndpoint.java | 1 |
请完成以下Java代码 | protected String doIt()
{
//
// Get the HU
final PickingSlotRow huRow = getSingleSelectedPickingSlotRow();
Check.assume(huRow.isTopLevelHU(), "row {} shall be a top level HU", huRow);
final I_M_HU hu = InterfaceWrapperHelper.load(huRow.getHuId(), I_M_HU.class);
//
// Remove the HU from it's picking slot
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(hu);
//
// Make sure the HU has the BPartner/Location of the picking slot
final PickingSlotRow pickingSlotRow = getRootRowForSelectedPickingSlotRows();
if (pickingSlotRow.getBPartnerId() > 0)
{
hu.setC_BPartner_ID(pickingSlotRow.getBPartnerId());
hu.setC_BPartner_Location_ID(pickingSlotRow.getBPartnerLocationId());
InterfaceWrapperHelper.save(hu);
}
//
// Move the HU to an after picking locator
moveToAfterPickingLocator(hu);
//
// Inactive all those picking candidates
pickingCandidateService.inactivateForHUId(HuId.ofRepoId(hu.getM_HU_ID()));
husExtractedEvents.add(HUExtractedFromPickingSlotEvent.builder()
.huId(hu.getM_HU_ID())
.bpartnerId(hu.getC_BPartner_ID())
.bpartnerLocationId(hu.getC_BPartner_Location_ID())
.build());
return MSG_OK;
} | @Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Invalidate the views
// Expectation: the HU shall disappear from picking slots view (left side) and shall appear on after picking HUs view (right side).
final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView();
invalidateView(pickingSlotsClearingView.getViewId());
//
husExtractedEvents.forEach(pickingSlotsClearingView::handleEvent);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutHU.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String name) {
this.login = name;
} | public Set<BlogPost> getBlogPosts() {
return blogPosts;
}
public void setBlogPosts(Set<BlogPost> blogPosts) {
this.blogPosts = blogPosts;
}
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
} | repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\querydsl\intro\entities\User.java | 1 |
请完成以下Java代码 | public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge angefragt.
@param QtyRequiered Menge angefragt */
@Override
public void setQtyRequiered (java.math.BigDecimal QtyRequiered)
{
set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered);
}
/** Get Menge angefragt.
@return Menge angefragt */
@Override
public java.math.BigDecimal getQtyRequiered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyRequiered);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Use line quantity. | @param UseLineQty Use line quantity */
@Override
public void setUseLineQty (boolean UseLineQty)
{
set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty));
}
/** Get Use line quantity.
@return Use line quantity */
@Override
public boolean isUseLineQty ()
{
Object oo = get_Value(COLUMNNAME_UseLineQty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLine.java | 1 |
请完成以下Java代码 | public class DigestAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean, Ordered {
private static final Log logger = LogFactory.getLog(DigestAuthenticationEntryPoint.class);
private @Nullable String key;
private @Nullable String realmName;
private int nonceValiditySeconds = 300;
private int order = Integer.MAX_VALUE; // ~ default
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public void afterPropertiesSet() {
Assert.hasLength(this.realmName, "realmName must be specified");
Assert.hasLength(this.key, "key must be specified");
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
// compute a nonce (do not use remote IP address due to proxy farms) format of
// nonce is: base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
long expiryTime = System.currentTimeMillis() + (this.nonceValiditySeconds * 1000);
String signatureValue = DigestAuthUtils.md5Hex(expiryTime + ":" + this.key);
String nonceValue = expiryTime + ":" + signatureValue;
String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes()));
// qop is quality of protection, as defined by RFC 2617. We do not use opaque due
// to IE violation of RFC 2617 in not representing opaque on subsequent requests
// in same session.
String authenticateHeader = "Digest realm=\"" + this.realmName + "\", " + "qop=\"auth\", nonce=\""
+ nonceValueBase64 + "\"";
if (authException instanceof NonceExpiredException) {
authenticateHeader = authenticateHeader + ", stale=\"true\"";
} | logger.debug(LogMessage.format("WWW-Authenticate header sent to user agent: %s", authenticateHeader));
response.addHeader("WWW-Authenticate", authenticateHeader);
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
public @Nullable String getKey() {
return this.key;
}
public int getNonceValiditySeconds() {
return this.nonceValiditySeconds;
}
public @Nullable String getRealmName() {
return this.realmName;
}
public void setKey(String key) {
this.key = key;
}
public void setNonceValiditySeconds(int nonceValiditySeconds) {
this.nonceValiditySeconds = nonceValiditySeconds;
}
public void setRealmName(String realmName) {
this.realmName = realmName;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\www\DigestAuthenticationEntryPoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class ConventionUtils {
private static final Set<Character> SEPARATORS;
static {
List<Character> chars = Arrays.asList('-', '_');
SEPARATORS = Collections.unmodifiableSet(new HashSet<>(chars));
}
/**
* Return the idiomatic metadata format for the given {@code value}.
* @param value a value
* @return the idiomatic format for the value, or the value itself if it already
* complies with the idiomatic metadata format.
*/
public static String toDashedCase(String value) {
StringBuilder dashed = new StringBuilder();
Character previous = null;
for (int i = 0; i < value.length(); i++) {
char current = value.charAt(i); | if (SEPARATORS.contains(current)) {
dashed.append("-");
}
else if (Character.isUpperCase(current) && previous != null && !SEPARATORS.contains(previous)) {
dashed.append("-").append(current);
}
else {
dashed.append(current);
}
previous = current;
}
return dashed.toString().toLowerCase(Locale.ENGLISH);
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\support\ConventionUtils.java | 2 |
请完成以下Java代码 | public XMLGregorianCalendar getLieferzeitpunkt() {
return lieferzeitpunkt;
}
/**
* Sets the value of the lieferzeitpunkt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setLieferzeitpunkt(XMLGregorianCalendar value) {
this.lieferzeitpunkt = value;
}
/**
* Gets the value of the tour property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTour() {
return tour;
}
/**
* Sets the value of the tour property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTour(String value) {
this.tour = value;
}
/**
* Gets the value of the grund property.
*
* @return
* possible object is
* {@link BestellungDefektgrund }
*
*/
public BestellungDefektgrund getGrund() {
return grund;
}
/**
* Sets the value of the grund property.
*
* @param value
* allowed object is
* {@link BestellungDefektgrund }
* | */
public void setGrund(BestellungDefektgrund value) {
this.grund = value;
}
/**
* Gets the value of the tourId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTourId() {
return tourId;
}
/**
* Sets the value of the tourId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTourId(String value) {
this.tourId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAnteil.java | 1 |
请完成以下Java代码 | public void setIncluded_Role(org.compiere.model.I_AD_Role Included_Role)
{
set_ValueFromPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class, Included_Role);
}
/** Set Included Role.
@param Included_Role_ID Included Role */
@Override
public void setIncluded_Role_ID (int Included_Role_ID)
{
if (Included_Role_ID < 1)
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, Integer.valueOf(Included_Role_ID));
}
/** Get Included Role.
@return Included Role */
@Override
public int getIncluded_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first | */
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Included.java | 1 |
请完成以下Java代码 | public ResultType setIndustry(Industry industry) {
LOG.debug("设置行业......");
BeanUtil.requireNonNull(industry, "行业对象为空");
String url = BASE_API_URL + "cgi-bin/template/api_set_industry?access_token=" + apiConfig.getAccessToken();
BaseResponse response = executePost(url, industry.toJsonString());
return ResultType.get(response.getErrcode());
}
/**
* 添加模版
*
* @param shortTemplateId 模版短id
* @return 操作结果
*/
public AddTemplateResponse addTemplate(String shortTemplateId) {
LOG.debug("添加模版......");
BeanUtil.requireNonNull(shortTemplateId, "短模版id必填");
String url = BASE_API_URL + "cgi-bin/template/api_add_template?access_token=" + apiConfig.getAccessToken();
;
Map<String, String> params = new HashMap<String, String>();
params.put("template_id_short", shortTemplateId);
BaseResponse r = executePost(url, JSON.toJSONString(params));
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
return JSON.parseObject(resultJson, AddTemplateResponse.class);
} | /**
* 发送模版消息
*
* @param msg 消息
* @return 发送结果
*/
public SendTemplateResponse send(TemplateMsg msg) {
LOG.debug("发送模版消息......");
BeanUtil.requireNonNull(msg.getTouser(), "openid is null");
BeanUtil.requireNonNull(msg.getTemplateId(), "template_id is null");
BeanUtil.requireNonNull(msg.getData(), "data is null");
// BeanUtil.requireNonNull(msg.getTopcolor(), "top color is null");
// BeanUtil.requireNonNull(msg.getUrl(), "url is null");
String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=" + apiConfig.getAccessToken();
;
BaseResponse r = executePost(url, msg.toJsonString());
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
SendTemplateResponse result = JSON.parseObject(resultJson, SendTemplateResponse.class);
return result;
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\TemplateMsgApi.java | 1 |
请完成以下Java代码 | public boolean shouldInclude(PropertySource<?> source, String name) {
if (isIncludeAll()) {
return true;
}
if (isMatch(source.getName(), excludeSourceNames) || isMatch(name, excludePropertyNames)) {
return false;
}
return isIncludeUnset() || isMatch(source.getName(), includeSourceNames) || isMatch(name, includePropertyNames);
}
private boolean isIncludeAll() {
return isIncludeUnset() && isExcludeUnset();
} | private boolean isIncludeUnset() {
return isEmpty(includeSourceNames) && isEmpty(includePropertyNames);
}
private boolean isExcludeUnset() {
return isEmpty(excludeSourceNames) && isEmpty(excludePropertyNames);
}
private boolean isEmpty(List<String> patterns) {
return patterns == null || patterns.isEmpty();
}
private boolean isMatch(String name, List<String> patterns) {
return name != null && !isEmpty(patterns) && patterns.stream().anyMatch(name::matches);
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\filter\DefaultPropertyFilter.java | 1 |
请完成以下Java代码 | public JSONLookupValuesList getAttributeTypeahead(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr//
, @PathVariable(PARAM_RowId) final String rowIdStr //
, @PathVariable("attributeName") final String attributeName //
, @RequestParam(name = "query", required = true) final String query //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes()
.getAttributeTypeahead(attributeName, query)
.transform(this::toJSONLookupValuesList);
}
private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList)
{
return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language());
} | @GetMapping("/attribute/{attributeName}/dropdown")
public JSONLookupValuesList getAttributeDropdown(
@PathVariable(PARAM_WindowId) final String windowIdStr //
, @PathVariable(PARAM_ViewId) final String viewIdStr //
, @PathVariable(PARAM_RowId) final String rowIdStr //
, @PathVariable("attributeName") final String attributeName //
)
{
userSession.assertLoggedIn();
final ViewId viewId = ViewId.of(windowIdStr, viewIdStr);
final DocumentId rowId = DocumentId.of(rowIdStr);
return viewsRepo.getView(viewId)
.getById(rowId)
.getAttributes()
.getAttributeDropdown(attributeName)
.transform(this::toJSONLookupValuesList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowAttributesRestController.java | 1 |
请完成以下Java代码 | protected IScriptExecutorFactory createScriptExecutorFactory()
{
return scriptExecutorFactory;
}
@Override
protected void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory)
{
scriptExecutorFactory.setDryRunMode(config.isDryRunMode());
}
@Override
protected IDatabase createDatabase()
{
return new SQLDatabase(config.getDbUrl(), config.getDbUsername(), config.getDbPassword());
}
@Override
protected ScriptsApplier createScriptApplier(final IDatabase database)
{
final ScriptsApplier scriptApplier = super.createScriptApplier(database);
scriptApplier.setSkipExecutingAfterScripts(config.isSkipExecutingAfterScripts());
return scriptApplier;
}
@Override
protected IScriptsApplierListener createScriptsApplierListener() | {
switch (config.getOnScriptFailure())
{
case FAIL:
return NullScriptsApplierListener.instance;
case ASK:
if (GraphicsEnvironment.isHeadless())
{
return ConsoleScriptsApplierListener.instance;
}
return new SwingUIScriptsApplierListener();
default:
throw new RuntimeException("Unexpected WorkspaceMigrateConfig.onScriptFailure=" + config.getOnScriptFailure());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceScriptsApplier.java | 1 |
请完成以下Java代码 | public void setSaveResponse(boolean saveResponse) {
this.saveResponse = saveResponse;
}
public boolean isSaveResponseTransient() {
return saveResponseTransient;
}
public void setSaveResponseTransient(boolean saveResponseTransient) {
this.saveResponseTransient = saveResponseTransient;
}
public boolean isSaveResponseAsJson() {
return saveResponseAsJson;
} | public void setSaveResponseAsJson(boolean saveResponseAsJson) {
this.saveResponseAsJson = saveResponseAsJson;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public boolean isNoRedirects() {
return httpRequest.isNoRedirects();
}
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\BaseHttpActivityDelegate.java | 1 |
请完成以下Java代码 | public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public String getEditorSourceValueId() {
return editorSourceValueId;
}
@Override
public void setEditorSourceValueId(String editorSourceValueId) {
this.editorSourceValueId = editorSourceValueId;
}
@Override
public String getEditorSourceExtraValueId() {
return editorSourceExtraValueId; | }
@Override
public void setEditorSourceExtraValueId(String editorSourceExtraValueId) {
this.editorSourceExtraValueId = editorSourceExtraValueId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean hasEditorSource() {
return this.editorSourceValueId != null;
}
@Override
public boolean hasEditorSourceExtra() {
return this.editorSourceExtraValueId != null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ModelEntityImpl.java | 1 |
请完成以下Java代码 | public class ShipmentScheduleFromSubscriptionOrderLineVetoer implements ModelWithoutShipmentScheduleVetoer
{
private static final Logger logger = LogManager.getLogger(ShipmentScheduleFromSubscriptionOrderLineVetoer.class);
private final ISubscriptionBL subscriptionBL = Services.get(ISubscriptionBL.class);
/**
* @param model
* the object for which we want to create a shipment schedule. The method
* assumes that it can obtain a {@link I_C_OrderLine} instance for model by using the
* {@link InterfaceWrapperHelper}.
*/
@Override
public OnMissingCandidate foundModelWithoutInOutCandidate(@NonNull final Object model) | {
final I_C_OrderLine ol = InterfaceWrapperHelper.create(model, I_C_OrderLine.class);
final boolean subscription = subscriptionBL.isSubscription(ol);
if (subscription)
{
Loggables.withLogger(logger, Level.DEBUG)
.addLog("ShipmentScheduleFromSubscriptionOrderLineVetoer - isSubscription={}; return {}; orderLine={}",
subscription, OnMissingCandidate.I_VETO, ol);
return OnMissingCandidate.I_VETO;
}
return OnMissingCandidate.I_DONT_CARE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\inoutcandidate\ShipmentScheduleFromSubscriptionOrderLineVetoer.java | 1 |
请完成以下Java代码 | public List<?> getWithLinkedDocuments()
{
return withLinkedDocuments;
}
@Override
public IMaterialTrackingQuery setOnMoreThanOneFound(final OnMoreThanOneFound onMoreThanOneFound)
{
Check.assumeNotNull(onMoreThanOneFound, "onMoreThanOneFound not null");
this.onMoreThanOneFound = onMoreThanOneFound;
return this;
}
@Override
public OnMoreThanOneFound getOnMoreThanOneFound()
{
return onMoreThanOneFound;
}
@Override
public IMaterialTrackingQuery setCompleteFlatrateTerm(final Boolean completeFlatrateTerm)
{
this.completeFlatrateTerm = completeFlatrateTerm;
return this;
}
@Override
public Boolean getCompleteFlatrateTerm()
{
return completeFlatrateTerm;
}
@Override
public IMaterialTrackingQuery setLot(final String lot)
{ | this.lot = lot;
return this;
}
@Override
public String getLot()
{
return lot;
}
@Override
public IMaterialTrackingQuery setReturnReadOnlyRecords(boolean returnReadOnlyRecords)
{
this.returnReadOnlyRecords = returnReadOnlyRecords;
return this;
}
@Override
public boolean isReturnReadOnlyRecords()
{
return returnReadOnlyRecords;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingQuery.java | 1 |
请完成以下Java代码 | public static LMQRCode fromGlobalQRCodeJsonString(@NonNull final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static LMQRCode fromGlobalQRCode(final GlobalQRCode globalQRCode)
{
if (!isHandled(globalQRCode))
{
throw new AdempiereException("Invalid Leich und Mehl QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), VERSION_1))
{
return fromGlobalQRCode_version1(globalQRCode);
}
else
{
throw new AdempiereException("Invalid Leich und Mehl QR Code version: " + version);
}
} | private static LMQRCode fromGlobalQRCode_version1(final GlobalQRCode globalQRCode)
{
// NOTE to dev: keep in sync with huQRCodes.js, parseQRCodePayload_LeichMehl_v1
try
{
final List<String> parts = SPLITTER.splitToList(globalQRCode.getPayloadAsJson());
return LMQRCode.builder()
.code(globalQRCode)
.weightInKg(new BigDecimal(parts.get(0)))
.bestBeforeDate(parts.size() >= 2 ? LocalDate.parse(parts.get(1), BEST_BEFORE_DATE_FORMAT) : null)
.lotNumber(parts.size() >= 3 ? StringUtils.trimBlankToNull(parts.get(2)) : null)
.productNo(parts.size() >= 4 ? StringUtils.trimBlankToNull(parts.get(3)) : null)
.build();
}
catch (Exception ex)
{
throw new AdempiereException("Invalid Leich und Mehl QR Code: " + globalQRCode, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\leich_und_mehl\LMQRCodeParser.java | 1 |
请完成以下Java代码 | public boolean isI_IsImported ()
{
Object oo = get_Value(COLUMNNAME_I_IsImported);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now. | @return Process Now */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set URL3.
@param URL3
Vollständige Web-Addresse, z.B. https://metasfresh.com/
*/
@Override
public void setURL3 (java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
/** Get URL3.
@return Vollständige Web-Addresse, z.B. https://metasfresh.com/
*/
@Override
public java.lang.String getURL3 ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL3);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner_GlobalID.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringbootAsyncApplication implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(SpringbootAsyncApplication.class);
@Autowired
private GitHubLookupService gitHubLookupService;
@Bean("threadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(1000);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("Async-");
return executor;
}
public static void main(String[] args) {
SpringApplication.run(SpringbootAsyncApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
// Kick of multiple, asynchronous lookups | CompletableFuture<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
CompletableFuture<User> page2 = gitHubLookupService.findUser("CloudFoundry");
CompletableFuture<User> page3 = gitHubLookupService.findUser("Spring-Projects");
CompletableFuture<User> page4 = gitHubLookupService.findUser("AlanBinu007");
// Wait until they are all done
CompletableFuture.allOf(page1, page2, page3, page4).join();
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
logger.info("--> " + page4.get());
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-async-example\src\main\java\net\alanbinu\springboot\springbootasyncexample\SpringbootAsyncApplication.java | 2 |
请完成以下Java代码 | public static void logProcessAccess(final RoleId roleId, final int id, final Boolean access)
{
logAccess(roleId, COLUMNNAME_AD_Process_ID, id, null, null, access, null);
}
public static void logTaskAccess(final RoleId roleId, final int id, final Boolean access)
{
logAccess(roleId, COLUMNNAME_AD_Task_ID, id, null, null, access, null);
}
public static void logWorkflowAccess(final RoleId roleId, final int id, final Boolean access)
{
logAccess(roleId, COLUMNNAME_AD_Workflow_ID, id, null, null, access, null);
}
public static void logDocActionAccess(final RoleId roleId, final DocTypeId docTypeId, final String docAction, final Boolean access)
{
logAccess(roleId, COLUMNNAME_C_DocType_ID, docTypeId.getRepoId(), COLUMNNAME_DocAction, docAction, access, null);
}
private static void logAccess(
@NonNull final RoleId roleId,
final String type,
final Object value,
final String type2,
final Object value2,
final Boolean access,
final String description)
{
final String permLogLevel = getPermLogLevel();
if (PERMLOGLEVEL_Disabled.equals(permLogLevel))
{
return;
}
final boolean isPermissionGranted = access != null;
if (isPermissionGranted && !PERMLOGLEVEL_Full.equals(permLogLevel))
{
// Permission granted, and there is no need to log all requests => nothing to do
return;
}
if (value instanceof Integer && ((Integer)value).intValue() <= 0)
{
// Skip invalid permissions request
return;
}
final Properties ctx = Env.getCtx();
final String trxName = null;
final boolean isReadWrite = access != null && access.booleanValue() == true;
final ArrayList<Object> params = new ArrayList<>();
final StringBuilder whereClause = new StringBuilder(COLUMNNAME_AD_Role_ID + "=? AND " + type + "=?");
params.add(roleId);
params.add(value);
if (type2 != null)
{
whereClause.append(" AND " + type2 + "=?");
params.add(value2);
}
MRolePermRequest req = new Query(ctx, Table_Name, whereClause.toString(), trxName)
.setParameters(params)
.setOrderBy(COLUMNNAME_AD_Role_PermRequest_ID + " DESC")
.first();
if (req == null)
{
req = new MRolePermRequest(ctx, 0, trxName);
req.setAD_Role_ID(roleId.getRepoId()); | req.set_ValueOfColumn(type, value);
if (type2 != null)
{
req.set_ValueOfColumn(type2, value2);
}
}
req.setIsActive(true);
req.setIsReadWrite(isReadWrite);
req.setIsPermissionGranted(isPermissionGranted);
req.setDescription(description);
savePermissionRequestAndHandleException(type, value, req);
}
private static void savePermissionRequestAndHandleException(
@NonNull final String type,
@NonNull final Object value,
@NonNull final MRolePermRequest req)
{
try
{
req.saveEx();
}
catch (final DBForeignKeyConstraintException e)
{
throw new NoSuchForeignKeyException(type + "=" + value + " is not a valid foreign key", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\model\MRolePermRequest.java | 1 |
请完成以下Java代码 | public int getDataEntry_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Registername.
@param TabName Registername */
@Override
public void setTabName (java.lang.String TabName)
{
set_Value (COLUMNNAME_TabName, TabName);
}
/** Get Registername.
@return Registername */
@Override
public java.lang.String getTabName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TabName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_SubTab.java | 1 |
请完成以下Java代码 | public void enableSqlQueriesTracing(@NonNull final IQueryStatisticsCollector sqlQueriesCollector)
{
this.sqlQueriesTracingEnabled = true;
TracingStatement.SQL_QUERIES_COLLECTOR = sqlQueriesCollector;
}
public void disableSqlQueriesTracing()
{
this.sqlQueriesTracingEnabled = false;
}
@Override
public CStatement newCStatement(final int resultSetType, final int resultSetConcurrency, final String trxName)
{
final CStatementProxy stmt = new CStatementProxy(resultSetType, resultSetConcurrency, trxName);
if (sqlQueriesTracingEnabled)
{
return new TracingStatement<>(stmt);
}
return stmt;
}
@Override
public CPreparedStatement newCPreparedStatement(final int resultSetType, final int resultSetConcurrency, final String sql, final String trxName)
{
final CPreparedStatementProxy pstmt = new CPreparedStatementProxy(resultSetType, resultSetConcurrency, sql, trxName);
if (sqlQueriesTracingEnabled)
{
return new TracingPreparedStatement<>(pstmt);
}
return pstmt;
}
@Override
public CCallableStatement newCCallableStatement(final int resultSetType, final int resultSetConcurrency, final String sql, final String trxName)
{ | return new CCallableStatementProxy(resultSetType, resultSetConcurrency, sql, trxName);
}
@Override
public CStatement newCStatement(final CStatementVO info)
{
final CStatementProxy stmt = new CStatementProxy(info);
if (sqlQueriesTracingEnabled)
{
return new TracingStatement<>(stmt);
}
return stmt;
}
@Override
public CPreparedStatement newCPreparedStatement(final CStatementVO info)
{
final CPreparedStatementProxy pstmt = new CPreparedStatementProxy(info);
if (sqlQueriesTracingEnabled)
{
return new TracingPreparedStatement<>(pstmt);
}
return pstmt;
}
@Override
public CCallableStatement newCCallableStatement(final CStatementVO info)
{
return new CCallableStatementProxy(info);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\StatementsFactory.java | 1 |
请完成以下Java代码 | public int getCM_Media_Server_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_Server_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Deployed.
@param IsDeployed
Entity is deployed
*/
public void setIsDeployed (boolean IsDeployed)
{
set_Value (COLUMNNAME_IsDeployed, Boolean.valueOf(IsDeployed));
}
/** Get Deployed.
@return Entity is deployed | */
public boolean isDeployed ()
{
Object oo = get_Value(COLUMNNAME_IsDeployed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Synchronized.
@param LastSynchronized
Date when last synchronized
*/
public void setLastSynchronized (Timestamp LastSynchronized)
{
set_Value (COLUMNNAME_LastSynchronized, LastSynchronized);
}
/** Get Last Synchronized.
@return Date when last synchronized
*/
public Timestamp getLastSynchronized ()
{
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_MediaDeploy.java | 1 |
请完成以下Java代码 | private String getFilename(String string) {
int lastSlash = string.lastIndexOf('/');
return (lastSlash == -1) ? string : string.substring(lastSlash + 1);
}
String getDescription() {
return this.description;
}
String getDescription(String existing) {
return existing + " from " + this.description;
}
@Override
public String toString() { | return this.uri;
}
static @Nullable JarUri from(URI uri) {
return from(uri.toString());
}
static @Nullable JarUri from(String uri) {
if (uri.startsWith(JAR_SCHEME) && uri.contains(JAR_EXTENSION)) {
return new JarUri(uri);
}
return null;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\JarUri.java | 1 |
请完成以下Java代码 | public AttributeSetInstanceId createAttributeSetInstanceFromAttributesKey(@NonNull final AttributesKey attributesKey)
{
if (attributesKey.isNone())
{
return AttributeSetInstanceId.NONE;
}
final ImmutableAttributeSet attributeSet = toImmutableAttributeSet(attributesKey);
final I_M_AttributeSetInstance asi = asiService().createASIFromAttributeSet(attributeSet);
return AttributeSetInstanceId.ofRepoId(asi.getM_AttributeSetInstance_ID());
}
public static ImmutableAttributeSet toImmutableAttributeSet(@NonNull final AttributesKey attributesKey)
{
try
{
final ImmutableAttributeSet.Builder builder = ImmutableAttributeSet.builder();
final HashSet<AttributeValueId> attributeValueIds = new HashSet<>();
for (final AttributesKeyPart part : attributesKey.getParts())
{
if (part.getType() == AttributeKeyPartType.AttributeIdAndValue)
{
final AttributeId attributeId = part.getAttributeId();
final Object value = part.getValue();
final AttributeValueId attributeValueId = null;
builder.attributeValue(attributeId, value, attributeValueId);
}
else if (part.getType() == AttributeKeyPartType.AttributeValueId)
{
attributeValueIds.add(part.getAttributeValueId());
}
}
for (final AttributeListValue attributeValueRecord : attributesRepo().retrieveAttributeValuesByIds(attributeValueIds)) | {
builder.attributeValue(attributeValueRecord);
}
return builder.build();
}
catch (final RuntimeException ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("attributesKey", attributesKey);
}
}
public static AttributesKey pruneEmptyParts(@NonNull final AttributesKey attributesKey)
{
final ImmutableList<AttributesKeyPart> notBlankParts = attributesKey.getParts().stream()
.filter(p -> Check.isNotBlank(p.getValue()))
.collect(ImmutableList.toImmutableList());
return AttributesKey.ofParts(notBlankParts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeys.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setOwner(TenantId tenantId, AssetProfile assetProfile, IdProvider idProvider) {
assetProfile.setTenantId(tenantId);
}
@Override
protected AssetProfile prepare(EntitiesImportCtx ctx, AssetProfile assetProfile, AssetProfile old, EntityExportData<AssetProfile> exportData, IdProvider idProvider) {
assetProfile.setDefaultRuleChainId(idProvider.getInternalId(assetProfile.getDefaultRuleChainId()));
assetProfile.setDefaultDashboardId(idProvider.getInternalId(assetProfile.getDefaultDashboardId()));
assetProfile.setDefaultEdgeRuleChainId(idProvider.getInternalId(assetProfile.getDefaultEdgeRuleChainId()));
return assetProfile;
}
@Override
protected AssetProfile saveOrUpdate(EntitiesImportCtx ctx, AssetProfile assetProfile, EntityExportData<AssetProfile> exportData, IdProvider idProvider, CompareResult compareResult) {
AssetProfile saved = assetProfileService.saveAssetProfile(assetProfile);
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, saved, exportData, idProvider);
}
return saved;
} | @Override
protected void onEntitySaved(User user, AssetProfile savedAssetProfile, AssetProfile oldAssetProfile) {
logEntityActionService.logEntityAction(savedAssetProfile.getTenantId(), savedAssetProfile.getId(),
savedAssetProfile, null, oldAssetProfile == null ? ActionType.ADDED : ActionType.UPDATED, user);
}
@Override
protected AssetProfile deepCopy(AssetProfile assetProfile) {
return new AssetProfile(assetProfile);
}
@Override
protected void cleanupForComparison(AssetProfile assetProfile) {
super.cleanupForComparison(assetProfile);
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AssetProfileImportService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DmnEngineResource {
@Autowired(required=false)
protected DmnRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "Get DMN engine info", tags = { "Engine" }, notes = "Returns a read-only view of the DMN engine that is used in this REST-service.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the engine info is returned."),
})
@GetMapping(value = "/dmn-management/engine", produces = "application/json")
public EngineInfoResponse getEngineInfo() {
if (restApiInterceptor != null) {
restApiInterceptor.accessDmnManagementInfo();
}
EngineInfoResponse response = new EngineInfoResponse();
try {
EngineInfo dmnEngineInfo = DmnEngines.getDmnEngineInfo(DmnEngines.getDefaultDmnEngine().getName());
if (dmnEngineInfo != null) {
response.setName(dmnEngineInfo.getName());
response.setResourceUrl(dmnEngineInfo.getResourceUrl()); | response.setException(dmnEngineInfo.getException());
} else {
response.setName(DmnEngines.getDefaultDmnEngine().getName());
}
} catch (Exception e) {
throw new FlowableException("Error retrieving DMN engine info", e);
}
response.setVersion(DmnEngine.class.getPackage().getImplementationVersion());
return response;
}
} | repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\management\DmnEngineResource.java | 2 |
请完成以下Java代码 | public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setUserAgent (final @Nullable java.lang.String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
@Override | public java.lang.String getUserAgent()
{
return get_ValueAsString(COLUMNNAME_UserAgent);
}
@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_UI_Trace.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class CustomerPricingContext
{
@NonNull
IPricingResult pricingResult;
@NonNull
IPricingContext pricingContext;
@NonNull
BPartnerLocationAndCaptureId bPartnerLocationAndCaptureId;
@NonNull
public ProductId getProductId()
{
return (ProductId)assumeNotNull(pricingContext.getProductId());
}
@NonNull
public BPartnerId getBPartnerId()
{
return (BPartnerId)assumeNotNull(pricingContext.getBPartnerId());
}
@NonNull
public OrgId getOrgId()
{
return (OrgId)assumeNotNull(pricingContext.getOrgId());
}
@NonNull
public CurrencyId getResultCurrencyId()
{
return (CurrencyId)assumeNotNull(pricingResult.getCurrencyId());
}
@NonNull
public UomId getResultUomId()
{
return (UomId)assumeNotNull(pricingResult.getPriceUomId());
} | @NonNull
public TaxCategoryId getResultTaxCategory()
{
return (TaxCategoryId)assumeNotNull(pricingResult.getTaxCategoryId());
}
@NonNull
public LocalDate getResultPriceDate()
{
return pricingResult.getPriceDate();
}
public boolean isTaxIncluded()
{
return pricingResult.isTaxIncluded();
}
@NonNull
public ProductPrice getProductPrice()
{
return ProductPrice.builder()
.productId(getProductId())
.uomId(getResultUomId())
.money(Money.of(pricingResult.getPriceStd(), getResultCurrencyId()))
.build();
}
private static Object assumeNotNull(@Nullable final Object arg)
{
Check.assumeNotNull(arg, "applies() - should've taken care of this!");
return arg;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\CustomerTradeMarginPricingRule.java | 2 |
请完成以下Java代码 | public String getErrorMessage() {
return this.errorMessage;
}
public String getClassName() {
return this.className;
}
public List<URL> getCandidateLocations() {
return this.candidateLocations;
}
public List<ClassDescriptor> getTypeHierarchy() {
return this.typeHierarchy;
}
}
protected static class ClassDescriptor {
private final String name; | private final URL location;
public ClassDescriptor(String name, URL location) {
this.name = name;
this.location = location;
}
public String getName() {
return this.name;
}
public URL getLocation() {
return this.location;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\NoSuchMethodFailureAnalyzer.java | 1 |
请完成以下Java代码 | public ReturnReason5Choice getRsn() {
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link ReturnReason5Choice }
*
*/
public void setRsn(ReturnReason5Choice value) {
this.rsn = value;
}
/**
* Gets the value of the addtlInf 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 addtlInf property.
*
* <p> | * For example, to add a new item, do as follows:
* <pre>
* getAddtlInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddtlInf() {
if (addtlInf == null) {
addtlInf = new ArrayList<String>();
}
return this.addtlInf;
}
} | 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\ReturnReasonInformation10.java | 1 |
请完成以下Java代码 | protected void doCleanupAfterCompletion(Object transaction) {
@SuppressWarnings(UNCHECKED)
KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) transaction;
TransactionSynchronizationManager.unbindResource(getProducerFactory());
KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder();
if (kafkaResourceHolder != null) {
kafkaResourceHolder.close();
kafkaResourceHolder.clear();
}
}
/**
* Kafka transaction object, representing a KafkaResourceHolder. Used as transaction object by
* KafkaTransactionManager.
* @see KafkaResourceHolder
*/
private static class KafkaTransactionObject<K, V> implements SmartTransactionObject {
private @Nullable KafkaResourceHolder<K, V> resourceHolder;
KafkaTransactionObject() {
} | public void setResourceHolder(@Nullable KafkaResourceHolder<K, V> resourceHolder) {
this.resourceHolder = resourceHolder;
}
public @Nullable KafkaResourceHolder<K, V> getResourceHolder() {
return this.resourceHolder;
}
@Override
public boolean isRollbackOnly() {
return this.resourceHolder != null && this.resourceHolder.isRollbackOnly();
}
@Override
public void flush() {
// no-op
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\transaction\KafkaTransactionManager.java | 1 |
请完成以下Java代码 | public class Banking extends AbstractModuleInterceptor
{
@Override
protected void onAfterInit()
{
final IBankStatementDAO bankStatementDAO = Services.get(IBankStatementDAO.class);
// Register the Document Reposting Handler
final IDocumentRepostingSupplierService documentBL = Services.get(IDocumentRepostingSupplierService.class);
documentBL.registerSupplier(new BankStatementDocumentRepostingSupplier(bankStatementDAO));
final IPaySelectionBL paySelectionBL = Services.get(IPaySelectionBL.class);
final IBankStatementListenerService bankStatementListenerService = Services.get(IBankStatementListenerService.class);
final IImportProcessFactory importProcessFactory = Services.get(IImportProcessFactory.class);
bankStatementListenerService.addListener(new PaySelectionBankStatementListener(paySelectionBL));
importProcessFactory.registerImportProcess(I_I_Datev_Payment.class, DatevPaymentImportProcess.class);
importProcessFactory.registerImportProcess(I_I_BankStatement.class, BankStatementImportProcess.class);
}
@Override
protected void registerInterceptors(final IModelValidationEngine engine)
{
final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class);
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
final ICashStatementBL cashStatementBL = Services.get(ICashStatementBL.class);
final BankAccountService bankAccountService = SpringContextHolder.instance.getBean(BankAccountService.class);
// Bank statement:
{
engine.addModelValidator(new de.metas.banking.model.validator.C_BankStatementLine(bankStatementBL)); | }
// de.metas.banking.payment sub-module (code moved from swat main validator)
{
engine.addModelValidator(new de.metas.banking.payment.modelvalidator.C_Payment(bankStatementBL, paymentBL, cashStatementBL)); // 04203
engine.addModelValidator(new de.metas.banking.payment.modelvalidator.C_PaySelection(bankAccountService)); // 04203
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_PaySelectionLine.instance); // 04203
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_Payment_Request.instance); // 08596
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_AllocationHdr.instance); // 08972
}
}
@Override
protected void registerCallouts(final IProgramaticCalloutProvider calloutsRegistry)
{
final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class);
calloutsRegistry.registerAnnotatedCallout(new de.metas.banking.callout.C_BankStatement(bankStatementBL));
calloutsRegistry.registerAnnotatedCallout(de.metas.banking.payment.callout.C_PaySelectionLine.instance);
calloutsRegistry.registerAnnotatedCallout(new de.metas.banking.callout.C_BankStatementLine(bankStatementBL));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\validator\Banking.java | 1 |
请完成以下Java代码 | public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
private String roles = "";
private String permission="";
public User(){}
public User(String userName, String userPassword, int active, String roles, String permission) {
UserName = userName;
UserPassword = userPassword;
this.active = active;
this.roles = roles;
this.permission = permission;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
} | public String getUserPassword() {
return UserPassword;
}
public void setUserPassword(String userPassword) {
UserPassword = userPassword;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\9.PosilkaAdmin\src\main\java\posilka\admin\model\User.java | 1 |
请完成以下Java代码 | protected void deleteChildExecutions(
ExecutionEntity parentExecution,
ExecutionEntity notToDeleteExecution,
CommandContext commandContext
) {
// TODO: would be good if this deleteChildExecutions could be removed and the one on the executionEntityManager is used
// The problem however, is that the 'notToDeleteExecution' is passed here.
// This could be solved by not reusing an execution, but creating a new
// Delete all child executions
ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
Collection<ExecutionEntity> childExecutions = executionEntityManager.findChildExecutionsByParentExecutionId(
parentExecution.getId()
);
if (CollectionUtil.isNotEmpty(childExecutions)) {
for (ExecutionEntity childExecution : childExecutions) {
if (childExecution.getId().equals(notToDeleteExecution.getId()) == false) {
deleteChildExecutions(childExecution, notToDeleteExecution, commandContext);
}
}
}
String deleteReason =
DeleteReason.BOUNDARY_EVENT_INTERRUPTING + " (" + notToDeleteExecution.getCurrentActivityId() + ")";
if (parentExecution.getCurrentFlowElement() instanceof CallActivity) {
ExecutionEntity subProcessExecution = executionEntityManager.findSubProcessInstanceBySuperExecutionId(
parentExecution.getId()
);
if (subProcessExecution != null) {
executionEntityManager.deleteProcessInstanceExecutionEntity(
subProcessExecution.getId(),
subProcessExecution.getCurrentActivityId(),
deleteReason,
true, | true
);
}
}
executionEntityManager.cancelExecutionAndRelatedData(parentExecution, deleteReason);
}
public boolean isInterrupting() {
return interrupting;
}
public void setInterrupting(boolean interrupting) {
this.interrupting = interrupting;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BoundaryEventActivityBehavior.java | 1 |
请完成以下Java代码 | public @Nullable String type() {
return this.details.type();
}
@Override
public @Nullable String alias() {
return this.details.alias();
}
@Override
public @Nullable String password() {
return this.details.password();
}
@Override
public @Nullable List<X509Certificate> certificates() {
return this.certificatesSupplier.get().certificates();
}
@Override
public @Nullable PrivateKey privateKey() {
return this.privateKeySupplier.get().privateKey();
}
@Override | public PemSslStore withAlias(@Nullable String alias) {
return new LoadedPemSslStore(this.details.withAlias(alias), this.resourceLoader);
}
@Override
public PemSslStore withPassword(@Nullable String password) {
return new LoadedPemSslStore(this.details.withPassword(password), this.resourceLoader);
}
private record PrivateKeyHolder(@Nullable PrivateKey privateKey) {
}
private record CertificatesHolder(@Nullable List<X509Certificate> certificates) {
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\LoadedPemSslStore.java | 1 |
请完成以下Java代码 | public class DmnDecisionTableRuleImpl {
public String id;
public String name;
protected List<DmnExpressionImpl> conditions = new ArrayList<DmnExpressionImpl>();
protected List<DmnExpressionImpl> conclusions = new ArrayList<DmnExpressionImpl>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DmnExpressionImpl> getConditions() {
return conditions;
}
public void setConditions(List<DmnExpressionImpl> conditions) {
this.conditions = conditions;
}
public List<DmnExpressionImpl> getConclusions() { | return conclusions;
}
public void setConclusions(List<DmnExpressionImpl> conclusions) {
this.conclusions = conclusions;
}
@Override
public String toString() {
return "DmnDecisionTableRuleImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", conditions=" + conditions +
", conclusions=" + conclusions +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionTableRuleImpl.java | 1 |
请完成以下Java代码 | public Mono<BookBorrowResponse> borrowBook(String userId, String bookId) {
return userService.getUser(userId)
.flatMap(user -> {
if (!user.isActive()) {
return Mono.error(new RuntimeException("User is not an active member"));
}
return bookService.getBook(bookId);
})
.flatMap(book -> {
if (!book.isAvailable()) {
return Mono.error(new RuntimeException("Book is not available"));
}
return Mono.just(new BookBorrowResponse(userId, bookId, "Accepted"));
});
}
public Mono<BookBorrowResponse> borrowBookZip(String userId, String bookId) {
Mono<User> userMono = userService.getUser(userId)
.switchIfEmpty(Mono.error(new RuntimeException("User not found")));
Mono<Book> bookMono = bookService.getBook(bookId)
.switchIfEmpty(Mono.error(new RuntimeException("Book not found")));
return Mono.zip(userMono, bookMono, (user, book) -> new BookBorrowResponse(userId, bookId, "Accepted"));
}
public Mono<Book> applyDiscount(Mono<Book> bookMono) {
return bookMono.map(book -> {
book.setPrice(book.getPrice() - book.getPrice() * 0.2);
return book;
});
}
public Mono<Book> applyTax(Mono<Book> bookMono) {
return bookMono.map(book -> {
book.setPrice(book.getPrice() + book.getPrice() * 0.1);
return book;
});
} | public Mono<Book> getFinalPricedBook(String bookId) {
return bookService.getBook(bookId)
.transform(this::applyTax)
.transform(this::applyDiscount);
}
public Mono<Book> conditionalDiscount(String userId, String bookId) {
return userService.getUser(userId)
.filter(User::isActive)
.flatMap(user -> bookService.getBook(bookId)
.transform(this::applyDiscount))
.switchIfEmpty(bookService.getBook(bookId))
.switchIfEmpty(Mono.error(new RuntimeException("Book not found")));
}
public Mono<BookBorrowResponse> handleErrorBookBorrow(String userId, String bookId) {
return borrowBook(userId, bookId).onErrorResume(ex -> Mono.just(new BookBorrowResponse(userId, bookId, "Rejected")));
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\MonoTransformer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class SecureServletWebOperation implements ServletWebOperation {
private final ServletWebOperation delegate;
private final SecurityInterceptor securityInterceptor;
private final EndpointId endpointId;
SecureServletWebOperation(ServletWebOperation delegate, SecurityInterceptor securityInterceptor,
EndpointId endpointId) {
this.delegate = delegate;
this.securityInterceptor = securityInterceptor;
this.endpointId = endpointId;
}
@Override
public @Nullable Object handle(HttpServletRequest request, @Nullable Map<String, String> body) {
SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, this.endpointId);
if (!securityResponse.getStatus().equals(HttpStatus.OK)) {
return new ResponseEntity<Object>(securityResponse.getMessage(), securityResponse.getStatus()); | }
return this.delegate.handle(request, body);
}
}
static class CloudFoundryWebEndpointServletHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, CloudFoundryLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\CloudFoundryWebEndpointServletHandlerMapping.java | 2 |
请完成以下Java代码 | private static void calculateResults(StatelessRuleSession statelessRuleSession) throws InvalidRuleSessionException, RemoteException {
List data = prepareData();
// execute the rules
List results = statelessRuleSession.executeRules(data);
checkResults(results);
}
private static List prepareData() {
List data = new ArrayList();
data.add(new Question("Can I have a bonus?", -5));
return data;
}
private static void checkResults(List results) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
if (obj instanceof Answer) {
log.info(obj.toString());
}
}
} | private static void registerRules(String rulesFile, String rulesURI, RuleServiceProvider serviceProvider) throws ConfigurationException, RuleExecutionSetCreateException, IOException, RuleExecutionSetRegisterException {
// Get the rule administrator.
RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator();
// load the rules
InputStream ruleInput = JessWithJsr94.class.getResourceAsStream(rulesFile);
HashMap vendorProperties = new HashMap();
// Create the RuleExecutionSet
RuleExecutionSet ruleExecutionSet = ruleAdministrator
.getLocalRuleExecutionSetProvider(vendorProperties)
.createRuleExecutionSet(ruleInput, vendorProperties);
// Register the rule execution set.
ruleAdministrator.registerRuleExecutionSet(rulesURI, ruleExecutionSet, vendorProperties);
}
} | repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\JessWithJsr94.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ParcelShopDelivery createParcelShopDelivery() {
return new ParcelShopDelivery();
}
/**
* Create an instance of {@link PrintOptions }
*
*/
public PrintOptions createPrintOptions() {
return new PrintOptions();
}
/**
* Create an instance of {@link Printer }
*
*/
public Printer createPrinter() {
return new Printer();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrders")
public JAXBElement<StoreOrders> createStoreOrders(StoreOrders value) { | return new JAXBElement<StoreOrders>(_StoreOrders_QNAME, StoreOrders.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrdersResponse")
public JAXBElement<StoreOrdersResponse> createStoreOrdersResponse(StoreOrdersResponse value) {
return new JAXBElement<StoreOrdersResponse>(_StoreOrdersResponse_QNAME, StoreOrdersResponse.class, null, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ObjectFactory.java | 2 |
请完成以下Java代码 | protected void produceHistoricExternalTaskFailedEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskFailedEvent(this);
}
protected void produceHistoricExternalTaskSuccessfulEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskSuccessfulEvent(this);
}
protected void produceHistoricExternalTaskDeletedEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskDeletedEvent(this);
}
public void extendLock(long newLockExpirationTime) {
ensureActive();
long newTime = ClockUtil.getCurrentTime().getTime() + newLockExpirationTime;
this.lockExpirationTime = new Date(newTime);
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class);
} | if (errorDetailsByteArrayId != null) {
referenceIdAndClass.put(errorDetailsByteArrayId, ByteArrayEntity.class);
}
return referenceIdAndClass;
}
public String getLastFailureLogId() {
return lastFailureLogId;
}
public void setLastFailureLogId(String lastFailureLogId) {
this.lastFailureLogId = lastFailureLogId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExternalTaskEntity.java | 1 |
请完成以下Java代码 | public static HttpResult<Boolean> success() {
SuccessResult<Boolean> result = new SuccessResult<Boolean>();
result.setStatus(true);
result.setEntry(true);
result.setCode(200);
return result;
}
public static <T> HttpResult<T> success(T entry, String message) {
SuccessResult<T> result = new SuccessResult<T>();
result.setStatus(true);
result.setEntry(entry);
result.setMessage(message);
result.setCode(200);
return result;
}
/**
* Result set data with paging information
*/
public static class PageSuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return HttpResult.RESPONSE_SUCCESS;
}
}
public static class SuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() { | return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_SUCCESS;
}
}
public static class FailureResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_FAILURE;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_FAILURE;
}
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\HttpResult.java | 1 |
请完成以下Java代码 | public static AggregationParams of(Aggregation aggregation, IntervalType intervalType, ZoneId tzId, long interval) {
return new AggregationParams(aggregation, intervalType, tzId, interval);
}
public long getInterval() {
if (intervalType == null) {
return 0L;
} else {
switch (intervalType) {
case WEEK:
case WEEK_ISO:
return TimeUnit.DAYS.toMillis(7);
case MONTH:
return TimeUnit.DAYS.toMillis(30);
case QUARTER:
return TimeUnit.DAYS.toMillis(90);
default:
return interval; | }
}
}
private static ZoneId getZoneId(String tzIdStr) {
if (StringUtils.isEmpty(tzIdStr)) {
return ZoneId.systemDefault();
}
try {
return ZoneId.of(tzIdStr, TZ_LINKS);
} catch (DateTimeException e) {
log.warn("[{}] Failed to convert the time zone. Fallback to default.", tzIdStr);
return ZoneId.systemDefault();
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\AggregationParams.java | 1 |
请完成以下Java代码 | public class DinousaurBitPacking {
static final short IS_EXTINCT = 0, IS_CARNIVOROUS = 1, IS_HERBIVOROUS = 2, IS_OMNIVOROUS = 3;
int id;
short age;
String feedingHabits;
String habitat;
short flag;
String kingdom;
String phylum;
String clazz;
String order;
String family;
String genus;
String species;
public DinousaurBitPacking(int id, short age, String feedingHabits, String habitat, short flag, String kingdom, String phylum, String clazz, String order, String family, String genus, String species) {
this.id = id;
this.age = age;
this.feedingHabits = feedingHabits;
this.habitat = habitat;
this.flag = flag;
this.kingdom = kingdom;
this.phylum = phylum;
this.clazz = clazz;
this.order = order;
this.family = family;
this.genus = genus; | this.species = species;
}
public static short convertToShort(boolean isExtinct, boolean isCarnivorous, boolean isHerbivorous, boolean isOmnivorous) {
short result = 0;
result |= (short) (isExtinct ? 1 << IS_EXTINCT : 0);
result |= (short) (isCarnivorous ? 1 << IS_CARNIVOROUS : 0);
result |= (short) (isHerbivorous ? 1 << IS_HERBIVOROUS : 0);
result |= (short) (isOmnivorous ? 1 << IS_OMNIVOROUS : 0);
return result;
}
public static boolean convertToBoolean(short value, short flagPosition) {
return (value >> flagPosition & 1) == 1;
}
} | repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\reducememoryfootprint\DinousaurBitPacking.java | 1 |
请完成以下Java代码 | public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (parentId != null) {
referenceIdAndClass.put(parentId, CaseExecutionEntity.class);
}
if (superCaseExecutionId != null) {
referenceIdAndClass.put(superCaseExecutionId, CaseExecutionEntity.class);
}
if (caseDefinitionId != null) {
referenceIdAndClass.put(caseDefinitionId, CmmnCaseDefinition.class);
}
return referenceIdAndClass;
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("caseDefinitionId", caseDefinitionId);
persistentState.put("businessKey", businessKey);
persistentState.put("activityId", activityId);
persistentState.put("parentId", parentId);
persistentState.put("currentState", currentState);
persistentState.put("previousState", previousState);
persistentState.put("superExecutionId", superExecutionId);
return persistentState;
}
public CmmnModelInstance getCmmnModelInstance() {
if(caseDefinitionId != null) {
return Context.getProcessEngineConfiguration()
.getDeploymentCache()
.findCmmnModelInstanceForCaseDefinition(caseDefinitionId);
} else {
return null;
}
}
public CmmnElement getCmmnModelElementInstance() {
CmmnModelInstance cmmnModelInstance = getCmmnModelInstance();
if(cmmnModelInstance != null) {
ModelElementInstance modelElementInstance = cmmnModelInstance.getModelElementById(activityId);
try {
return (CmmnElement) modelElementInstance;
} catch(ClassCastException e) {
ModelElementType elementType = modelElementInstance.getElementType();
throw new ProcessEngineException("Cannot cast "+modelElementInstance+" to CmmnElement. "
+ "Is of type "+elementType.getTypeName() + " Namespace "
+ elementType.getTypeNamespace(), e);
} | } else {
return null;
}
}
public ProcessEngineServices getProcessEngineServices() {
return Context
.getProcessEngineConfiguration()
.getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public String getCaseDefinitionTenantId() {
CaseDefinitionEntity caseDefinition = (CaseDefinitionEntity) getCaseDefinition();
return caseDefinition.getTenantId();
}
public <T extends CoreExecution> void performOperation(CoreAtomicOperation<T> operation) {
Context.getCommandContext()
.performOperation((CmmnAtomicOperation) operation, this);
}
public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) {
Context.getCommandContext()
.performOperation((CmmnAtomicOperation) operation, this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionEntity.java | 1 |
请完成以下Java代码 | public Account getAccountById(@PathVariable("id") int id){
return accountService.findAccountById(id);
}
@RequestMapping(value = "/{id}",method = RequestMethod.PUT)
public String updateAccount(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name,
@RequestParam(value = "money" ,required = true)double money){
Account account=new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
int t=accountService.update(account);
if(t==1){
return account.toString();
}else {
return "fail";
}
}
@RequestMapping(value = "",method = RequestMethod.POST) | public String postAccount( @RequestParam(value = "name")String name,
@RequestParam(value = "money" )double money){
Account account=new Account();
account.setMoney(money);
account.setName(name);
int t= accountService.add(account);
if(t==1){
return account.toString();
}else {
return "fail";
}
}
} | repos\SpringBootLearning-master\springboot-jdbc\src\main\java\com\forezp\web\AccountController.java | 1 |
请完成以下Java代码 | public Date addHoursToDateUsingInstant(Date date, int hours) {
return Date.from(date.toInstant()
.plus(Duration.ofHours(hours)));
}
public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
return localDateTime.plusHours(hours);
}
public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) {
return localDateTime.minusHours(hours);
}
public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
return zonedDateTime.plusHours(hours);
}
public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { | return zonedDateTime.minusHours(hours);
}
public Instant addHoursToInstant(Instant instant, int hours) {
return instant.plus(hours, ChronoUnit.HOURS);
}
public Instant subtractHoursToInstant(Instant instant, int hours) {
return instant.minus(hours, ChronoUnit.HOURS);
}
public Date addHoursWithApacheCommons(Date date, int hours) {
return DateUtils.addHours(date, hours);
}
} | repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\datetime\AddHoursToDate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class VerifyServiceImpl implements VerifyService {
@Value("${code.expiration}")
private Long expiration;
private final RedisUtils redisUtils;
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
EmailVo emailVo;
String content;
String redisKey = key + email;
// 如果不存在有效的验证码,就创建一个新的
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate("email.ftl");
String oldCode = redisUtils.get(redisKey, String.class);
if(oldCode == null){
String code = RandomUtil.randomNumbers (6);
// 存入缓存
if(!redisUtils.set(redisKey, code, expiration)){
throw new BadRequestException("服务异常,请联系网站负责人");
}
content = template.render(Dict.create().set("code",code));
// 存在就再次发送原来的验证码
} else {
content = template.render(Dict.create().set("code",oldCode)); | }
emailVo = new EmailVo(Collections.singletonList(email),"ELADMIN后台管理系统",content);
return emailVo;
}
@Override
public void validated(String key, String code) {
String value = redisUtils.get(key, String.class);
if(!code.equals(value)){
throw new BadRequestException("无效验证码");
} else {
redisUtils.del(key);
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\VerifyServiceImpl.java | 2 |
请完成以下Java代码 | public PermissionCheckBuilder composite() {
return new PermissionCheckBuilder(this);
}
public PermissionCheckBuilder done() {
parent.compositeChecks.add(this.build());
return parent;
}
public CompositePermissionCheck build() {
validate();
CompositePermissionCheck permissionCheck = new CompositePermissionCheck(disjunctive);
permissionCheck.setAtomicChecks(atomicChecks);
permissionCheck.setCompositeChecks(compositeChecks);
return permissionCheck; | }
public List<PermissionCheck> getAtomicChecks() {
return atomicChecks;
}
protected void validate() {
if (!atomicChecks.isEmpty() && !compositeChecks.isEmpty()) {
throw new ProcessEngineException("Mixed authorization checks of atomic and composite permissions are not supported");
}
}
public boolean isPermissionDisabled(Permission permission) {
AuthorizationManager authorizationManager = Context.getCommandContext().getAuthorizationManager();
return authorizationManager.isPermissionDisabled(permission);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheckBuilder.java | 1 |
请完成以下Java代码 | public void addFormType(AbstractFormFieldType formType) {
formTypes.put(formType.getName(), formType);
}
public AbstractFormFieldType parseFormPropertyType(Element formFieldElement, BpmnParse bpmnParse) {
AbstractFormFieldType formType = null;
String typeText = formFieldElement.attribute("type");
String datePatternText = formFieldElement.attribute("datePattern");
if (typeText == null && DefaultFormHandler.FORM_FIELD_ELEMENT.equals(formFieldElement.getTagName())) {
bpmnParse.addError("form field must have a 'type' attribute", formFieldElement);
}
if ("date".equals(typeText) && datePatternText!=null) {
formType = new DateFormType(datePatternText);
} else if ("enum".equals(typeText)) {
// ACT-1023: Using linked hashmap to preserve the order in which the entries are defined
Map<String, String> values = new LinkedHashMap<String, String>();
for (Element valueElement: formFieldElement.elementsNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS,"value")) {
String valueId = valueElement.attribute("id");
String valueName = valueElement.attribute("name");
values.put(valueId, valueName);
} | formType = new EnumFormType(values);
} else if (typeText!=null) {
formType = formTypes.get(typeText);
if (formType==null) {
bpmnParse.addError("unknown type '"+typeText+"'", formFieldElement);
}
}
return formType;
}
public AbstractFormFieldType getFormType(String name) {
return formTypes.get(name);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\FormTypes.java | 1 |
请完成以下Java代码 | public final class VTreeCellRenderer extends DefaultTreeCellRenderer
{
/**
*
*/
private static final long serialVersionUID = -7611138520740658446L;
/**
* Constructor
*/
public VTreeCellRenderer()
{
super();
setBackgroundNonSelectionColor(null); // metas
} // VTreeCellRenderer
/**
* Get Tree Cell Renderer Component. Sets Icon, Name, Description for leaves
*
* @param tree tree
* @param value value
* @param Selected selected
* @param expanded expanded
* @param leaf leaf
* @param row row
* @param HasFocus focus
* @return renderer
*/
@Override
public Component getTreeCellRendererComponent(
final JTree tree,
final Object value,
final boolean Selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean HasFocus)
{
final VTreeCellRenderer c = (VTreeCellRenderer)super.getTreeCellRendererComponent
(tree, value, Selected, expanded, leaf, row, HasFocus);
c.setFont(c.getFont().deriveFont(Font.PLAIN)); // metas
setBackground(null); // metas: reset background
if (!leaf)
{
// task 09079: also setting custom icons for summary nodes
// note: we didn't move the logic to select the icon into MTreeNode because currently MTreeNode is aiming a leafs that have a partcular *action* like window, form process. MTreeNode is not
// about mere summary nodes.
final String iconName = expanded ? "mOpen": "mClosed";
c.setIcon(Images.getImageIcon2(iconName));
return c;
}
// We have a leaf
final MTreeNode nd = (MTreeNode)value;
// metas: add special handling for the product category tree
if (I_M_Product_Category.Table_Name.equals(nd.getImageIndiactor())) | {
// if (Selected) {
// c.setLeafIcon(c.getOpenIcon());
// } else {
c.setLeafIcon(c.getClosedIcon());
// }
}
else
{
final String iconName = nd.getIconName();
final Icon icon = Images.getImageIcon2(iconName);
if (icon != null)
{
c.setIcon(icon);
}
}
c.setText(nd.getName());
c.setToolTipText(nd.getDescription());
if (!Selected)
{
c.setForeground(nd.getColor());
}
// metas: begin:
if (nd.isPlaceholder())
{
c.setFont(c.getFont().deriveFont(Font.ITALIC));
}
if (nd.getBackgroundColor() != null)
{
c.setBackground(nd.getBackgroundColor());
}
else
{
c.setBackground(null);
}
// metas: end
return c;
} // getTreeCellRendererComponent
} // VTreeCellRenderer | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreeCellRenderer.java | 1 |
请完成以下Java代码 | public static class FilterSupplier extends SimpleFilterSupplier {
public FilterSupplier() {
super(RetryFilterFunctions.class);
}
}
public static class RetryConfig {
private int retries = 3;
private Set<HttpStatus.Series> series = new HashSet<>(List.of(HttpStatus.Series.SERVER_ERROR));
private Set<Class<? extends Throwable>> exceptions = new HashSet<>(
List.of(IOException.class, TimeoutException.class, RetryException.class));
private Set<HttpMethod> methods = new HashSet<>(List.of(HttpMethod.GET));
private boolean cacheBody = false;
public int getRetries() {
return retries;
}
public RetryConfig setRetries(int retries) {
this.retries = retries;
return this;
}
public Set<HttpStatus.Series> getSeries() {
return series;
}
public RetryConfig setSeries(Set<HttpStatus.Series> series) {
this.series = series;
return this;
}
public RetryConfig addSeries(HttpStatus.Series... series) {
this.series.addAll(Arrays.asList(series));
return this;
}
public Set<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Set<Class<? extends Throwable>> exceptions) {
this.exceptions = exceptions;
return this;
}
public RetryConfig addExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions.addAll(Arrays.asList(exceptions));
return this;
}
public Set<HttpMethod> getMethods() { | return methods;
}
public RetryConfig setMethods(Set<HttpMethod> methods) {
this.methods = methods;
return this;
}
public RetryConfig addMethods(HttpMethod... methods) {
this.methods.addAll(Arrays.asList(methods));
return this;
}
public boolean isCacheBody() {
return cacheBody;
}
public RetryConfig setCacheBody(boolean cacheBody) {
this.cacheBody = cacheBody;
return this;
}
}
public static class RetryException extends NestedRuntimeException {
private final ServerRequest request;
private final ServerResponse response;
RetryException(ServerRequest request, ServerResponse response) {
super(null);
this.request = request;
this.response = response;
}
public ServerRequest getRequest() {
return request;
}
public ServerResponse getResponse() {
return response;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RetryFilterFunctions.java | 1 |
请完成以下Java代码 | final class HUAttributeChanges
{
@Getter
private final HuId huId;
private final HashMap<AttributeId, HUAttributeChange> attributes = new HashMap<>();
@Getter
private Instant lastChangeDate;
public HUAttributeChanges(@NonNull final HuId huId)
{
this.huId = huId;
}
public void collect(@NonNull HUAttributeChange change)
{
Check.assumeEquals(huId, change.getHuId(), "Invalid HuId for {}. Expected: {}", change, huId);
attributes.compute(change.getAttributeId(), (attributeId, previousChange) -> mergeChange(previousChange, change));
lastChangeDate = max(lastChangeDate, change.getDate());
}
private static Instant max(@Nullable final Instant instant1, @Nullable final Instant instant2)
{
if (instant1 == null)
{
return instant2;
}
else if (instant2 == null)
{
return null;
}
else if (instant1.isAfter(instant2))
{
return instant1;
}
else
{
return instant2;
} | }
private static HUAttributeChange mergeChange(
@Nullable final HUAttributeChange previousChange,
@NonNull final HUAttributeChange currentChange)
{
return previousChange != null
? previousChange.mergeWithNextChange(currentChange)
: currentChange;
}
public boolean isEmpty()
{
return attributes.isEmpty();
}
public AttributesKey getOldAttributesKey()
{
return toAttributesKey(HUAttributeChange::getOldAttributeKeyPartOrNull);
}
public AttributesKey getNewAttributesKey()
{
return toAttributesKey(HUAttributeChange::getNewAttributeKeyPartOrNull);
}
private AttributesKey toAttributesKey(final Function<HUAttributeChange, AttributesKeyPart> keyPartExtractor)
{
if (attributes.isEmpty())
{
return AttributesKey.NONE;
}
final ImmutableList<AttributesKeyPart> parts = attributes.values()
.stream()
.map(keyPartExtractor)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return AttributesKey.ofParts(parts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChanges.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String uploadMore() {
return "uploadMore";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@PostMapping("/uploadMore")
public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
RedirectAttributes redirectAttributes) {
if (files.length==0) { | redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
for(MultipartFile file:files){
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
redirectAttributes.addFlashAttribute("message", "You successfully uploaded all");
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-6 课:使用 Spring Boot 和 Thymeleaf 演示上传文件\spring-boot-file-upload\src\main\java\com\neo\controller\UploadController.java | 2 |
请完成以下Java代码 | protected String getEngineVersion() {
return AppEngine.VERSION;
}
@Override
protected String getSchemaVersionPropertyName() {
return "app.schema.version";
}
@Override
protected String getDbSchemaLockName() {
return APP_DB_SCHEMA_LOCK_NAME;
}
@Override
protected String getEngineTableName() {
return "ACT_APP_DEPLOYMENT";
}
@Override
protected String getChangeLogTableName() { | return "ACT_APP_DATABASECHANGELOG";
}
@Override
protected String getDbVersionForChangelogVersion(String changeLogVersion) {
if (StringUtils.isNotEmpty(changeLogVersion) && changeLogVersionMap.containsKey(changeLogVersion)) {
return changeLogVersionMap.get(changeLogVersion);
}
return "6.3.0.1";
}
@Override
protected String getResourcesRootDirectory() {
return "org/flowable/app/db/";
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\db\AppDbSchemaManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean isUnboundidEnabled(String mode) {
return "unboundid".equals(mode) || unboundIdPresent;
}
private String getPort(Element element) {
String port = element.getAttribute(ATT_PORT);
return (StringUtils.hasText(port) ? port : getDefaultPort());
}
private String getDefaultPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return String.valueOf(serverSocket.getLocalPort());
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
private static class EmbeddedLdapServerConfigBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
} | @SuppressWarnings("unused")
private DefaultSpringSecurityContextSource createEmbeddedContextSource(String suffix) {
int port = getPort();
String providerUrl = "ldap://127.0.0.1:" + port + "/" + suffix;
return new DefaultSpringSecurityContextSource(providerUrl);
}
private int getPort() {
if (unboundIdPresent) {
UnboundIdContainer unboundIdContainer = this.applicationContext.getBean(UnboundIdContainer.class);
return unboundIdContainer.getPort();
}
throw new IllegalStateException("Embedded LDAP server is not provided");
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapServerBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public class HikariCPDemo {
public static List<Employee> fetchData() {
final String SQL_QUERY = "select * from emp";
List<Employee> employees = null;
try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<Employee>();
Employee employee;
while (rs.next()) {
employee = new Employee();
employee.setEmpNo(rs.getInt("empno"));
employee.setEname(rs.getString("ename"));
employee.setJob(rs.getString("job"));
employee.setMgr(rs.getInt("mgr"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSal(rs.getInt("sal")); | employee.setComm(rs.getInt("comm"));
employee.setDeptno(rs.getInt("deptno"));
employees.add(employee);
}
} catch (SQLException e) {
e.printStackTrace();
}
return employees;
}
public static void main(String[] args) {
fetchData();
}
} | repos\tutorials-master\libraries-data-db\src\main\java\com\baeldung\libraries\hikaricp\HikariCPDemo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DaysOfWeekExploder implements IDateSequenceExploder
{
public static final DaysOfWeekExploder of(final Collection<DayOfWeek> weekDays)
{
final ImmutableSet<DayOfWeek> weekDaysSet = ImmutableSet.copyOf(weekDays);
if (weekDaysSet.equals(ALL_DAYS_OF_WEEK_LIST))
{
return ALL_DAYS_OF_WEEK;
}
return new DaysOfWeekExploder(weekDaysSet);
}
public static final DaysOfWeekExploder of(final DayOfWeek... weekDays)
{
return of(ImmutableSet.copyOf(weekDays));
}
private static final ImmutableSet<DayOfWeek> ALL_DAYS_OF_WEEK_LIST = ImmutableSet.copyOf(DayOfWeek.values());
public static final DaysOfWeekExploder ALL_DAYS_OF_WEEK = new DaysOfWeekExploder(ALL_DAYS_OF_WEEK_LIST);
private final ImmutableSet<DayOfWeek> weekDays;
private final DayOfWeek firstDayOfTheWeek;
private DaysOfWeekExploder(final ImmutableSet<DayOfWeek> weekDays)
{
Check.assumeNotEmpty(weekDays, "weekDays not empty");
this.weekDays = weekDays;
this.firstDayOfTheWeek = DayOfWeek.MONDAY; | }
/**
* @return all dates which are in same week as <code>date</code> and are equal or after it
*/
@Override
public Set<LocalDateTime> explodeForward(final LocalDateTime date)
{
final DayOfWeek currentDayOfWeek = date.getDayOfWeek();
return weekDays.stream()
.filter(dayOfWeek -> dayOfWeek.getValue() >= currentDayOfWeek.getValue())
.map(dayOfWeek -> date.with(TemporalAdjusters.nextOrSame(dayOfWeek)))
.collect(ImmutableSet.toImmutableSet());
}
/**
* @return all dates which are in one week range from <code>date</code>
*/
@Override
public Set<LocalDateTime> explodeBackward(final LocalDateTime date)
{
return weekDays.stream()
.map(dayOfWeek -> date.with(TemporalAdjusters.previousOrSame(dayOfWeek)))
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DaysOfWeekExploder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public Object getCachedValue() {
return cachedValue;
}
@Override
public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue;
}
// misc methods ///////////////////////////////////////////////////////////////
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(type != null ? type.getTypeName() : "null");
if (executionId != null) {
sb.append(", executionId=").append(executionId);
} | if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (subScopeId != null) {
sb.append(", subScopeId=").append(subScopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInstanceEntityImpl.java | 2 |
请完成以下Java代码 | public <T> T[] toArray(T[] a) {
return null;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean addAll(Collection<? extends E> c) {
return false;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
}
@Override
public E get(int index) {
return null;
}
@Override
public E set(int index, E element) {
return null;
}
@Override | public void add(int index, E element) {
}
@Override
public E remove(int index) {
return null;
}
@Override
public int indexOf(Object o) {
return 0;
}
@Override
public int lastIndexOf(Object o) {
return 0;
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
return null;
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return null;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\MyList.java | 1 |
请完成以下Java代码 | private Map<String, Object> getPropertiesMap()
{
if (_properties == null)
{
synchronized (this)
{
if (_properties == null)
{
_properties = new ConcurrentHashMap<>();
}
}
}
return _properties;
}
private Map<String, Object> getPropertiesMapOrNull()
{
synchronized (this)
{
return _properties;
}
}
@Nullable
@Override
public final <T> T setProperty(final String name, final Object value)
{
Check.assumeNotEmpty(name, "name is not empty");
// Handle null value case
if (value == null)
{
final Map<String, Object> properties = getPropertiesMapOrNull();
if (properties == null)
{
return null;
}
@SuppressWarnings("unchecked") final T valueOld = (T)properties.remove(name);
return valueOld;
}
else
{
@SuppressWarnings("unchecked") final T valueOld = (T)getPropertiesMap().put(name, value);
return valueOld;
} | }
@Override
public final <T> T getProperty(final String name)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().get(name);
return value;
}
@Override
public <T> T getProperty(final String name, final Supplier<T> valueInitializer)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.get());
return value;
}
@Override
public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.apply(this));
return value;
}
@Override
public <T> T setAndGetProperty(@NonNull final String name, @NonNull final Function<T, T> valueRemappingFunction)
{
final BiFunction<? super String, ? super Object, ?> remappingFunction = (propertyName, oldValue) -> {
@SuppressWarnings("unchecked") final T oldValueCasted = (T)oldValue;
return valueRemappingFunction.apply(oldValueCasted);
};
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().compute(name, remappingFunction);
return value;
}
protected final void setDebugConnectionBackendId(final String debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrx.java | 1 |
请完成以下Java代码 | private boolean heartbeatJudge(final int threshold) {
if (machines.size() == 0) {
return false;
}
if (threshold > 0) {
long healthyCount = machines.stream()
.filter(MachineInfo::isHealthy)
.count();
if (healthyCount == 0) {
// No healthy machines.
return machines.stream()
.max(Comparator.comparingLong(MachineInfo::getLastHeartbeat))
.map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold)
.orElse(false);
}
}
return true;
} | /**
* Check whether current application has no healthy machines and should not be displayed.
*
* @return true if the application should be displayed in the sidebar, otherwise false
*/
public boolean isShown() {
return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis());
}
/**
* Check whether current application has no healthy machines and should be removed.
*
* @return true if the application is dead and should be removed, otherwise false
*/
public boolean isDead() {
return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis());
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppInfo.java | 1 |
请完成以下Java代码 | public final InvoiceCandidateEnqueuer setFailOnChanges(final boolean failOnChanges)
{
this._failOnChanges = failOnChanges;
return this;
}
private boolean isFailOnChanges()
{
// Use the explicit setting if available
if (_failOnChanges != null)
{
return _failOnChanges;
}
// Use the sysconfig setting
return sysConfigBL.getBooleanValue(SYSCONFIG_FailOnChanges, DEFAULT_FailOnChanges);
}
private IInvoiceCandidatesChangesChecker newInvoiceCandidatesChangesChecker()
{
if (isFailOnChanges())
{
return new InvoiceCandidatesChangesChecker()
.setTotalNetAmtToInvoiceChecksum(_totalNetAmtToInvoiceChecksum);
}
else
{
return IInvoiceCandidatesChangesChecker.NULL;
}
} | @Override
public IInvoiceCandidateEnqueuer setTotalNetAmtToInvoiceChecksum(final BigDecimal totalNetAmtToInvoiceChecksum)
{
this._totalNetAmtToInvoiceChecksum = totalNetAmtToInvoiceChecksum;
return this;
}
@Override
public IInvoiceCandidateEnqueuer setAsyncBatchId(final AsyncBatchId asyncBatchId)
{
_asyncBatchId = asyncBatchId;
return this;
}
@Override
public IInvoiceCandidateEnqueuer setPriority(final IWorkpackagePrioStrategy priority)
{
_priority = priority;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateEnqueuer.java | 1 |
请完成以下Java代码 | public class ProcessVariablesMapping {
private MappingType mappingType;
private Map<String, Mapping> inputs = new HashMap<>();
private Map<String, Mapping> outputs = new HashMap<>();
private boolean ephemeral;
public Map<String, Mapping> getInputs() {
return inputs;
}
public void setInputs(Map<String, Mapping> inputs) {
this.inputs = inputs;
}
public Mapping getInputMapping(String inputName) {
return inputs.get(inputName);
}
public Map<String, Mapping> getOutputs() {
return outputs;
}
public void setOutputs(Map<String, Mapping> outputs) {
this.outputs = outputs;
}
public MappingType getMappingType() {
return mappingType;
} | public void setMappingType(MappingType mappingType) {
this.mappingType = mappingType;
}
public enum MappingType {
MAP_ALL,
MAP_ALL_INPUTS,
MAP_ALL_OUTPUTS,
}
public boolean isEphemeral() {
return this.ephemeral;
}
public void setEphemeral(boolean ephemeral) {
this.ephemeral = ephemeral;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\ProcessVariablesMapping.java | 1 |
请完成以下Java代码 | public List<String> getUserAccountsByDepCode(String orgCode) {
return null;
}
@Override
public boolean dictTableWhiteListCheckBySql(String selectSql) {
return false;
}
@Override
public boolean dictTableWhiteListCheckByDict(String tableOrDictCode, String... fields) {
return false;
}
@Override
public void announcementAutoRelease(String dataId, String currentUserName) {
}
@Override
public SysDepartModel queryCompByOrgCode(String orgCode) {
return null;
}
@Override
public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) {
return null; | }
@Override
public Object runAiragFlow(AiragFlowDTO airagFlowDTO) {
return null;
}
@Override
public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) {
}
@Override
public String getDepartPathNameByOrgCode(String orgCode, String depId) {
return "";
}
@Override
public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) {
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String title;
private int sold;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
} | public void setTitle(String title) {
this.title = title;
}
public int getSold() {
return sold;
}
public void setSold(int sold) {
this.sold = sold;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", title=" + title + ", sold=" + sold + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootTopNRowsPerGroup\src\main\java\com\bookstore\entity\Author.java | 2 |
请完成以下Java代码 | public void setM_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID)
{
if (M_Shipper_RoutingCode_ID < 1)
set_Value (COLUMNNAME_M_Shipper_RoutingCode_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID);
}
@Override
public int getM_Shipper_RoutingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_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 setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setPrevious_ID (final int Previous_ID)
{
if (Previous_ID < 1)
set_Value (COLUMNNAME_Previous_ID, null);
else
set_Value (COLUMNNAME_Previous_ID, Previous_ID);
}
@Override
public int getPrevious_ID()
{
return get_ValueAsInt(COLUMNNAME_Previous_ID);
} | @Override
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVisitorsAddress (final boolean VisitorsAddress)
{
set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress);
}
@Override
public boolean isVisitorsAddress()
{
return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PayPalConfigRepository implements PayPalConfigProvider
{
private final CCache<Integer, PayPalConfig> cache = CCache.<Integer, PayPalConfig> builder()
.tableName(I_PayPal_Config.Table_Name)
.build();
@Override
public PayPalConfig getConfig()
{
return cache.getOrLoad(0, this::retrievePayPalConfig);
}
private PayPalConfig retrievePayPalConfig()
{
final I_PayPal_Config record = Services.get(IQueryBL.class).createQueryBuilderOutOfTrx(I_PayPal_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_PayPal_Config.class);
if (record == null)
{
throw new AdempiereException("@NotFound@ @PayPal_Config_ID@");
} | return toPayPalConfig(record);
}
private static PayPalConfig toPayPalConfig(@NonNull final I_PayPal_Config record)
{
return PayPalConfig.builder()
.clientId(record.getPayPal_ClientId())
.clientSecret(record.getPayPal_ClientSecret())
.sandbox(record.isPayPal_Sandbox())
.baseUrl(record.getPayPal_BaseUrl())
.webUrl(record.getPayPal_WebUrl())
//
.orderApproveMailTemplateId(MailTemplateId.ofRepoId(record.getPayPal_PayerApprovalRequest_MailTemplate_ID()))
.orderApproveCallbackUrl(record.getPayPal_PaymentApprovedCallbackUrl())
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\config\PayPalConfigRepository.java | 2 |
请完成以下Java代码 | private void doHeadersAfter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HeaderWriterResponse headerWriterResponse = new HeaderWriterResponse(request, response);
HeaderWriterRequest headerWriterRequest = new HeaderWriterRequest(request, headerWriterResponse);
try {
filterChain.doFilter(headerWriterRequest, headerWriterResponse);
}
finally {
headerWriterResponse.writeHeaders();
}
}
void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
for (HeaderWriter writer : this.headerWriters) {
writer.writeHeaders(request, response);
}
}
/**
* Allow writing headers at the beginning of the request.
* @param shouldWriteHeadersEagerly boolean to allow writing headers at the beginning
* of the request.
* @since 5.2
*/
public void setShouldWriteHeadersEagerly(boolean shouldWriteHeadersEagerly) {
this.shouldWriteHeadersEagerly = shouldWriteHeadersEagerly;
}
class HeaderWriterResponse extends OnCommittedResponseWrapper {
private final HttpServletRequest request;
HeaderWriterResponse(HttpServletRequest request, HttpServletResponse response) {
super(response);
this.request = request;
}
@Override
protected void onResponseCommitted() {
writeHeaders();
this.disableOnResponseCommitted();
}
protected void writeHeaders() {
if (isDisableOnResponseCommitted()) {
return;
}
HeaderWriterFilter.this.writeHeaders(this.request, getHttpResponse());
}
private HttpServletResponse getHttpResponse() {
return (HttpServletResponse) getResponse();
}
}
static class HeaderWriterRequest extends HttpServletRequestWrapper {
private final HeaderWriterResponse response;
HeaderWriterRequest(HttpServletRequest request, HeaderWriterResponse response) {
super(request);
this.response = response;
} | @Override
public RequestDispatcher getRequestDispatcher(String path) {
return new HeaderWriterRequestDispatcher(super.getRequestDispatcher(path), this.response);
}
}
static class HeaderWriterRequestDispatcher implements RequestDispatcher {
private final RequestDispatcher delegate;
private final HeaderWriterResponse response;
HeaderWriterRequestDispatcher(RequestDispatcher delegate, HeaderWriterResponse response) {
this.delegate = delegate;
this.response = response;
}
@Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.delegate.forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.response.onResponseCommitted();
this.delegate.include(request, response);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\HeaderWriterFilter.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_Asset_Use[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Asset.
@param A_Asset_ID
Asset used internally or by customers
*/
public void setA_Asset_ID (int A_Asset_ID)
{
if (A_Asset_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID));
}
/** Get Asset.
@return Asset used internally or by customers
*/
public int getA_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set A_Asset_Use_ID.
@param A_Asset_Use_ID A_Asset_Use_ID */
public void setA_Asset_Use_ID (int A_Asset_Use_ID)
{
if (A_Asset_Use_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, Integer.valueOf(A_Asset_Use_ID));
}
/** Get A_Asset_Use_ID.
@return A_Asset_Use_ID */
public int getA_Asset_Use_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Use_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{ | return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Use_ID()));
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set UseDate.
@param UseDate UseDate */
public void setUseDate (Timestamp UseDate)
{
set_Value (COLUMNNAME_UseDate, UseDate);
}
/** Get UseDate.
@return UseDate */
public Timestamp getUseDate ()
{
return (Timestamp)get_Value(COLUMNNAME_UseDate);
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
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_A_Asset_Use.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDelisId() {
return delisId;
}
/**
* Sets the value of the delisId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDelisId(String value) {
this.delisId = value;
}
/**
* Gets the value of the password property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPassword() {
return password;
}
/**
* Sets the value of the password property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPassword(String value) { | this.password = value;
}
/**
* Gets the value of the messageLanguage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageLanguage() {
return messageLanguage;
}
/**
* Sets the value of the messageLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLanguage(String value) {
this.messageLanguage = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\GetAuth.java | 2 |
请完成以下Java代码 | class M_Cost
{
private final ICostElementRepository costElementRepository;
private final IProductCostingBL productCostingBL;
public M_Cost(
@NonNull final ICostElementRepository costElementRepository,
@NonNull final IProductCostingBL productCostingBL)
{
this.costElementRepository = costElementRepository;
this.productCostingBL = productCostingBL;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(final I_M_Cost costRecord)
{
final CostElementId costElementId = CostElementId.ofRepoId(costRecord.getM_CostElement_ID());
final CostElement costElement = costElementRepository.getByIdIfExists(costElementId).orElse(null);
final boolean userEntry = InterfaceWrapperHelper.isUIAction(costRecord);
// Check if data entry makes sense
if (userEntry)
{
final ProductId productId = ProductId.ofRepoId(costRecord.getM_Product_ID());
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(costRecord.getC_AcctSchema_ID());
final CostingLevel costingLevel = productCostingBL.getCostingLevel(productId, acctSchemaId);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(costRecord.getM_AttributeSetInstance_ID());
if (CostingLevel.Client.equals(costingLevel))
{
final OrgId orgId = OrgId.ofRepoIdOrAny(costRecord.getAD_Org_ID());
if (orgId.isRegular() || asiId.isRegular())
{
throw new AdempiereException("@CostingLevelClient@");
}
}
else if (CostingLevel.BatchLot.equals(costingLevel))
{
if (asiId.isNone() && costElement != null && costElement.isMaterial())
{ | throw new FillMandatoryException(I_M_Cost.COLUMNNAME_M_AttributeSetInstance_ID);
}
costRecord.setAD_Org_ID(OrgId.ANY.getRepoId());
}
}
// Cannot enter calculated
if (userEntry && costElement != null && !costElement.isAllowUserChangingCurrentCosts())
{
throw new AdempiereException("@IsCalculated@");
}
// Percentage
if (costElement != null
&& (!costElement.isAllowUserChangingCurrentCosts() || costElement.isMaterial())
&& costRecord.getPercent() != 0)
{
costRecord.setPercent(0);
}
if (costRecord.getPercent() != 0)
{
costRecord.setCurrentCostPrice(BigDecimal.ZERO);
costRecord.setFutureCostPrice(BigDecimal.ZERO);
costRecord.setCumulatedAmt(BigDecimal.ZERO);
costRecord.setCumulatedQty(BigDecimal.ZERO);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\interceptors\M_Cost.java | 1 |
请完成以下Java代码 | private static byte[] aes(byte[] encrypted, byte[] aesKey, int mode) {
Assert.isTrue(aesKey.length == 32, "IllegalAesKey, aesKey's length must be 32");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(mode, keySpec, iv);
return cipher.doFinal(encrypted);
}
/**
* 提供基于PKCS7算法的加解密接口.
*/
private static class Pkcs7Encoder {
private static final int BLOCK_SIZE = 32;
private static byte[] encode(byte[] src) {
int count = src.length;
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
// 获得补位所用的字符
byte pad = (byte) (amountToPad & 0xFF);
byte[] pads = new byte[amountToPad];
for (int index = 0; index < amountToPad; index++) { | pads[index] = pad;
}
int length = count + amountToPad;
byte[] dest = new byte[length];
System.arraycopy(src, 0, dest, 0, count);
System.arraycopy(pads, 0, dest, count, amountToPad);
return dest;
}
private static byte[] decode(byte[] decrypted) {
int pad = decrypted[decrypted.length - 1];
if (pad < 1 || pad > BLOCK_SIZE) {
pad = 0;
}
if (pad > 0) {
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
return decrypted;
}
}
} | repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtCrypto.java | 1 |
请完成以下Java代码 | public Criteria andCategoryIdBetween(Long value1, Long value2) {
addCriterion("category_id between", value1, value2, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdNotBetween(Long value1, Long value2) {
addCriterion("category_id not between", value1, value2, "categoryId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
} | public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsResourceExample.java | 1 |
请完成以下Java代码 | public abstract class FileUtils {
/**
* Utility to remove duplicate files from an "output" directory if they already exist
* in an "origin". Recursively scans the origin directory looking for files (not
* directories) that exist in both places and deleting the copy.
* @param outputDirectory the output directory
* @param originDirectory the origin directory
*/
public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) {
if (originDirectory.isDirectory()) {
String[] files = originDirectory.list();
Assert.state(files != null, "'files' must not be null");
for (String name : files) {
File targetFile = new File(outputDirectory, name);
if (targetFile.exists() && targetFile.canWrite()) {
if (!targetFile.isDirectory()) {
targetFile.delete();
}
else {
FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name));
}
}
}
}
}
/**
* Returns {@code true} if the given jar file has been signed.
* @param file the file to check
* @return if the file has been signed
* @throws IOException on IO error
*/
public static boolean isSignedJarFile(@Nullable File file) throws IOException { | if (file == null) {
return false;
}
try (JarFile jarFile = new JarFile(file)) {
if (hasDigestEntry(jarFile.getManifest())) {
return true;
}
}
return false;
}
private static boolean hasDigestEntry(@Nullable Manifest manifest) {
return (manifest != null) && manifest.getEntries().values().stream().anyMatch(FileUtils::hasDigestName);
}
private static boolean hasDigestName(Attributes attributes) {
return attributes.keySet().stream().anyMatch(FileUtils::isDigestName);
}
private static boolean isDigestName(Object name) {
return String.valueOf(name).toUpperCase(Locale.ROOT).endsWith("-DIGEST");
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\FileUtils.java | 1 |
请完成以下Java代码 | private Node delete(Node node, int key) {
if (node == null) {
return node;
} else if (node.key > key) {
node.left = delete(node.left, key);
} else if (node.key < key) {
node.right = delete(node.right, key);
} else {
if (node.left == null || node.right == null) {
node = (node.left == null) ? node.right : node.left;
} else {
Node mostLeftChild = mostLeftChild(node.right);
node.key = mostLeftChild.key;
node.right = delete(node.right, node.key);
}
}
if (node != null) {
node = rebalance(node);
}
return node;
}
private Node mostLeftChild(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null) {
current = current.left;
}
return current;
}
private Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) > height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
} else if (balance < -1) {
if (height(z.left.left) > height(z.left.right)) {
z = rotateRight(z);
} else {
z.left = rotateLeft(z.left);
z = rotateRight(z);
}
}
return z;
} | private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x);
return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\avltree\AVLTree.java | 1 |
请完成以下Java代码 | private void refreshIncludedTabs(GridTab mTab)
{
for (GridTab detailTab : mTab.getIncludedTabs())
{
detailTab.dataRefreshAll();
}
}
public static class BPartnerContact
{
private final int C_BPartner_ID;
private final int AD_User_ID;
public BPartnerContact(int cBPartnerID, int aDUserID)
{
super();
C_BPartner_ID = cBPartnerID;
AD_User_ID = aDUserID;
}
public int getC_BPartner_ID()
{ | return C_BPartner_ID;
}
public int getAD_User_ID()
{
return AD_User_ID;
}
@Override
public String toString()
{
return "BPartnerContact [C_BPartner_ID=" + C_BPartner_ID
+ ", AD_User_ID=" + AD_User_ID + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CalloutR_Group.java | 1 |
请完成以下Java代码 | public GLN asGLN()
{
Check.assume(Type.GLN.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN, this);
final Matcher glnMatcher = Type.GLN.pattern.matcher(rawValue);
if (glnMatcher.find())
{
return GLN.ofString(glnMatcher.group(1));
}
else
{
throw new AdempiereException("External identifier of GLN parsing failed. External Identifier:" + rawValue);
}
}
@NonNull
public GlnWithLabel asGlnWithLabel()
{
Check.assume(Type.GLN_WITH_LABEL.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN_WITH_LABEL, this);
final Matcher glnWithLabelMatcher = Type.GLN_WITH_LABEL.pattern.matcher(rawValue);
if (glnWithLabelMatcher.find())
{
return GlnWithLabel.ofString(glnWithLabelMatcher.group(1));
}
else
{
throw new AdempiereException("External identifier of GLN parsing failed. External Identifier:" + rawValue);
}
}
@NonNull
public String asValue()
{
Check.assume(Type.VALUE.equals(type),
"The type of this instance needs to be {}; this={}", Type.VALUE, this);
final Matcher valueMatcher = Type.VALUE.pattern.matcher(rawValue);
if (!valueMatcher.matches())
{
throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue);
}
return valueMatcher.group(1);
} | @NonNull
public String asGTIN()
{
Check.assume(Type.GTIN.equals(type),
"The type of this instance needs to be {}; this={}", Type.GTIN, this);
final Matcher gtinMatcher = Type.GTIN.pattern.matcher(rawValue);
if (!gtinMatcher.matches())
{
throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue);
}
return gtinMatcher.group(1);
}
@AllArgsConstructor
@Getter
public enum Type
{
METASFRESH_ID(Pattern.compile("^\\d+$")),
EXTERNAL_REFERENCE(Pattern.compile("^ext-([a-zA-Z0-9_]+)-(.+)$")),
GLN(Pattern.compile("^gln-(.+)")),
/**
* GLN with an optional additional label that can be used in case metasfresh has multiple BPartners which share the same GLN.
*/
GLN_WITH_LABEL(Pattern.compile("^glnl-([^_]+_.+)")),
GTIN(Pattern.compile("^gtin-(.+)")),
VALUE(Pattern.compile("^val-(.+)"));
private final Pattern pattern;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalIdentifier.java | 1 |
请完成以下Java代码 | public Pattern getTopicPattern() {
return topicPattern;
}
public void setTopicPattern(Pattern topicPattern) {
this.topicPattern = topicPattern;
}
@Override
public String getClientIdPrefix() {
return clientIdPrefix;
}
public void setClientIdPrefix(String clientIdPrefix) {
this.clientIdPrefix = clientIdPrefix;
}
@Override
public Integer getConcurrency() {
return concurrency;
}
public void setConcurrency(Integer concurrency) {
this.concurrency = concurrency;
}
@Override
public Boolean getAutoStartup() {
return null;
}
@Override
public Properties getConsumerProperties() {
return consumerProperties;
}
public void setConsumerProperties(Properties consumerProperties) {
this.consumerProperties = consumerProperties;
}
@Override
public void setupListenerContainer(MessageListenerContainer listenerContainer, MessageConverter messageConverter) {
GenericMessageListener<ConsumerRecord<K, V>> messageListener = getMessageListener();
Assert.state(messageListener != null, () -> "Endpoint [" + this + "] must provide a non null message listener");
listenerContainer.setupMessageListener(messageListener);
} | @Override
public boolean isSplitIterables() {
return splitIterables;
}
public void setSplitIterables(boolean splitIterables) {
this.splitIterables = splitIterables;
}
@Override
public String getMainListenerId() {
return mainListenerId;
}
public void setMainListenerId(String mainListenerId) {
this.mainListenerId = mainListenerId;
}
@Override
public void afterPropertiesSet() throws Exception {
boolean topicsEmpty = getTopics().isEmpty();
boolean topicPartitionsEmpty = ObjectUtils.isEmpty(getTopicPartitionsToAssign());
if (!topicsEmpty && !topicPartitionsEmpty) {
throw new IllegalStateException("Topics or topicPartitions must be provided but not both for " + this);
}
if (this.topicPattern != null && (!topicsEmpty || !topicPartitionsEmpty)) {
throw new IllegalStateException("Only one of topics, topicPartitions or topicPattern must are allowed for "
+ this);
}
if (this.topicPattern == null && topicsEmpty && topicPartitionsEmpty) {
throw new IllegalStateException("At least one of topics, topicPartitions or topicPattern must be provided "
+ "for " + this);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + this.id
+ "] topics=" + this.topics
+ "' | topicPattern='" + this.topicPattern + "'"
+ "' | topicPartitions='" + this.topicPartitions + "'"
+ " | messageListener='" + messageListener + "'";
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\SimpleKafkaListenerEndpoint.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.