instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() {
return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\User.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> deleteConversation(@PathVariable("id") String id) { return chatService.deleteConversation(id); } /** * 更新会话标题 * * @param updateTitleParams * @return * @author chenrui * @date 2025/3/3 16:55 */ @IgnoreAuth @PutMapping(value = "/conversation/update/title") public Result<?> updateConversationTitle(@RequestBody ChatConversation updateTitleParams) { return chatService.updateConversationTitle(updateTitleParams); } /** * 获取消息 * * @return 返回一个Result对象,包含消息的信息 * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/messages") public Result<?> getMessages(@RequestParam(value = "conversationId", required = true) String conversationId) { return chatService.getMessages(conversationId); } /** * 清空消息 * * @return * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/messages/clear/{conversationId}") public Result<?> clearMessage(@PathVariable(value = "conversationId") String conversationId) { return chatService.clearMessage(conversationId); } /** * 继续接收消息 * * @param requestId * @return * @author chenrui * @date 2025/8/11 17:49 */ @IgnoreAuth @GetMapping(value = "/receive/{requestId}") public SseEmitter receiveByRequestId(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.receiveByRequestId(requestId); }
/** * 根据请求ID停止某个请求的处理 * * @param requestId 请求的唯一标识符,用于识别和停止特定的请求 * @return 返回一个Result对象,表示停止请求的结果 * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/stop/{requestId}") public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.stop(requestId); } /** * 上传文件 * for [QQYUN-12135]AI聊天,上传图片提示非法token * * @param request * @param response * @return * @throws Exception * @author chenrui * @date 2025/4/25 11:04 */ @IgnoreAuth @PostMapping(value = "/upload") public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception { String bizPath = "airag"; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取上传文件对象 MultipartFile file = multipartRequest.getFile("file"); String savePath; if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) { savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath); } else { savePath = CommonUtils.upload(file, bizPath, uploadType); } Result<?> result = new Result<>(); result.setMessage(savePath); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java
2
请完成以下Java代码
public static class ProcessedImage { private String mediaType; private int width; private int height; @With private byte[] data; private long size; private ProcessedImage preview; } @Data public static class ScadaSymbolMetadataInfo { private String title; private String description; private String[] searchTags; private int widgetSizeX; private int widgetSizeY; public ScadaSymbolMetadataInfo(String fileName, JsonNode metaData) { if (metaData != null && metaData.has("title")) { title = metaData.get("title").asText(); } else { title = fileName; } if (metaData != null && metaData.has("description")) { description = metaData.get("description").asText(); } else { description = ""; } if (metaData != null && metaData.has("searchTags") && metaData.get("searchTags").isArray()) { var tagsNode = (ArrayNode) metaData.get("searchTags"); searchTags = new String[tagsNode.size()]; for (int i = 0; i < tagsNode.size(); i++) { searchTags[i] = tagsNode.get(i).asText(); }
} else { searchTags = new String[0]; } if (metaData != null && metaData.has("widgetSizeX")) { widgetSizeX = metaData.get("widgetSizeX").asInt(); } else { widgetSizeX = 3; } if (metaData != null && metaData.has("widgetSizeY")) { widgetSizeY = metaData.get("widgetSizeY").asInt(); } else { widgetSizeY = 3; } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\ImageUtils.java
1
请完成以下Java代码
public void collect(@NonNull final HUAttributeChange change) { Check.assume(!disposed.get(), "Collector shall not be disposed: {}", this); final HUAttributeChanges huChanges = huAttributeChangesMap.computeIfAbsent(change.getHuId(), HUAttributeChanges::new); huChanges.collect(change); } public void createAndPostMaterialEvents() { if (disposed.getAndSet(true)) { throw new AdempiereException("Collector was already disposed: " + this); } final List<AttributesChangedEvent> events = new ArrayList<>(); for (final HUAttributeChanges huAttributeChanges : huAttributeChangesMap.values()) { events.addAll(createMaterialEvent(huAttributeChanges)); } events.forEach(materialEventService::enqueueEventAfterNextCommit); } private List<AttributesChangedEvent> createMaterialEvent(final HUAttributeChanges changes) { if (changes.isEmpty()) { return ImmutableList.of(); } final HuId huId = changes.getHuId(); final I_M_HU hu = handlingUnitsBL.getById(huId); // // Consider only those HUs which have QtyOnHand if (!huStatusBL.isQtyOnHand(hu.getHUStatus())) { return ImmutableList.of(); } // // Consider only VHUs if (!handlingUnitsBL.isVirtual(hu))
{ return ImmutableList.of(); } final EventDescriptor eventDescriptor = EventDescriptor.ofClientAndOrg(hu.getAD_Client_ID(), hu.getAD_Org_ID()); final Instant date = changes.getLastChangeDate(); final WarehouseId warehouseId = warehousesRepo.getWarehouseIdByLocatorRepoId(hu.getM_Locator_ID()); final AttributesKeyWithASI oldStorageAttributes = toAttributesKeyWithASI(changes.getOldAttributesKey()); final AttributesKeyWithASI newStorageAttributes = toAttributesKeyWithASI(changes.getNewAttributesKey()); final List<IHUProductStorage> productStorages = handlingUnitsBL.getStorageFactory() .getStorage(hu) .getProductStorages(); final List<AttributesChangedEvent> events = new ArrayList<>(); for (final IHUProductStorage productStorage : productStorages) { events.add(AttributesChangedEvent.builder() .eventDescriptor(eventDescriptor) .warehouseId(warehouseId) .date(date) .productId(productStorage.getProductId().getRepoId()) .qty(productStorage.getQtyInStockingUOM().toBigDecimal()) .oldStorageAttributes(oldStorageAttributes) .newStorageAttributes(newStorageAttributes) .huId(productStorage.getHuId().getRepoId()) .build()); } return events; } private AttributesKeyWithASI toAttributesKeyWithASI(final AttributesKey attributesKey) { return attributesKeyWithASIsCache.computeIfAbsent(attributesKey, this::createAttributesKeyWithASI); } private AttributesKeyWithASI createAttributesKeyWithASI(final AttributesKey attributesKey) { final AttributeSetInstanceId asiId = AttributesKeys.createAttributeSetInstanceFromAttributesKey(attributesKey); return AttributesKeyWithASI.of(attributesKey, asiId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChangesCollector.java
1
请完成以下Java代码
public ADHyperlink getADHyperlink(String uri) { try { return getADHyperlink(new URI(uri)); } catch (URISyntaxException e) { throw new AdempiereException(e); } } public ADHyperlink getADHyperlink(final URI uri) { String protocol = uri.getScheme(); if (!PROTOCOL.equals(protocol)) return null; String host = uri.getHost(); if (!HOST.equals(host)) return null; String actionStr = uri.getPath(); if (actionStr.startsWith("/")) actionStr = actionStr.substring(1); ADHyperlink.Action action = ADHyperlink.Action.valueOf(actionStr); Map<String, String> params = StringUtils.parseURLQueryString(uri.getQuery()); return new ADHyperlink(action, params); } private String encodeParams(Map<String, String> params) { StringBuilder urlParams = new StringBuilder(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> e : params.entrySet()) { if (urlParams.length() > 0) { // We need to use %26 instead of "&" because of org.compiere.process.ProcessInfo.getSummary(), // which strips ampersands urlParams.append("%26"); } urlParams.append(encode(e.getKey())); urlParams.append("="); urlParams.append(encode(e.getValue())); } } return urlParams.toString(); } private URI toURI(ADHyperlink link) {
String urlParams = encodeParams(link.getParameters()); String urlStr = PROTOCOL + "://" + HOST + "/" + link.getAction().toString() + "?" + urlParams; try { return new URI(urlStr); } catch (URISyntaxException e) { throw new AdempiereException(e); } } private String encode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AdempiereException(e); } } private String decode(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AdempiereException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\util\ADHyperlinkBuilder.java
1
请完成以下Java代码
public ClientSetup setAccountNo(final String accountNo) { if (!Check.isEmpty(accountNo, true)) { orgBankAccount.setAccountNo(accountNo.trim()); } return this; } public final String getAccountNo() { return orgBankAccount.getAccountNo(); } public String getIBAN() { return orgBankAccount.getIBAN(); } public ClientSetup setIBAN(final String iban) { if (!Check.isEmpty(iban, true)) { orgBankAccount.setIBAN(iban.trim()); } return this; } public ClientSetup setC_Bank_ID(final int bankId) { if (bankId > 0) { orgBankAccount.setC_Bank_ID(bankId); } return this; } public final int getC_Bank_ID() { return orgBankAccount.getC_Bank_ID(); } public ClientSetup setPhone(final String phone) { if (!Check.isEmpty(phone, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setPhone(phone.trim()); } return this; } public final String getPhone() { return orgContact.getPhone(); } public ClientSetup setFax(final String fax) { if (!Check.isEmpty(fax, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window
orgContact.setFax(fax.trim()); } return this; } public final String getFax() { return orgContact.getFax(); } public ClientSetup setEMail(final String email) { if (!Check.isEmpty(email, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setEMail(email.trim()); } return this; } public final String getEMail() { return orgContact.getEMail(); } public ClientSetup setBPartnerDescription(final String bpartnerDescription) { if (Check.isEmpty(bpartnerDescription, true)) { return this; } orgBPartner.setDescription(bpartnerDescription.trim()); return this; } public String getBPartnerDescription() { return orgBPartner.getDescription(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
1
请完成以下Java代码
private CreateMatchInvoiceCommand createMatchInvoiceCommand(final @NonNull CreateMatchInvoiceRequest request) { return CreateMatchInvoiceCommand.builder() .orderCostService(this) .matchInvoiceService(matchInvoiceService) .invoiceBL(invoiceBL) .inoutBL(inoutBL) .moneyService(moneyService) .request(request) .build(); } public Money getInvoiceLineOpenAmt(InvoiceAndLineId invoiceAndLineId) { final I_C_InvoiceLine invoiceLine = invoiceBL.getLineById(invoiceAndLineId); return getInvoiceLineOpenAmt(invoiceLine); } public Money getInvoiceLineOpenAmt(I_C_InvoiceLine invoiceLine) { final InvoiceId invoiceId = InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID()); final I_C_Invoice invoice = invoiceBL.getById(invoiceId); Money openAmt = Money.of(invoiceLine.getLineNetAmt(), CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final Money matchedAmt = matchInvoiceService.getCostAmountMatched(InvoiceAndLineId.ofRepoId(invoiceId, invoiceLine.getC_InvoiceLine_ID())).orElse(null); if (matchedAmt != null) { openAmt = openAmt.subtract(matchedAmt); } return openAmt; } public void cloneAllByOrderId( @NonNull final OrderId orderId, @NonNull final OrderCostCloneMapper mapper) { final List<OrderCost> originalOrderCosts = orderCostRepository.getByOrderId(orderId); final ImmutableList<OrderCost> clonedOrderCosts = originalOrderCosts.stream() .map(originalOrderCost -> originalOrderCost.copy(mapper)) .collect(ImmutableList.toImmutableList()); orderCostRepository.saveAll(clonedOrderCosts); } public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo) { orderCostRepository.changeByOrderLineId( orderLineInfo.getOrderLineId(), orderCost -> { orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL); updateCreatedOrderLineIfAny(orderCost); }); }
private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost) { if (orderCost.getCreatedOrderLineId() == null) { return; } CreateOrUpdateOrderLineFromOrderCostCommand.builder() .orderBL(orderBL) .moneyService(moneyService) .orderCost(orderCost) .build() .execute(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId); } public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId) { return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java
1
请在Spring Boot框架中完成以下Java代码
public Result updateProduct(ProdUpdateReq prodUpdateReq) { //增量更新产品 return productService.updateProduct(prodUpdateReq); } @Override public Result<List<ProductEntity>> findProducts(ProdQueryReq prodQueryReq) { return productService.findProducts(prodQueryReq); } @Override public Result createCategoty(CategoryEntity categoryEntity) { return productService.createCategoty(categoryEntity); } @Override public Result modifyCategory(CategoryEntity categoryEntity) { return productService.modifyCategory(categoryEntity); } @Override public Result deleteCategory(String categoryId) { return productService.deleteCategory(categoryId); } @Override
public Result<List<CategoryEntity>> findCategorys(CategoryQueryReq categoryQueryReq) { return productService.findCategorys(categoryQueryReq); } @Override public Result createBrand(BrandInsertReq brandInsertReq) { return productService.createBrand(brandInsertReq); } @Override public Result modifyBrand(BrandInsertReq brandInsertReq) { return productService.modifyBrand(brandInsertReq); } @Override public Result<List<BrandEntity>> findBrands(BrandQueryReq brandQueryReq) { return productService.findBrands(brandQueryReq); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\product\ProductControllerImpl.java
2
请完成以下Java代码
@Nullable private Class<? extends IProcessDefaultParametersProvider> getProcessDefaultParametersProvider() { final Class<?> processClass = getProcessClassOrNull(); if (processClass == null || !IProcessDefaultParametersProvider.class.isAssignableFrom(processClass)) { return null; } try { return processClass.asSubclass(IProcessDefaultParametersProvider.class); } catch (final Exception e) { logger.warn(e.getLocalizedMessage(), e); return null; } } public Builder setParametersDescriptor(final DocumentEntityDescriptor parametersDescriptor) { this.parametersDescriptor = parametersDescriptor; return this; } private DocumentEntityDescriptor getParametersDescriptor() { return parametersDescriptor; } public Builder setLayout(final ProcessLayout layout) { this.layout = layout; return this; } private ProcessLayout getLayout() { Check.assumeNotNull(layout, "Parameter layout is not null"); return layout; } public Builder setStartProcessDirectly(final boolean startProcessDirectly)
{ this.startProcessDirectly = startProcessDirectly; return this; } private boolean isStartProcessDirectly() { if (startProcessDirectly != null) { return startProcessDirectly; } else { return computeIsStartProcessDirectly(); } } private boolean computeIsStartProcessDirectly() { return (getParametersDescriptor() == null || getParametersDescriptor().getFields().isEmpty()) && TranslatableStrings.isEmpty(getLayout().getDescription()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessDescriptor.java
1
请完成以下Java代码
public class PrimitiveMaps { public static void main(String[] args) { hppcMap(); eclipseCollectionsMap(); fastutilMap(); } private static void hppcMap() { //Regular maps IntLongHashMap intLongHashMap = new IntLongHashMap(); intLongHashMap.put(25,1L); intLongHashMap.put(150,Long.MAX_VALUE); intLongHashMap.put(1,0L); intLongHashMap.get(150); IntObjectMap<BigDecimal> intObjectMap = new IntObjectHashMap<BigDecimal>(); intObjectMap.put(1, BigDecimal.valueOf(1)); intObjectMap.put(2, BigDecimal.valueOf(2500)); BigDecimal value = intObjectMap.get(2); //Scatter maps IntLongScatterMap intLongScatterMap = new IntLongScatterMap(); intLongScatterMap.put(1, 1L); intLongScatterMap.put(2, -2L); intLongScatterMap.put(1000,0L); intLongScatterMap.get(1000); IntObjectScatterMap<BigDecimal> intObjectScatterMap = new IntObjectScatterMap<BigDecimal>(); intObjectScatterMap.put(1, BigDecimal.valueOf(1)); intObjectScatterMap.put(2, BigDecimal.valueOf(2500)); value = intObjectScatterMap.get(2); } private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap(); int2BooleanMap.put(1, true); int2BooleanMap.put(7, false); int2BooleanMap.put(4, true); boolean value = int2BooleanMap.get(1); //Lambda style iteration Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> { System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue())); }); //Iterator based loop ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap); while(iterator.hasNext()) { Int2BooleanMap.Entry entry = iterator.next(); System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue())); } } private static void eclipseCollectionsMap() { MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty(); mutableIntIntMap.addToValue(1, 1); ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty(); MutableObjectDoubleMap<String> dObject = ObjectDoubleMaps.mutable.empty(); dObject.addToValue("price", 150.5); dObject.addToValue("quality", 4.4); dObject.addToValue("stability", 0.8); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\primitives\PrimitiveMaps.java
1
请完成以下Java代码
public String getName() { return this.getAttribute(this.nameAttributeKey).toString(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public Map<String, Object> getAttributes() { return this.attributes; } private Set<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) { SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<>( Comparator.comparing(GrantedAuthority::getAuthority)); sortedAuthorities.addAll(authorities); return sortedAuthorities; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } DefaultOAuth2User that = (DefaultOAuth2User) obj; if (!this.getName().equals(that.getName())) { return false; } if (!this.getAuthorities().equals(that.getAuthorities())) { return false; } return this.getAttributes().equals(that.getAttributes()); }
@Override public int hashCode() { int result = this.getName().hashCode(); result = 31 * result + this.getAuthorities().hashCode(); result = 31 * result + this.getAttributes().hashCode(); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ["); sb.append(this.getName()); sb.append("], Granted Authorities: ["); sb.append(getAuthorities()); sb.append("], User Attributes: ["); sb.append(getAttributes()); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\user\DefaultOAuth2User.java
1
请完成以下Java代码
public void setUp() { for (long i = 0; i < set1Size; i++) { employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < list1Size; i++) { employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set2Size; i++) { employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < list2Size; i++) { employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set3Size; i++) { employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set4Size; i++) { employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false))); } } } @Benchmark public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) { return state.employeeSet1.removeAll(state.employeeList1); } @Benchmark public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) { return state.employeeSet2.removeAll(state.employeeList2); }
@Benchmark public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) { return state.employeeSet3.removeAll(state.employeeSet4); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName()) .threads(1) .forks(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server") .build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-3\src\main\java\com\baeldung\collections\removeallperformance\HashSetBenchmark.java
1
请完成以下Java代码
public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); // add links if operations are authorized UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(rootResourcePath) .path(UserRestService.PATH) .path(resourceId); URI baseUri = baseUriBuilder.build(); URI profileUri = baseUriBuilder.path("/profile").build(); dto.addReflexiveLink(profileUri, HttpMethod.GET, "self"); if(!identityService.isReadOnly() && isAuthorized(DELETE)) { dto.addReflexiveLink(baseUri, HttpMethod.DELETE, "delete"); } if(!identityService.isReadOnly() && isAuthorized(UPDATE)) { dto.addReflexiveLink(profileUri, HttpMethod.PUT, "update"); } return dto; } public void deleteUser() { ensureNotReadOnly(); identityService.deleteUser(resourceId); } public void unlockUser() { ensureNotReadOnly(); identityService.unlockUser(resourceId); } public void updateCredentials(UserCredentialsDto account) { ensureNotReadOnly(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); if(currentAuthentication != null && currentAuthentication.getUserId() != null) { if(!identityService.checkPassword(currentAuthentication.getUserId(), account.getAuthenticatedUserPassword())) { throw new InvalidRequestException(Status.BAD_REQUEST, "The given authenticated user password is not valid."); } } User dbUser = findUserObject(); if(dbUser == null) { throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); }
dbUser.setPassword(account.getPassword()); identityService.saveUser(dbUser); } public void updateProfile(UserProfileDto profile) { ensureNotReadOnly(); User dbUser = findUserObject(); if(dbUser == null) { throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); } profile.update(dbUser); identityService.saveUser(dbUser); } protected User findUserObject() { try { return identityService.createUserQuery() .userId(resourceId) .singleResult(); } catch(ProcessEngineException e) { throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing user query: "+e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\UserResourceImpl.java
1
请完成以下Java代码
public class Bankstatement { private BigInteger ktoNr = null; private BigInteger blz = null; private String auftragsreferenzNr = null; private String bezugsrefernznr = null; private BigInteger auszugsNr = null; private Saldo anfangsSaldo = null; private Saldo schlussSaldo = null; private Saldo aktuellValutenSaldo = null; private Saldo zukunftValutenSaldo = null; private List<BankstatementLine> lines = null; public Bankstatement() { lines = new ArrayList<BankstatementLine>(); } public BigInteger getKtoNr() { return ktoNr; } public void setKtoNr(BigInteger ktoNr) { this.ktoNr = ktoNr; } public BigInteger getBlz() { return blz; } public void setBlz(BigInteger blz) { this.blz = blz; } public String getAuftragsreferenzNr() { return auftragsreferenzNr; } public void setAuftragsreferenzNr(String auftragsreferenzNr) { this.auftragsreferenzNr = auftragsreferenzNr; } public String getBezugsrefernznr() { return bezugsrefernznr; }
public void setBezugsrefernznr(String bezugsrefernznr) { this.bezugsrefernznr = bezugsrefernznr; } public BigInteger getAuszugsNr() { return auszugsNr; } public void setAuszugsNr(BigInteger auszugsNr) { this.auszugsNr = auszugsNr; } public Saldo getAnfangsSaldo() { return anfangsSaldo; } public void setAnfangsSaldo(Saldo anfangsSaldo) { this.anfangsSaldo = anfangsSaldo; } public Saldo getSchlussSaldo() { return schlussSaldo; } public void setSchlussSaldo(Saldo schlussSaldo) { this.schlussSaldo = schlussSaldo; } public Saldo getAktuellValutenSaldo() { return aktuellValutenSaldo; } public void setAktuellValutenSaldo(Saldo aktuellValutenSaldo) { this.aktuellValutenSaldo = aktuellValutenSaldo; } public Saldo getZukunftValutenSaldo() { return zukunftValutenSaldo; } public void setZukunftValutenSaldo(Saldo zukunftValutenSaldo) { this.zukunftValutenSaldo = zukunftValutenSaldo; } public List<BankstatementLine> getLines() { return lines; } public void setLines(List<BankstatementLine> lines) { this.lines = lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Bankstatement.java
1
请完成以下Java代码
public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSeqNo_SideList (final int SeqNo_SideList) { set_Value (COLUMNNAME_SeqNo_SideList, SeqNo_SideList); } @Override public int getSeqNo_SideList() { return get_ValueAsInt(COLUMNNAME_SeqNo_SideList); } @Override public void setUIStyle (final @Nullable java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } @Override public java.lang.String getUIStyle() { return get_ValueAsString(COLUMNNAME_UIStyle); } /** * ViewEditMode AD_Reference_ID=541263 * Reference name: ViewEditMode */
public static final int VIEWEDITMODE_AD_Reference_ID=541263; /** Never = N */ public static final String VIEWEDITMODE_Never = "N"; /** OnDemand = D */ public static final String VIEWEDITMODE_OnDemand = "D"; /** Always = Y */ public static final String VIEWEDITMODE_Always = "Y"; @Override public void setViewEditMode (final @Nullable java.lang.String ViewEditMode) { set_Value (COLUMNNAME_ViewEditMode, ViewEditMode); } @Override public java.lang.String getViewEditMode() { return get_ValueAsString(COLUMNNAME_ViewEditMode); } /** * WidgetSize AD_Reference_ID=540724 * Reference name: WidgetSize_WEBUI */ public static final int WIDGETSIZE_AD_Reference_ID=540724; /** Small = S */ public static final String WIDGETSIZE_Small = "S"; /** Medium = M */ public static final String WIDGETSIZE_Medium = "M"; /** Large = L */ public static final String WIDGETSIZE_Large = "L"; /** ExtraLarge = XL */ public static final String WIDGETSIZE_ExtraLarge = "XL"; /** XXL = XXL */ public static final String WIDGETSIZE_XXL = "XXL"; @Override public void setWidgetSize (final @Nullable java.lang.String WidgetSize) { set_Value (COLUMNNAME_WidgetSize, WidgetSize); } @Override public java.lang.String getWidgetSize() { return get_ValueAsString(COLUMNNAME_WidgetSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java
1
请完成以下Spring Boot application配置
spring: datasource: url: jdbc:h2:mem:mydb;MODE=PostgreSQL username: sa password: password driverClassName: org.h2.Driver jpa: database-platform: com.baeldung.arrayscollections.dialects.CustomDialect defer-datasource-initialization: true
show-sql: true properties: hibernate: format_sql: true sql: init: data-locations:
repos\tutorials-master\persistence-modules\hibernate6\src\main\resources\application-customdialect.yaml
2
请完成以下Java代码
public void unassignHUs(@NonNull final TableRecordReference modelRef, @NonNull final Collection<HuId> husToUnassign) { huAssignmentDAO.deleteHUAssignments(Env.getCtx(), modelRef, husToUnassign, ITrx.TRXNAME_ThreadInherited); } @Override public IHUAssignmentBuilder createHUAssignmentBuilder() { return new HUAssignmentBuilder(); } @Override public void copyHUAssignments( @NonNull final Object sourceModel, @NonNull final Object targetModel) { final List<I_M_HU_Assignment> // huAssignmentsForSource = huAssignmentDAO.retrieveTopLevelHUAssignmentsForModel(sourceModel);
for (final I_M_HU_Assignment huAssignment : huAssignmentsForSource) { createHUAssignmentBuilder() .setTemplateForNewRecord(huAssignment) .setModel(targetModel) .build(); } } @Override public ImmutableSetMultimap<TableRecordReference, HuId> getHUsByRecordRefs(@NonNull final TableRecordReferenceSet recordRefs) { return huAssignmentDAO.retrieveHUsByRecordRefs(recordRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBL.java
1
请完成以下Java代码
public String getProcessDefinitionKey() { return processDefinitionKey; } public String getTenantId() { return tenantId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId(); result.timestamp = historicExternalTaskLog.getTimestamp();
result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries(); result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = roleService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取所有角色") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody 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 void setMessageType(MessageType messageType) { this.messageType = messageType; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public enum MessageType { text, interactive } public static class Card { /** * This is header title. */ private String title = "Codecentric's Spring Boot Admin notice"; private String themeColor = "red"; public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public String getThemeColor() { return themeColor; } public void setThemeColor(String themeColor) { this.themeColor = themeColor; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\FeiShuNotifier.java
1
请完成以下Java代码
public void setIsPackagingTax (final boolean IsPackagingTax) { set_Value (COLUMNNAME_IsPackagingTax, IsPackagingTax); } @Override public boolean isPackagingTax() { return get_ValueAsBoolean(COLUMNNAME_IsPackagingTax); } @Override public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setIsWholeTax (final boolean IsWholeTax) { set_Value (COLUMNNAME_IsWholeTax, IsWholeTax); } @Override public boolean isWholeTax() { return get_ValueAsBoolean(COLUMNNAME_IsWholeTax); } @Override
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceTax.java
1
请在Spring Boot框架中完成以下Java代码
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(final ContextRefreshedEvent event) { final ApplicationContext applicationContext = event.getApplicationContext(); SpringContextHolder.instance.setApplicationContext(applicationContext); // gh #427: allow service implementations to be managed by spring. Services.setExternalServiceImplProvider(new SpringApplicationContextAsServiceImplProvider(applicationContext)); } private static final class SpringApplicationContextAsServiceImplProvider implements IServiceImplProvider { private final ApplicationContext applicationContext; private SpringApplicationContextAsServiceImplProvider(final ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(applicationContext).toString(); } @Override public <T extends IService> T provideServiceImpl(@NonNull final Class<T> serviceClazz) { try { return applicationContext.getBean(serviceClazz); } catch (final NoUniqueBeanDefinitionException e) {
// not ok; we have > 1 matching beans defined in the spring context. So far that always indicated some sort of mistake, so let's escalate. throw e; } catch (final NoSuchBeanDefinitionException e) { // ok; the bean is not in the spring context, so let's just return null return null; } catch (final IllegalStateException e) { if (Adempiere.isUnitTestMode()) { // added for @SpringBootTests starting up with a 'Marked for closing' Context, mostly due to DirtiesContext.ClassMode.BEFORE_CLASS return null; } throw e; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\StartupListener.java
2
请完成以下Java代码
public class RootPropertyResolver extends ELResolver { private final Map<String, Object> map = Collections.synchronizedMap(new HashMap<>()); private final boolean readOnly; /** * Create a read/write root property resolver */ public RootPropertyResolver() { this(false); } /** * Create a root property resolver * * @param readOnly */ public RootPropertyResolver(boolean readOnly) { this.readOnly = readOnly; } private boolean isResolvable(Object base) { return base == null; } private boolean resolve(ELContext context, Object base, Object property) { context.setPropertyResolved(isResolvable(base) && property instanceof String); return context.isPropertyResolved(); } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return isResolvable(context) ? String.class : null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { return resolve(context, base, property) ? Object.class : null; } @Override public Object getValue(ELContext context, Object base, Object property) { if (resolve(context, base, property)) { if (!isProperty((String) property)) { throw new PropertyNotFoundException("Cannot find property " + property); } return getProperty((String) property); } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return resolve(context, base, property) ? readOnly : false; } @Override public void setValue(ELContext context, Object base, Object property, Object value) throws PropertyNotWritableException { if (resolve(context, base, property)) {
if (readOnly) { throw new PropertyNotWritableException("Resolver is read only!"); } setProperty((String) property, value); } } @Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (resolve(context, base, method)) { throw new NullPointerException("Cannot invoke method " + method + " on null"); } return null; } /** * Get property value * * @param property * property name * @return value associated with the given property */ public Object getProperty(String property) { return map.get(property); } /** * Set property value * * @param property * property name * @param value * property value */ public void setProperty(String property, Object value) { map.put(property, value); } /** * Test property * * @param property * property name * @return <code>true</code> if the given property is associated with a value */ public boolean isProperty(String property) { return map.containsKey(property); } /** * Get properties * * @return all property names (in no particular order) */ public Iterable<String> properties() { return map.keySet(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\util\RootPropertyResolver.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public PartitionElement getPartitionElement() { return partitionElementRefAttribute.getReferenceTargetElement(this); } public void setPartitionElement(PartitionElement partitionElement) { partitionElementRefAttribute.setReferenceTargetElement(this, partitionElement); } public PartitionElement getPartitionElementChild() { return partitionElementChild.getChild(this); }
public void setPartitionElementChild(PartitionElement partitionElement) { partitionElementChild.setChild(this, partitionElement); } public Collection<FlowNode> getFlowNodeRefs() { return flowNodeRefCollection.getReferenceTargetElements(this); } public ChildLaneSet getChildLaneSet() { return childLaneSetChild.getChild(this); } public void setChildLaneSet(ChildLaneSet childLaneSet) { childLaneSetChild.setChild(this, childLaneSet); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\LaneImpl.java
1
请完成以下Java代码
public boolean hasMoreElements() { return names.hasMoreElements(); } @Override public String nextElement() { String headerNames = names.nextElement(); validateAllowedHeaderName(headerNames); return headerNames; } }; } @Override public String getParameter(String name) { if (name != null) { validateAllowedParameterName(name); } String value = super.getParameter(name); if (value != null) { validateAllowedParameterValue(name, value); } return value; } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> parameterMap = super.getParameterMap(); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String name = entry.getKey(); String[] values = entry.getValue(); validateAllowedParameterName(name); for (String value : values) { validateAllowedParameterValue(name, value); } } return parameterMap; } @Override public Enumeration<String> getParameterNames() { Enumeration<String> paramaterNames = super.getParameterNames(); return new Enumeration<>() { @Override public boolean hasMoreElements() { return paramaterNames.hasMoreElements(); } @Override public String nextElement() { String name = paramaterNames.nextElement(); validateAllowedParameterName(name); return name; } }; } @Override public String[] getParameterValues(String name) { if (name != null) { validateAllowedParameterName(name); }
String[] values = super.getParameterValues(name); if (values != null) { for (String value : values) { validateAllowedParameterValue(name, value); } } return values; } private void validateAllowedHeaderName(String headerNames) { if (!StrictHttpFirewall.this.allowedHeaderNames.test(headerNames)) { throw new RequestRejectedException( "The request was rejected because the header name \"" + headerNames + "\" is not allowed."); } } private void validateAllowedHeaderValue(String name, String value) { if (!StrictHttpFirewall.this.allowedHeaderValues.test(value)) { throw new RequestRejectedException("The request was rejected because the header: \"" + name + " \" has a value \"" + value + "\" that is not allowed."); } } private void validateAllowedParameterName(String name) { if (!StrictHttpFirewall.this.allowedParameterNames.test(name)) { throw new RequestRejectedException( "The request was rejected because the parameter name \"" + name + "\" is not allowed."); } } private void validateAllowedParameterValue(String name, String value) { if (!StrictHttpFirewall.this.allowedParameterValues.test(value)) { throw new RequestRejectedException("The request was rejected because the parameter: \"" + name + " \" has a value \"" + value + "\" that is not allowed."); } } @Override public void reset() { } }; }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\StrictHttpFirewall.java
1
请完成以下Java代码
public class SequentialTbRuleEngineSubmitStrategy extends AbstractTbRuleEngineSubmitStrategy { private final AtomicInteger msgIdx = new AtomicInteger(0); private volatile BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer; private volatile UUID expectedMsgId; public SequentialTbRuleEngineSubmitStrategy(String queueName) { super(queueName); } @Override public void submitAttempt(BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer) { this.msgConsumer = msgConsumer; msgIdx.set(0); submitNext(); } @Override public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) { super.update(reprocessMap); } @Override protected void doOnSuccess(UUID id) { if (expectedMsgId.equals(id)) { msgIdx.incrementAndGet(); submitNext(); }
} private void submitNext() { int listSize = orderedMsgList.size(); int idx = msgIdx.get(); if (idx < listSize) { IdMsgPair<TransportProtos.ToRuleEngineMsg> pair = orderedMsgList.get(idx); expectedMsgId = pair.uuid; if (log.isDebugEnabled()) { log.debug("[{}] submitting [{}] message to rule engine", queueName, pair.msg); } msgConsumer.accept(pair.uuid, pair.msg); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\SequentialTbRuleEngineSubmitStrategy.java
1
请完成以下Spring Boot application配置
# REDIS # Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09 spring.redis.database=0 # Redis\u670D\u52A1\u5668\u5730\u5740 spring.redis.host=localhost # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3 spring.redis.port=6379 # Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09 spring.redis.password= # \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED8\u8BA4 8 spring.redis.lettuce.pool.max-active=8 # \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09 \u9ED
8\u8BA4 -1 spring.redis.lettuce.pool.max-wait=-1 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 8 spring.redis.lettuce.pool.max-idle=8 # \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5 \u9ED8\u8BA4 0 spring.redis.lettuce.pool.min-idle=0
repos\spring-boot-leaning-master\2.x_42_courses\第 4-2 课:Spring Boot 和 Redis 常用操作\spring-boot-redis\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private boolean isCachePdxReadSerializedEnabled() { return SimpleCacheResolver.getInstance().resolve() .filter(GemFireCache::getPdxReadSerialized) .isPresent(); } private boolean isPdxReadSerializedEnabled(@NonNull Environment environment) { return Optional.ofNullable(environment) .filter(env -> env.getProperty(PDX_READ_SERIALIZED_PROPERTY, Boolean.class, false)) .isPresent(); } } private static final boolean DEFAULT_EXPORT_ENABLED = false; private static final Predicate<Environment> disableGemFireShutdownHookPredicate = environment -> Optional.ofNullable(environment) .filter(env -> env.getProperty(CacheDataImporterExporterReference.EXPORT_ENABLED_PROPERTY_NAME, Boolean.class, DEFAULT_EXPORT_ENABLED)) .isPresent(); static abstract class AbstractDisableGemFireShutdownHookSupport { boolean shouldDisableGemFireShutdownHook(@Nullable Environment environment) { return disableGemFireShutdownHookPredicate.test(environment); } /** * If we do not disable Apache Geode's {@link org.apache.geode.distributed.DistributedSystem} JRE/JVM runtime * shutdown hook then the {@link org.apache.geode.cache.Region} is prematurely closed by the JRE/JVM shutdown hook * before Spring's {@link org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor}s can do * their work of exporting data from the {@link org.apache.geode.cache.Region} as JSON. */ void disableGemFireShutdownHook(@Nullable Environment environment) { System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString()); } } static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter { static final String EXPORT_ENABLED_PROPERTY_NAME = AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME; }
static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return shouldDisableGemFireShutdownHook(context.getEnvironment()); } } public static class DisableGemFireShutdownHookEnvironmentPostProcessor extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (shouldDisableGemFireShutdownHook(environment)) { disableGemFireShutdownHook(environment); } } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java
2
请完成以下Java代码
public VertragsdatenTag getTag() { return tag; } /** * Sets the value of the tag property. * * @param value * allowed object is * {@link VertragsdatenTag } * */ public void setTag(VertragsdatenTag value) { this.tag = value; } /** * Gets the value of the endezeit property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getEndezeit() { return endezeit; } /** * Sets the value of the endezeit property. * * @param value * allowed object is
* {@link XMLGregorianCalendar } * */ public void setEndezeit(XMLGregorianCalendar value) { this.endezeit = value; } /** * Gets the value of the hauptbestellzeit property. * * @return * possible object is * {@link VertragsdatenHauptbestellzeit } * */ public VertragsdatenHauptbestellzeit getHauptbestellzeit() { return hauptbestellzeit; } /** * Sets the value of the hauptbestellzeit property. * * @param value * allowed object is * {@link VertragsdatenHauptbestellzeit } * */ public void setHauptbestellzeit(VertragsdatenHauptbestellzeit value) { this.hauptbestellzeit = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenBestellfenster.java
1
请完成以下Java代码
public Map<Class<?>, String> getUpdateStatements() { return updateStatements; } public void setUpdateStatements(Map<Class<?>, String> updateStatements) { this.updateStatements = updateStatements; } public Map<Class<?>, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class<?>, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class<?>, String> getBulkDeleteStatements() { return bulkDeleteStatements; } public void setBulkDeleteStatements(Map<Class<?>, String> bulkDeleteStatements) { this.bulkDeleteStatements = bulkDeleteStatements; } public Map<Class<?>, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class<?>, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseCatalog() { return databaseCatalog; } public void setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) { this.tablePrefixIsSchema = tablePrefixIsSchema; } public boolean isTablePrefixIsSchema() { return tablePrefixIsSchema; } public int getMaxNrOfStatementsInBulkInsert() { return maxNrOfStatementsInBulkInsert; } public void setMaxNrOfStatementsInBulkInsert(int maxNrOfStatementsInBulkInsert) { this.maxNrOfStatementsInBulkInsert = maxNrOfStatementsInBulkInsert; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSessionFactory.java
1
请完成以下Java代码
public class DefaultPrintingQueueSource extends AbstractPrintingQueueSource { private final Properties ctx; private final IPrintingQueueQuery printingQueueQuery; private final PrintingQueueProcessingInfo printingQueueProcessingInfo; public DefaultPrintingQueueSource( @NonNull final Properties ctx, @NonNull final IPrintingQueueQuery printingQueueQuery, final PrintingQueueProcessingInfo printingQueueProcessingInfo) { this.ctx = ctx; this.printingQueueQuery = printingQueueQuery.copy(); this.printingQueueProcessingInfo = printingQueueProcessingInfo; } @Override public PrintingQueueProcessingInfo getProcessingInfo() { return printingQueueProcessingInfo; } /** * Iterate {@link I_C_Printing_Queue}s which are not processed yet. * * IMPORTANT: items are returned in FIFO order (ordered by {@link I_C_Printing_Queue#COLUMNNAME_C_Printing_Queue_ID}) */ @Override public Iterator<I_C_Printing_Queue> createItemsIterator() { return createPrintingQueueIterator(ctx, printingQueueQuery, ITrx.TRXNAME_None); } /** * Similar to {@link #createItemsIterator()}, but retrieves an iterator about all items have the same * <ul> * <li><code>AD_Client_ID</code> * <li><code>AD_Org_ID</code> * <li><code>Copies</code> * </ul> * as the given item, but excluding the given item itself. */ @Override public Iterator<I_C_Printing_Queue> createRelatedItemsIterator(@NonNull final I_C_Printing_Queue item) { final IPrintingQueueQuery queryRelated = printingQueueQuery.copy(); queryRelated.setAD_Client_ID(item.getAD_Client_ID()); queryRelated.setAD_Org_ID(item.getAD_Org_ID());
queryRelated.setIgnoreC_Printing_Queue_ID(item.getC_Printing_Queue_ID()); queryRelated.setCopies(item.getCopies()); // 08958 return createPrintingQueueIterator(ctx, queryRelated, ITrx.TRXNAME_None); } private Iterator<I_C_Printing_Queue> createPrintingQueueIterator(final Properties ctx, final IPrintingQueueQuery queueQuery, final String trxName) { final IQuery<I_C_Printing_Queue> query = Services.get(IPrintingDAO.class).createQuery(ctx, queueQuery, trxName); // IMPORTANT: we need to query only one item at time (BufferSize=1) because else // it could happen that we re-process again an item which was already processed but it was cached in the buffer. query.setOption(IQuery.OPTION_IteratorBufferSize, 1); final Iterator<I_C_Printing_Queue> it = query.iterate(I_C_Printing_Queue.class); return it; } @Override public String getTrxName() { // mass processing of not printed queue items shall be out of transaction return ITrx.TRXNAME_None; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\DefaultPrintingQueueSource.java
1
请完成以下Java代码
public class HistoricIdentityLinkEntityImpl extends AbstractEntityNoRevision implements HistoricIdentityLinkEntity, Serializable, BulkDeleteable { private static final long serialVersionUID = 1L; protected String type; protected String userId; protected String groupId; protected String taskId; protected String processInstanceId; protected byte[] details; public HistoricIdentityLinkEntityImpl() {} public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("id", this.id); persistentState.put("type", this.type); if (this.userId != null) { persistentState.put("userId", this.userId); } if (this.groupId != null) { persistentState.put("groupId", this.groupId); } if (this.taskId != null) { persistentState.put("taskId", this.taskId); } if (this.processInstanceId != null) { persistentState.put("processInstanceId", this.processInstanceId); } if (this.details != null) { persistentState.put("details", this.details); } return persistentState; } public boolean isUser() { return userId != null; } public boolean isGroup() { return groupId != null; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserId() { return userId;
} public void setUserId(String userId) { if (this.groupId != null && userId != null) { throw new ActivitiException("Cannot assign a userId to a task assignment that already has a groupId"); } this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { if (this.userId != null && groupId != null) { throw new ActivitiException("Cannot assign a groupId to a task assignment that already has a userId"); } this.groupId = groupId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public byte[] getDetails() { return this.details; } public void setDetails(byte[] details) { this.details = details; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java
1
请完成以下Java代码
public List<String> getDisable() { return disabledHeaders.stream().toList(); } /** * Binds the list of default/opt-out header names to disable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param disable - list of default/opt-out header names to disable */ public void setDisable(List<String> disable) { if (disable != null) { disabledHeaders = disable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } } /** * @return the opt-in header names to enable */ public Set<String> getEnabledHeaders() { return enabledHeaders; } /** * Binds the list of default/opt-out header names to enable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param enable - list of default/opt-out header enable */ public void setEnable(List<String> enable) { if (enable != null) { enabledHeaders = enable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } }
/** * @return the default/opt-out header names to disable */ public Set<String> getDisabledHeaders() { return disabledHeaders; } /** * @return the default/opt-out header names to apply */ public Set<String> getDefaultHeaders() { return defaultHeaders; } @Override public String toString() { return "SecureHeadersProperties{" + "xssProtectionHeader='" + xssProtectionHeader + '\'' + ", strictTransportSecurity='" + strictTransportSecurity + '\'' + ", frameOptions='" + frameOptions + '\'' + ", contentTypeOptions='" + contentTypeOptions + '\'' + ", referrerPolicy='" + referrerPolicy + '\'' + ", contentSecurityPolicy='" + contentSecurityPolicy + '\'' + ", downloadOptions='" + downloadOptions + '\'' + ", permittedCrossDomainPolicies='" + permittedCrossDomainPolicies + '\'' + ", permissionsPolicy='" + permissionsPolicy + '\'' + ", defaultHeaders=" + defaultHeaders + ", enable=" + enabledHeaders + ", disable=" + disabledHeaders + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersProperties.java
1
请完成以下Java代码
public void registerCalloutProvider(final ICalloutProvider providerToAdd) { final ICalloutProvider providersOld = providers; final ICalloutProvider providersNew = CompositeCalloutProvider.compose(providersOld, providerToAdd); if (providersNew == providersOld) { return; } providers = providersNew; logger.info("Registered provider: {}", providerToAdd); } /** * * @return registered providers */ @VisibleForTesting final List<ICalloutProvider> getCalloutProvidersList() { final ICalloutProvider providers = this.providers; if (providers instanceof CompositeCalloutProvider) { return ((CompositeCalloutProvider)providers).getProvidersList(); } else if (NullCalloutProvider.isNull(providers)) { return ImmutableList.of(); } else {
return ImmutableList.of(providers); } } @Override public ICalloutProvider getProvider() { return providers; } @Override public TableCalloutsMap getCallouts(final Properties ctx, final String tableName) { return providers.getCallouts(ctx, tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutFactory.java
1
请完成以下Java代码
public boolean isCatchWeight(@NonNull final org.compiere.model.I_C_OrderLine orderLine) { return InvoicableQtyBasedOn.ofNullableCodeOrNominal(orderLine.getInvoicableQtyBasedOn()).isCatchWeight(); } @Override public Optional<BPartnerId> getBPartnerId(@NonNull final OrderLineId orderLineId) { final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); return BPartnerId.optionalOfRepoId(orderLine.getC_BPartner_ID()); } @Override public Optional<BPartnerId> getBPartnerId(@NonNull final OrderAndLineId orderLineId) { final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); return BPartnerId.optionalOfRepoId(orderLine.getC_BPartner_ID()); } @Override public void setTax(@NonNull final org.compiere.model.I_C_OrderLine orderLine) { final I_C_Order orderRecord = orderBL().getById(OrderId.ofRepoId(orderLine.getC_Order_ID())); final TaxCategoryId taxCategoryId = getTaxCategoryId(orderLine); final WarehouseId warehouseId = warehouseAdvisor.evaluateWarehouse(orderLine); final CountryId countryFromId = warehouseBL.getCountryId(warehouseId); final BPartnerLocationAndCaptureId bpLocationId = OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).getBPartnerLocationAndCaptureId(); final boolean isSOTrx = orderRecord.isSOTrx(); final Timestamp taxDate = orderLine.getDatePromised(); final BPartnerId effectiveBillPartnerId = orderBL().getEffectiveBillPartnerId(orderRecord); // if we set the tax for a sales order, consider whether the customer is exempt from taxes final Boolean isTaxExempt; if (isSOTrx && effectiveBillPartnerId != null) { final I_C_BPartner billBPartnerRecord = bpartnerDAO.getById(effectiveBillPartnerId); // Only set if TRUE - otherwise leave null (don't filter) isTaxExempt = billBPartnerRecord.isTaxExempt() ? Boolean.TRUE : null;
} else { isTaxExempt = null; } final Tax tax = taxDAO.getBy(TaxQuery.builder() .fromCountryId(countryFromId) .orgId(OrgId.ofRepoId(orderLine.getAD_Org_ID())) .bPartnerLocationId(bpLocationId) .warehouseId(warehouseId) .dateOfInterest(taxDate) .taxCategoryId(taxCategoryId) .soTrx(SOTrx.ofBoolean(isSOTrx)) .isTaxExempt(isTaxExempt) .build()); if (tax == null) { TaxNotFoundException.builder() .taxCategoryId(taxCategoryId) .isSOTrx(isSOTrx) .isTaxExempt(isTaxExempt) .billDate(taxDate) .billFromCountryId(countryFromId) .billToC_Location_ID(bpLocationId.getLocationCaptureId()) .build() .throwOrLogWarning(true, logger); } orderLine.setC_Tax_ID(tax.getTaxId().getRepoId()); orderLine.setC_TaxCategory_ID(tax.getTaxCategoryId().getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLineBL.java
1
请完成以下Java代码
public String getDescription() { return description; } @JsonIgnore public boolean isDisabled() { return disabled != null && disabled; } @JsonIgnore public boolean isEnabled() { return !isDisabled(); } public boolean isQuickAction() { return quickAction; }
public boolean isDefaultQuickAction() { return defaultQuickAction; } private int getSortNo() { return sortNo; } @JsonAnyGetter public Map<String, Object> getDebugProperties() { return debugProperties; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONDocumentAction.java
1
请完成以下Java代码
public class ActivityInstanceQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, ActivityInstanceQueryProperty> properties = new HashMap<>(); public static final ActivityInstanceQueryProperty ACTIVITY_INSTANCE_ID = new ActivityInstanceQueryProperty("ID_"); public static final ActivityInstanceQueryProperty PROCESS_INSTANCE_ID = new ActivityInstanceQueryProperty("PROC_INST_ID_"); public static final ActivityInstanceQueryProperty EXECUTION_ID = new ActivityInstanceQueryProperty("EXECUTION_ID_"); public static final ActivityInstanceQueryProperty ACTIVITY_ID = new ActivityInstanceQueryProperty("ACT_ID_"); public static final ActivityInstanceQueryProperty ACTIVITY_NAME = new ActivityInstanceQueryProperty("ACT_NAME_"); public static final ActivityInstanceQueryProperty ACTIVITY_TYPE = new ActivityInstanceQueryProperty("ACT_TYPE_"); public static final ActivityInstanceQueryProperty PROCESS_DEFINITION_ID = new ActivityInstanceQueryProperty("PROC_DEF_ID_"); public static final ActivityInstanceQueryProperty START = new ActivityInstanceQueryProperty("START_TIME_"); public static final ActivityInstanceQueryProperty END = new ActivityInstanceQueryProperty("END_TIME_"); public static final ActivityInstanceQueryProperty DURATION = new ActivityInstanceQueryProperty("DURATION_"); public static final ActivityInstanceQueryProperty TENANT_ID = new ActivityInstanceQueryProperty("TENANT_ID_"); private String name;
public ActivityInstanceQueryProperty(String name) { this.name = name; properties.put(name, this); } @Override public String getName() { return name; } public static ActivityInstanceQueryProperty findByName(String propertyName) { return properties.get(propertyName); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ActivityInstanceQueryProperty.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(NAME_KEY, REGEXP_KEY); } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { List<HttpCookie> cookies = exchange.getRequest().getCookies().get(config.name); if (cookies == null || config.regexp == null) { return false; } return cookies.stream().anyMatch(cookie -> cookie.getValue().matches(config.regexp)); } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Cookie: name=%s regexp=%s", config.name, config.regexp); } }; } public static class Config { @NotEmpty
private @Nullable String name; @NotEmpty private @Nullable String regexp; public @Nullable String getName() { return name; } public Config setName(String name) { this.name = name; return this; } public @Nullable String getRegexp() { return regexp; } public Config setRegexp(String regexp) { this.regexp = regexp; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\CookieRoutePredicateFactory.java
1
请完成以下Java代码
public boolean isNew() { return isGeneratedAttribute; } @Override protected void setInternalValueDate(Date value) { attributeInstance.setValueDate(TimeUtil.asTimestamp(value)); } @Override protected Date getInternalValueDate() { return attributeInstance.getValueDate(); } @Override protected void setInternalValueDateInitial(Date value) {
throw new UnsupportedOperationException("Setting initial value not supported"); } @Override protected Date getInternalValueDateInitial() { return null; } @Override public boolean isOnlyIfInProductAttributeSet() { // FIXME tsa: figure out why this returns false instead of using the flag from M_HU_PI_Attribute?! return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AIWithHUPIAttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
protected Function<Endpoints, Endpoints> alignWithManagementUrl(InstanceId instanceId, String managementUrl) { return (endpoints) -> { if (!managementUrl.startsWith("https:")) { return endpoints; } if (endpoints.stream().noneMatch((e) -> e.getUrl().startsWith("http:"))) { return endpoints; } log.warn( "Endpoints for instance {} queried from {} are falsely using http. Rewritten to https. Consider configuring this instance to use 'server.forward-headers-strategy=native'.", instanceId, managementUrl); return Endpoints.of(endpoints.stream() .map((e) -> Endpoint.of(e.getId(), e.getUrl().replaceFirst("http:", "https:"))) .toList()); }; } protected Mono<Endpoints> convertResponse(Response response) { List<Endpoint> endpoints = response.getLinks() .entrySet() .stream() .filter((e) -> !e.getKey().equals("self") && !e.getValue().isTemplated()) .map((e) -> Endpoint.of(e.getKey(), e.getValue().getHref())) .toList(); return endpoints.isEmpty() ? Mono.empty() : Mono.just(Endpoints.of(endpoints)); } @Data protected static class Response { @JsonProperty("_links") private Map<String, EndpointRef> links = new HashMap<>();
@Data protected static class EndpointRef { private final String href; private final boolean templated; @JsonCreator EndpointRef(@JsonProperty("href") String href, @JsonProperty("templated") boolean templated) { this.href = href; this.templated = templated; } } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\endpoints\QueryIndexEndpointStrategy.java
2
请在Spring Boot框架中完成以下Java代码
public final class ReactiveUserDetailsServiceAutoConfiguration { private static final String NOOP_PASSWORD_PREFIX = "{noop}"; private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$"); private static final Log logger = LogFactory.getLog(ReactiveUserDetailsServiceAutoConfiguration.class); @Bean MapReactiveUserDetailsService reactiveUserDetailsService(SecurityProperties properties, ObjectProvider<PasswordEncoder> passwordEncoder) { SecurityProperties.User user = properties.getUser(); UserDetails userDetails = getUserDetails(user, getOrDeducePassword(user, passwordEncoder.getIfAvailable())); return new MapReactiveUserDetailsService(userDetails); } private UserDetails getUserDetails(SecurityProperties.User user, String password) { List<String> roles = user.getRoles(); return User.withUsername(user.getName()).password(password).roles(StringUtils.toStringArray(roles)).build(); } private String getOrDeducePassword(SecurityProperties.User user, @Nullable PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; }
return NOOP_PASSWORD_PREFIX + password; } static class RSocketEnabledOrReactiveWebApplication extends AnyNestedCondition { RSocketEnabledOrReactiveWebApplication() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(RSocketMessageHandler.class) static class RSocketSecurityEnabledCondition { } @ConditionalOnWebApplication(type = Type.REACTIVE) static class ReactiveWebApplicationCondition { } } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\ReactiveUserDetailsServiceAutoConfiguration.java
2
请完成以下Java代码
public boolean comparesEqualTo(final BigDecimal val) { return value.compareTo(val) == 0; } public int signum() { return value.signum(); } public MutableBigDecimal min(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) <= 0) { return this; } else {
return value; } } public MutableBigDecimal max(final MutableBigDecimal value) { if (this.value.compareTo(value.getValue()) >= 0) { return this; } else { return value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableBigDecimal.java
1
请完成以下Java代码
public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setErrorMsg (java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg); } @Override public void setImportStatus (java.lang.String ImportStatus) { set_Value (COLUMNNAME_ImportStatus, ImportStatus); } @Override public java.lang.String getImportStatus() { return (java.lang.String)get_Value(COLUMNNAME_ImportStatus); } @Override public void setJsonRequest (java.lang.String JsonRequest) { set_ValueNoCheck (COLUMNNAME_JsonRequest, JsonRequest); } @Override
public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setJsonResponse (java.lang.String JsonResponse) { set_Value (COLUMNNAME_JsonResponse, JsonResponse); } @Override public java.lang.String getJsonResponse() { return (java.lang.String)get_Value(COLUMNNAME_JsonResponse); } @Override public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID)); } @Override public int getPP_Cost_Collector_ImportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleRssController { @GetMapping(value = "/rss1") public String articleMvcFeed() { return "articleFeedView"; } @GetMapping(value = "/rss2", produces = {"application/rss+xml", "application/rss+json"}) @ResponseBody public Channel articleHttpFeed() { List<Article> items = new ArrayList<>(); Article item1 = new Article(); item1.setLink("http://www.baeldung.com/netty-exception-handling"); item1.setTitle("Exceptions in Netty"); item1.setDescription("In this quick article, we’ll be looking at exception handling in Netty."); item1.setPublishedDate(new Date()); item1.setAuthor("Carlos"); Article item2 = new Article(); item2.setLink("http://www.baeldung.com/cockroachdb-java"); item2.setTitle("Guide to CockroachDB in Java"); item2.setDescription("This tutorial is an introductory guide to using CockroachDB with Java."); item2.setPublishedDate(new Date()); item2.setAuthor("Baeldung"); items.add(item1); items.add(item2); Channel channelData = buildChannel(items); return channelData;
} private Channel buildChannel(List<Article> articles){ Channel channel = new Channel("rss_2.0"); channel.setLink("http://localhost:8080/spring-mvc-simple/rss"); channel.setTitle("Article Feed"); channel.setDescription("Article Feed Description"); channel.setPubDate(new Date()); List<Item> items = new ArrayList<>(); for (Article article : articles) { Item item = new Item(); item.setLink(article.getLink()); item.setTitle(article.getTitle()); Description description1 = new Description(); description1.setValue(article.getDescription()); item.setDescription(description1); item.setPubDate(article.getPublishedDate()); item.setAuthor(article.getAuthor()); items.add(item); } channel.setItems(items); return channel; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\rss\ArticleRssController.java
2
请完成以下Java代码
public static final class Builder { public String getFieldName() { return fieldName; } public String getParameterName() { return parameterName; } public DocumentFieldWidgetType getWidgetType() { return widgetType; } public Builder displayName(@NonNull final ITranslatableString displayName) { this.displayName = TranslatableStrings.copyOf(displayName); return this; } public Builder displayName(final String displayName) { this.displayName = TranslatableStrings.constant(displayName); return this; } public Builder displayName(final AdMessageKey displayName) { return displayName(TranslatableStrings.adMessage(displayName)); } public ITranslatableString getDisplayName()
{ return displayName; } public Builder lookupDescriptor(@NonNull final Optional<LookupDescriptor> lookupDescriptor) { this.lookupDescriptor = lookupDescriptor; return this; } public Builder lookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor) { return lookupDescriptor(Optional.ofNullable(lookupDescriptor)); } public Builder lookupDescriptor(@NonNull final UnaryOperator<LookupDescriptor> mapper) { if (this.lookupDescriptor!= null) // don't replace with isPresent() since it could be null at this point { return lookupDescriptor(this.lookupDescriptor.map(mapper)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParamDescriptor.java
1
请完成以下Java代码
public abstract class PvmAtomicOperationCreateConcurrentExecution implements PvmAtomicOperation { public void execute(PvmExecutionImpl execution) { // Invariant: execution is the Scope Execution for the activity's flow scope. PvmActivity activityToStart = execution.getNextActivity(); execution.setNextActivity(null); PvmExecutionImpl propagatingExecution = execution.createConcurrentExecution(); // set next activity on propagating execution propagatingExecution.setActivity(activityToStart); setDelayedPayloadToNewScope(propagatingExecution, (CoreModelElement) activityToStart); concurrentExecutionCreated(propagatingExecution); } protected abstract void concurrentExecutionCreated(PvmExecutionImpl propagatingExecution); public boolean isAsync(PvmExecutionImpl execution) { return false; }
protected void setDelayedPayloadToNewScope(PvmExecutionImpl execution, CoreModelElement scope) { String activityType = (String) scope.getProperty(BpmnProperties.TYPE.getName()); if (ActivityTypes.START_EVENT_MESSAGE.equals(activityType) // Event subprocess message start event || ActivityTypes.BOUNDARY_MESSAGE.equals(activityType)) { PvmExecutionImpl processInstance = execution.getProcessInstance(); if (processInstance.getPayloadForTriggeredScope() != null) { execution.setVariablesLocal(processInstance.getPayloadForTriggeredScope()); // clear the process instance processInstance.setPayloadForTriggeredScope(null); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationCreateConcurrentExecution.java
1
请完成以下Java代码
public static void updateWeightNet(@NonNull final IWeightable weightable) { // NOTE: we calculate WeightGross, no matter if our HU is allowed to be weighted by user // final boolean weightUOMFriendly = weightable.isWeightable(); final BigDecimal weightTare = weightable.getWeightTareTotal(); final BigDecimal weightGross = weightable.getWeightGross(); final BigDecimal weightNet = weightGross.subtract(weightTare); final BigDecimal weightNetActual; // // If Gross < Tare, we need to propagate the net value with the initial container's Tare value re-added (+) to preserve the real mathematical values if (weightNet.signum() >= 0) { weightNetActual = weightNet; // propagate net value below normally weightable.setWeightNet(weightNetActual); } else {
weightNetActual = weightNet.add(weightable.getWeightTareInitial()); // only subtract seed value (the container's weight) weightable.setWeightNet(weightNetActual); weightable.setWeightNetNoPropagate(weightNet); // directly set the correct value we're expecting } } public static boolean isWeightableAttribute(@NonNull final AttributeCode attributeCode) { return Weightables.ATTR_WeightGross.equals(attributeCode) || Weightables.ATTR_WeightNet.equals(attributeCode) || Weightables.ATTR_WeightTare.equals(attributeCode) || Weightables.ATTR_WeightTareAdjust.equals(attributeCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\Weightables.java
1
请完成以下Java代码
public CommandExecutor getCommandExecutor() { return commandExecutor; } public CommandContext getCommandContext() { return commandContext; } public String getMessageName() { return messageName; } public String getBusinessKey() { return businessKey; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public Map<String, Object> getCorrelationProcessInstanceVariables() { return correlationProcessInstanceVariables; } public Map<String, Object> getCorrelationLocalVariables() { return correlationLocalVariables; } public Map<String, Object> getPayloadProcessInstanceVariables() { return payloadProcessInstanceVariables; } public VariableMap getPayloadProcessInstanceVariablesLocal() { return payloadProcessInstanceVariablesLocal;
} public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() { return payloadProcessInstanceVariablesToTriggeredScope; } public boolean isExclusiveCorrelation() { return isExclusiveCorrelation; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isExecutionsOnly() { return executionsOnly; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java
1
请完成以下Java代码
public class VerfuegbarkeitsantwortArtikel { @XmlElement(name = "AnfrageMenge") protected int anfrageMenge; @XmlElement(name = "AnfragePzn") protected long anfragePzn; @XmlElement(name = "Substitution") protected VerfuegbarkeitSubstitution substitution; @XmlElement(name = "Anteile", required = true) protected List<VerfuegbarkeitAnteil> anteile; /** * Gets the value of the anfrageMenge property. * */ public int getAnfrageMenge() { return anfrageMenge; } /** * Sets the value of the anfrageMenge property. * */ public void setAnfrageMenge(int value) { this.anfrageMenge = value; } /** * Gets the value of the anfragePzn property. * */ public long getAnfragePzn() { return anfragePzn; } /** * Sets the value of the anfragePzn property. * */ public void setAnfragePzn(long value) { this.anfragePzn = value; } /** * Gets the value of the substitution property. * * @return * possible object is * {@link VerfuegbarkeitSubstitution }
* */ public VerfuegbarkeitSubstitution getSubstitution() { return substitution; } /** * Sets the value of the substitution property. * * @param value * allowed object is * {@link VerfuegbarkeitSubstitution } * */ public void setSubstitution(VerfuegbarkeitSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link VerfuegbarkeitAnteil } * * */ public List<VerfuegbarkeitAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<VerfuegbarkeitAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsantwortArtikel.java
1
请完成以下Java代码
public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public void setCcy(String value) { this.ccy = value; } /** * Gets the value of the nm property. * * @return * possible object is
* {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashAccount16.java
1
请完成以下Java代码
protected ExecutionEntity resolveExecution(HistoryCleanupContext context) { return null; } @Override protected EverLivingJobEntity newJobInstance(HistoryCleanupContext context) { return new EverLivingJobEntity(); } @Override protected void postInitialize(HistoryCleanupContext context, EverLivingJobEntity job) { } @Override public EverLivingJobEntity reconfigure(HistoryCleanupContext context, EverLivingJobEntity job) { HistoryCleanupJobHandlerConfiguration configuration = resolveJobHandlerConfiguration(context); job.setJobHandlerConfiguration(configuration); return job; } @Override protected HistoryCleanupJobHandlerConfiguration resolveJobHandlerConfiguration(HistoryCleanupContext context) { HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration(); config.setImmediatelyDue(context.isImmediatelyDue()); config.setMinuteFrom(context.getMinuteFrom()); config.setMinuteTo(context.getMinuteTo()); return config; } @Override
protected int resolveRetries(HistoryCleanupContext context) { return context.getMaxRetries(); } @Override public Date resolveDueDate(HistoryCleanupContext context) { return resolveDueDate(context.isImmediatelyDue()); } private Date resolveDueDate(boolean isImmediatelyDue) { CommandContext commandContext = Context.getCommandContext(); if (isImmediatelyDue) { return ClockUtil.getCurrentTime(); } else { final BatchWindow currentOrNextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager() .getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration()); if (currentOrNextBatchWindow != null) { return currentOrNextBatchWindow.getStart(); } else { return null; } } } public ParameterValueProvider getJobPriorityProvider() { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); long historyCleanupJobPriority = configuration.getHistoryCleanupJobPriority(); return new ConstantValueProvider(historyCleanupJobPriority); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public static ClientKeyStore loadClientKeyStore(String keyStorePath, String keyStorePass, String privateKeyPass){ try{ return loadClientKeyStore(new FileInputStream(keyStorePath), keyStorePass, privateKeyPass); }catch(Exception e){ logger.error("loadClientKeyFactory fail : "+e.getMessage(), e); return null; } } public static ClientKeyStore loadClientKeyStore(InputStream keyStoreStream, String keyStorePass, String privateKeyPass){ try{ KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keyStoreStream, keyStorePass.toCharArray()); kmf.init(ks, privateKeyPass.toCharArray()); return new ClientKeyStore(kmf); }catch(Exception e){ logger.error("loadClientKeyFactory fail : "+e.getMessage(), e); return null; } } public static TrustKeyStore loadTrustKeyStore(String keyStorePath, String keyStorePass){ try{ return loadTrustKeyStore(new FileInputStream(keyStorePath), keyStorePass); }catch(Exception e){ logger.error("loadTrustCertFactory fail : "+e.getMessage(), e); return null;
} } public static TrustKeyStore loadTrustKeyStore(InputStream keyStoreStream, String keyStorePass){ try{ TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keyStoreStream, keyStorePass.toCharArray()); tmf.init(ks); return new TrustKeyStore(tmf); }catch(Exception e){ logger.error("loadTrustCertFactory fail : "+e.getMessage(), e); return null; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpUtils.java
2
请完成以下Java代码
public class InOutCostDeleteCommand { @NonNull private final OrderCostRepository orderCostRepository; @NonNull private final InOutCostRepository inOutCostRepository; @NonNull private final InOutId inoutId; @Builder private InOutCostDeleteCommand( final @NonNull OrderCostRepository orderCostRepository, final @NonNull InOutCostRepository inOutCostRepository, // final @NonNull InOutId inoutId) { this.orderCostRepository = orderCostRepository; this.inOutCostRepository = inOutCostRepository; this.inoutId = inoutId; } public void execute() { final ImmutableList<InOutCost> inoutCosts = inOutCostRepository.getByInOutId(inoutId);
if (inoutCosts.isEmpty()) { return; } final ImmutableSet<OrderCostId> orderCostIds = inoutCosts.stream().map(InOutCost::getOrderCostId).collect(ImmutableSet.toImmutableSet()); final ImmutableMap<OrderCostId, OrderCost> orderCostsById = Maps.uniqueIndex(orderCostRepository.getByIds(orderCostIds), OrderCost::getId); for (final InOutCost inoutCost : inoutCosts) { final OrderCost orderCost = orderCostsById.get(inoutCost.getOrderCostId()); orderCost.addInOutCost( OrderCostAddInOutRequest.builder() .orderLineId(inoutCost.getOrderLineId()) .qty(inoutCost.getQty().negate()) .costAmount(inoutCost.getCostAmount().negate()) .build()); } inOutCostRepository.deleteAll(inoutCosts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCostDeleteCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentServiceImp implements StudentService { @Autowired private StudentDao studentDao; @Override public int add(Student student) { return this.studentDao.add(student); } @Override public int update(Student student) { return this.studentDao.update(student); } @Override
public int deleteBysno(String sno) { return this.studentDao.deleteBysno(sno); } @Override public List<Map<String, Object>> queryStudentListMap() { return this.studentDao.queryStudentsListMap(); } @Override public Student queryStudentBySno(String sno) { return this.studentDao.queryStudentBySno(sno); } }
repos\SpringAll-master\04.Spring-Boot-JdbcTemplate\src\main\java\com\springboot\service\impl\StudentServiceImp.java
2
请完成以下Java代码
public BigDecimal getQty() { return forecastLine.getQty(); } @Override public int getM_HU_PI_Item_Product_ID() { final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID(); if (forecastLine_PIItemProductId > 0) { return forecastLine_PIItemProductId; } return -1; } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return forecastLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { forecastLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId)
{ values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java
1
请完成以下Java代码
public PartyIdentification32 getInvcr() { return invcr; } /** * Sets the value of the invcr property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setInvcr(PartyIdentification32 value) { this.invcr = value; } /** * Gets the value of the invcee property. * * @return * possible object is * {@link PartyIdentification32 } * */ public PartyIdentification32 getInvcee() { return invcee; } /** * Sets the value of the invcee property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setInvcee(PartyIdentification32 value) { this.invcee = value; } /** * Gets the value of the addtlRmtInf property. *
* <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addtlRmtInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddtlRmtInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddtlRmtInf() { if (addtlRmtInf == null) { addtlRmtInf = new ArrayList<String>(); } return this.addtlRmtInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\StructuredRemittanceInformation7.java
1
请完成以下Java代码
public int getDisplayLength() { return displayLength; } public void setDisplayLength(final int displayLength) { this.displayLength = displayLength; } public int getColumnDisplayLength() { return columnDisplayLength; } public void setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; } public boolean isSameLine() { return sameLine; } public void setSameLine(final boolean sameLine) { this.sameLine = sameLine; } /** * Is this a long (string/text) field (over 60/2=30 characters) * * @return true if long field */ public boolean isLongField() { // if (m_vo.displayType == DisplayType.String // || m_vo.displayType == DisplayType.Text // || m_vo.displayType == DisplayType.Memo // || m_vo.displayType == DisplayType.TextLong // || m_vo.displayType == DisplayType.Image) return displayLength >= MAXDISPLAY_LENGTH / 2; // return false; } // isLongField public int getSpanX() { return spanX; } public int getSpanY() { return spanY;
} public static final class Builder { private int displayLength = 0; private int columnDisplayLength = 0; private boolean sameLine = false; private int spanX = 1; private int spanY = 1; private Builder() { super(); } public GridFieldLayoutConstraints build() { return new GridFieldLayoutConstraints(this); } public Builder setDisplayLength(final int displayLength) { this.displayLength = displayLength; return this; } public Builder setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; return this; } public Builder setSameLine(final boolean sameLine) { this.sameLine = sameLine; return this; } public Builder setSpanX(final int spanX) { this.spanX = spanX; return this; } public Builder setSpanY(final int spanY) { this.spanY = spanY; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldLayoutConstraints.java
1
请完成以下Java代码
public StringAttributeBuilder namespace(String namespaceUri) { return (StringAttributeBuilder) super.namespace(namespaceUri); } @Override public StringAttributeBuilder defaultValue(String defaultValue) { return (StringAttributeBuilder) super.defaultValue(defaultValue); } @Override public StringAttributeBuilder required() { return (StringAttributeBuilder) super.required(); } @Override public StringAttributeBuilder idAttribute() { return (StringAttributeBuilder) super.idAttribute(); } /** * Create a new {@link AttributeReferenceBuilder} for the reference source element instance * * @param referenceTargetElement the reference target model element instance * @return the new attribute reference builder */ public <V extends ModelElementInstance> AttributeReferenceBuilder<V> qNameAttributeReference(Class<V> referenceTargetElement) { AttributeImpl<String> attribute = (AttributeImpl<String>) build(); AttributeReferenceBuilderImpl<V> referenceBuilder = new QNameAttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement); setAttributeReference(referenceBuilder); return referenceBuilder; } public <V extends ModelElementInstance> AttributeReferenceBuilder<V> idAttributeReference(Class<V> referenceTargetElement) { AttributeImpl<String> attribute = (AttributeImpl<String>) build(); AttributeReferenceBuilderImpl<V> referenceBuilder = new AttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement); setAttributeReference(referenceBuilder); return referenceBuilder; } @SuppressWarnings("rawtypes") public <V extends ModelElementInstance> AttributeReferenceCollectionBuilder<V> idAttributeReferenceCollection(Class<V> referenceTargetElement, Class<? extends AttributeReferenceCollection> attributeReferenceCollection) { AttributeImpl<String> attribute = (AttributeImpl<String>) build(); AttributeReferenceCollectionBuilder<V> referenceBuilder = new AttributeReferenceCollectionBuilderImpl<V>(attribute, referenceTargetElement, attributeReferenceCollection); setAttributeReference(referenceBuilder);
return referenceBuilder; } protected <V extends ModelElementInstance> void setAttributeReference(AttributeReferenceBuilder<V> referenceBuilder) { if (this.referenceBuilder != null) { throw new ModelException("An attribute cannot have more than one reference"); } this.referenceBuilder = referenceBuilder; } @Override public void performModelBuild(Model model) { super.performModelBuild(model); if (referenceBuilder != null) { ((ModelBuildOperation) referenceBuilder).performModelBuild(model); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\StringAttributeBuilderImpl.java
1
请完成以下Java代码
public static byte[] fileAsByteArray(File file) { try { return inputStreamAsByteArray(new FileInputStream(file)); } catch(FileNotFoundException e) { throw LOG.fileNotFoundException(file.getAbsolutePath(), e); } } /** * Returns the input stream of a file with specified filename * * @param filename the name of a File to load * @return the file content as input stream * @throws IoUtilException if the file cannot be loaded */ public static InputStream fileAsStream(String filename) { File classpathFile = getClasspathFile(filename); return fileAsStream(classpathFile); } /** * Returns the input stream of a file. * * @param file the File to load * @return the file content as input stream * @throws IoUtilException if the file cannot be loaded */ public static InputStream fileAsStream(File file) { try { return new BufferedInputStream(new FileInputStream(file)); } catch(FileNotFoundException e) { throw LOG.fileNotFoundException(file.getAbsolutePath(), e); } } /** * Returns the File for a filename. * * @param filename the filename to load * @return the file object */ public static File getClasspathFile(String filename) { if(filename == null) { throw LOG.nullParameter("filename"); } return getClasspathFile(filename, null);
} /** * Returns the File for a filename. * * @param filename the filename to load * @param classLoader the classLoader to load file with, if null falls back to TCCL and then this class's classloader * @return the file object * @throws IoUtilException if the file cannot be loaded */ public static File getClasspathFile(String filename, ClassLoader classLoader) { if(filename == null) { throw LOG.nullParameter("filename"); } URL fileUrl = null; if (classLoader != null) { fileUrl = classLoader.getResource(filename); } if (fileUrl == null) { // Try the current Thread context classloader classLoader = Thread.currentThread().getContextClassLoader(); fileUrl = classLoader.getResource(filename); if (fileUrl == null) { // Finally, try the classloader for this class classLoader = IoUtil.class.getClassLoader(); fileUrl = classLoader.getResource(filename); } } if(fileUrl == null) { throw LOG.fileNotFoundException(filename); } try { return new File(fileUrl.toURI()); } catch(URISyntaxException e) { throw LOG.fileNotFoundException(filename, e); } } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\IoUtil.java
1
请完成以下Java代码
public java.math.BigDecimal getWorkingTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WorkingTime); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } @Override public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID) { if (C_Manufacturing_Aggregation_ID < 1) set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null); else set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID); } @Override public int getC_Manufacturing_Aggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_PlanningSchema.java
1
请完成以下Java代码
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials() .toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } } @Override protected void doAfterPropertiesSet() throws Exception { Assert.notNull(this.userDetailsService, "A UserDetailsService must be set"); this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD); } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
UserDetails loadedUser; try { loadedUser = this.userDetailsService.loadUserByUsernameAndDomain(auth.getPrincipal() .toString(), auth.getDomain()); } catch (UsernameNotFoundException notFound) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials() .toString(); passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword); } throw notFound; } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new InternalAuthenticationServiceException("UserDetailsService returned null, " + "which is an interface contract violation"); } return loadedUser; } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\CustomUserDetailsAuthenticationProvider.java
1
请完成以下Java代码
protected void dispatchTransactionEventListener(FlowableEvent event, FlowableEventListener listener) { TransactionContext transactionContext = Context.getTransactionContext(); if (transactionContext == null) { return; } ExecuteEventListenerTransactionListener transactionListener = new ExecuteEventListenerTransactionListener(listener, event); if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.COMMITTING.name())) { transactionContext.addTransactionListener(TransactionState.COMMITTING, transactionListener); } else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.COMMITTED.name())) { transactionContext.addTransactionListener(TransactionState.COMMITTED, transactionListener); } else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.ROLLINGBACK.name())) { transactionContext.addTransactionListener(TransactionState.ROLLINGBACK, transactionListener); } else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.ROLLED_BACK.name())) { transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, transactionListener); } else { LOGGER.warn("Unrecognised TransactionState {}", listener.getOnTransaction());
} } protected synchronized void addTypedEventListener(FlowableEventListener listener, FlowableEventType type) { List<FlowableEventListener> listeners = typedListeners.get(type); if (listeners == null) { // Add an empty list of listeners for this type listeners = new CopyOnWriteArrayList<>(); typedListeners.put(type, listeners); } if (!listeners.contains(listener)) { listeners.add(listener); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableEventSupport.java
1
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) { this.ttlAmt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is
* {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BatchInformation2.java
1
请完成以下Java代码
public class SubprocessValidator extends ProcessLevelValidator { @Override protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) { List<SubProcess> subProcesses = process.findFlowElementsOfType(SubProcess.class); for (SubProcess subProcess : subProcesses) { if (!(subProcess instanceof EventSubProcess)) { // Verify start events List<StartEvent> startEvents = process.findFlowElementsInSubProcessOfType( subProcess, StartEvent.class, false ); if (startEvents.size() > 1) { addError(errors, Problems.SUBPROCESS_MULTIPLE_START_EVENTS, process, subProcess);
} for (StartEvent startEvent : startEvents) { if (!startEvent.getEventDefinitions().isEmpty()) { addError( errors, Problems.SUBPROCESS_START_EVENT_EVENT_DEFINITION_NOT_ALLOWED, process, startEvent ); } } } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\SubprocessValidator.java
1
请完成以下Java代码
public void setBkTxCd(BankTransactionCodeStructure4 value) { this.bkTxCd = value; } /** * Gets the value of the avlbty property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the avlbty property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAvlbty().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link CashBalanceAvailability2 } * * */ public List<CashBalanceAvailability2> getAvlbty() { if (avlbty == null) { avlbty = new ArrayList<CashBalanceAvailability2>(); } return this.avlbty; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TotalsPerBankTransactionCode2.java
1
请完成以下Java代码
public Criteria andFinishOrderAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("finish_order_amount not between", value1, value2, "finishOrderAmount"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() {
return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTagExample.java
1
请完成以下Java代码
protected @Nullable Long size() { return null; } @Override protected long hitCount() { return this.cache.getStatistics().getHits(); } @Override protected Long missCount() { return this.cache.getStatistics().getMisses(); } @Override protected @Nullable Long evictionCount() { return null; } @Override protected long putCount() { return this.cache.getStatistics().getPuts();
} @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { FunctionCounter.builder("cache.removals", this.cache, (cache) -> cache.getStatistics().getDeletes()) .tags(getTagsWithCacheName()) .description("Cache removals") .register(registry); FunctionCounter.builder("cache.gets", this.cache, (cache) -> cache.getStatistics().getPending()) .tags(getTagsWithCacheName()) .tag("result", "pending") .description("The number of pending requests") .register(registry); TimeGauge .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) .tags(getTagsWithCacheName()) .description("The time the cache has spent waiting on a lock") .register(registry); } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\metrics\RedisCacheMetrics.java
1
请完成以下Java代码
public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null); else set_Value (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Phys.Inventory Line. @return Unique line in an Inventory document */ public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Scrapped Quantity. @param ScrappedQty The Quantity scrapped due to QA issues */ public void setScrappedQty (BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Scrapped Quantity. @return The Quantity scrapped due to QA issues */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Target Quantity. @param TargetQty Target Movement Quantity */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Target Quantity. @return Target Movement Quantity */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineConfirm.java
1
请完成以下Java代码
public boolean supports(AuthenticationToken token) { //这个token就是从过滤器中传入的jwtToken return token instanceof HeaderToken; } //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } //认证 //这个token就是从过滤器中传入的jwtToken @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String headerKey = (String) token.getPrincipal();
if (headerKey == null) { throw new NullPointerException("headerKey 不允许为空"); } if (!"123".equals(headerKey)) { throw new AuthenticationException("认证失败"); } // 校验逻辑 //... //下面是验证这个user是否是真实存在的 log.info("使用header认证: " + headerKey); return new SimpleAuthenticationInfo(headerKey, headerKey, "HeaderRealm"); //这里返回的是类似账号密码的东西,但是jwtToken都是jwt字符串。还需要一个该Realm的类名 } }
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\shiro\realm\HeaderRealm.java
1
请完成以下Java代码
public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public String getDatabaseType() { return databaseType; } public Map<String, String> getStatementMappings() { return statementMappings; } public void setStatementMappings(Map<String, String> statementMappings) { this.statementMappings = statementMappings; } public Map<Class< ? >, String> getInsertStatements() { return insertStatements; } public void setInsertStatements(Map<Class< ? >, String> insertStatements) { this.insertStatements = insertStatements; } public Map<Class< ? >, String> getUpdateStatements() { return updateStatements; } public void setUpdateStatements(Map<Class< ? >, String> updateStatements) { this.updateStatements = updateStatements; } public Map<Class< ? >, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class< ? >, String> getSelectStatements() { return selectStatements; }
public void setSelectStatements(Map<Class< ? >, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbIdentityUsed() { return isDbIdentityUsed; } public void setDbIdentityUsed(boolean isDbIdentityUsed) { this.isDbIdentityUsed = isDbIdentityUsed; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public boolean isCmmnEnabled() { return cmmnEnabled; } public void setCmmnEnabled(boolean cmmnEnabled) { this.cmmnEnabled = cmmnEnabled; } public boolean isDmnEnabled() { return dmnEnabled; } public void setDmnEnabled(boolean dmnEnabled) { this.dmnEnabled = dmnEnabled; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bid Comment. @param B_BidComment_ID Make a comment to a Bid Topic */ public void setB_BidComment_ID (int B_BidComment_ID) { if (B_BidComment_ID < 1) set_ValueNoCheck (COLUMNNAME_B_BidComment_ID, null); else set_ValueNoCheck (COLUMNNAME_B_BidComment_ID, Integer.valueOf(B_BidComment_ID)); } /** Get Bid Comment. @return Make a comment to a Bid Topic */ public int getB_BidComment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_BidComment_ID); if (ii == null) return 0; return ii.intValue(); } public I_B_Topic getB_Topic() throws RuntimeException { return (I_B_Topic)MTable.get(getCtx(), I_B_Topic.Table_Name) .getPO(getB_Topic_ID(), get_TrxName()); } /** Set Topic. @param B_Topic_ID Auction Topic */ public void setB_Topic_ID (int B_Topic_ID) { if (B_Topic_ID < 1) set_Value (COLUMNNAME_B_Topic_ID, null); else set_Value (COLUMNNAME_B_Topic_ID, Integer.valueOf(B_Topic_ID)); }
/** Get Topic. @return Auction Topic */ public int getB_Topic_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_Topic_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_BidComment.java
1
请完成以下Java代码
public void setIsHandOverLocation (final boolean IsHandOverLocation) { set_Value (COLUMNNAME_IsHandOverLocation, IsHandOverLocation); } @Override public boolean isHandOverLocation() { return get_ValueAsBoolean(COLUMNNAME_IsHandOverLocation); } @Override public void setIsOneTime (final boolean IsOneTime) { set_Value (COLUMNNAME_IsOneTime, IsOneTime); } @Override public boolean isOneTime() { return get_ValueAsBoolean(COLUMNNAME_IsOneTime); } @Override public void setIsRemitTo (final boolean IsRemitTo) { set_Value (COLUMNNAME_IsRemitTo, IsRemitTo); } @Override public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsReplicationLookupDefault (final boolean IsReplicationLookupDefault) { set_Value (COLUMNNAME_IsReplicationLookupDefault, IsReplicationLookupDefault); } @Override public boolean isReplicationLookupDefault() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationLookupDefault); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setIsShipToDefault (final boolean IsShipToDefault) { set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault); } @Override public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
public void switchDynamicAllocation(final PickingSlotId pickingSlotId, final boolean isDynamic) { final I_M_PickingSlot pickingSlot = pickingSlotRepository.getById(pickingSlotId); if (isDynamic == pickingSlot.isDynamic()) { //nothing to do return; } if (pickingSlot.isDynamic()) { turnOffDynamicAllocation(pickingSlot); } else { turnOnDynamicAllocation(pickingSlot); } } private void turnOnDynamicAllocation(@NonNull final I_M_PickingSlot pickingSlot) { pickingSlot.setIsDynamic(true); pickingSlotRepository.save(pickingSlot); } private void turnOffDynamicAllocation(@NonNull final I_M_PickingSlot pickingSlot) { final PickingSlotId pickingSlotId = PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID()); final boolean released = releasePickingSlot(ReleasePickingSlotRequest.ofPickingSlotId(pickingSlotId)); if (!released) { throw new AdempiereException(SLOT_CANNOT_BE_RELEASED) .markAsUserValidationError(); } pickingSlot.setIsDynamic(false); pickingSlotRepository.save(pickingSlot); } public PickingSlotQueues getNotEmptyQueues(@NonNull final PickingSlotQueueQuery query) { return pickingSlotQueueRepository.getNotEmptyQueues(query); } public PickingSlotQueue getPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId)
{ return pickingSlotQueueRepository.getPickingSlotQueue(pickingSlotId); } public void removeFromPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIdsToRemove) { huPickingSlotBL.removeFromPickingSlotQueue(pickingSlotId, huIdsToRemove); } public List<PickingSlotReservation> getPickingSlotReservations(@NonNull Set<PickingSlotId> pickingSlotIds) { return pickingSlotRepository.getByIds(pickingSlotIds) .stream() .map(PickingSlotService::extractReservation) .collect(ImmutableList.toImmutableList()); } private static PickingSlotReservation extractReservation(final I_M_PickingSlot pickingSlot) { return PickingSlotReservation.builder() .pickingSlotId(PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID())) .reservationValue(extractReservationValue(pickingSlot)) .build(); } private static PickingSlotReservationValue extractReservationValue(final I_M_PickingSlot pickingSlot) { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID()); return PickingSlotReservationValue.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, pickingSlot.getC_BPartner_Location_ID())) .build(); } public void addToPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIds) { huPickingSlotBL.addToPickingSlotQueue(pickingSlotId, huIds); } public PickingSlotQueuesSummary getNotEmptyQueuesSummary(@NonNull final PickingSlotQueueQuery query) { return pickingSlotQueueRepository.getNotEmptyQueuesSummary(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotService.java
1
请在Spring Boot框架中完成以下Java代码
private void collectReceivedHU(@NonNull final I_M_HU hu) { this.receivedHUs.add(hu); } private void collectReceivedHUs(@NonNull final List<I_M_HU> hus) { this.receivedHUs.addAll(hus); } private void setCatchWeightForReceivedHUs() { if (catchWeight == null) { return; } if (receivedHUs.isEmpty()) { //shouldn't happen throw new AdempiereException("No HUs have been received!"); } final PackedHUWeightNetUpdater weightUpdater = new PackedHUWeightNetUpdater(uomConversionBL, handlingUnitsBL.createMutableHUContextForProcessing(), getProductId(), catchWeight); weightUpdater.updatePackToHUs(receivedHUs); } @NonNull private ProductId getProductId() { final I_PP_Order_BOMLine coProductLine = getCOProductLine(); if (coProductLine != null) { return ProductId.ofRepoId(coProductLine.getM_Product_ID()); } else { final I_PP_Order ppOrder = getPPOrder(); return ProductId.ofRepoId(ppOrder.getM_Product_ID()); } } @NonNull private Quantity getTotalQtyReceived() { clearLoadedData(); final I_PP_Order_BOMLine ppOrderBomLine = getCOProductLine(); if (ppOrderBomLine != null) { return loadingAndSavingSupportServices.getQuantities(ppOrderBomLine).getQtyIssuedOrReceived().negate(); } return loadingAndSavingSupportServices.getQuantities(getPPOrder()).getQtyReceived(); } private boolean isCoProduct() { return getCOProductLine() != null;
} private void setQRCodeAttribute(@NonNull final I_M_HU hu) { if (barcode == null) {return;} final IAttributeStorage huAttributes = handlingUnitsBL.getAttributeStorage(hu); if (!huAttributes.hasAttribute(HUAttributeConstants.ATTR_QRCode)) {return;} huAttributes.setSaveOnChange(true); huAttributes.setValue(HUAttributeConstants.ATTR_QRCode, barcode.getAsString()); } private void save() { newSaver().saveActivityStatuses(job); } @NonNull private ManufacturingJobLoaderAndSaver newSaver() {return new ManufacturingJobLoaderAndSaver(loadingAndSavingSupportServices);} private void autoIssueForWhatWasReceived() { job = jobService.autoIssueWhatWasReceived(job, RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\receive\ReceiveGoodsCommand.java
2
请完成以下Java代码
public void setValue(Object value, ValueFields valueFields) { if (value instanceof ParallelMultiInstanceLoopVariable) { valueFields.setTextValue(((ParallelMultiInstanceLoopVariable) value).getExecutionId()); valueFields.setTextValue2(((ParallelMultiInstanceLoopVariable) value).getType()); } else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } @Override public Object getValue(ValueFields valueFields) { CommandContext commandContext = CommandContextUtil.getCommandContext(); if (commandContext != null) { return getValue(valueFields, commandContext); } else { return processEngineConfiguration.getCommandExecutor() .execute(context -> getValue(valueFields, context)); } } protected Object getValue(ValueFields valueFields, CommandContext commandContext) { String multiInstanceRootId = valueFields.getTextValue(); String type = valueFields.getTextValue2(); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ExecutionEntityManager executionEntityManager = processEngineConfiguration.getExecutionEntityManager(); ExecutionEntity multiInstanceRootExecution = executionEntityManager.findById(multiInstanceRootId); if (multiInstanceRootExecution == null) { // We used to have a bug where we would create this variable type for a parallel multi instance with no instances. // Therefore, if the multi instance root execution is null it means that we have no active, nor completed instances.
return 0; } List<? extends ExecutionEntity> childExecutions = multiInstanceRootExecution.getExecutions(); int nrOfActiveInstances = (int) childExecutions.stream().filter(execution -> execution.isActive() && !(execution.getCurrentFlowElement() instanceof BoundaryEvent)).count(); if (ParallelMultiInstanceLoopVariable.COMPLETED_INSTANCES.equals(type)) { Object nrOfInstancesValue = multiInstanceRootExecution.getVariable(NUMBER_OF_INSTANCES); int nrOfInstances = (Integer) (nrOfInstancesValue != null ? nrOfInstancesValue : 0); return nrOfInstances - nrOfActiveInstances; } else if (ParallelMultiInstanceLoopVariable.ACTIVE_INSTANCES.equals(type)) { return nrOfActiveInstances; } else { //TODO maybe throw exception return 0; } } @Override public boolean isReadOnly() { return true; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\variable\ParallelMultiInstanceLoopVariableType.java
1
请完成以下Java代码
public void setImage(final Image image) { m_image = image; if (m_image == null) { return; } MediaTracker mt = new MediaTracker(this); mt.addImage(m_image, 0); try { mt.waitForID(0); } catch (Exception e) { } Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this)); this.setPreferredSize(dim); } // setImage /** * Paint * * @param g graphics */ @Override public void paint(final Graphics g) { Insets in = getInsets(); if (m_image != null)
{ g.drawImage(m_image, in.left, in.top, this); } } // paint /** * Update * * @param g graphics */ @Override public void update(final Graphics g) { paint(g); } // update } // GImage } // Attachment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\Attachment.java
1
请完成以下Java代码
public void setWStoreUser (String WStoreUser) { set_Value (COLUMNNAME_WStoreUser, WStoreUser); } /** Get WebStore User. @return User ID of the Web Store EMail address */ public String getWStoreUser () { return (String)get_Value(COLUMNNAME_WStoreUser); } /** Set WebStore Password. @param WStoreUserPW
Password of the Web Store EMail address */ public void setWStoreUserPW (String WStoreUserPW) { set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW); } /** Get WebStore Password. @return Password of the Web Store EMail address */ public String getWStoreUserPW () { return (String)get_Value(COLUMNNAME_WStoreUserPW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java
1
请完成以下Java代码
public void setInternalName (final String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @Override public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours) { set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours); } @Override public String getKeepAliveTimeHours() { return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours); } /** * NotificationType AD_Reference_ID=540643 * Reference name: _NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643; /** Async Batch Processed = ABP */
public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP"; /** Workpackage Processed = WPP */ public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP"; @Override public void setNotificationType (final @Nullable String NotificationType) { set_Value (COLUMNNAME_NotificationType, NotificationType); } @Override public String getNotificationType() { return get_ValueAsString(COLUMNNAME_NotificationType); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java
1
请完成以下Java代码
public static String messageName(SparkplugMessageType type) { return STATE.equals(type) ? "sparkplugConnectionState" : type.name(); } public boolean isState() { return this.equals(STATE); } public boolean isDeath() { return this.equals(DDEATH) || this.equals(NDEATH); } public boolean isCommand() { return this.equals(DCMD) || this.equals(NCMD); } public boolean isData() { return this.equals(DDATA) || this.equals(NDATA); } public boolean isBirth() { return this.equals(DBIRTH) || this.equals(NBIRTH); } public boolean isRecord() { return this.equals(DRECORD) || this.equals(NRECORD); } public boolean isSubscribe() {
return isCommand() || isData() || isRecord(); } public boolean isNode() { return this.equals(NBIRTH) || this.equals(NCMD) || this.equals(NDATA) ||this.equals(NDEATH) || this.equals(NRECORD); } public boolean isDevice() { return this.equals(DBIRTH) || this.equals(DCMD) || this.equals(DDATA) ||this.equals(DDEATH) || this.equals(DRECORD); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugMessageType.java
1
请在Spring Boot框架中完成以下Java代码
public Result<String> pay(String orderId, HttpServletRequest httpReq) { // 获取买家ID String buyerId = getUserId(httpReq); // 支付 String html = orderService.pay(orderId, buyerId); // 成功 return Result.newSuccessResult(html); } @Override public Result cancelOrder(String orderId, HttpServletRequest httpReq) { // 获取买家ID String buyerId = getUserId(httpReq); // 取消订单 orderService.cancelOrder(orderId, buyerId); // 成功 return Result.newSuccessResult(); } @Override public Result confirmDelivery(String orderId, String expressNo, HttpServletRequest httpReq) { // 获取卖家ID String sellerId = getUserId(httpReq); // 确认收货 orderService.confirmDelivery(orderId, expressNo, sellerId); // 成功 return Result.newSuccessResult(); } @Override public Result confirmReceive(String orderId, HttpServletRequest httpReq) { // 获取买家ID
String buyerId = getUserId(httpReq); // 确认收货 orderService.confirmReceive(orderId, buyerId); // 成功 return Result.newSuccessResult(); } /** * 获取用户ID * @param httpReq HTTP请求 * @return 用户ID */ private String getUserId(HttpServletRequest httpReq) { UserEntity userEntity = userUtil.getUser(httpReq); if (userEntity == null) { throw new CommonBizException(ExpCodeEnum.UNLOGIN); } return userEntity.getId(); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\order\OrderControllerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class UserId implements RepoIdAware { public static final UserId SYSTEM = new UserId(0); public static final UserId METASFRESH = new UserId(100); /** * Used by the reports service when it accesses the REST-API */ public static final UserId JSON_REPORTS = new UserId(540057); @JsonCreator public static UserId ofRepoId(final int repoId) { final UserId userId = ofRepoIdOrNull(repoId); return Check.assumeNotNull(userId, "Unable to create a userId for repoId={}", repoId); } @Nullable public static UserId ofRepoIdOrNull(final int repoId) { if (repoId == SYSTEM.getRepoId()) { return SYSTEM; } else if (repoId == METASFRESH.getRepoId()) { return METASFRESH; } else if (repoId == JSON_REPORTS.getRepoId()) { return JSON_REPORTS; } else { return repoId >= 0 ? new UserId(repoId) : null; } } public static UserId ofRepoIdOrSystem(final int repoId) { final UserId id = ofRepoIdOrNull(repoId); return id != null ? id : UserId.SYSTEM; } /** * Will be deprecated. * Consider using {#ofRegularUserRepoIdOrNull(Integer)} */ @Nullable public static UserId ofRepoIdOrNullIfSystem(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? ofRepoId(repoId) : null; } @Nullable public static UserId ofRegularUserRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && isRegularUser(repoId) ? ofRepoId(repoId) : null; } public static Optional<UserId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId));
} public static int toRepoId(@Nullable final UserId userId) { return toRepoIdOr(userId, -1); } public static int toRepoIdOr( @Nullable final UserId userId, final int defaultValue) { return userId != null ? userId.getRepoId() : defaultValue; } public static boolean equals(@Nullable final UserId userId1, @Nullable final UserId userId2) { return Objects.equals(userId1, userId2); } int repoId; private UserId(final int userRepoId) { this.repoId = Check.assumeGreaterOrEqualToZero(userRepoId, "userRepoId"); } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isSystemUser() {return isSystemUser(repoId);} private static boolean isSystemUser(final int repoId) {return repoId == SYSTEM.repoId;} public boolean isRegularUser() {return !isSystemUser();} private static boolean isRegularUser(int repoId) {return !isSystemUser(repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserId.java
2
请在Spring Boot框架中完成以下Java代码
public class BasicAuthenticationSecurityConfiguration { //Filter chain // authenticate all requests //basic authentication //disabling csrf //stateless rest api @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //1: Response to preflight request doesn't pass access control check //2: basic auth return http .authorizeHttpRequests(
auth -> auth .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) .sessionManagement( session -> session.sessionCreationPolicy (SessionCreationPolicy.STATELESS)) // .csrf().disable() Deprecated in SB 3.1.x .csrf(csrf -> csrf.disable()) // Starting from SB 3.1.x using Lambda DSL // .csrf(AbstractHttpConfigurer::disable) // Starting from SB 3.1.x using Method Reference .build(); } }
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\basic\BasicAuthenticationSecurityConfiguration.java
2
请完成以下Java代码
public GatewayFilter apply(NameConfig config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(request.getQueryParams()); queryParams.remove(config.getName()); try { MultiValueMap<String, String> encodedQueryParams = ServerWebExchangeUtils .encodeQueryParams(queryParams); URI newUri = UriComponentsBuilder.fromUri(request.getURI()) .replaceQueryParams(unmodifiableMultiValueMap(encodedQueryParams)) .build(true) .toUri(); ServerHttpRequest updatedRequest = exchange.getRequest().mutate().uri(newUri).build(); return chain.filter(exchange.mutate().request(updatedRequest).build()); }
catch (IllegalArgumentException ex) { throw new IllegalStateException("Invalid URI query: \"" + queryParams + "\""); } } @Override public String toString() { return filterToStringCreator(RemoveRequestParameterGatewayFilterFactory.this) .append("name", config.getName()) .toString(); } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RemoveRequestParameterGatewayFilterFactory.java
1
请完成以下Java代码
private Color getColor (boolean primary) { String add = primary ? "" : "_1"; // is either BD or Int Integer Red = (Integer)m_mTab.getValue("Red" + add); Integer Green = (Integer)m_mTab.getValue("Green" + add); Integer Blue = (Integer)m_mTab.getValue("Blue" + add); // int red = Red == null ? 0 : Red.intValue(); int green = Green == null ? 0 : Green.intValue(); int blue = Blue == null ? 0 : Blue.intValue(); // return new Color (red, green, blue); } // getColor /** * Get URL from Image * @param AD_Image_ID image * @return URL as String or null */ private URL getURL(final Integer AD_Image_ID) { if (AD_Image_ID == null || AD_Image_ID.intValue() <= 0) return null; return MImage.getURLOrNull(AD_Image_ID); } // getURL /*************************************************************************/ /** * Action Listener - Open Dialog * @param e event */ @Override public void actionPerformed (ActionEvent e) { // Show Dialog MFColor cc = ColorEditor.showDialog(SwingUtils.getFrame(this), color); if (cc == null) { log.info( "VColor.actionPerformed - no color"); return; } setBackgroundColor(cc); // set Button repaint(); // Update Values m_mTab.setValue("ColorType", cc.getType().getCode()); if (cc.isFlat()) { setColor (cc.getFlatColor(), true); } else if (cc.isGradient()) { setColor (cc.getGradientUpperColor(), true); setColor (cc.getGradientLowerColor(), false);
m_mTab.setValue("RepeatDistance", new BigDecimal(cc.getGradientRepeatDistance())); m_mTab.setValue("StartPoint", String.valueOf(cc.getGradientStartPoint())); } else if (cc.isLine()) { setColor (cc.getLineBackColor(), true); setColor (cc.getLineColor(), false); m_mTab.getValue("LineWidth"); m_mTab.getValue("LineDistance"); } else if (cc.isTexture()) { setColor (cc.getTextureTaintColor(), true); // URL url = cc.getTextureURL(); // m_mTab.setValue("AD_Image_ID"); m_mTab.setValue("ImageAlpha", new BigDecimal(cc.getTextureCompositeAlpha())); } color = cc; } // actionPerformed /** * Set Color in Tab * @param c Color * @param primary true if primary false if secondary */ private void setColor (Color c, boolean primary) { String add = primary ? "" : "_1"; m_mTab.setValue("Red" + add, new BigDecimal(c.getRed())); m_mTab.setValue("Green" + add, new BigDecimal(c.getGreen())); m_mTab.setValue("Blue" + add, new BigDecimal(c.getBlue())); } // setColor // metas: Ticket#2011062310000013 @Override public boolean isAutoCommit() { return false; } } // VColor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VColor.java
1
请完成以下Java代码
private void setButtonVisibility(final CButton button, final boolean visible) { if (button == null) { return; } button.setVisible(visible); } private void enableDisableButtons(final JTable table) { final boolean enabled = table.getSelectedRow() >= 0; if (bZoomPrimary != null) { bZoomPrimary.setEnabled(enabled);
} if (bZoomSecondary != null) { bZoomSecondary.setEnabled(enabled); } } @Override public void dispose() { // task 09330: we reversed the order of setEnabled and dispose and that apparently solved the problem from this task getParent().setEnabled(true); super.dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\history\impl\InvoiceHistory.java
1
请完成以下Java代码
/* package */static String extractSequenceNumber(final String fileName) { final int indexOf = fileName.indexOf("_"); if (indexOf <= 0) { // no '_' or empty prefix => return full name return fileName; } return fileName.substring(0, indexOf); } public GloballyOrderedScannerDecorator(final IScriptScanner scanner) { super(scanner); } @Override public boolean hasNext() { return lexiographicallyOrderedScriptsSupplier.get().hasNext(); } @Override public IScript next() { return lexiographicallyOrderedScriptsSupplier.get().next(); } @Override public void remove() { lexiographicallyOrderedScriptsSupplier.get().remove(); }
@SuppressWarnings("unused") private void dumpTofile(SortedSet<IScript> lexiagraphicallySortedScripts) { FileWriter writer; try { writer = new FileWriter(GloballyOrderedScannerDecorator.class.getName() + "_sorted_scripts.txt"); for (final IScript script : lexiagraphicallySortedScripts) { writer.write(script.toString() + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(getInternalScanner()) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\GloballyOrderedScannerDecorator.java
1
请完成以下Java代码
public static JsonExternalReferenceItem of( @NonNull final JsonExternalReferenceLookupItem lookupItem) { return new JsonExternalReferenceItem(lookupItem, null, null, null, null, null); } @NonNull JsonExternalReferenceLookupItem lookupItem; @Nullable @JsonInclude(JsonInclude.Include.NON_NULL) JsonMetasfreshId metasfreshId; @Nullable @JsonInclude(JsonInclude.Include.NON_NULL) String version; @Nullable @JsonInclude(JsonInclude.Include.NON_NULL) String externalReferenceUrl; @Nullable @JsonInclude(JsonInclude.Include.NON_NULL) JsonExternalSystemName systemName;
@Nullable @JsonInclude(JsonInclude.Include.NON_NULL) JsonMetasfreshId externalReferenceId; @JsonCreator @Builder private JsonExternalReferenceItem( @JsonProperty("lookupItem") @NonNull final JsonExternalReferenceLookupItem lookupItem, @JsonProperty("metasfreshId") @Nullable final JsonMetasfreshId metasfreshId, @JsonProperty("version") @Nullable final String version, @JsonProperty("externalReferenceUrl") @Nullable final String externalReferenceUrl, @JsonProperty("systemName") @Nullable final JsonExternalSystemName systemName, @JsonProperty("externalReferenceId") @Nullable final JsonMetasfreshId externalReferenceId) { this.lookupItem = lookupItem; this.metasfreshId = metasfreshId; this.version = version; this.externalReferenceUrl = externalReferenceUrl; this.systemName = systemName; this.externalReferenceId = externalReferenceId; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalreference\src\main\java\de\metas\common\externalreference\v1\JsonExternalReferenceItem.java
1
请完成以下Java代码
public void collectDocumentValidStatusChanged(final DocumentPath documentPath, final DocumentValidStatus documentValidStatus) { // do nothing } @Override public void collectValidStatus(final IDocumentFieldView documentField) { // do nothing } @Override public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus) { // do nothing } @Override public void collectDeleted(final DocumentPath documentPath) { // do nothing } @Override public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId) { // do nothing } @Override
public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew) { // do nothing } @Override public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete) { // do nothing } @Override public void collectEvent(final IDocumentFieldChangedEvent event) { // do nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\NullDocumentChangesCollector.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonProductCategory { @ApiModelProperty( // allowEmptyValue = false, // dataType = "java.lang.Integer", // value = "This translates to `M_Product_Category_ID`.") @NonNull ProductCategoryId id; @NonNull String value; @NonNull String name;
@Nullable String description; @ApiModelProperty( // allowEmptyValue = false, // dataType = "java.lang.Integer", // value = "This translates to `M_Product_Category.M_Product_Category_Parent_ID`.") @Nullable ProductCategoryId parentProductCategoryId; boolean defaultCategory; @NonNull JsonCreatedUpdatedInfo createdUpdatedInfo; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\response\JsonProductCategory.java
2
请完成以下Java代码
public void localize(ProcessInstance processInstance, String locale, boolean withLocalizationFallback) { ExecutionEntity processInstanceExecution = (ExecutionEntity) processInstance; processInstanceExecution.setLocalizedName(null); processInstanceExecution.setLocalizedDescription(null); if (locale != null) { String processDefinitionId = processInstanceExecution.getProcessDefinitionId(); if (processDefinitionId != null) { ObjectNode languageNode = BpmnOverrideContext.getLocalizationElementProperties(locale, processInstanceExecution.getProcessDefinitionKey(), processDefinitionId, withLocalizationFallback); if (languageNode != null) { JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME); if (languageNameNode != null && !languageNameNode.isNull()) { processInstanceExecution.setLocalizedName(languageNameNode.asString()); } JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION); if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) { processInstanceExecution.setLocalizedDescription(languageDescriptionNode.asString()); } } } } } @Override
public void localize(HistoricProcessInstance historicProcessInstance, String locale, boolean withLocalizationFallback) { HistoricProcessInstanceEntity processInstanceEntity = (HistoricProcessInstanceEntity) historicProcessInstance; processInstanceEntity.setLocalizedName(null); processInstanceEntity.setLocalizedDescription(null); if (locale != null) { String processDefinitionId = processInstanceEntity.getProcessDefinitionId(); if (processDefinitionId != null) { ObjectNode languageNode = BpmnOverrideContext.getLocalizationElementProperties(locale, processInstanceEntity.getProcessDefinitionKey(), processDefinitionId, withLocalizationFallback); if (languageNode != null) { JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME); if (languageNameNode != null && !languageNameNode.isNull()) { processInstanceEntity.setLocalizedName(languageNameNode.asString()); } JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION); if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) { processInstanceEntity.setLocalizedDescription(languageDescriptionNode.asString()); } } } } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DefaultProcessLocalizationManager.java
1
请完成以下Java代码
private static final TableModelMetaInfo<?> getTableModelMetaInfoOrNull(final TableModel model) { if (!(model instanceof AnnotatedTableModel<?>)) { return null; } final TableModelMetaInfo<?> metaInfo = ((AnnotatedTableModel<?>)model).getMetaInfo(); return metaInfo; } private TableCellRenderer createTableCellRenderer(final TableColumnInfo columnMetaInfo) { if (columnMetaInfo.isSelectionColumn()) { return new SelectionColumnCellRenderer(); } final int displayTypeToUse = columnMetaInfo.getDisplayType(DisplayType.String); return new AnnotatedTableCellRenderer(displayTypeToUse); } private TableCellEditor createTableCellEditor(final TableColumnInfo columnMetaInfo) { if (columnMetaInfo.isSelectionColumn()) { return new SelectionColumnCellEditor(); } return new AnnotatedTableCellEditor(columnMetaInfo); } /** * Synchronize changes from {@link TableColumnInfo} to {@link TableColumnExt}. * * @author tsa * */ private static final class TableColumnInfo2TableColumnExtSynchronizer implements PropertyChangeListener { private final WeakReference<TableColumnExt> columnExtRef; private boolean running = false; public TableColumnInfo2TableColumnExtSynchronizer(final TableColumnExt columnExt) { super(); columnExtRef = new WeakReference<>(columnExt); } private TableColumnExt getTableColumnExt() { return columnExtRef.getValue(); } @Override
public void propertyChange(final PropertyChangeEvent evt) { // Avoid recursion if (running) { return; } running = true; try { final TableColumnInfo columnMetaInfo = (TableColumnInfo)evt.getSource(); final TableColumnExt columnExt = getTableColumnExt(); if (columnExt == null) { // ColumnExt reference expired: // * remove this listener because there is no point to have this listener invoked in future // * exit quickly because there is nothing to do columnMetaInfo.removePropertyChangeListener(this); return; } updateColumnExtFromMetaInfo(columnExt, columnMetaInfo); } finally { running = false; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableColumnFactory.java
1
请完成以下Java代码
public String getTypeName() { return TYPE_NAME; } public boolean isCachable() { return forceCacheable; } public boolean isAbleToStore(Object value) { if (value == null) { return true; } return mappings.isJPAEntity(value); } public void setValue(Object value, ValueFields valueFields) { EntityManagerSession entityManagerSession = Context.getCommandContext().getSession(EntityManagerSession.class); if (entityManagerSession == null) { throw new ActivitiException("Cannot set JPA variable: " + EntityManagerSession.class + " not configured"); } else { // Before we set the value we must flush all pending changes from // the entitymanager // If we don't do this, in some cases the primary key will not yet // be set in the object // which will cause exceptions down the road. entityManagerSession.flush(); } if (value != null) { String className = mappings.getJPAClassString(value); String idString = mappings.getJPAIdString(value);
valueFields.setTextValue(className); valueFields.setTextValue2(idString); } else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } public Object getValue(ValueFields valueFields) { if (valueFields.getTextValue() != null && valueFields.getTextValue2() != null) { return mappings.getJPAEntity(valueFields.getTextValue(), valueFields.getTextValue2()); } return null; } /** * Force the value to be cacheable. */ public void setForceCacheable(boolean forceCachedValue) { this.forceCacheable = forceCachedValue; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JPAEntityVariableType.java
1
请完成以下Java代码
public V call() throws Exception { this.originalSecurityContext = this.securityContextHolderStrategy.getContext(); try { this.securityContextHolderStrategy.setContext(this.delegateSecurityContext); return this.delegate.call(); } finally { SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext(); if (emptyContext.equals(this.originalSecurityContext)) { this.securityContextHolderStrategy.clearContext(); } else { this.securityContextHolderStrategy.setContext(this.originalSecurityContext); } this.originalSecurityContext = null; } } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; if (!this.explicitSecurityContextProvided) { this.delegateSecurityContext = securityContextHolderStrategy.getContext(); } } @Override public String toString() { return this.delegate.toString(); } /** * Creates a {@link DelegatingSecurityContextCallable} and with the given * {@link Callable} and {@link SecurityContext}, but if the securityContext is null * will defaults to the current {@link SecurityContext} on the * {@link SecurityContextHolder} * @param delegate the delegate {@link DelegatingSecurityContextCallable} to run with * the specified {@link SecurityContext}. Cannot be null.
* @param securityContext the {@link SecurityContext} to establish for the delegate * {@link Callable}. If null, defaults to {@link SecurityContextHolder#getContext()} * @return */ public static <V> Callable<V> create(Callable<V> delegate, SecurityContext securityContext) { return (securityContext != null) ? new DelegatingSecurityContextCallable<>(delegate, securityContext) : new DelegatingSecurityContextCallable<>(delegate); } static <V> Callable<V> create(Callable<V> delegate, @Nullable SecurityContext securityContext, SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(delegate, "delegate cannot be null"); Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); DelegatingSecurityContextCallable<V> callable = (securityContext != null) ? new DelegatingSecurityContextCallable<>(delegate, securityContext) : new DelegatingSecurityContextCallable<>(delegate); callable.setSecurityContextHolderStrategy(securityContextHolderStrategy); return callable; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextCallable.java
1
请在Spring Boot框架中完成以下Java代码
public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the freetextqual property. * * @return * possible object is * {@link String } * */ public String getFREETEXTQUAL() { return freetextqual; } /** * Sets the value of the freetextqual property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTQUAL(String value) { this.freetextqual = value; } /** * Gets the value of the freetext property. * * @return * possible object is * {@link String } * */ public String getFREETEXT() { return freetext; } /** * Sets the value of the freetext property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXT(String value) { this.freetext = value; } /** * Gets the value of the freetextcode property. * * @return * possible object is
* {@link String } * */ public String getFREETEXTCODE() { return freetextcode; } /** * Sets the value of the freetextcode property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTCODE(String value) { this.freetextcode = value; } /** * Gets the value of the freetextlanguage property. * * @return * possible object is * {@link String } * */ public String getFREETEXTLANGUAGE() { return freetextlanguage; } /** * Sets the value of the freetextlanguage property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTLANGUAGE(String value) { this.freetextlanguage = value; } /** * Gets the value of the freetextfunction property. * * @return * possible object is * {@link String } * */ public String getFREETEXTFUNCTION() { return freetextfunction; } /** * Sets the value of the freetextfunction property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTFUNCTION(String value) { this.freetextfunction = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTEXT1.java
2
请在Spring Boot框架中完成以下Java代码
public class QuoteDTO implements Serializable { private Long id; @NotNull private String symbol; @NotNull private BigDecimal price; @NotNull private ZonedDateTime lastTrade; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public ZonedDateTime getLastTrade() { return lastTrade; }
public void setLastTrade(ZonedDateTime lastTrade) { this.lastTrade = lastTrade; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QuoteDTO quoteDTO = (QuoteDTO) o; if (quoteDTO.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), quoteDTO.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "QuoteDTO{" + "id=" + getId() + ", symbol='" + getSymbol() + "'" + ", price=" + getPrice() + ", lastTrade='" + getLastTrade() + "'" + "}"; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteDTO.java
2
请在Spring Boot框架中完成以下Java代码
public final class TransactionAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnSingleCandidate(ReactiveTransactionManager.class) TransactionalOperator transactionalOperator(ReactiveTransactionManager transactionManager) { return TransactionalOperator.create(transactionManager); } @Configuration(proxyBeanMethods = false) @ConditionalOnSingleCandidate(PlatformTransactionManager.class) static class TransactionTemplateConfiguration { @Bean @ConditionalOnMissingBean(TransactionOperations.class) TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(TransactionManager.class) @ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class) static class EnableTransactionManagementConfiguration { @Configuration(proxyBeanMethods = false) @EnableTransactionManagement(proxyTargetClass = false)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", havingValue = false) static class JdkDynamicAutoProxyConfiguration { } @Configuration(proxyBeanMethods = false) @EnableTransactionManagement(proxyTargetClass = true) @ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true) static class CglibAutoProxyConfiguration { } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(AbstractTransactionAspect.class) static class AspectJTransactionManagementConfiguration { @Bean static LazyInitializationExcludeFilter eagerTransactionAspect() { return LazyInitializationExcludeFilter.forBeanTypes(AbstractTransactionAspect.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-transaction\src\main\java\org\springframework\boot\transaction\autoconfigure\TransactionAutoConfiguration.java
2
请完成以下Java代码
public boolean isOrAlphabetic() { return orAlphabetic; } public void setOrAlphabetic(boolean orAlphabetic) { this.orAlphabetic = orAlphabetic; } public boolean isNot() { return not; } public void setNot(boolean not) { this.not = not; } public boolean isNotAlphabetic() { return notAlphabetic; } public void setNotAlphabetic(boolean notAlphabetic) { this.notAlphabetic = notAlphabetic; } @Override public String toString() { return "SpelRelational{" + "equal=" + equal + ", equalAlphabetic=" + equalAlphabetic +
", notEqual=" + notEqual + ", notEqualAlphabetic=" + notEqualAlphabetic + ", lessThan=" + lessThan + ", lessThanAlphabetic=" + lessThanAlphabetic + ", lessThanOrEqual=" + lessThanOrEqual + ", lessThanOrEqualAlphabetic=" + lessThanOrEqualAlphabetic + ", greaterThan=" + greaterThan + ", greaterThanAlphabetic=" + greaterThanAlphabetic + ", greaterThanOrEqual=" + greaterThanOrEqual + ", greaterThanOrEqualAlphabetic=" + greaterThanOrEqualAlphabetic + ", and=" + and + ", andAlphabetic=" + andAlphabetic + ", or=" + or + ", orAlphabetic=" + orAlphabetic + ", not=" + not + ", notAlphabetic=" + notAlphabetic + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRelational.java
1
请完成以下Java代码
private int unlockUser(final int accountLockExpire, final int AD_User_IDToUnlock) { final int result[] = { 0 }; Services.get(ITrxManager.class).runInNewTrx(new TrxRunnable() { @Override public void run(final String localTrxName) throws Exception { final org.compiere.model.I_AD_User user = InterfaceWrapperHelper.create(getCtx(), AD_User_IDToUnlock, I_AD_User.class, localTrxName); final Timestamp curentLogin = (new Timestamp(System.currentTimeMillis())); final long loginFailureTime = user.getLoginFailureDate().getTime(); final long newloginFailureTime = loginFailureTime + (1000 * 60 * accountLockExpire); final Timestamp acountUnlock = new Timestamp(newloginFailureTime);
if (curentLogin.compareTo(acountUnlock) > 0) { user.setLoginFailureCount(0); user.setIsAccountLocked(false); InterfaceWrapperHelper.save(user); result[0] = 1; } } }); return result[0]; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_ExpireLocks.java
1
请完成以下Java代码
public ImmutableList<ExternalId> toExternalIds(@NonNull final Collection<JsonExternalId> externalLineIds) { return externalLineIds .stream() .map(JsonExternalIds::toExternalId) .collect(ImmutableList.toImmutableList()); } public JsonExternalId of(@NonNull final ExternalId externalId) { return JsonExternalId.of(externalId.getValue()); } public JsonExternalId ofOrNull(@Nullable final ExternalId externalId) { if (externalId == null) { return null; } return JsonExternalId.of(externalId.getValue()); }
public boolean equals(@Nullable final JsonExternalId id1, @Nullable final JsonExternalId id2) { return Objects.equals(id1, id2); } public static boolean isEqualTo( @Nullable final JsonExternalId jsonExternalId, @Nullable final ExternalId externalId) { if (jsonExternalId == null && externalId == null) { return true; } if (jsonExternalId == null ^ externalId == null) { return false; // one is null, the other one isn't } return Objects.equals(jsonExternalId.getValue(), externalId.getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\JsonExternalIds.java
1
请完成以下Java代码
private boolean rowsHaveSingleProductId() { // getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); doesn't work from checkPreconditionsApplicable final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds()); final IQueryFilter<I_M_DiscountSchemaBreak> selectionQueryFilter = viewSqlWhereClause.toQueryFilter(); return pricingConditionsRepo.isSingleProductId(selectionQueryFilter); } @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final String parameterName = parameter.getColumnName(); if (PARAM_M_Product_ID.equals(parameterName)) { final IQueryFilter<I_M_DiscountSchemaBreak> selectionQueryFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final ProductId uniqueProductIdForSelection = pricingConditionsRepo.retrieveUniqueProductIdForSelectionOrNull(selectionQueryFilter); if (uniqueProductIdForSelection == null) { // should not happen because of the preconditions above return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } return uniqueProductIdForSelection.getRepoId(); } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } 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