instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class TestMain {
public static void main(String[] args) throws IOException {
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36");
headers.put("Cookie",
"yunsuo_session_verify=1a3375389647fba22b7902b9fb4ace23; UM_distinctid=1653ca373b49dd-08590abd5d5966-e323462-1fa400-1653ca373b5d45; CNZZDATA1261546263=791873602-1534320347-%7C1534320347; JSESSIONID=BBAEDA8A8DED1B76BF8B5F576B52FFDD; PD=9ebee55477eac1bcc49b735f29d4f4134928223a2c77d03ba86aebe3044aa69c698511426b80c7d7");
headers.put("Referer",
"https://www.patexplorer.com/results/s.html?sc=&q=%E6%AD%A6%E6%B1%89%E7%91%9E%E5%8D%9A%E7%A7%91%E5%88%9B%E7%94%9F%E7%89%A9%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&fq=&type=s&sort=&sortField=");
headers.put("Host", "www.patexplorer.com");
headers.put("Origin", "https://www.patexplorer.com");
headers.put("X-Requested-With", "XMLHttpRequest");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
headers.put("Accept", "*/*");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("Content-Length", "199");
Map<String, String> data = new HashMap<>(); | data.put("sc", "");
data.put("q", "武汉瑞博科创生物技术有限公司");
data.put("sort", "");
data.put("sortField", "");
data.put("fq", "");
data.put("pageSize", "");
data.put("pageIndex", "");
data.put("type", "s");
data.put("merge", "no-merge");
Document post = Jsoup
.connect("https://www.patexplorer.com/results/list/YzhkYWIwYzRlZWIwZmJmZDRiMGMyZDRjOTdjZmM4MmU=")
.headers(headers).data(data).post();
System.out.println(post.body());
}
} | repos\spring-boot-quick-master\quick-vw-crawler\src\main\java\com\crawler\vw\TestMain.java | 1 |
请完成以下Java代码 | public class RabbitInboundEvent implements InboundEvent {
protected final Message message;
protected Collection<String> stringContentTypes;
protected Map<String, Object> headers;
public RabbitInboundEvent(Message message) {
this.message = message;
this.stringContentTypes = new HashSet<>();
this.stringContentTypes.add(MessageProperties.CONTENT_TYPE_JSON);
this.stringContentTypes.add(MessageProperties.CONTENT_TYPE_JSON_ALT);
this.stringContentTypes.add(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
this.stringContentTypes.add(MessageProperties.CONTENT_TYPE_XML);
}
@Override
public Object getRawEvent() {
return message;
}
@Override
public Object getBody() {
byte[] body = message.getBody();
MessageProperties messageProperties = message.getMessageProperties();
String contentType = messageProperties != null ? messageProperties.getContentType() : null;
String bodyContent = null;
if (stringContentTypes.contains(contentType)) {
bodyContent = new String(body, StandardCharsets.UTF_8);
} else {
bodyContent = Base64.getEncoder().encodeToString(body);
}
return bodyContent;
}
@Override
public Map<String, Object> getHeaders() {
if (headers == null) {
headers = retrieveHeaders();
}
return headers;
} | protected Map<String, Object> retrieveHeaders() {
Map<String, Object> headers = new HashMap<>();
Map<String, Object> headerMap = message.getMessageProperties().getHeaders();
for (String headerName : headerMap.keySet()) {
headers.put(headerName, headerMap.get(headerName));
}
return headers;
}
public Collection<String> getStringContentTypes() {
return stringContentTypes;
}
public void setStringContentTypes(Collection<String> stringContentTypes) {
this.stringContentTypes = stringContentTypes;
}
@Override
public String toString() {
return "RabbitInboundEvent{" +
"message=" + message +
", stringContentTypes=" + stringContentTypes +
", headers=" + headers +
'}';
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitInboundEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUQRCodeAttribute
{
@NonNull AttributeCode code;
@NonNull String displayName;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Nullable String value;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Nullable String valueRendered;
@Builder
@Jacksonized
private HUQRCodeAttribute(
@NonNull final AttributeCode code,
@NonNull final String displayName,
@Nullable final String value,
@Nullable final String valueRendered)
{
this.code = code;
this.displayName = displayName;
this.value = StringUtils.trimBlankToNull(value);
this.valueRendered = valueRendered != null ? valueRendered : this.value;
} | @Nullable
public BigDecimal getValueAsBigDecimal()
{
final String valueNorm = StringUtils.trimBlankToNull(value);
return valueNorm != null ? NumberUtils.asBigDecimal(valueNorm) : null;
}
@Nullable
public LocalDate getValueAsLocalDate()
{
final String valueNorm = StringUtils.trimBlankToNull(value);
return valueNorm != null ? LocalDate.parse(valueNorm) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeAttribute.java | 2 |
请完成以下Java代码 | private I_AD_ImpFormat_Row createImpFormatRow(@NonNull final I_AD_ImpFormat impFormat, @NonNull final I_AD_Column column, final AtomicInteger index)
{
final I_AD_ImpFormat_Row impRow = newInstance(I_AD_ImpFormat_Row.class);
impRow.setAD_Column_ID(column.getAD_Column_ID());
impRow.setAD_ImpFormat_ID(impFormat.getAD_ImpFormat_ID());
impRow.setName(column.getName());
final int adRefId = column.getAD_Reference_ID();
impRow.setDataType(extractDisplayType(adRefId));
impRow.setSeqNo(index.get());
impRow.setStartNo(index.get());
save(impRow);
return impRow;
}
private String extractDisplayType(final int adRefId)
{ | if (DisplayType.isText(adRefId))
{
return X_AD_ImpFormat_Row.DATATYPE_String;
}
else if (DisplayType.isNumeric(adRefId))
{
return X_AD_ImpFormat_Row.DATATYPE_Number;
}
else if (DisplayType.isDate(adRefId))
{
return X_AD_ImpFormat_Row.DATATYPE_Date;
}
else
{
return X_AD_ImpFormat_Row.DATATYPE_Constant;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_ImpFormat_Row_Create_Based_OnTable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class VoidOrderAndRelatedDocsService
{
private final ImmutableListMultimap<RecordsToHandleKey, VoidOrderAndRelatedDocsHandler> key2handlers;
private final ImmutableListMultimap<SourceRecordsKey, RelatedRecordsProvider> key2providers;
public VoidOrderAndRelatedDocsService(
@NonNull final Optional<List<VoidOrderAndRelatedDocsHandler>> handlers,
@NonNull final Optional<List<RelatedRecordsProvider>> providers)
{
this.key2handlers = Multimaps.index(
handlers.orElse(ImmutableList.of()),
VoidOrderAndRelatedDocsHandler::getRecordsToHandleKey);
this.key2providers = Multimaps.index(
providers.orElse(ImmutableList.of()),
RelatedRecordsProvider::getSourceRecordsKey);
}
public void invokeHandlers(@NonNull final VoidOrderAndRelatedDocsRequest request)
{
final IPair<RecordsToHandleKey, List<ITableRecordReference>> recordsToHandle = request.getRecordsToHandle();
final RecordsToHandleKey currentKey = recordsToHandle.getLeft();
final SourceRecordsKey sourceRecordsKey = currentKey.toSourceRecordsKey();
for (final RelatedRecordsProvider currentProvider : key2providers.get(sourceRecordsKey))
{
final List<ITableRecordReference> inputForProvider = recordsToHandle.getRight();
final IPair<SourceRecordsKey, List<ITableRecordReference>> relatedRecords = currentProvider.provideRelatedRecords(inputForProvider);
// recurse
if (relatedRecords.getRight().isEmpty())
{
continue;
}
final VoidOrderAndRelatedDocsRequest recursionRequest = createRecursionRequest(request, relatedRecords);
invokeHandlers(recursionRequest);
} | final ImmutableList<VoidOrderAndRelatedDocsHandler> handlersForKey = key2handlers.get(currentKey); // returns empty list if there are no handlers
for (final VoidOrderAndRelatedDocsHandler handlerForCurrentKey : handlersForKey)
{
handlerForCurrentKey.handleOrderVoided(request);
}
}
private VoidOrderAndRelatedDocsRequest createRecursionRequest(
@NonNull final VoidOrderAndRelatedDocsRequest originalRequest,
@NonNull final IPair<SourceRecordsKey, List<ITableRecordReference>> relatedRecords)
{
final RecordsToHandleKey recordsToHandleKey = RecordsToHandleKey.ofSourceRecordsKey(relatedRecords.getLeft());
final IPair<RecordsToHandleKey, List<ITableRecordReference>> //
recordsToHandle = ImmutablePair.of(recordsToHandleKey, relatedRecords.getRight());
final VoidOrderAndRelatedDocsRequest recursionRequest = originalRequest
.toBuilder()
.recordsToHandle(recordsToHandle)
.build();
return recursionRequest;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\voidorderandrelateddocs\VoidOrderAndRelatedDocsService.java | 2 |
请完成以下Java代码 | private String getBodyContentAsString() {
try {
String contentType = this.messageProperties.getContentType();
if (MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT.equals(contentType)) {
return "[serialized object]";
}
String encoding = encoding();
if (this.body.length <= maxBodyLength // NOSONAR
&& (MessageProperties.CONTENT_TYPE_TEXT_PLAIN.equals(contentType)
|| MessageProperties.CONTENT_TYPE_JSON.equals(contentType)
|| MessageProperties.CONTENT_TYPE_JSON_ALT.equals(contentType)
|| MessageProperties.CONTENT_TYPE_XML.equals(contentType))) {
return new String(this.body, encoding);
}
}
catch (Exception e) {
// ignore
}
// Comes out as '[B@....b' (so harmless)
return this.body.toString() + "(byte[" + this.body.length + "])"; //NOSONAR
}
private String encoding() {
String encoding = this.messageProperties.getContentEncoding();
if (encoding == null) {
encoding = bodyEncoding;
}
return encoding;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.body); | result = prime * result + ((this.messageProperties == null) ? 0 : this.messageProperties.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Message other = (Message) obj;
if (!Arrays.equals(this.body, other.body)) {
return false;
}
if (this.messageProperties == null) {
return other.messageProperties == null;
}
return this.messageProperties.equals(other.messageProperties);
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\Message.java | 1 |
请完成以下Java代码 | public static void update(AuthorizationCreateDto dto, Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) {
dbAuthorization.setGroupId(dto.getGroupId());
dbAuthorization.setUserId(dto.getUserId());
dbAuthorization.setResourceType(dto.getResourceType());
dbAuthorization.setResourceId(dto.getResourceId());
dbAuthorization.setPermissions(PermissionConverter.getPermissionsForNames(dto.getPermissions(), dto.getResourceType(), engineConfiguration));
}
//////////////////////////////////////////////////////
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String[] getPermissions() {
return permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) { | this.groupId = groupId;
}
public Integer getResourceType() {
return resourceType;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationCreateDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocalDate getDateClose()
{
return DateUtils.toLocalDate(dateClose);
}
public void setDateClose(final LocalDate dateClose)
{
this.dateClose = DateUtils.toSqlDate(dateClose);
}
public List<RfqQty> getQuantities()
{
return quantities;
}
public ImmutableSet<LocalDate> generateAllDaysSet()
{
final ArrayList<LocalDate> dates = DateUtils.getDaysList(getDateStart(), getDateEnd());
dates.addAll(quantities
.stream()
.map(RfqQty::getDatePromised)
.collect(ImmutableSet.toImmutableSet()));
dates.sort(LocalDate::compareTo);
return ImmutableSet.copyOf(dates);
}
public void setPricePromisedUserEntered(@NonNull final BigDecimal pricePromisedUserEntered)
{
this.pricePromisedUserEntered = pricePromisedUserEntered;
}
public BigDecimal getQtyPromisedUserEntered()
{
return quantities.stream()
.map(RfqQty::getQtyPromisedUserEntered)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised)
{
final RfqQty rfqQty = getOrCreateQty(date);
rfqQty.setQtyPromisedUserEntered(qtyPromised);
updateConfirmedByUser();
}
private RfqQty getOrCreateQty(@NonNull final LocalDate date)
{
final RfqQty existingRfqQty = getRfqQtyByDate(date);
if (existingRfqQty != null)
{
return existingRfqQty;
}
else
{
final RfqQty rfqQty = RfqQty.builder()
.rfq(this)
.datePromised(date)
.build();
addRfqQty(rfqQty);
return rfqQty;
}
}
private void addRfqQty(final RfqQty rfqQty)
{ | rfqQty.setRfq(this);
quantities.add(rfqQty);
}
@Nullable
public RfqQty getRfqQtyByDate(@NonNull final LocalDate date)
{
for (final RfqQty rfqQty : quantities)
{
if (date.equals(rfqQty.getDatePromised()))
{
return rfqQty;
}
}
return null;
}
private void updateConfirmedByUser()
{
this.confirmedByUser = computeConfirmedByUser();
}
private boolean computeConfirmedByUser()
{
if (pricePromised.compareTo(pricePromisedUserEntered) != 0)
{
return false;
}
for (final RfqQty rfqQty : quantities)
{
if (!rfqQty.isConfirmedByUser())
{
return false;
}
}
return true;
}
public void closeIt()
{
this.closed = true;
}
public void confirmByUser()
{
this.pricePromised = getPricePromisedUserEntered();
quantities.forEach(RfqQty::confirmByUser);
updateConfirmedByUser();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class MethodSecurityAdvisorRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
registerAsAdvisor("preFilterAuthorization", registry);
registerAsAdvisor("preAuthorizeAuthorization", registry);
registerAsAdvisor("postFilterAuthorization", registry);
registerAsAdvisor("postAuthorizeAuthorization", registry);
registerAsAdvisor("securedAuthorization", registry);
registerAsAdvisor("jsr250Authorization", registry);
registerAsAdvisor("authorizeReturnObject", registry);
}
private void registerAsAdvisor(String prefix, BeanDefinitionRegistry registry) {
String advisorName = prefix + "Advisor";
if (registry.containsBeanDefinition(advisorName)) {
return;
}
String interceptorName = prefix + "MethodInterceptor";
if (!registry.containsBeanDefinition(interceptorName)) {
return;
}
BeanDefinition definition = registry.getBeanDefinition(interceptorName);
if (!(definition instanceof RootBeanDefinition)) {
return;
}
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AdvisorWrapper.class);
builder.setFactoryMethod("of");
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
builder.addConstructorArgReference(interceptorName);
RootBeanDefinition advisor = (RootBeanDefinition) builder.getBeanDefinition();
advisor.setTargetType(Advisor.class);
registry.registerBeanDefinition(advisorName, advisor);
}
public static final class AdvisorWrapper | implements PointcutAdvisor, MethodInterceptor, Ordered, AopInfrastructureBean {
private final AuthorizationAdvisor advisor;
private AdvisorWrapper(AuthorizationAdvisor advisor) {
this.advisor = advisor;
}
public static AdvisorWrapper of(AuthorizationAdvisor advisor) {
return new AdvisorWrapper(advisor);
}
@Override
public Advice getAdvice() {
return this.advisor.getAdvice();
}
@Override
public Pointcut getPointcut() {
return this.advisor.getPointcut();
}
@Override
public int getOrder() {
return this.advisor.getOrder();
}
@Nullable
@Override
public Object invoke(@NonNull MethodInvocation invocation) throws Throwable {
return this.advisor.invoke(invocation);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecurityAdvisorRegistrar.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<String> loadDictItem(String ids) {
return this.loadDictItem(ids, true);
}
@Override
public List<String> loadDictItem(String ids, boolean delNotExist) {
String[] idArray = ids.split(",");
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<>();
query.in(SysCategory::getId, Arrays.asList(idArray));
// 查询数据
List<SysCategory> list = super.list(query);
// 取出name并返回
List<String> textList;
// 代码逻辑说明: 新增delNotExist参数,设为false不删除数据库里不存在的key ----
if (delNotExist) {
textList = list.stream().map(SysCategory::getName).collect(Collectors.toList());
} else {
textList = new ArrayList<>();
for (String id : idArray) {
List<SysCategory> res = list.stream().filter(i -> id.equals(i.getId())).collect(Collectors.toList());
textList.add(res.size() > 0 ? res.get(0).getName() : id);
} | }
return textList;
}
@Override
public List<String> loadDictItemByNames(String names, boolean delNotExist) {
List<String> nameList = Arrays.asList(names.split(SymbolConstant.COMMA));
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<>();
query.select(SysCategory::getId, SysCategory::getName);
query.in(SysCategory::getName, nameList);
// 查询数据
List<SysCategory> list = super.list(query);
// 取出id并返回
return nameList.stream().map(name -> {
SysCategory res = list.stream().filter(i -> name.equals(i.getName())).findFirst().orElse(null);
if (res == null) {
return delNotExist ? null : name;
}
return res.getId();
}).filter(Objects::nonNull).collect(Collectors.toList());
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysCategoryServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SoehenleSendTargetWeightRequest implements IDeviceRequest<NoDeviceResponse>
{
private static final int DEFAULT_SCALE = 2;
@NonNull
BigDecimal targetWeight;
@Nullable
Integer targetWeightScale;
@NonNull
@Builder.Default
BigDecimal positiveTolerance = BigDecimal.ZERO;
@NonNull
@Builder.Default
BigDecimal negativeTolerance = BigDecimal.ZERO;
@Override
public Class<NoDeviceResponse> getResponseClass()
{
return NoDeviceResponse.class;
}
@NonNull
public String getCmd()
{
final int scale = getTargetScale();
return "<K180K"
+ format(targetWeight, scale) + ";"
+ format(negativeTolerance, scale) + ";"
+ format(positiveTolerance, scale) + ">"; | }
private int getTargetScale()
{
return Optional.ofNullable(targetWeightScale).orElse(DEFAULT_SCALE);
}
/**
* Formats decimal value to fit Soehenle scale specs.
*/
@NonNull
private static String format(@NonNull final BigDecimal value, final int scale)
{
final BigDecimal absValue = value.abs();
final BigDecimal valueToUse = absValue.setScale(scale, RoundingMode.HALF_UP);
return NumberUtils.toStringWithCustomDecimalSeparator(valueToUse, ',');
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\soehenle\SoehenleSendTargetWeightRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult<List<UmsRole>> listAll() {
List<UmsRole> roleList = roleService.list();
return CommonResult.success(roleList);
}
@ApiOperation("根据角色名称分页获取角色列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<UmsRole>> list(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<UmsRole> roleList = roleService.list(keyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(roleList));
}
@ApiOperation("修改角色状态")
@RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
UmsRole umsRole = new UmsRole();
umsRole.setStatus(status);
int count = roleService.update(id, umsRole);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取角色相关菜单")
@RequestMapping(value = "/listMenu/{roleId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsMenu>> listMenu(@PathVariable Long roleId) {
List<UmsMenu> roleList = roleService.listMenu(roleId);
return CommonResult.success(roleList);
}
@ApiOperation("获取角色相关资源")
@RequestMapping(value = "/listResource/{roleId}", method = RequestMethod.GET) | @ResponseBody
public CommonResult<List<UmsResource>> listResource(@PathVariable Long roleId) {
List<UmsResource> roleList = roleService.listResource(roleId);
return CommonResult.success(roleList);
}
@ApiOperation("给角色分配菜单")
@RequestMapping(value = "/allocMenu", method = RequestMethod.POST)
@ResponseBody
public CommonResult allocMenu(@RequestParam Long roleId, @RequestParam List<Long> menuIds) {
int count = roleService.allocMenu(roleId, menuIds);
return CommonResult.success(count);
}
@ApiOperation("给角色分配资源")
@RequestMapping(value = "/allocResource", method = RequestMethod.POST)
@ResponseBody
public CommonResult allocResource(@RequestParam Long roleId, @RequestParam List<Long> resourceIds) {
int count = roleService.allocResource(roleId, resourceIds);
return CommonResult.success(count);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsRoleController.java | 2 |
请完成以下Java代码 | public int getC_Project_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_Asset_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A)
{
set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A);
}
@Override
public void setPJ_Asset_Acct (final int PJ_Asset_Acct)
{
set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct);
}
@Override
public int getPJ_Asset_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct); | }
@Override
public org.compiere.model.I_C_ValidCombination getPJ_WIP_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A)
{
set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A);
}
@Override
public void setPJ_WIP_Acct (final int PJ_WIP_Acct)
{
set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct);
}
@Override
public int getPJ_WIP_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java | 1 |
请完成以下Java代码 | protected boolean isExploded() {
Archive archive = getArchive();
return (archive != null) && archive.isExploded();
}
ClassPathIndexFile getClassPathIndex(Archive archive) throws IOException {
if (!archive.isExploded()) {
return null; // Regular archives already have a defined order
}
String location = getClassPathIndexFileLocation(archive);
return ClassPathIndexFile.loadIfPossible(archive.getRootDirectory(), location);
}
private String getClassPathIndexFileLocation(Archive archive) throws IOException {
Manifest manifest = archive.getManifest();
Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null;
String location = (attributes != null) ? attributes.getValue(BOOT_CLASSPATH_INDEX_ATTRIBUTE) : null;
return (location != null) ? location : getEntryPathPrefix() + DEFAULT_CLASSPATH_INDEX_FILE_NAME;
}
/**
* Return the archive being launched or {@code null} if there is no archive.
* @return the launched archive
*/
protected abstract Archive getArchive();
/**
* Returns the main class that should be launched.
* @return the name of the main class
* @throws Exception if the main class cannot be obtained
*/
protected abstract String getMainClass() throws Exception;
/**
* Returns the archives that will be used to construct the class path.
* @return the class path archives
* @throws Exception if the class path archives cannot be obtained
*/
protected abstract Set<URL> getClassPathUrls() throws Exception; | /**
* Return the path prefix for relevant entries in the archive.
* @return the entry path prefix
*/
protected String getEntryPathPrefix() {
return "BOOT-INF/";
}
/**
* Determine if the specified entry is a nested item that should be added to the
* classpath.
* @param entry the entry to check
* @return {@code true} if the entry is a nested item (jar or directory)
*/
protected boolean isIncludedOnClassPath(Archive.Entry entry) {
return isLibraryFileOrClassesDirectory(entry);
}
protected boolean isLibraryFileOrClassesDirectory(Archive.Entry entry) {
String name = entry.name();
if (entry.isDirectory()) {
return name.equals("BOOT-INF/classes/");
}
return name.startsWith("BOOT-INF/lib/");
}
protected boolean isIncludedOnClassPathAndNotIndexed(Entry entry) {
if (!isIncludedOnClassPath(entry)) {
return false;
}
return (this.classPathIndex == null) || !this.classPathIndex.containsEntry(entry.name());
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\Launcher.java | 1 |
请完成以下Java代码 | public void benchMarkComputeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingCompute(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkMergeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingMerge(getString());
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
} | private String getString() {
return
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
+ "\n"
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\incrementmapkey\BenchmarkMapMethodsJMH.java | 1 |
请完成以下Java代码 | public void validateLocatorChange(@NonNull final I_M_HU hu)
{
final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class);
huStatusBL.assertLocatorChangeIsAllowed(hu, hu.getHUStatus());
}
/**
* Updates the status, locator BP and BPL for child handling units.
*
* Note that this method only updates the direct children, but that will cause it to be called again and so on.
*
* @param hu
*/
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = {
I_M_HU.COLUMNNAME_HUStatus,
I_M_HU.COLUMNNAME_IsActive,
I_M_HU.COLUMNNAME_C_BPartner_ID,
I_M_HU.COLUMNNAME_C_BPartner_Location_ID,
I_M_HU.COLUMNNAME_M_Locator_ID
})
public void updateChildren(final I_M_HU hu)
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
//
// Retrieve included HUs
final List<I_M_HU> childHUs = handlingUnitsDAO.retrieveIncludedHUs(hu);
if (childHUs.isEmpty())
{
// no children => nothing to do
return;
}
//
// Extract relevant fields from parent
// NOTE: make sure these fields are in the list of columns changed of ModelChange annotation
final String parentHUStatus = hu.getHUStatus();
final boolean parentIsActive = hu.isActive();
final int parentBPartnerId = hu.getC_BPartner_ID(); | final int parentBPLocationId = hu.getC_BPartner_Location_ID();
final int parentLocatorId = hu.getM_Locator_ID();
final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(hu);
final IHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(contextProvider);
//
// Iterate children and update relevant fields from parent
for (final I_M_HU childHU : childHUs)
{
Services.get(IHUStatusBL.class).setHUStatus(huContext, childHU, parentHUStatus);
childHU.setIsActive(parentIsActive);
childHU.setC_BPartner_ID(parentBPartnerId);
childHU.setC_BPartner_Location_ID(parentBPLocationId);
childHU.setM_Locator_ID(parentLocatorId);
handlingUnitsDAO.saveHU(childHU);
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE }, ifColumnsChanged = {
I_M_HU.COLUMNNAME_HUStatus,
I_M_HU.COLUMNNAME_IsActive,
I_M_HU.COLUMNNAME_C_BPartner_ID,
I_M_HU.COLUMNNAME_M_Locator_ID
})
public void fireStorageSegmentChanged(final I_M_HU hu)
{
// Consider only VHUs
if (!Services.get(IHandlingUnitsBL.class).isVirtual(hu))
{
return;
}
final ShipmentScheduleSegmentFromHU storageSegment = new ShipmentScheduleSegmentFromHU(hu);
Services.get(IShipmentScheduleInvalidateBL.class).notifySegmentChanged(storageSegment);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU.java | 1 |
请完成以下Java代码 | public ProductId getProductId()
{
return productId;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public IAttributeSet getAttributesFrom()
{
return attributeStorageFrom;
}
@Override
public IAttributeStorage getAttributesTo()
{
return attributeStorageTo; | }
@Override
public IHUStorage getHUStorageFrom()
{
return huStorageFrom;
}
@Override
public IHUStorage getHUStorageTo()
{
return huStorageTo;
}
@Override
public BigDecimal getQtyUnloaded()
{
return qtyUnloaded;
}
@Override
public boolean isVHUTransfer()
{
return vhuTransfer;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequest.java | 1 |
请完成以下Java代码 | private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config) {
SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
rollingPolicy.setContext(config.getContext());
rollingPolicy.setFileNamePattern(
resolve(config, "${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}"));
rollingPolicy
.setCleanHistoryOnStart(resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}"));
rollingPolicy.setMaxFileSize(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}"));
rollingPolicy.setTotalSizeCap(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}"));
rollingPolicy.setMaxHistory(resolveInt(config, "${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}"));
appender.setRollingPolicy(rollingPolicy);
rollingPolicy.setParent(appender);
config.start(rollingPolicy);
}
private boolean resolveBoolean(LogbackConfigurator config, String val) {
return Boolean.parseBoolean(resolve(config, val));
}
private int resolveInt(LogbackConfigurator config, String val) {
return Integer.parseInt(resolve(config, val));
}
private FileSize resolveFileSize(LogbackConfigurator config, String val) {
return FileSize.valueOf(resolve(config, val));
}
private Charset resolveCharset(LogbackConfigurator config, String val) {
return Charset.forName(resolve(config, val));
}
private String resolve(LogbackConfigurator config, String val) {
try {
return OptionHelper.substVars(val, config.getContext());
}
catch (ScanException ex) {
throw new RuntimeException(ex); | }
}
private static String faint(String value) {
return color(value, AnsiStyle.FAINT);
}
private static String cyan(String value) {
return color(value, AnsiColor.CYAN);
}
private static String magenta(String value) {
return color(value, AnsiColor.MAGENTA);
}
private static String colorByLevel(String value) {
return "%clr(" + value + "){}";
}
private static String color(String value, AnsiElement ansiElement) {
return "%clr(" + value + "){" + ColorConverter.getName(ansiElement) + "}";
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DefaultLogbackConfiguration.java | 1 |
请完成以下Java代码 | public int getWinWidth()
{
return WinWidth;
}
public int getWinHeight()
{
return WinHeight;
}
public String getWindowType()
{
return WindowType;
} | private int getBaseTable_ID()
{
return _BaseTable_ID;
}
boolean isLoadAllLanguages()
{
return loadAllLanguages;
}
boolean isApplyRolePermissions()
{
return applyRolePermissions;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java | 1 |
请完成以下Java代码 | private void sendEventsNow(final List<WebsocketEvent> events)
{
events.forEach(this::sendEventNow);
}
private void sendEventNow(final WebsocketEvent event)
{
logger.debug("Sending {}", event);
final WebsocketTopicName destination = event.getDestination();
final Object payload = event.getPayload();
final boolean converted = event.isConverted();
if (converted)
{
final Message<?> message = (Message<?>)payload;
websocketMessagingTemplate.send(destination.getAsString(), message);
}
else
{
websocketMessagingTemplate.convertAndSend(destination.getAsString(), payload);
}
eventsLog.logEvent(destination, payload);
}
@lombok.Value
@lombok.Builder
private static class WebsocketEvent
{
WebsocketTopicName destination;
Object payload;
boolean converted;
}
private static class WebsocketEventsQueue
{
/**
* internal name, used for logging
*/
private final String name;
private final boolean doAutoflush;
private final List<WebsocketEvent> events = new ArrayList<>();
private final Debouncer<WebsocketEvent> debouncer;
public WebsocketEventsQueue(
@NonNull final String name,
final Debouncer<WebsocketEvent> debouncer,
final boolean autoflush)
{
this.name = name;
this.doAutoflush = autoflush;
this.debouncer = debouncer; | }
public void enqueueObject(final WebsocketTopicName destination, final Object payload)
{
final WebsocketEvent event = WebsocketEvent.builder()
.destination(destination)
.payload(payload)
.converted(false)
.build();
if (doAutoflush)
{
debouncer.add(event);
}
else
{
enqueue(event);
}
}
public void enqueueMessage(final WebsocketTopicName destination, final Message<?> message)
{
final WebsocketEvent event = WebsocketEvent.builder()
.destination(destination)
.payload(message)
.converted(true)
.build();
if (doAutoflush)
{
debouncer.add(event);
}
else
{
enqueue(event);
}
}
private void enqueue(@NonNull final WebsocketEvent event)
{
events.add(event);
logger.debug("[name={}] Enqueued event={}", name, event);
}
public void sendEventsAndClear()
{
logger.debug("Sending all queued events");
final List<WebsocketEvent> eventsToSend = new ArrayList<>(events);
events.clear();
debouncer.addAll(eventsToSend);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\sender\WebsocketSender.java | 1 |
请完成以下Java代码 | public void setFromClause (String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
public String getFromClause ()
{
return (String)get_Value(COLUMNNAME_FromClause);
}
/** Set Valid.
@param IsValid
Element is valid
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Valid.
@return Element is valid
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
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());
}
/** Set Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Post Processing.
@param PostProcessing
Process SQL after executing the query
*/
public void setPostProcessing (String PostProcessing)
{
set_Value (COLUMNNAME_PostProcessing, PostProcessing);
}
/** Get Post Processing.
@return Process SQL after executing the query | */
public String getPostProcessing ()
{
return (String)get_Value(COLUMNNAME_PostProcessing);
}
/** Set Pre Processing.
@param PreProcessing
Process SQL before executing the query
*/
public void setPreProcessing (String PreProcessing)
{
set_Value (COLUMNNAME_PreProcessing, PreProcessing);
}
/** Get Pre Processing.
@return Process SQL before executing the query
*/
public String getPreProcessing ()
{
return (String)get_Value(COLUMNNAME_PreProcessing);
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MainController {
@RequestMapping("/")
public String root() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index() {
return "index";
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute( "loginError" , true);
return "login";
} | @GetMapping("/401")
public String accessDenied() {
return "401";
}
@GetMapping("/user/common")
public String common() {
return "user/common";
}
@GetMapping("/user/admin")
public String admin() {
return "user/admin";
}
} | repos\SpringBootLearning-master (1)\springboot-security\src\main\java\com\gf\controller\MainController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PerformanceMonitorInterceptor performanceMonitorInterceptor() {
return new PerformanceMonitorInterceptor(true);
}
@Bean
public Advisor performanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.monitor()");
return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor());
}
@Bean
public Person person(){
return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12));
}
@Bean
public PersonService personService(){
return new PersonService(); | }
@Bean
public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() {
return new MyPerformanceMonitorInterceptor(true);
}
@Bean
public Advisor myPerformanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("com.baeldung.performancemonitor.AopConfiguration.myMonitor()");
return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor());
}
} | repos\tutorials-master\spring-aop-2\src\main\java\com\baeldung\performancemonitor\AopConfiguration.java | 2 |
请完成以下Java代码 | public java.lang.String getColumnName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Backup value null.
@param IsBackupNull
The backup value is null.
*/
@Override
public void setIsBackupNull (boolean IsBackupNull)
{
set_Value (COLUMNNAME_IsBackupNull, Boolean.valueOf(IsBackupNull));
}
/** Get Backup value null.
@return The backup value is null.
*/
@Override
public boolean isBackupNull ()
{
Object oo = get_Value(COLUMNNAME_IsBackupNull);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set New value null.
@param IsNewNull
The new value is null.
*/
@Override
public void setIsNewNull (boolean IsNewNull)
{
set_Value (COLUMNNAME_IsNewNull, Boolean.valueOf(IsNewNull));
}
/** Get New value null.
@return The new value is null.
*/
@Override
public boolean isNewNull ()
{
Object oo = get_Value(COLUMNNAME_IsNewNull);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Old value null.
@param IsOldNull
The old value was null.
*/
@Override
public void setIsOldNull (boolean IsOldNull)
{
set_Value (COLUMNNAME_IsOldNull, Boolean.valueOf(IsOldNull));
}
/** Get Old value null.
@return The old value was null.
*/
@Override
public boolean isOldNull ()
{
Object oo = get_Value(COLUMNNAME_IsOldNull); | if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set New Value.
@param NewValue
New field value
*/
@Override
public void setNewValue (java.lang.String NewValue)
{
set_Value (COLUMNNAME_NewValue, NewValue);
}
/** Get New Value.
@return New field value
*/
@Override
public java.lang.String getNewValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_NewValue);
}
/** Set Old Value.
@param OldValue
The old file data
*/
@Override
public void setOldValue (java.lang.String OldValue)
{
set_Value (COLUMNNAME_OldValue, OldValue);
}
/** Get Old Value.
@return The old file data
*/
@Override
public java.lang.String getOldValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_OldValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTransportService(TransportService transportService) {
this.transportService = transportService;
}
@Override
public DeviceProfile getOrCreate(DeviceProfileId id, TransportProtos.DeviceProfileProto proto) {
DeviceProfile profile = deviceProfiles.get(id);
if (profile == null) {
profile = ProtoUtils.fromProto(proto);
deviceProfiles.put(id, profile);
}
return profile;
}
@Override
public DeviceProfile get(DeviceProfileId id) {
return this.getDeviceProfile(id);
}
@Override
public void put(DeviceProfile profile) {
deviceProfiles.put(profile.getId(), profile);
}
@Override
public DeviceProfile put(TransportProtos.DeviceProfileProto proto) {
DeviceProfile deviceProfile = ProtoUtils.fromProto(proto);
put(deviceProfile);
return deviceProfile;
}
@Override
public void evict(DeviceProfileId id) {
deviceProfiles.remove(id);
}
private DeviceProfile getDeviceProfile(DeviceProfileId id) {
DeviceProfile profile = deviceProfiles.get(id); | if (profile == null) {
deviceProfileFetchLock.lock();
try {
TransportProtos.GetEntityProfileRequestMsg msg = TransportProtos.GetEntityProfileRequestMsg.newBuilder()
.setEntityType(EntityType.DEVICE_PROFILE.name())
.setEntityIdMSB(id.getId().getMostSignificantBits())
.setEntityIdLSB(id.getId().getLeastSignificantBits())
.build();
TransportProtos.GetEntityProfileResponseMsg entityProfileMsg = transportService.getEntityProfile(msg);
profile = ProtoUtils.fromProto(entityProfileMsg.getDeviceProfile());
this.put(profile);
} finally {
deviceProfileFetchLock.unlock();
}
}
return profile;
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportDeviceProfileCache.java | 2 |
请完成以下Java代码 | public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@CamundaQueryParam(value = "endDate", converter = DateConverter.class)
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
protected String getOrderByValue(String sortBy) {
return null;
}
@Override
protected boolean isValidSortByValue(String value) {
return false;
}
public void validateAndPrepareQuery() {
if (subscriptionStartDate == null || !subscriptionStartDate.before(ClockUtil.now())) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST,
"subscriptionStartDate parameter has invalid value: " + subscriptionStartDate);
} | if (startDate != null && endDate != null && !endDate.after(startDate)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "endDate parameter must be after startDate");
}
if (!VALID_GROUP_BY_VALUES.contains(groupBy)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupBy);
}
if (metrics == null || metrics.isEmpty()) {
metrics = VALID_METRIC_VALUES;
}
// convert metrics to internal names
this.metrics = metrics.stream()
.map(MetricsUtil::resolveInternalName)
.collect(Collectors.toSet());
}
public int getSubscriptionMonth() {
return subscriptionMonth;
}
public int getSubscriptionDay() {
return subscriptionDay;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\plugin\base\dto\MetricsAggregatedQueryDto.java | 1 |
请完成以下Java代码 | public class InMemoryTbQueueConsumer<T extends TbQueueMsg> implements TbQueueConsumer<T> {
private final InMemoryStorage storage;
private volatile Set<TopicPartitionInfo> partitions;
private volatile boolean stopped;
private volatile boolean subscribed;
public InMemoryTbQueueConsumer(InMemoryStorage storage, String topic) {
this.storage = storage;
this.topic = topic;
stopped = false;
}
private final String topic;
@Override
public String getTopic() {
return topic;
}
@Override
public void subscribe() {
partitions = Collections.singleton(new TopicPartitionInfo(topic, null, null, true));
subscribed = true;
}
@Override
public void subscribe(Set<TopicPartitionInfo> partitions) {
this.partitions = partitions;
subscribed = true;
}
@Override
public void stop() {
stopped = true;
}
@Override
public void unsubscribe() {
stopped = true;
subscribed = false;
}
@Override
public List<T> poll(long durationInMillis) {
if (subscribed) {
@SuppressWarnings("unchecked")
List<T> messages = partitions
.stream()
.map(tpi -> {
try {
return storage.get(tpi.getFullTopicName());
} catch (InterruptedException e) {
if (!stopped) {
log.error("Queue was interrupted.", e);
}
return Collections.emptyList();
}
})
.flatMap(List::stream)
.map(msg -> (T) msg).collect(Collectors.toList());
if (messages.size() > 0) { | return messages;
}
try {
Thread.sleep(durationInMillis);
} catch (InterruptedException e) {
if (!stopped) {
log.error("Failed to sleep.", e);
}
}
}
return Collections.emptyList();
}
@Override
public void commit() {
}
@Override
public boolean isStopped() {
return stopped;
}
@Override
public Set<TopicPartitionInfo> getPartitions() {
return partitions;
}
@Override
public List<String> getFullTopicNames() {
return partitions.stream().map(TopicPartitionInfo::getFullTopicName).collect(Collectors.toList());
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\InMemoryTbQueueConsumer.java | 1 |
请完成以下Java代码 | public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode)
{
return map.values()
.stream()
.filter(pickFrom -> HUQRCode.equals(pickFrom.getPickFromHU().getQrCode(), qrCode))
.findFirst()
.orElseThrow(() -> new AdempiereException("No HU found for " + qrCode));
}
public boolean isNothingPicked()
{
return map.values().stream().allMatch(PickingJobStepPickFrom::isNotPicked);
}
public PickingJobStepPickFromMap reduceWithPickedEvent(
@NonNull PickingJobStepPickFromKey key,
@NonNull PickingJobStepPickedTo pickedTo)
{
return withChangedPickFrom(key, pickFrom -> pickFrom.withPickedEvent(pickedTo));
}
public PickingJobStepPickFromMap reduceWithUnpickEvent(
@NonNull PickingJobStepPickFromKey key,
@NonNull PickingJobStepUnpickInfo unpicked)
{
return withChangedPickFrom(key, pickFrom -> pickFrom.withUnPickedEvent(unpicked));
}
private PickingJobStepPickFromMap withChangedPickFrom(
@NonNull PickingJobStepPickFromKey key,
@NonNull UnaryOperator<PickingJobStepPickFrom> pickFromMapper)
{
if (!map.containsKey(key))
{
throw new AdempiereException("No PickFrom " + key + " found in " + this);
}
final ImmutableMap<PickingJobStepPickFromKey, PickingJobStepPickFrom> newMap = CollectionUtils.mapValue(map, key, pickFromMapper);
return !Objects.equals(this.map, newMap)
? new PickingJobStepPickFromMap(newMap)
: this;
}
public Optional<Quantity> getQtyPicked()
{
return map.values()
.stream()
.map(pickFrom -> pickFrom.getQtyPicked().orElse(null))
.filter(Objects::nonNull)
.reduce(Quantity::add); | }
public Optional<Quantity> getQtyRejected()
{
// returning only from mainPickFrom because I wanted to keep the same logic we already have in misc/services/mobile-webui/mobile-webui-frontend/src/utils/picking.js, getQtyPickedOrRejectedTotalForLine
return getMainPickFrom().getQtyRejected();
}
@NonNull
public List<HuId> getPickedHUIds()
{
return map.values()
.stream()
.map(PickingJobStepPickFrom::getPickedTo)
.filter(Objects::nonNull)
.filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0)
.map(PickingJobStepPickedTo::getPickedHuIds)
.flatMap(List::stream)
.collect(ImmutableList.toImmutableList());
}
@NonNull
public Optional<PickingJobStepPickedToHU> getLastPickedHU()
{
return map.values()
.stream()
.map(PickingJobStepPickFrom::getPickedTo)
.filter(Objects::nonNull)
.filter(pickedTo -> pickedTo.getQtyPicked().signum() > 0)
.map(PickingJobStepPickedTo::getLastPickedHu)
.filter(Optional::isPresent)
.map(Optional::get)
.max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFromMap.java | 1 |
请完成以下Java代码 | private boolean hasFileSystem(URI uri) {
try {
FileSystems.getFileSystem(uri);
return true;
}
catch (FileSystemNotFoundException ex) {
return isCreatingNewFileSystem();
}
}
private boolean isCreatingNewFileSystem() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (StackTraceElement element : stack) {
if (FILE_SYSTEMS_CLASS_NAME.equals(element.getClassName())) {
return "newFileSystem".equals(element.getMethodName());
}
}
return false;
}
@Override
public FileSystemProvider provider() {
return this.provider;
}
Path getJarPath() {
return this.jarPath;
}
@Override
public void close() throws IOException {
if (this.closed) {
return;
}
this.closed = true;
synchronized (this.zipFileSystems) {
this.zipFileSystems.values()
.stream()
.filter(FileSystem.class::isInstance)
.map(FileSystem.class::cast)
.forEach(this::closeZipFileSystem);
}
this.provider.removeFileSystem(this);
}
private void closeZipFileSystem(FileSystem zipFileSystem) {
try {
zipFileSystem.close();
}
catch (Exception ex) {
// Ignore
}
}
@Override
public boolean isOpen() {
return !this.closed;
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public String getSeparator() {
return "/!";
}
@Override
public Iterable<Path> getRootDirectories() {
assertNotClosed();
return Collections.emptySet();
}
@Override
public Iterable<FileStore> getFileStores() {
assertNotClosed();
return Collections.emptySet();
}
@Override
public Set<String> supportedFileAttributeViews() {
assertNotClosed();
return SUPPORTED_FILE_ATTRIBUTE_VIEWS;
}
@Override
public Path getPath(String first, String... more) {
assertNotClosed();
if (more.length != 0) {
throw new IllegalArgumentException("Nested paths must contain a single element");
}
return new NestedPath(this, first);
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) { | throw new UnsupportedOperationException("Nested paths do not support path matchers");
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service");
}
@Override
public WatchService newWatchService() throws IOException {
throw new UnsupportedOperationException("Nested paths do not support the WatchService");
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
NestedFileSystem other = (NestedFileSystem) obj;
return this.jarPath.equals(other.jarPath);
}
@Override
public int hashCode() {
return this.jarPath.hashCode();
}
@Override
public String toString() {
return this.jarPath.toAbsolutePath().toString();
}
private void assertNotClosed() {
if (this.closed) {
throw new ClosedFileSystemException();
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java | 1 |
请完成以下Java代码 | public boolean checkFirstDownlink() {
boolean result = firstEdrxDownlink;
firstEdrxDownlink = false;
return result;
}
public void onDeviceUpdate(Device device) {
this.profileId = device.getDeviceProfileId();
var data = device.getDeviceData();
if (data.getTransportConfiguration() != null && data.getTransportConfiguration().getType().equals(DeviceTransportType.COAP)) {
CoapDeviceTransportConfiguration configuration = (CoapDeviceTransportConfiguration) data.getTransportConfiguration();
this.powerMode = configuration.getPowerMode();
this.edrxCycle = configuration.getEdrxCycle();
this.psmActivityTimer = configuration.getPsmActivityTimer();
this.pagingTransmissionWindow = configuration.getPagingTransmissionWindow();
}
}
public void addQueuedNotification(TransportProtos.AttributeUpdateNotificationMsg msg) {
if (missedAttributeUpdates == null) {
missedAttributeUpdates = msg;
} else {
Map<String, TransportProtos.TsKvProto> updatedAttrs = new HashMap<>(missedAttributeUpdates.getSharedUpdatedCount() + msg.getSharedUpdatedCount());
Set<String> deletedKeys = new HashSet<>(missedAttributeUpdates.getSharedDeletedCount() + msg.getSharedDeletedCount());
for (TransportProtos.TsKvProto oldUpdatedAttrs : missedAttributeUpdates.getSharedUpdatedList()) {
updatedAttrs.put(oldUpdatedAttrs.getKv().getKey(), oldUpdatedAttrs);
}
deletedKeys.addAll(msg.getSharedDeletedList()); | for (TransportProtos.TsKvProto newUpdatedAttrs : msg.getSharedUpdatedList()) {
updatedAttrs.put(newUpdatedAttrs.getKv().getKey(), newUpdatedAttrs);
}
deletedKeys.addAll(msg.getSharedDeletedList());
for (String deletedKey : msg.getSharedDeletedList()) {
updatedAttrs.remove(deletedKey);
}
missedAttributeUpdates = TransportProtos.AttributeUpdateNotificationMsg.newBuilder().addAllSharedUpdated(updatedAttrs.values()).addAllSharedDeleted(deletedKeys).build();
}
}
public TransportProtos.AttributeUpdateNotificationMsg getAndClearMissedUpdates() {
var result = this.missedAttributeUpdates;
this.missedAttributeUpdates = null;
return result;
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\client\TbCoapClientState.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMaxInactiveInterval(Duration maxInactiveInterval) {
this.maxInactiveInterval = maxInactiveInterval;
}
public void setRedisNamespace(String namespace) {
Assert.hasText(namespace, "namespace cannot be empty or null");
this.redisNamespace = namespace;
}
public void setSaveMode(SaveMode saveMode) {
Assert.notNull(saveMode, "saveMode cannot be null");
this.saveMode = saveMode;
}
public Duration getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
public String getRedisNamespace() {
return this.redisNamespace;
}
public SaveMode getSaveMode() {
return this.saveMode;
}
public SessionIdGenerator getSessionIdGenerator() {
return this.sessionIdGenerator;
}
public RedisSerializer<Object> getDefaultRedisSerializer() {
return this.defaultRedisSerializer;
}
@Autowired
public void setRedisConnectionFactory(
@SpringSessionRedisConnectionFactory ObjectProvider<ReactiveRedisConnectionFactory> springSessionRedisConnectionFactory,
ObjectProvider<ReactiveRedisConnectionFactory> redisConnectionFactory) {
ReactiveRedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory
.getIfAvailable();
if (redisConnectionFactoryToUse == null) {
redisConnectionFactoryToUse = redisConnectionFactory.getObject();
}
this.redisConnectionFactory = redisConnectionFactoryToUse;
}
@Autowired(required = false)
@Qualifier("springSessionDefaultRedisSerializer")
public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) {
this.defaultRedisSerializer = defaultRedisSerializer;
}
@Autowired(required = false)
public void setSessionRepositoryCustomizer(
ObjectProvider<ReactiveSessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) {
this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList());
} | protected List<ReactiveSessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() {
return this.sessionRepositoryCustomizers;
}
protected ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() {
RedisSerializer<String> keySerializer = RedisSerializer.string();
RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer
: new JdkSerializationRedisSerializer();
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer)
.key(keySerializer)
.hashKey(keySerializer)
.build();
return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext);
}
public ReactiveRedisConnectionFactory getRedisConnectionFactory() {
return this.redisConnectionFactory;
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\AbstractRedisWebSessionConfiguration.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public boolean canMap(Object parameter) {
return parameter != null;
}
public String writeValue(Object value) {
try {
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, value);
return stringWriter.toString();
}
catch (IOException e) {
throw LOG.unableToWriteValue(value, e);
}
}
@SuppressWarnings("unchecked")
public <T> T readValue(String value, String typeIdentifier) {
try {
Class<?> cls = Class.forName(typeIdentifier);
return (T) readValue(value, cls);
}
catch (ClassNotFoundException e) {
JavaType javaType = constructJavaTypeFromCanonicalString(typeIdentifier);
return readValue(value, javaType);
}
}
public <T> T readValue(String value, Class<T> cls) {
try {
return objectMapper.readValue(value, cls);
}
catch (JsonParseException e) {
throw LOG.unableToReadValue(value, e);
}
catch (JsonMappingException e) {
throw LOG.unableToReadValue(value, e);
}
catch (IOException e) { | throw LOG.unableToReadValue(value, e);
}
}
protected <C> C readValue(String value, JavaType type) {
try {
return objectMapper.readValue(value, type);
}
catch (JsonParseException e) {
throw LOG.unableToReadValue(value, e);
}
catch (JsonMappingException e) {
throw LOG.unableToReadValue(value, e);
}
catch (IOException e) {
throw LOG.unableToReadValue(value, e);
}
}
public JavaType constructJavaTypeFromCanonicalString(String canonicalString) {
try {
return TypeFactory.defaultInstance().constructFromCanonical(canonicalString);
}
catch (IllegalArgumentException e) {
throw LOG.unableToConstructJavaType(canonicalString, e);
}
}
public String getCanonicalTypeName(Object value) {
ensureNotNull("value", value);
for (TypeDetector typeDetector : typeDetectors) {
if (typeDetector.canHandle(value)) {
return typeDetector.detectType(value);
}
}
throw LOG.unableToDetectCanonicalType(value);
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\JacksonJsonDataFormat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RenderedAddressAndCapturedLocation
{
public static RenderedAddressAndCapturedLocation of(@Nullable final String renderedAddress, @Nullable final LocationId capturedLocationId)
{
if (Check.isEmpty(renderedAddress) && capturedLocationId == null)
{
return NONE;
}
else
{
return new RenderedAddressAndCapturedLocation(renderedAddress, capturedLocationId);
}
}
public static RenderedAddressAndCapturedLocation of(@Nullable final String renderedAddress, final int capturedLocationRepoId)
{
return of(renderedAddress, LocationId.ofRepoIdOrNull(capturedLocationRepoId));
}
public static RenderedAddressAndCapturedLocation NONE = new RenderedAddressAndCapturedLocation("", null);
@Nullable
String renderedAddress;
@Nullable
LocationId capturedLocationId;
private RenderedAddressAndCapturedLocation(@Nullable final String renderedAddress, @Nullable final LocationId capturedLocationId)
{
this.renderedAddress = renderedAddress;
this.capturedLocationId = capturedLocationId;
} | /**
* @deprecated please use getRenderedAddress().
*/
@Override
@Deprecated
public String toString()
{
return getRenderedAddress();
}
public boolean isNone()
{
return this.equals(NONE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\RenderedAddressAndCapturedLocation.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AttachmentMetadata archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen, ob Anlage archiviert ist
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen, ob Anlage archiviert ist")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AttachmentMetadata attachmentMetadata = (AttachmentMetadata) o;
return Objects.equals(this.type, attachmentMetadata.type) &&
Objects.equals(this.therapyId, attachmentMetadata.therapyId) &&
Objects.equals(this.therapyTypeId, attachmentMetadata.therapyTypeId) &&
Objects.equals(this.woundLocation, attachmentMetadata.woundLocation) &&
Objects.equals(this.patientId, attachmentMetadata.patientId) &&
Objects.equals(this.createdBy, attachmentMetadata.createdBy) &&
Objects.equals(this.createdAt, attachmentMetadata.createdAt) &&
Objects.equals(this.archived, attachmentMetadata.archived);
} | @Override
public int hashCode() {
return Objects.hash(type, therapyId, therapyTypeId, woundLocation, patientId, createdBy, createdAt, archived);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AttachmentMetadata {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n");
sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n");
sb.append(" woundLocation: ").append(toIndentedString(woundLocation)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\AttachmentMetadata.java | 2 |
请完成以下Java代码 | public String getTarget() {
return this.target;
}
}
/**
* Description of a {@link Cache} entry.
*/
public static final class CacheEntryDescriptor extends CacheDescriptor {
private final String name;
private final String cacheManager;
public CacheEntryDescriptor(Cache cache, String cacheManager) {
super(cache.getNativeCache().getClass().getName()); | this.name = cache.getName();
this.cacheManager = cacheManager;
}
public String getName() {
return this.name;
}
public String getCacheManager() {
return this.cacheManager;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\actuate\endpoint\CachesEndpoint.java | 1 |
请完成以下Java代码 | public final void clearBatch() throws SQLException
{
delegate.clearBatch();
}
@Override
public final int[] executeBatch() throws SQLException
{
return trace(delegate::executeBatch);
}
@Override
public final Connection getConnection() throws SQLException
{
return delegate.getConnection();
}
@Override
public final boolean getMoreResults(final int current) throws SQLException
{
return delegate.getMoreResults(current);
}
@Override
public final ResultSet getGeneratedKeys() throws SQLException
{
return delegate.getGeneratedKeys();
}
@Override
public final int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, autoGeneratedKeys));
}
@Override
public final int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, columnIndexes));
}
@Override
public final int executeUpdate(final String sql, final String[] columnNames) throws SQLException
{
return trace(sql, () -> delegate.executeUpdate(sql, columnNames));
}
@Override
public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, autoGeneratedKeys));
}
@Override
public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, columnIndexes));
}
@Override
public final boolean execute(final String sql, final String[] columnNames) throws SQLException
{
return trace(sql, () -> delegate.execute(sql, columnNames));
}
@Override
public final int getResultSetHoldability() throws SQLException | {
return delegate.getResultSetHoldability();
}
@Override
public final boolean isClosed() throws SQLException
{
return delegate.isClosed();
}
@Override
public final void setPoolable(final boolean poolable) throws SQLException
{
delegate.setPoolable(poolable);
}
@Override
public final boolean isPoolable() throws SQLException
{
return delegate.isPoolable();
}
@Override
public final void closeOnCompletion() throws SQLException
{
delegate.closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return delegate.isCloseOnCompletion();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java | 1 |
请完成以下Java代码 | public void performExecution(ActivityExecution execution) throws Exception {
TaskEntity task = new TaskEntity((ExecutionEntity) execution);
task.insert();
// initialize task properties
taskDecorator.decorate(task, execution);
// fire lifecycle events after task is initialized
task.transitionTo(TaskState.STATE_CREATED);
}
public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception {
leave(execution);
}
// migration
@Override
public void migrateScope(ActivityExecution scopeExecution) {
}
@Override
public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) {
ExecutionEntity execution = migratingInstance.resolveRepresentativeExecution();
for (TaskEntity task : execution.getTasks()) {
migratingInstance.addMigratingDependentInstance(new MigratingUserTaskInstance(task, migratingInstance));
parseContext.consume(task);
Collection<VariableInstanceEntity> variables = task.getVariablesInternal();
if (variables != null) {
for (VariableInstanceEntity variable : variables) {
// we don't need to represent task variables in the migrating instance structure because
// they are migrated by the MigratingTaskInstance as well
parseContext.consume(variable); | }
}
}
}
// getters
public TaskDefinition getTaskDefinition() {
return taskDecorator.getTaskDefinition();
}
public ExpressionManager getExpressionManager() {
return taskDecorator.getExpressionManager();
}
public TaskDecorator getTaskDecorator() {
return taskDecorator;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\UserTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public Expression createExpression(String expression) {
ValueExpression valueExpression = expressionFactory.createValueExpression(parsingElContext, expression.trim(), Object.class);
return new JuelExpression(valueExpression, expression);
}
public void setExpressionFactory(ExpressionFactory expressionFactory) {
this.expressionFactory = expressionFactory;
}
public ELContext getElContext(VariableScope variableScope) {
ELContext elContext = null;
if (variableScope instanceof VariableScopeImpl) {
VariableScopeImpl variableScopeImpl = (VariableScopeImpl) variableScope;
elContext = variableScopeImpl.getCachedElContext();
}
if (elContext == null) {
elContext = createElContext(variableScope);
if (variableScope instanceof VariableScopeImpl) {
((VariableScopeImpl) variableScope).setCachedElContext(elContext);
}
}
return elContext;
}
protected ActivitiElContext createElContext(VariableScope variableScope) {
ELResolver elResolver = createElResolver(variableScope);
return new ActivitiElContext(elResolver);
}
protected ELResolver createElResolver(VariableScope variableScope) {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver(variableScope));
if (beans != null) { | // ACT-1102: Also expose all beans in configuration when using standalone activiti, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new JsonNodeELResolver());
elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification
elResolver.add(new BeanELResolver());
return elResolver;
}
public Map<Object, Object> getBeans() {
return beans;
}
public void setBeans(Map<Object, Object> beans) {
this.beans = beans;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static final class RequestMatcherDelegatingAuthorizationManagerFactory
implements FactoryBean<AuthorizationManager<HttpServletRequest>> {
private Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> beans;
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
@Override
public AuthorizationManager<HttpServletRequest> getObject() throws Exception {
RequestMatcherDelegatingAuthorizationManager.Builder builder = RequestMatcherDelegatingAuthorizationManager
.builder();
for (Map.Entry<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> entry : this.beans
.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
AuthorizationManager<HttpServletRequest> manager = builder.build();
if (!this.observationRegistry.isNoop()) {
return new ObservationAuthorizationManager<>(this.observationRegistry, manager);
}
return manager;
}
@Override
public Class<?> getObjectType() {
return AuthorizationManager.class;
}
public void setRequestMatcherMap(Map<RequestMatcher, AuthorizationManager<RequestAuthorizationContext>> beans) {
this.beans = beans;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
static class DefaultWebSecurityExpressionHandlerBeanFactory | extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultHttpSecurityExpressionHandler handler = new DefaultHttpSecurityExpressionHandler();
@Override
public DefaultHttpSecurityExpressionHandler getBean() {
if (this.rolePrefix != null) {
this.handler.setDefaultRolePrefix(this.rolePrefix);
}
return this.handler;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\AuthorizationFilterParser.java | 2 |
请完成以下Java代码 | public Type getType() {
return Type.UNQUALIFIED;
}
/**
* Null-safe builder method used to configure the {@link DistributedMember member} that is the subject
* of this event.
*
* @param distributedMember {@link DistributedMember} that is the subject of this event.
* @return this {@link MembershipEvent}.
* @see org.apache.geode.distributed.DistributedMember
* @see #getDistributedMember()
*/
@SuppressWarnings("unchecked")
public T withMember(DistributedMember distributedMember) {
this.distributedMember = distributedMember; | return (T) this;
}
/**
* An {@link Enum enumeration} of different type of {@link MembershipEvent MembershipEvents}.
*/
public enum Type {
MEMBER_DEPARTED,
MEMBER_JOINED,
MEMBER_SUSPECT,
QUORUM_LOST,
UNQUALIFIED;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JtaDemoApplication {
@Bean("dataSourceAccount")
public DataSource dataSource() throws Exception {
return createHsqlXADatasource("jdbc:hsqldb:mem:accountDb");
}
@Bean("dataSourceAudit")
public DataSource dataSourceAudit() throws Exception {
return createHsqlXADatasource("jdbc:hsqldb:mem:auditDb");
}
private DataSource createHsqlXADatasource(String connectionUrl) throws Exception {
JDBCXADataSource dataSource = new JDBCXADataSource();
dataSource.setUrl(connectionUrl); | dataSource.setUser("sa");
AtomikosXADataSourceWrapper wrapper = new AtomikosXADataSourceWrapper();
return wrapper.wrapDataSource(dataSource);
}
@Bean("jdbcTemplateAccount")
public JdbcTemplate jdbcTemplate(@Qualifier("dataSourceAccount") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean("jdbcTemplateAudit")
public JdbcTemplate jdbcTemplateAudit(@Qualifier("dataSourceAudit") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\jtademo\JtaDemoApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Amount for calculation the document's commission amount.
*
* @return
* possible object is
* {@link MonetaryAmountType }
*
*/ | public MonetaryAmountType getCommissionBaseAmount() {
return commissionBaseAmount;
}
/**
* Sets the value of the commissionBaseAmount property.
*
* @param value
* allowed object is
* {@link MonetaryAmountType }
*
*/
public void setCommissionBaseAmount(MonetaryAmountType value) {
this.commissionBaseAmount = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ItemType.java | 2 |
请完成以下Java代码 | public String getStatusIn() {
return statusIn;
}
/**
* Sets the value of the statusIn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatusIn(String value) {
this.statusIn = value;
}
/**
* Gets the value of the statusOut property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatusOut() {
return statusOut; | }
/**
* Sets the value of the statusOut property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatusOut(String value) {
this.statusOut = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\StatusType.java | 1 |
请完成以下Java代码 | private XMLCompany createXMLCompany(@NonNull final CompanyType company)
{
return XMLCompany.builder()
.companyName(company.getCompanyname())
.build();
}
private XMLParty createXmlParty(@NonNull final PartyType eanParty)
{
final XMLParty.XMLPartyBuilder partyBuilder = XMLParty.builder();
if (eanParty.getEanParty() != null)
{
partyBuilder.eanParty(eanParty.getEanParty());
}
return partyBuilder.build();
}
private XMLPatientAddress createXmlPatientAddress(@NonNull final PatientAddressType patient)
{
final XMLPatientAddress.XMLPatientAddressBuilder patientAddressBuilder = XMLPatientAddress.builder();
if (patient.getPerson() != null)
{
patientAddressBuilder.person(createXmlPersonType(patient.getPerson()));
}
return patientAddressBuilder.build();
}
private XMLPersonType createXmlPersonType(@NonNull final PersonType person)
{
return XMLPersonType.builder()
.familyName(person.getFamilyname())
.givenName(person.getGivenname())
.build();
}
private XmlRejected createXmlRejected(@NonNull final RejectedType rejected)
{
final XmlRejectedBuilder rejectedBuilder = XmlRejected.builder();
rejectedBuilder.explanation(rejected.getExplanation())
.statusIn(rejected.getStatusIn())
.statusOut(rejected.getStatusOut()); | if (rejected.getError() != null && !rejected.getError().isEmpty())
{
rejectedBuilder.errors(createXmlErrors(rejected.getError()));
}
return rejectedBuilder.build();
}
private List<XmlError> createXmlErrors(@NonNull final List<ErrorType> error)
{
final ImmutableList.Builder<XmlError> errorsBuilder = ImmutableList.builder();
for (final ErrorType errorType : error)
{
final XmlError xmlError = XmlError
.builder()
.code(errorType.getCode())
.errorValue(errorType.getErrorValue())
.recordId(errorType.getRecordId())
.text(errorType.getText())
.validValue(errorType.getValidValue())
.build();
errorsBuilder.add(xmlError);
}
return errorsBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Invoice440ToCrossVersionModelTool.java | 1 |
请完成以下Java代码 | public InvoicesView getByIdOrNull(final ViewId invoicesViewId)
{
final ViewId paymentsViewId = toPaymentsViewId(invoicesViewId);
final PaymentsView paymentsView = paymentsViewFactory.getByIdOrNull(paymentsViewId);
return paymentsView != null
? paymentsView.getInvoicesView()
: null;
}
private static ViewId toPaymentsViewId(final ViewId invoicesViewId)
{
return invoicesViewId.withWindowId(PaymentsViewFactory.WINDOW_ID);
}
@Override
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
}
@Override | public Stream<IView> streamAllViews()
{
return paymentsViewFactory.streamAllViews()
.map(PaymentsView::cast)
.map(PaymentsView::getInvoicesView);
}
@Override
public void invalidateView(final ViewId invoicesViewId)
{
final InvoicesView invoicesView = getByIdOrNull(invoicesViewId);
if (invoicesView != null)
{
invoicesView.invalidateAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesViewFactory.java | 1 |
请完成以下Java代码 | public Author addBook(Book book) {
this.books.add(book);
book.setAuthor(this);
return this;
}
public Author removeBook(Book book) {
book.setAuthor(null);
this.books.remove(book);
return this;
}
public Long getId() {
return id;
}
public Author id(Long id) {
this.id = id;
return this;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Author name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public Author genre(String genre) {
this.genre = genre;
return this;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public Author age(int age) {
this.age = age;
return this; | }
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
public Author books(List<Book> books) {
this.books = books;
return this;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootFluentApiAdditionalMethods\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public List<Comment> findCommentsByType(String type) {
return getDbSqlSession().selectList("selectCommentsByType", type);
}
@Override
@SuppressWarnings("unchecked")
public List<Event> findEventsByTaskId(String taskId) {
return getDbSqlSession().selectList("selectEventsByTaskId", taskId);
}
@Override
@SuppressWarnings("unchecked")
public List<Event> findEventsByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectEventsByProcessInstanceId", processInstanceId);
}
@Override
public void deleteCommentsByTaskId(String taskId) {
getDbSqlSession().delete("deleteCommentsByTaskId", taskId, CommentEntityImpl.class);
}
@Override
public void deleteCommentsByProcessInstanceId(String processInstanceId) {
getDbSqlSession().delete("deleteCommentsByProcessInstanceId", processInstanceId, CommentEntityImpl.class);
}
@Override
@SuppressWarnings("unchecked")
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectCommentsByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("processInstanceId", processInstanceId); | params.put("type", type);
return getDbSqlSession().selectListWithRawParameter(
"selectCommentsByProcessInstanceIdAndType",
params,
0,
Integer.MAX_VALUE
);
}
@Override
public Comment findComment(String commentId) {
return findById(commentId);
}
@Override
public Event findEvent(String commentId) {
return findById(commentId);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisCommentDataManager.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("LU", luHU)
.add("TU", tuHU)
.add("VHU", vhu)
.toString();
}
public I_M_HU getM_TU_HU()
{
return tuHU;
} | public I_M_HU getM_LU_HU()
{
return luHU;
}
public I_M_HU getVHU()
{
return vhu;
}
public I_M_HU getTopLevelHU()
{
return CoalesceUtil.coalesce(luHU, tuHU, vhu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\LUTUCUPair.java | 1 |
请完成以下Java代码 | public I_AD_PrinterHW_Calibration retrieveCalibration(final I_AD_PrinterHW_MediaSize hwMediaSize, final I_AD_PrinterHW_MediaTray hwTray)
{
Check.assume(hwMediaSize != null, "Param 'hwMediaSize' is not null");
Check.assume(hwTray != null, "Param 'hwTray' is not null");
final Properties ctx = InterfaceWrapperHelper.getCtx(hwMediaSize);
final String trxName = InterfaceWrapperHelper.getTrxName(hwMediaSize);
return new Query(ctx, I_AD_PrinterHW_Calibration.Table_Name, I_AD_PrinterHW_Calibration.COLUMNNAME_AD_PrinterHW_MediaSize_ID + "=? AND "
+ I_AD_PrinterHW_Calibration.COLUMNNAME_AD_PrinterHW_MediaTray_ID + "=?", trxName)
.setParameters(hwMediaSize.getAD_PrinterHW_MediaSize_ID(), hwTray.getAD_PrinterHW_MediaTray_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.firstOnly(I_AD_PrinterHW_Calibration.class);
}
@Override
public List<I_AD_Printer> retrievePrinters(final Properties ctx, final int adOrgId) | {
final int adClientId = Env.getAD_Client_ID(ctx);
final String whereClause = I_AD_Printer.COLUMNNAME_AD_Client_ID + " IN (0, ?)"
+ " AND " + I_AD_Printer.COLUMNNAME_AD_Org_ID + " IN (0, ?)";
return new Query(ctx, I_AD_Printer.Table_Name, whereClause, ITrx.TRXNAME_None)
.setParameters(adClientId, adOrgId)
.setOnlyActiveRecords(true)
.setOrderBy(
I_AD_Printer.COLUMNNAME_AD_Client_ID + " DESC"
+ ", " + I_AD_Printer.COLUMNNAME_AD_Org_ID + " DESC"
+ ", " + I_AD_Printer.COLUMNNAME_PrinterName)
.list(I_AD_Printer.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingDAO.java | 1 |
请完成以下Java代码 | 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 Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override | public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelection.java | 1 |
请完成以下Java代码 | public List<DbOperation> addRemovalTimeToByteArraysByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
// Make individual statements for each entity type that references byte arrays.
// This can lead to query plans that involve less aggressive locking by databases (e.g. DB2).
// See CAM-10360 for reference.
List<DbOperation> operations = new ArrayList<>();
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateVariableByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateDecisionInputsByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateDecisionOutputsByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateJobLogByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateExternalTaskLogByteArraysByProcessInstanceId", parameters)); | operations.add(getDbEntityManager()
.updatePreserveOrder(ByteArrayEntity.class, "updateAttachmentByteArraysByProcessInstanceId", parameters));
return operations;
}
public DbOperation deleteByteArraysByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(ByteArrayEntity.class, "deleteByteArraysByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RevolutExportService
{
private static final String EXPORT_FILE_NAME_TEMPLATE = "Revolut_Export_:C_PaySelection_ID:_:timestamp.csv";
private static final String EXPORT_ID_PLACEHOLDER = ":C_PaySelection_ID:";
private static final String TIMESTAMP_PLACEHOLDER = ":timestamp";
private static final String CSV_FORMAT = "text/csv";
private final ICountryDAO countryDAO = Services.get(ICountryDAO.class);
private final RevolutExportRepo revolutExportRepo;
public RevolutExportService(@NonNull final RevolutExportRepo revolutExportRepo)
{
this.revolutExportRepo = revolutExportRepo;
}
@NonNull
public List<RevolutPaymentExport> saveAll(@NonNull final List<RevolutPaymentExport> request)
{
return revolutExportRepo.saveAll(request);
}
@NonNull
public ReportResultData exportToCsv(
@NonNull final PaySelectionId paySelectionId,
@NonNull final List<RevolutPaymentExport> exportList)
{
final StringBuilder csvBuilder = new StringBuilder(RevolutExportCsvRow.getCSVHeader());
exportList.stream()
.map(RevolutExportCsvRow::new)
.map(row -> row.toCSVRow(countryDAO))
.forEach(row -> csvBuilder.append("\n").append(row)); | return buildResult(csvBuilder.toString(), paySelectionId);
}
@NonNull
private ReportResultData buildResult(
@NonNull final String fileData,
@NonNull final PaySelectionId paySelectionId)
{
final byte[] fileDataBytes = fileData.getBytes(StandardCharsets.UTF_8);
return ReportResultData.builder()
.reportData(new ByteArrayResource(fileDataBytes))
.reportFilename(EXPORT_FILE_NAME_TEMPLATE
.replace(EXPORT_ID_PLACEHOLDER, String.valueOf(paySelectionId.getRepoId()))
.replace(TIMESTAMP_PLACEHOLDER, String.valueOf(System.currentTimeMillis())))
.reportContentType(CSV_FORMAT)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\RevolutExportService.java | 2 |
请完成以下Java代码 | public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0, j = 0;
while ((i + patternSize) <= textSize) {
j = patternSize - 1;
while (text[i + j] == pattern[j]) {
j--;
if (j < 0)
return i;
}
i++;
}
return -1;
}
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
int shift[] = new int[256];
for (int k = 0; k < 256; k++) {
shift[k] = pattern.length;
}
for (int k = 0; k < pattern.length - 1; k++) { | shift[pattern[k]] = pattern.length - 1 - k;
}
int i = 0, j = 0;
while ((i + pattern.length) <= text.length) {
j = pattern.length - 1;
while (text[i + j] == pattern[j]) {
j -= 1;
if (j < 0)
return i;
}
i = i + shift[text[i + pattern.length - 1]];
}
return -1;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\textsearch\TextSearchAlgorithms.java | 1 |
请完成以下Java代码 | public ScriptEngine getScriptEngineForName(String name, boolean cache) {
return getProcessApplicationScriptEnvironment().getScriptEngineForName(name, cache);
}
/**
* see {@link ProcessApplicationScriptEnvironment#getEnvironmentScripts()}
*/
public Map<String, List<ExecutableScript>> getEnvironmentScripts() {
return getProcessApplicationScriptEnvironment().getEnvironmentScripts();
}
protected ProcessApplicationScriptEnvironment getProcessApplicationScriptEnvironment() {
if (processApplicationScriptEnvironment == null) {
synchronized (this) {
if (processApplicationScriptEnvironment == null) {
processApplicationScriptEnvironment = new ProcessApplicationScriptEnvironment(this);
}
}
}
return processApplicationScriptEnvironment;
}
public VariableSerializers getVariableSerializers() {
return variableSerializers;
}
public void setVariableSerializers(VariableSerializers variableSerializers) {
this.variableSerializers = variableSerializers; | }
/**
* <p>Provides the default Process Engine name to deploy to, if no Process Engine
* was defined in <code>processes.xml</code>.</p>
*
* @return the default deploy-to Process Engine name.
* The default value is "default".
*/
public String getDefaultDeployToEngineName() {
return defaultDeployToEngineName;
}
/**
* <p>Programmatically set the name of the Process Engine to deploy to if no Process Engine
* is defined in <code>processes.xml</code>. This allows to circumvent the "default" Process
* Engine name and set a custom one.</p>
*
* @param defaultDeployToEngineName
*/
protected void setDefaultDeployToEngineName(String defaultDeployToEngineName) {
this.defaultDeployToEngineName = defaultDeployToEngineName;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\AbstractProcessApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(sessionRepositoryInterceptor());
}
@Override
public final void registerStompEndpoints(StompEndpointRegistry registry) {
if (registry instanceof WebMvcStompEndpointRegistry) {
WebMvcStompEndpointRegistry mvcRegistry = (WebMvcStompEndpointRegistry) registry;
configureStompEndpoints(new SessionStompEndpointRegistry(mvcRegistry, sessionRepositoryInterceptor()));
}
}
/**
* Register STOMP endpoints mapping each to a specific URL and (optionally) enabling
* and configuring SockJS fallback options with a
* {@link SessionRepositoryMessageInterceptor} automatically added as an interceptor.
* @param registry the {@link StompEndpointRegistry} which automatically has a
* {@link SessionRepositoryMessageInterceptor} added to it.
*/
protected abstract void configureStompEndpoints(StompEndpointRegistry registry);
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
registration.addDecoratorFactory(wsConnectHandlerDecoratorFactory());
}
@Bean
public static WebSocketRegistryListener webSocketRegistryListener() {
return new WebSocketRegistryListener();
}
@Bean
public WebSocketConnectHandlerDecoratorFactory wsConnectHandlerDecoratorFactory() {
return new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher);
}
@Bean
@SuppressWarnings("unchecked")
public SessionRepositoryMessageInterceptor<S> sessionRepositoryInterceptor() {
return new SessionRepositoryMessageInterceptor<>(this.sessionRepository);
}
/**
* A {@link StompEndpointRegistry} that applies {@link HandshakeInterceptor}.
*/
static class SessionStompEndpointRegistry implements StompEndpointRegistry {
private final WebMvcStompEndpointRegistry registry;
private final HandshakeInterceptor interceptor;
SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) {
this.registry = registry;
this.interceptor = interceptor;
}
@Override
public StompWebSocketEndpointRegistration addEndpoint(String... paths) {
StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths);
endpoints.addInterceptors(this.interceptor); | return endpoints;
}
@Override
public void setOrder(int order) {
this.registry.setOrder(order);
}
@Override
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
this.registry.setUrlPathHelper(urlPathHelper);
}
@Override
public WebMvcStompEndpointRegistry setErrorHandler(StompSubProtocolErrorHandler errorHandler) {
return this.registry.setErrorHandler(errorHandler);
}
@Override
public WebMvcStompEndpointRegistry setPreserveReceiveOrder(boolean preserveReceiveOrder) {
return this.registry.setPreserveReceiveOrder(preserveReceiveOrder);
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\config\annotation\AbstractSessionWebSocketMessageBrokerConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RevolutPaymentExport
{
@Nullable
RevolutPaymentExportId revolutPaymentExportId;
@NonNull
TableRecordReference recordReference;
@NonNull
String name;
@NonNull
OrgId orgId;
@NonNull
Amount amount;
@NonNull
RecipientType recipientType;
@Nullable
String accountNo;
@Nullable
String routingNo;
@Nullable
String IBAN;
@Nullable
String SwiftCode;
@Nullable
String paymentReference;
@Nullable
String regionName;
@Nullable
String addressLine1;
@Nullable
String addressLine2;
@Nullable
String city;
@Nullable
String postalCode;
@Nullable
CountryId recipientCountryId;
@Nullable
CountryId recipientBankCountryId;
@Builder
RevolutPaymentExport( | @Nullable final RevolutPaymentExportId revolutPaymentExportId,
@NonNull final TableRecordReference recordReference,
@NonNull final String name,
@NonNull final OrgId orgId,
@NonNull final Amount amount,
@NonNull final RecipientType recipientType,
@Nullable final CountryId recipientBankCountryId,
@Nullable final String accountNo,
@Nullable final String routingNo,
@Nullable final String IBAN,
@Nullable final String SwiftCode,
@Nullable final String paymentReference,
@Nullable final String regionName,
@Nullable final String addressLine1,
@Nullable final String addressLine2,
@Nullable final String city,
@Nullable final String postalCode,
@Nullable final CountryId recipientCountryId)
{
if (IBAN == null && accountNo == null)
{
throw new AdempiereException("No IBAN or accountNo found for paySelectionLine")
.appendParametersToMessage()
.setParameter("paySelectionLineId", recordReference.getRecord_ID());
}
this.revolutPaymentExportId = revolutPaymentExportId;
this.recordReference = recordReference;
this.name = name;
this.orgId = orgId;
this.amount = amount;
this.accountNo = accountNo;
this.routingNo = routingNo;
this.IBAN = IBAN;
this.SwiftCode = SwiftCode;
this.paymentReference = paymentReference;
this.regionName = regionName;
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.city = city;
this.postalCode = postalCode;
this.recipientCountryId = recipientCountryId;
this.recipientBankCountryId = recipientBankCountryId;
this.recipientType = recipientType;
}
@NonNull
public RevolutPaymentExportId getIdNotNull()
{
if (revolutPaymentExportId == null)
{
throw new AdempiereException("getIdNotNull() should be called only for already persisted RevolutExport record!")
.appendParametersToMessage()
.setParameter("RevolutPaymentExportId", this);
}
return revolutPaymentExportId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\model\RevolutPaymentExport.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OrderResponsePackageItem
{
@JsonProperty("requestId")
OrderCreateRequestPackageItemId requestId;
@JsonProperty("pzn")
PZN pzn;
@JsonProperty("qty")
Quantity qty;
@JsonProperty("deliverySpecifications")
DeliverySpecifications deliverySpecifications;
@JsonProperty("parts")
List<OrderResponsePackageItemPart> parts;
@JsonProperty("substitution")
OrderResponsePackageItemSubstitution substitution;
@JsonProperty("olCandId")
int olCandId;
@JsonProperty("purchaseCandidateId")
@JsonInclude(JsonInclude.Include.NON_NULL) | MSV3PurchaseCandidateId purchaseCandidateId;
@Builder
@JsonCreator
private OrderResponsePackageItem(
@JsonProperty("requestId") @NonNull final OrderCreateRequestPackageItemId requestId,
@JsonProperty("pzn") @NonNull final PZN pzn,
@JsonProperty("qty") @NonNull final Quantity qty,
@JsonProperty("deliverySpecifications") @NonNull final DeliverySpecifications deliverySpecifications,
@JsonProperty("parts") @NonNull @Singular List<OrderResponsePackageItemPart> parts,
@JsonProperty("substitution") final OrderResponsePackageItemSubstitution substitution,
@JsonProperty("olCandId") int olCandId,
@JsonProperty("purchaseCandidateId") MSV3PurchaseCandidateId purchaseCandidateId)
{
this.requestId = requestId;
this.pzn = pzn;
this.qty = qty;
this.deliverySpecifications = deliverySpecifications;
this.parts = ImmutableList.copyOf(parts);
this.substitution = substitution;
this.olCandId = olCandId;
this.purchaseCandidateId = purchaseCandidateId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderResponsePackageItem.java | 2 |
请完成以下Java代码 | public int getPA_ColorSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ColorSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Goal.
@param PA_Goal_ID
Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Goal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Goal getPA_GoalParent() throws RuntimeException
{
return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name)
.getPO(getPA_GoalParent_ID(), get_TrxName()); }
/** Set Parent Goal.
@param PA_GoalParent_ID
Parent Goal
*/
public void setPA_GoalParent_ID (int PA_GoalParent_ID)
{
if (PA_GoalParent_ID < 1)
set_Value (COLUMNNAME_PA_GoalParent_ID, null);
else
set_Value (COLUMNNAME_PA_GoalParent_ID, Integer.valueOf(PA_GoalParent_ID));
}
/** Get Parent Goal.
@return Parent Goal
*/
public int getPA_GoalParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalParent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_Value (COLUMNNAME_PA_Measure_ID, null); | else
set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java | 1 |
请完成以下Java代码 | public final String getStatusCode() {
return statusCode;
}
/**
* @param argStatusCode
* the statusCode to set
*/
public final void setStatusCode(final String argStatusCode) {
this.statusCode = argStatusCode;
}
/**
* @return the message
*/
public final String getMessage() {
return message;
}
/**
* @param argMessage
* the message to set
*/
public final void setMessage(final String argMessage) {
this.message = argMessage;
}
/**
* @return the navTabId
*/
public final String getNavTabId() {
return navTabId;
}
/**
* @param argNavTabId
* the navTabId to set
*/
public final void setNavTabId(final String argNavTabId) {
this.navTabId = argNavTabId; | }
/**
* @return the callbackType
*/
public final String getCallbackType() {
return callbackType;
}
/**
* @param argCallbackType
* the callbackType to set
*/
public final void setCallbackType(final String argCallbackType) {
this.callbackType = argCallbackType;
}
/**
* @return the forwardUrl
*/
public final String getForwardUrl() {
return forwardUrl;
}
/**
* @param argForwardUrl
* the forwardUrl to set
*/
public final void setForwardUrl(final String argForwardUrl) {
this.forwardUrl = argForwardUrl;
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\dwz\DwzAjax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RpUserInfo getDataByMerchentNo(String merchantNo) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userNo", merchantNo);
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpUserInfoDao.getBy(paramMap);
}
/**
* 根据手机号获取商户信息
* @param mobile
* @return
*/
@Override
public RpUserInfo getDataByMobile(String mobile){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("mobile", mobile); | paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpUserInfoDao.getBy(paramMap);
}
/**
* 获取所有用户
* @return
*/
@Override
public List<RpUserInfo> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpUserInfoDao.listBy(paramMap);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpUserInfoServiceImpl.java | 2 |
请完成以下Java代码 | public Quantity addTo(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.add(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.add(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public Quantity subtractFrom(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.subtract(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.subtract(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
} | }
public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qtyConv = qtyConverter.apply(qty);
if (qtyConv.equals(qty))
{
return this;
}
return toBuilder().qty(qtyConv).build();
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java | 1 |
请完成以下Java代码 | public class WeightGrossAttributeValueCallout extends AbstractWeightAttributeValueCallout
{
/**
* Recalculates the net weight based on the current values of the given <code>attributeSet</code>'s Weight Gross and Weight Tare values.
*
* @see org.adempiere.mm.attributes.api.impl.AttributeSetCalloutExecutor#executeCallouts(IAttributeSet, I_M_Attribute, Object, Object) the implementation
*/
@Override
public void onValueChanged0(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
recalculateWeightNet(attributeSet);
}
/**
* @return {@link BigDecimal#ZERO}
*/
@Override
public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute,
@Nullable final Object valueInitialDefault)
{
// we don't support a value different from null
Check.assumeNull(valueInitialDefault, "valueInitialDefault null");
return BigDecimal.ZERO;
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number;
}
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return true;
}
@Override
public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return BigDecimal.ZERO;
}
@Override
protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
final IWeightable weightable = getWeightableOrNull(attributeSet);
if (weightable == null)
{
return false; | }
final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue());
if (!weightable.isWeightGrossAttribute(attributeCode))
{
return false;
}
if (!weightable.hasWeightGross())
{
return false;
}
if (!weightable.hasWeightTare())
{
return false;
}
if (!(attributeValueContext instanceof IHUAttributePropagationContext))
{
return false;
}
final IHUAttributePropagationContext huAttributePropagationContext = (IHUAttributePropagationContext)attributeValueContext;
final AttributeCode attr_WeightNet = weightable.getWeightNetAttribute();
if (huAttributePropagationContext.isExternalInput()
&& huAttributePropagationContext.isValueUpdatedBefore(attr_WeightNet))
{
//
// Net weight was set externally. Do not modify it.
return false;
}
return true;
}
@Override
public boolean isDisplayedUI(@NonNull final IAttributeSet attributeSet, @NonNull final I_M_Attribute attribute)
{
return isLUorTUorTopLevelVHU(attributeSet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightGrossAttributeValueCallout.java | 1 |
请完成以下Java代码 | public @NonNull WFNodeAction getAction() {return node.getAction();}
public @NonNull ITranslatableString getName() {return node.getName();}
@NonNull
public ITranslatableString getDescription() {return node.getDescription();}
@NonNull
public ITranslatableString getHelp() {return node.getHelp();}
public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();}
public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();}
public void setXPosition(final int x) { this.xPosition = x; }
public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();} | public void setYPosition(final int y) { this.yPosition = y; }
public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId)
{
return node.getTransitions(clientId)
.stream()
.map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition))
.collect(ImmutableList.toImmutableList());
}
public void saveEx()
{
workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder()
.nodeId(getId())
.xPosition(getXPosition())
.yPosition(getYPosition())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java | 1 |
请完成以下Java代码 | public class ActivateProcessDefinitionCmd extends AbstractSetProcessDefinitionStateCmd {
public ActivateProcessDefinitionCmd(UpdateProcessDefinitionSuspensionStateBuilderImpl builder) {
super(builder);
}
@Override
protected SuspensionState getNewSuspensionState() {
return SuspensionState.ACTIVE;
}
@Override
protected String getDelayedExecutionJobHandlerType() {
return TimerActivateProcessDefinitionHandler.TYPE;
} | @Override
protected AbstractSetJobDefinitionStateCmd getSetJobDefinitionStateCmd(UpdateJobDefinitionSuspensionStateBuilderImpl jobDefinitionSuspensionStateBuilder) {
return new ActivateJobDefinitionCmd(jobDefinitionSuspensionStateBuilder);
}
@Override
protected ActivateProcessInstanceCmd getNextCommand(UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder) {
return new ActivateProcessInstanceCmd(processInstanceCommandBuilder);
}
@Override
protected String getLogEntryOperation() {
return UserOperationLogEntry.OPERATION_TYPE_ACTIVATE_PROCESS_DEFINITION;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivateProcessDefinitionCmd.java | 1 |
请完成以下Java代码 | public void execute(Runnable command) {
executor.execute(command);
}
public void showExecutorInfo() {
LOG.info("NotifyExecutor Info : corePoolSize = " + corePoolSize +
" | maxPoolSize = " + maxPoolSize + " | workQueueSize = " +
workQueueSize + " | taskCount = " + executor.getTaskCount() +
" | activeCount = " + executor.getActiveCount() +
" | completedTaskCount = " + executor.getCompletedTaskCount());
}
public void setNotifyRadio(int notifyRadio) {
this.notifyRadio = notifyRadio;
}
public void setWorkQueueSize(int workQueueSize) { | this.workQueueSize = workQueueSize;
}
public void setKeepAliveTime(long keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
} | repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\utils\SettThreadPoolExecutor.java | 1 |
请完成以下Java代码 | public abstract class AbstractTestContainerTests {
private static final Log LOG = LogFactory.getLog(AbstractTestContainerTests.class);
protected static final @Nullable RabbitMQContainer RABBITMQ;
static {
if (System.getProperty("spring.rabbit.use.local.server") == null
&& System.getenv("SPRING_RABBIT_USE_LOCAL_SERVER") == null) {
String image = "rabbitmq:management";
String cache = System.getenv().get("IMAGE_CACHE");
if (cache != null) {
image = cache + image;
}
DockerImageName imageName = DockerImageName.parse(image)
.asCompatibleSubstituteFor("rabbitmq");
RABBITMQ = new RabbitMQContainer(imageName)
.withExposedPorts(5672, 15672, 5552)
.withStartupTimeout(Duration.ofMinutes(2));
}
else {
RABBITMQ = null;
}
}
@BeforeAll
static void startContainer() throws IOException, InterruptedException {
if (RABBITMQ != null) {
RABBITMQ.start();
RABBITMQ.execInContainer("rabbitmq-plugins", "enable", "rabbitmq_stream");
}
else {
LOG.info("The local RabbitMQ broker will be used instead of Testcontainers.");
}
} | public static int amqpPort() {
return RABBITMQ != null ? RABBITMQ.getAmqpPort() : 5672;
}
public static int managementPort() {
return RABBITMQ != null ? RABBITMQ.getMappedPort(15672) : 15672;
}
public static int streamPort() {
return RABBITMQ != null ? RABBITMQ.getMappedPort(5552) : 5552;
}
public static String restUri() {
return RABBITMQ != null ? RABBITMQ.getHttpUrl() + "/api/" : "http://localhost:" + managementPort() + "/api/";
}
} | repos\spring-amqp-main\spring-rabbit-junit\src\main\java\org\springframework\amqp\rabbit\junit\AbstractTestContainerTests.java | 1 |
请完成以下Java代码 | public class AddIdentityLinkForCaseDefinitionCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected CmmnEngineConfiguration cmmnEngineConfiguration;
protected String caseDefinitionId;
protected String userId;
protected String groupId;
public AddIdentityLinkForCaseDefinitionCmd(String caseDefinitionId, String userId, String groupId,
CmmnEngineConfiguration cmmnEngineConfiguration) {
validateParams(userId, groupId, caseDefinitionId);
this.caseDefinitionId = caseDefinitionId;
this.userId = userId;
this.groupId = groupId;
this.cmmnEngineConfiguration = cmmnEngineConfiguration;
}
protected void validateParams(String userId, String groupId, String caseDefinitionId) {
if (caseDefinitionId == null) {
throw new FlowableIllegalArgumentException("caseDefinitionId is null"); | }
if (userId == null && groupId == null) {
throw new FlowableIllegalArgumentException("userId and groupId cannot both be null");
}
}
@Override
public Void execute(CommandContext commandContext) {
CaseDefinitionEntity caseDefinition = cmmnEngineConfiguration.getCaseDefinitionEntityManager().findById(caseDefinitionId);
if (caseDefinition == null) {
throw new FlowableObjectNotFoundException("Cannot find case definition with id " + caseDefinitionId, CaseDefinition.class);
}
IdentityLinkEntity identityLinkEntity = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.createScopeDefinitionIdentityLink(caseDefinition.getId(), ScopeTypes.CMMN, userId, groupId);
caseDefinition.getIdentityLinks().add(identityLinkEntity);
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AddIdentityLinkForCaseDefinitionCmd.java | 1 |
请完成以下Java代码 | public void showJSCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>{@code
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>}
* </pre>
*
*/
public void showHTMLCodeSnippetUsingJavadoc() {
// do nothing
} | /**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>
* </pre>
*
*/
public void showHTMLCodeSnippetIssueUsingJavadoc() {
// do nothing
}
} | repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\CodeSnippetFormatting.java | 1 |
请完成以下Java代码 | public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isResend() { | return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public Person getSender() {
return sender;
}
public void setSender(Person sender) {
this.sender = sender;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\json\CustomJsonProperties.java | 1 |
请完成以下Java代码 | public Instant getLastAccessedTime() {
return this.lastAccessedTime;
}
@Override
public void setMaxInactiveInterval(Duration interval) {
this.maxInactiveInterval = interval;
}
@Override
public Duration getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
@Override
public boolean isExpired() {
return isExpired(Instant.now());
}
boolean isExpired(Instant now) {
if (this.maxInactiveInterval.isNegative()) {
return false;
}
return now.minus(this.maxInactiveInterval).compareTo(this.lastAccessedTime) >= 0;
}
@Override
@SuppressWarnings("unchecked")
public <T> T getAttribute(String attributeName) {
return (T) this.sessionAttrs.get(attributeName);
}
@Override
public Set<String> getAttributeNames() {
return new HashSet<>(this.sessionAttrs.keySet());
}
@Override
public void setAttribute(String attributeName, Object attributeValue) {
if (attributeValue == null) {
removeAttribute(attributeName);
}
else {
this.sessionAttrs.put(attributeName, attributeValue);
}
}
@Override
public void removeAttribute(String attributeName) {
this.sessionAttrs.remove(attributeName);
} | /**
* Sets the time that this {@link Session} was created. The default is when the
* {@link Session} was instantiated.
* @param creationTime the time that this {@link Session} was created.
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
/**
* Sets the identifier for this {@link Session}. The id should be a secure random
* generated value to prevent malicious users from guessing this value. The default is
* a secure random generated identifier.
* @param id the identifier for this session.
*/
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Session && this.id.equals(((Session) obj).getId());
}
@Override
public int hashCode() {
return this.id.hashCode();
}
private static String generateId() {
return UUID.randomUUID().toString();
}
/**
* Sets the {@link SessionIdGenerator} to use when generating a new session id.
* @param sessionIdGenerator the {@link SessionIdGenerator} to use.
* @since 3.2
*/
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
private static final long serialVersionUID = 7160779239673823561L;
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java | 1 |
请完成以下Java代码 | public void doUpdateAfterFirstPass(
final Properties ctx,
final IShipmentSchedulesDuringUpdate candidates)
{
for (final DeliveryGroupCandidate groupCandidate : candidates.getCandidates())
{
for (final DeliveryLineCandidate lineCandidate : groupCandidate.getLines())
{
if (lineCandidate.isDiscarded())
{
// this line won't be delivered anyways. Nothing to do
continue;
}
handleOnlyOneOpenInv(ctx, candidates, lineCandidate);
}
}
}
private void handleOnlyOneOpenInv(final Properties ctx,
final IShipmentSchedulesDuringUpdate candidates, | final DeliveryLineCandidate lineCandidate)
{
try (final MDCCloseable mdcClosable = ShipmentSchedulesMDC.putShipmentScheduleId(lineCandidate.getShipmentScheduleId()))
{
final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(lineCandidate.getBillBPartnerId());
final String creditStatus = I_C_BPartner.SO_CREDITSTATUS_ONE_OPEN_INVOICE;
if (creditStatus.equals(stats.getSOCreditStatus()))
{
final BigDecimal soCreditUsed = stats.getSOCreditUsed();
if (soCreditUsed.signum() > 0)
{
logger.debug("Discard lineCandidate because of an existing open invoice");
candidates.addStatusInfo(lineCandidate, Services.get(IMsgBL.class).getMsg(ctx, MSG_OPEN_INVOICE_1P, new Object[] { soCreditUsed }));
lineCandidate.setDiscarded();
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\OnlyOneOpenInvoiceCandProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "createdBy", cascade = CascadeType.PERSIST)
private List<Playlist> playlists;
@OneToMany(mappedBy = "user", cascade = CascadeType.PERSIST)
@OrderColumn(name = "arrangement_index")
private List<FavoriteSong> favoriteSongs;
@ManyToMany
private Set<Album> followingAlbums;
User(String name) {
this.name = name;
this.playlists = new ArrayList<>();
this.favoriteSongs = new ArrayList<>();
this.followingAlbums = new HashSet<>();
}
void followAlbum(Album album) {
this.followingAlbums.add(album);
}
void createPlaylist(String name) {
this.playlists.add(new Playlist(name, this)); | }
void addSongToFavorites(Song song) {
this.favoriteSongs.add(new FavoriteSong(song, this));
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected User() {
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\multiplebagfetchexception\User.java | 2 |
请完成以下Java代码 | public Schema getSchema() {
return aliased() ? null : Public.PUBLIC;
}
@Override
public UniqueKey<StoreRecord> getPrimaryKey() {
return Keys.STORE_PKEY;
}
@Override
public Store as(String alias) {
return new Store(DSL.name(alias), this);
}
@Override
public Store as(Name alias) {
return new Store(alias, this);
}
@Override
public Store as(Table<?> alias) {
return new Store(alias.getQualifiedName(), this);
}
/**
* Rename this table
*/
@Override
public Store rename(String name) {
return new Store(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Store rename(Name name) {
return new Store(name, null);
}
/**
* Rename this table
*/
@Override
public Store rename(Table<?> name) {
return new Store(name.getQualifiedName(), null);
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Condition condition) {
return new Store(getQualifiedName(), aliased() ? this : null, null, condition);
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Collection<? extends Condition> conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Condition... conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Field<Boolean> condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table | */
@Override
@PlainSQL
public Store where(SQL condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, Object... binds) {
return where(DSL.condition(condition, binds));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, QueryPart... parts) {
return where(DSL.condition(condition, parts));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereExists(Select<?> select) {
return where(DSL.exists(select));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereNotExists(Select<?> select) {
return where(DSL.notExists(select));
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Store.java | 1 |
请完成以下Java代码 | public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds)
{
return huEditorRepo.buildSqlWhereClause(getDefaultSelection(), rowIds);
}
public static boolean isHighVolume(final DocumentFilterList stickyFilters)
{
final HUIdsFilterData huIdsFilterData = HUIdsFilterHelper.extractFilterData(stickyFilters).orElse(null);
return huIdsFilterData == null || huIdsFilterData.isPossibleHighVolume(HIGHVOLUME_THRESHOLD);
}
private static class DefaultSelectionHolder
{
private final HUEditorViewRepository huEditorViewRepository;
private final ViewEvaluationCtx viewEvaluationCtx;
private final ViewId viewId;
private final DocumentFilterList filters;
private final DocumentQueryOrderByList orderBys;
private final SqlDocumentFilterConverterContext filterConverterCtx;
private final SynchronizedMutable<ViewRowIdsOrderedSelection> defaultSelectionRef;
@Builder
private DefaultSelectionHolder(
@NonNull final HUEditorViewRepository huEditorViewRepository,
final ViewEvaluationCtx viewEvaluationCtx,
final ViewId viewId,
@NonNull final DocumentFilterList filters,
@Nullable final DocumentQueryOrderByList orderBys,
final SqlDocumentFilterConverterContext filterConverterCtx)
{
this.huEditorViewRepository = huEditorViewRepository;
this.viewEvaluationCtx = viewEvaluationCtx;
this.viewId = viewId;
this.filters = filters;
this.orderBys = orderBys;
this.filterConverterCtx = filterConverterCtx;
defaultSelectionRef = Mutables.synchronizedMutable(create());
}
private ViewRowIdsOrderedSelection create()
{
return huEditorViewRepository.createSelection(viewEvaluationCtx, viewId, filters, orderBys, filterConverterCtx);
} | public ViewRowIdsOrderedSelection get()
{
return defaultSelectionRef.computeIfNull(this::create);
}
/**
* @return true if selection was really changed
*/
public boolean change(@NonNull final UnaryOperator<ViewRowIdsOrderedSelection> mapper)
{
final ViewRowIdsOrderedSelection defaultSelectionOld = defaultSelectionRef.getValue();
defaultSelectionRef.computeIfNull(this::create); // make sure it's not null (might be null if it was invalidated)
final ViewRowIdsOrderedSelection defaultSelectionNew = defaultSelectionRef.compute(mapper);
return !ViewRowIdsOrderedSelection.equals(defaultSelectionOld, defaultSelectionNew);
}
public void delete()
{
defaultSelectionRef.computeIfNotNull(defaultSelection -> {
huEditorViewRepository.deleteSelection(defaultSelection);
return null;
});
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_HighVolume.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
else if (obj instanceof QuickInputPath)
{
final QuickInputPath other = (QuickInputPath)obj;
return Objects.equals(rootDocumentPath, other.rootDocumentPath)
&& Objects.equals(detailId, other.detailId)
&& Objects.equals(quickInputId, other.quickInputId);
}
else
{
return false;
}
} | public DocumentPath getRootDocumentPath()
{
return rootDocumentPath;
}
public DetailId getDetailId()
{
return detailId;
}
public DocumentId getQuickInputId()
{
return quickInputId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputPath.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
@Override
public String getEventName() {
return eventName;
}
@Override
public String getProcessInstanceBusinessKey() {
return processInstanceBusinessKey;
}
@Override
public String getProcessInstanceBusinessStatus() {
return processInstanceBusinessStatus;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public String getParentId() {
return parentId;
}
@Override
public String getSuperExecutionId() {
return superExecutionId;
}
@Override
public String getCurrentActivityId() {
return currentActivityId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
@Override
public boolean isActive() {
return active;
} | @Override
public boolean isEnded() {
return ended;
}
@Override
public boolean isConcurrent() {
return concurrent;
}
@Override
public boolean isProcessInstanceType() {
return processInstanceType;
}
@Override
public boolean isScope() {
return scope;
}
@Override
public boolean isMultiInstanceRoot() {
return multiInstanceRoot;
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("currentActivityId='" + currentActivityId + "'")
.add("processInstanceId='" + processInstanceId + "'")
.add("processDefinitionId='" + processDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java | 1 |
请完成以下Java代码 | private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String breaksTableName = I_M_DiscountSchemaBreak.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(breaksTableName));
}
@Override
protected String doIt()
{
final IQueryFilter<I_M_DiscountSchemaBreak> queryFilter = getProcessInfo().getQueryFilterOrElse(null);
if (queryFilter == null)
{
throw new AdempiereException("@NoSelection@");
} | final boolean allowCopyToSameSchema = true;
final CopyDiscountSchemaBreaksRequest request = CopyDiscountSchemaBreaksRequest.builder()
.filter(queryFilter)
.pricingConditionsId(PricingConditionsId.ofRepoId(p_PricingConditionsId))
.productId(ProductId.ofRepoId(p_ProductId))
.allowCopyToSameSchema(allowCopyToSameSchema)
.direction(Direction.SourceTarget)
.build();
pricingConditionsRepo.copyDiscountSchemaBreaksWithProductId(request);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pricing\process\M_DiscountSchemaBreak_CopyToOtherSchema_Product.java | 1 |
请完成以下Java代码 | public final class SwingEventNotifierUI
{
public static final String NOTIFICATIONS_MaxDisplayed = "EventNotifier.MaxDisplayed";
public static final int NOTIFICATIONS_MaxDisplayed_Default = 10;
public static final String NOTIFICATIONS_AutoFadeAwayTimeMillis = "EventNotifier.AutoFadeAwayTimeMillis";
public static final int NOTIFICATIONS_AutoFadeAwayTimeMillis_Default = 15 * 1000; // 13sec
/** Defines the gap (in pixels) between last notification and screen bottom (see FRESH-441) */
public static final String NOTIFICATIONS_BottomGap = "EventNotifier.BottomGap";
public static final int NOTIFICATIONS_BottomGap_Default = 40;
public static final String ITEM_BackgroundColor = "EventNotifier.Item.Background";
public static final String ITEM_Border = "EventNotifier.Item.Border";
public static final String ITEM_SummaryText_Font = "EventNotifier.Item.SummaryText.Font";
public static final String ITEM_DetailText_Font = "EventNotifier.Item.DetailText.Font";
public static final String ITEM_TextColor = "EventNotifier.Item.TextColor";
public static final String ITEM_MinimumSize = "EventNotifier.Item.MinimumSize";
public static final String ITEM_MaximumSize = "EventNotifier.Item.MaximumSize";
//
public static final String ITEM_Button_Insets = "EventNotifier.Item.Button.Insets";
public static final String ITEM_Button_Border = "EventNotifier.Item.Button.Border";
public static final String ITEM_Button_Size = "EventNotifier.Item.Button.Dimension";
public static final Color COLOR_Transparent = new Color(0, 0, 0, 0);
public static final Object[] getUIDefaults()
{ | return new Object[] {
//
// Notifications settings
NOTIFICATIONS_MaxDisplayed, NOTIFICATIONS_MaxDisplayed_Default
, NOTIFICATIONS_AutoFadeAwayTimeMillis, NOTIFICATIONS_AutoFadeAwayTimeMillis_Default
, NOTIFICATIONS_BottomGap, NOTIFICATIONS_BottomGap_Default
//
// Item settings
, ITEM_BackgroundColor, AdempierePLAF.createActiveValueProxy(AdempiereLookAndFeel.MANDATORY_BG_KEY, Color.WHITE) // same as mandatory background color
, ITEM_Border, new BorderUIResource(BorderFactory.createLineBorder(Color.GRAY, 1))
, ITEM_SummaryText_Font, new FontUIResource("Serif", Font.BOLD, 12)
, ITEM_DetailText_Font, new FontUIResource("Serif", Font.PLAIN, 12)
, ITEM_TextColor, null
, ITEM_MinimumSize, new DimensionUIResource(230, 45)
, ITEM_MaximumSize, null
//
// Button settings (i.e. the close button)
, ITEM_Button_Insets, new InsetsUIResource(1, 4, 1, 4)
, ITEM_Button_Size, 20
, ITEM_Button_Border, new BorderUIResource(BorderFactory.createEmptyBorder())
};
}
private SwingEventNotifierUI()
{
super();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SwingEventNotifierUI.java | 1 |
请完成以下Java代码 | public Optional<PersonEntity> getById(int id) throws SQLException {
String query = "SELECT id, name, FROM persons WHERE id = '" + id + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
if (resultSet.first()) {
PersonEntity result = new PersonEntity(resultSet.getInt("id"),
resultSet.getString("name"));
return Optional.of(result);
} else {
return Optional.empty();
}
}
public void insert(PersonEntity personEntity) throws SQLException {
String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '"
+ personEntity.getName() + "')";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}
public void insert(List<PersonEntity> personEntities) throws SQLException {
for (PersonEntity personEntity : personEntities) {
insert(personEntity);
}
}
public void update(PersonEntity personEntity) throws SQLException {
String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = " | + personEntity.getId();
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}
public void deleteById(int id) throws SQLException {
String query = "DELETE FROM persons WHERE id = " + id;
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}
public List<PersonEntity> getAll() throws SQLException {
String query = "SELECT id, name, FROM persons";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
List<PersonEntity> result = new ArrayList<>();
while (resultSet.next()) {
result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name")));
}
return result;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\statmentVsPreparedstatment\StatementPersonDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private JsonAttachmentRequest getAttachmentRequest(
@NonNull final JsonBOM jsonBOM,
@NonNull final String basePathForExportDirectories)
{
final String filePath = jsonBOM.getAttachmentFilePath();
if (Check.isBlank(filePath))
{
return null;
}
final String bpartnerMetasfreshId = jsonBOM.getBPartnerMetasfreshId();
if (Check.isBlank(bpartnerMetasfreshId))
{
throw new RuntimeCamelException("Missing METASFRESHID! ARTNRID=" + jsonBOM.getProductId());
} | final JsonExternalReferenceTarget targetBPartner = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_BPARTNER, bpartnerMetasfreshId);
final JsonExternalReferenceTarget targetProduct = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_PRODUCT, ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId()));
final JsonAttachment attachment = JsonAttachmentUtil.createLocalFileJsonAttachment(basePathForExportDirectories, filePath);
return JsonAttachmentRequest.builder()
.targets(ImmutableList.of(targetBPartner, targetProduct))
.orgCode(getAuthOrgCode())
.attachment(attachment)
.build();
}
@NonNull
private String getAuthOrgCode()
{
return ((TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials()).getOrgCode();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\ProductsAttachFileProcessor.java | 2 |
请完成以下Java代码 | public class ApplicationRequestAuthorizer implements RequestAuthorizer {
@Override
public Authorization authorize(Map<String, String> parameters) {
Authentications authentications = Authentications.getCurrent();
if (authentications == null) {
// the user is not authenticated
// grant user anonymous access
return grantAnnonymous();
} else {
String engineName = parameters.get("engine");
String appName = parameters.get("app");
Authentication engineAuth = authentications.getAuthenticationForProcessEngine(engineName);
if (engineAuth == null) {
// the user is not authenticated
// grant user anonymous access
return grantAnnonymous();
}
// get process engine
ProcessEngine processEngine = Cockpit.getProcessEngine(engineName);
if (processEngine == null) {
// the process engine does not exist
// grant user anonymous access
return grantAnnonymous();
}
// check authorization
if (engineAuth instanceof UserAuthentication) {
UserAuthentication userAuth = (UserAuthentication) engineAuth; | if (userAuth.isAuthorizedForApp(appName)) {
return Authorization.granted(userAuth).forApplication(appName);
} else {
return Authorization.denied(userAuth).forApplication(appName);
}
}
}
// no auth granted
return Authorization.denied(Authentication.ANONYMOUS);
}
private Authorization grantAnnonymous() {
return Authorization.granted(Authentication.ANONYMOUS);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\ApplicationRequestAuthorizer.java | 1 |
请完成以下Java代码 | default void rejectIt(DocumentTableFields docFields)
{
throw new UnsupportedOperationException("The action RejectIt is not implemented by default");
}
default void voidIt(DocumentTableFields docFields)
{
throw new UnsupportedOperationException("The action VoidIt is not implemented by default");
}
default void unCloseIt(DocumentTableFields docFields)
{
throw new UnsupportedOperationException("The action UnCloseIt is not implemented by default");
}
default void reverseCorrectIt(DocumentTableFields docFields)
{
throw new UnsupportedOperationException("The action ReverseCorrectIt is not implemented by default");
}
default void reverseAccrualIt(DocumentTableFields docFields)
{ | throw new UnsupportedOperationException("The action ReverseAccrual It is not implemented by default");
}
default void closeIt(DocumentTableFields docFields)
{
docFields.setProcessed(true);
docFields.setDocAction(IDocument.ACTION_None);
}
default void reactivateIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException("Reactivate action is not supported");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentHandler.java | 1 |
请完成以下Java代码 | private void commit() {
int M_Product_ID = getM_Product_ID();
if (M_Product_ID <= 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_M_Product_ID);
String productStr = fProduct.getDisplay();
if (productStr == null)
productStr = "";
BigDecimal qty = getQtyOrdered();
if (qty == null || qty.signum() == 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_QtyOrdered);
//
MOrderLine line = new MOrderLine(order);
line.setM_Product_ID(getM_Product_ID(), true);
line.setQty(qty);
line.saveEx();
//
reset(true);
changed = true;
refreshIncludedTabs();
setInfo(Msg.parseTranslation(Env.getCtx(),
"@RecordSaved@ - @M_Product_ID@:" + productStr
+ ", @QtyOrdered@:" + qty), false, null); | }
public void showCenter() {
AEnv.showCenterWindow(getOwner(), this);
}
public boolean isChanged() {
return changed;
}
public void refreshIncludedTabs() {
for (GridTab includedTab : orderTab.getIncludedTabs()) {
includedTab.dataRefreshAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\OrderLineCreate.java | 1 |
请完成以下Java代码 | public synchronized void put(String key,Object element)
{
try
{
if( containsKey(key) )
{
elements.add(keys.location(key),element);
}
else
{
keys.add( key );
elements.add(element);
}
}
catch(org.apache.ecs.storage.NoSuchObjectException nsoe)
{
}
}
public synchronized void remove(String key)
{
try
{
if(containsKey(key))
{
elements.remove(keys.location(key));
elements.remove(elements.location(key));
}
}
catch(org.apache.ecs.storage.NoSuchObjectException nsoe)
{
}
}
public int size()
{
return keys.getCurrentSize();
}
public boolean contains(Object element)
{
try
{
elements.location(element);
return(true);
}
catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject)
{
return false;
}
}
public Enumeration keys()
{
return keys; | }
public boolean containsKey(String key)
{
try
{
keys.location(key);
}
catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject)
{
return false;
}
return(true);
}
public Enumeration elements()
{
return elements;
}
public Object get(String key)
{
try
{
if( containsKey(key) )
return(elements.get(keys.location(key)));
}
catch(org.apache.ecs.storage.NoSuchObjectException nsoe)
{
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Hash.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicDataSourceConfig {
@Value("${spring.datasource.primary.url}")
private String primaryUrl;
@Value("${spring.datasource.user.url}")
private String userUrl;
@Value("${mybatis.mapper-locations}")
private String resources;
//当两个数据库连接账号密码不一样时
// @Value("${spring.datasource.user.username}")
// private String userName;
// @Value("${spring.datasource.user.password}")
// private String password;
@Autowired
private HikariConfig hikariConfig;
@Primary
@Bean(name = "primaryDataSource")
public DataSource getPrimaryDataSource() {
return hikariConfig.getHikariDataSource(primaryUrl);
}
@Bean(name = "userDataSource")
public DataSource getUserDataSource() {
return hikariConfig.getHikariDataSource(userUrl);
}
//当两个数据库连接账号密码不一样时使用
// @Bean(name = "userDataSource") | // public DataSource getUserDataSource() {
// return hikariConfig.getHikariDataSource(userUrl, userName, password);
// }
@Bean("dynamicDataSource")
public DynamicDataSource dynamicDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
@Qualifier("userDataSource") DataSource userDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DatabaseTypeEnum.PRIMARY, primaryDataSource);
targetDataSources.put(DatabaseTypeEnum.USER, userDataSource);
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
dataSource.setDefaultTargetDataSource(primaryDataSource);// 默认的datasource设置为myTestDbDataSource
return dataSource;
}
/**
* 根据数据源创建SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(resources));
return bean.getObject();
}
} | repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\config\DynamicDataSourceConfig.java | 2 |
请完成以下Java代码 | public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
// 下面为实现UserDetails而需要的重写方法!
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override | public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add( new SimpleGrantedAuthority( role.getName() ) );
}
return authorities;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
} | repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\model\entity\User.java | 1 |
请完成以下Java代码 | public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
@Override
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public String toEventMessage(String message) {
String eventMessage = message.replaceAll("\\s+", " ");
if (eventMessage.length() > 163) {
eventMessage = eventMessage.substring(0, 160) + "...";
}
return eventMessage;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type | + ", userId=" + userId
+ ", time=" + time
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", revision= "+ revision
+ ", removalTime=" + removalTime
+ ", action=" + action
+ ", message=" + message
+ ", fullMessage=" + fullMessage
+ ", tenantId=" + tenantId
+ "]";
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<FlowRule> convert(String value) {
try {
return Arrays.asList(objectMapper.readValue(value, FlowRule[].class));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 FlowRuleManager 中
FlowRuleManager.register2Property(refreshableDataSource.getProperty());
// 创建 FileWritableDataSource 对象
FileWritableDataSource<List<FlowRule>> fileWritableDataSource = new FileWritableDataSource<>(path,
new Converter<List<FlowRule>, String>() {
@Override
public String convert(List<FlowRule> source) {
try {
return objectMapper.writeValueAsString(source);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
});
// 注册到 WritableDataSourceRegistry 中
WritableDataSourceRegistry.registerFlowDataSource(fileWritableDataSource);
return fileWritableDataSource;
} | private void mkdirs(String path) {
File file = new File(path);
if (file.exists()) {
return;
}
file.mkdirs();
}
private void creteFile(String path) throws IOException {
File file = new File(path);
if (file.exists()) {
return;
}
file.createNewFile();
}
} | repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-file\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java | 2 |
请完成以下Java代码 | int getModifiers() {
return this.modifiers;
}
CodeBlock getCode() {
return this.code;
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Builder for creating a {@link JavaMethodDeclaration}.
*/
public static final class Builder {
private final String name;
private List<Parameter> parameters = new ArrayList<>();
private String returnType = "void";
private int modifiers;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
} | /**
* Sets the return type.
* @param returnType the return type
* @return this for method chaining
*/
public Builder returning(String returnType) {
this.returnType = returnType;
return this;
}
/**
* Sets the parameters.
* @param parameters the parameters
* @return this for method chaining
*/
public Builder parameters(Parameter... parameters) {
this.parameters = Arrays.asList(parameters);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return the method containing the body
*/
public JavaMethodDeclaration body(CodeBlock code) {
return new JavaMethodDeclaration(this, code);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaMethodDeclaration.java | 1 |
请完成以下Java代码 | public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
/** Get DB Column Name.
@return Name of the column in the database
*/
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
}
/** 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 Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
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());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationAttribute.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public EventSubscriptionQueryImpl tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public EventSubscriptionQueryImpl configuration(String configuration) {
this.configuration = configuration;
return this;
}
public EventSubscriptionQueryImpl orderByCreated() {
return orderBy(EventSubscriptionQueryProperty.CREATED);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionCountByQueryCriteria(this);
}
@Override
public List<EventSubscriptionEntity> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getEventSubscriptionId() {
return eventSubscriptionId;
}
public String getEventName() {
return eventName;
}
public String getEventType() { | return eventType;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getActivityId() {
return activityId;
}
public String getConfiguration() {
return configuration;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\EventSubscriptionQueryImpl.java | 1 |
请完成以下Java代码 | public String getTopic() {
return this.topicPartition.topic();
}
public @Nullable Long getOffset() {
return this.offset;
}
/**
* Set the offset.
* @param offset the offset.
* @since 2.5.5
*/
public void setOffset(Long offset) {
this.offset = offset;
}
public boolean isRelativeToCurrent() {
return this.relativeToCurrent;
}
/**
* Set whether the offset is relative to the current position.
* @param relativeToCurrent true for relative to current.
* @since 2.5.5
*/
public void setRelativeToCurrent(boolean relativeToCurrent) {
this.relativeToCurrent = relativeToCurrent;
}
public @Nullable SeekPosition getPosition() {
return this.position;
}
public @Nullable Function<Long, Long> getOffsetComputeFunction() { | return this.offsetComputeFunction;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TopicPartitionOffset that = (TopicPartitionOffset) o;
return Objects.equals(this.topicPartition, that.topicPartition)
&& Objects.equals(this.position, that.position);
}
@Override
public int hashCode() {
return Objects.hash(this.topicPartition, this.position);
}
@Override
public String toString() {
return "TopicPartitionOffset{" +
"topicPartition=" + this.topicPartition +
", offset=" + this.offset +
", relativeToCurrent=" + this.relativeToCurrent +
(this.position == null ? "" : (", position=" + this.position.name())) +
'}';
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\TopicPartitionOffset.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ImmutableSet<LocatorId> getAssignedLocatorIds()
{
return assignedLocatorIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedLocatorIds);
}
@NonNull
public DeviceConfig.Builder setAssignedLocatorIds(final Set<LocatorId> assignedLocatorIds)
{
this.assignedLocatorIds = assignedLocatorIds;
return this;
}
@NonNull
public DeviceConfig.Builder setBeforeHooksClassname(@NonNull final ImmutableList<String> beforeHooksClassname)
{
this.beforeHooksClassname = beforeHooksClassname;
return this;
}
@NonNull
private ImmutableList<String> getBeforeHooksClassname()
{
return Optional.ofNullable(beforeHooksClassname).orElseGet(ImmutableList::of); | }
@NonNull
public DeviceConfig.Builder setDeviceConfigParams(@NonNull final ImmutableMap<String, String> deviceConfigParams)
{
this.deviceConfigParams = deviceConfigParams;
return this;
}
@NonNull
private ImmutableMap<String, String> getDeviceConfigParams()
{
return deviceConfigParams == null ? ImmutableMap.of() : deviceConfigParams;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfig.java | 2 |
请完成以下Java代码 | public class EnsureCleanDbPlugin implements BpmPlatformPlugin {
protected static final String DATABASE_NOT_CLEAN = "Database was not clean!\n";
protected static final String CACHE_IS_NOT_CLEAN = "Cache was not clean!\n";
protected Logger logger = Logger.getLogger(EnsureCleanDbPlugin.class.getName());
private AtomicInteger counter = new AtomicInteger();
@Override
public void postProcessApplicationDeploy(ProcessApplicationInterface processApplication) {
counter.incrementAndGet();
}
@SuppressWarnings("resource")
@Override
public void postProcessApplicationUndeploy(ProcessApplicationInterface processApplication) {
// some tests deploy multiple PAs. => only clean DB after last PA is undeployed
// if the deployment fails for example during parsing the deployment counter was not incremented
// so we have to check if the counter is already zero otherwise we go into the negative values
// best example is TestWarDeploymentWithBrokenBpmnXml in integration-test-engine test suite
if(counter.get() == 0 || counter.decrementAndGet() == 0) {
final ProcessEngine defaultProcessEngine = BpmPlatform.getDefaultProcessEngine();
try {
logger.log(Level.INFO, "=== Ensure Clean Database ===");
ManagementServiceImpl managementService = (ManagementServiceImpl) defaultProcessEngine.getManagementService();
PurgeReport report = managementService.purge();
if (report.isEmpty()) {
logger.log(Level.INFO, "Clean DB and cache."); | } else {
StringBuilder builder = new StringBuilder();
DatabasePurgeReport databasePurgeReport = report.getDatabasePurgeReport();
if (!databasePurgeReport.isEmpty()) {
builder.append(DATABASE_NOT_CLEAN).append(databasePurgeReport.getPurgeReportAsString());
}
CachePurgeReport cachePurgeReport = report.getCachePurgeReport();
if (!cachePurgeReport.isEmpty()) {
builder.append(CACHE_IS_NOT_CLEAN).append(cachePurgeReport.getPurgeReportAsString());
}
logger.log(Level.INFO, builder.toString());
}
}
catch(Throwable e) {
logger.log(Level.SEVERE, "Could not clean DB:", e);
}
}
}
} | repos\camunda-bpm-platform-master\qa\ensure-clean-db-plugin\src\main\java\org\camunda\qa\impl\EnsureCleanDbPlugin.java | 1 |
请完成以下Java代码 | public boolean isStopping() {
return false;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
* eclipse.jetty.util.component.LifeCycle.Listener)
*/
@Override
public void removeLifeCycleListener(Listener arg0) {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#start()
*/
@Override
public void start() throws Exception {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#stop()
*/
@Override
public void stop() throws Exception {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#destroy()
*/
@Override
public void destroy() {
} | /*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#getServer()
*/
@Override
public Server getServer() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
LOG.info("Received a new request");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
* Server)
*/
@Override
public void setServer(Server server) {
}
} | repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\jetty\programmatic\LoggingRequestHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private String isbn;
public Book() {
}
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} | public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\listrepositories\entity\Book.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SpringLiquibase liquibase(
@Qualifier("taskExecutor") Executor executor,
LiquibaseProperties liquibaseProperties,
R2dbcProperties dataSourceProperties
) {
SpringLiquibase liquibase = new AsyncSpringLiquibase(executor, env);
liquibase.setDataSource(createLiquibaseDataSource(liquibaseProperties, dataSourceProperties));
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabelFilter(liquibaseProperties.getLabelFilter());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); | liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
private static DataSource createLiquibaseDataSource(LiquibaseProperties liquibaseProperties, R2dbcProperties dataSourceProperties) {
String user = Optional.ofNullable(liquibaseProperties.getUser()).orElse(dataSourceProperties.getUsername());
String password = Optional.ofNullable(liquibaseProperties.getPassword()).orElse(dataSourceProperties.getPassword());
return DataSourceBuilder.create().url(liquibaseProperties.getUrl()).username(user).password(password).build();
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\LiquibaseConfiguration.java | 2 |
请完成以下Java代码 | public java.lang.String getInvoiceDocumentNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceDocumentNo);
}
/** Set Zahlungseingang.
@param IsReceipt
Dies ist eine Verkaufs-Transaktion (Zahlungseingang)
*/
@Override
public void setIsReceipt (boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, Boolean.valueOf(IsReceipt));
}
/** Get Zahlungseingang.
@return Dies ist eine Verkaufs-Transaktion (Zahlungseingang)
*/
@Override
public boolean isReceipt ()
{
Object oo = get_Value(COLUMNNAME_IsReceipt);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zahlungsbetrag.
@param PayAmt
Gezahlter Betrag
*/
@Override
public void setPayAmt (BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Zahlungsbetrag.
@return Gezahlter Betrag
*/
@Override
public BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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 Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
@Override
public void setTransactionCode (java.lang.String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
@Override
public java.lang.String getTransactionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_I_Datev_Payment.java | 1 |
请完成以下Java代码 | public void setM_HU_Reservation_ID (final int M_HU_Reservation_ID)
{
if (M_HU_Reservation_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, M_HU_Reservation_ID);
}
@Override
public int getM_HU_Reservation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Reservation_ID);
}
@Override
public de.metas.handlingunits.model.I_M_Picking_Job_Step getM_Picking_Job_Step()
{
return get_ValueAsPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class);
}
@Override
public void setM_Picking_Job_Step(final de.metas.handlingunits.model.I_M_Picking_Job_Step M_Picking_Job_Step)
{
set_ValueFromPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class, M_Picking_Job_Step);
}
@Override
public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID)
{
if (M_Picking_Job_Step_ID < 1)
set_Value (COLUMNNAME_M_Picking_Job_Step_ID, null);
else
set_Value (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID);
}
@Override
public int getM_Picking_Job_Step_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID);
}
@Override
public void setQtyReserved (final BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public de.metas.handlingunits.model.I_M_HU getVHU()
{
return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU)
{
set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java | 1 |
请完成以下Java代码 | public abstract class GroupQueryImpl extends AbstractQuery<GroupQuery, Group> implements GroupQuery {
private static final long serialVersionUID = 1L;
protected String id;
protected String[] ids;
protected String name;
protected String nameLike;
protected String type;
protected String userId;
protected String procDefId;
protected String tenantId;
public GroupQueryImpl() {
}
public GroupQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
public GroupQuery groupId(String id) {
ensureNotNull("Provided id", id);
this.id = id;
return this;
}
public GroupQuery groupIdIn(String... ids) {
ensureNotNull("Provided ids", (Object[]) ids);
this.ids = ids;
return this;
}
public GroupQuery groupName(String name) {
ensureNotNull("Provided name", name);
this.name = name;
return this;
}
public GroupQuery groupNameLike(String nameLike) {
ensureNotNull("Provided nameLike", nameLike);
this.nameLike = nameLike;
return this;
}
public GroupQuery groupType(String type) {
ensureNotNull("Provided type", type);
this.type = type;
return this;
}
public GroupQuery groupMember(String userId) {
ensureNotNull("Provided userId", userId);
this.userId = userId;
return this;
}
public GroupQuery potentialStarter(String procDefId) {
ensureNotNull("Provided processDefinitionId", procDefId);
this.procDefId = procDefId;
return this;
}
public GroupQuery memberOfTenant(String tenantId) {
ensureNotNull("Provided tenantId", tenantId);
this.tenantId = tenantId;
return this;
}
//sorting //////////////////////////////////////////////////////// | public GroupQuery orderByGroupId() {
return orderBy(GroupQueryProperty.GROUP_ID);
}
public GroupQuery orderByGroupName() {
return orderBy(GroupQueryProperty.NAME);
}
public GroupQuery orderByGroupType() {
return orderBy(GroupQueryProperty.TYPE);
}
//getters ////////////////////////////////////////////////////////
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getTenantId() {
return tenantId;
}
public String[] getIds() {
return ids;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\GroupQueryImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.