instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public GolfTournament register(Golfer... players) { return register(Arrays.asList(ArrayUtils.nullSafeArray(players, Golfer.class))); } public GolfTournament register(Iterable<Golfer> players) { StreamSupport.stream(CollectionUtils.nullSafeIterable(players).spliterator(), false) .filter(Objects::nonNull) .forEach(this.players::add); return this; } @Getter @ToString @EqualsAndHashCode @RequiredArgsConstructor(staticName = "of") public static class Pairing { private final AtomicBoolean signedScorecard = new AtomicBoolean(false); @NonNull private final Golfer playerOne; @NonNull private final Golfer playerTwo; public synchronized void setHole(int hole) { this.playerOne.setHole(hole);
this.playerTwo.setHole(hole); } public synchronized int getHole() { return getPlayerOne().getHole(); } public boolean in(@NonNull Golfer golfer) { return this.playerOne.equals(golfer) || this.playerTwo.equals(golfer); } public synchronized int nextHole() { return getHole() + 1; } public synchronized boolean signScorecard() { return getHole() >= 18 && this.signedScorecard.compareAndSet(false, true); } } }
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfTournament.java
1
请完成以下Java代码
public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId) { final HuId huId = getHuId(); if (huId == null) { throw new AdempiereException("Not a PickedHURow!") .appendParametersToMessage() .setParameter("PickingSlotRow", this); } final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId); if (hasOpenPickingForOrderId) { return true; }
if (isLU()) { return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId)) .isPresent(); } return false; } @NonNull private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId) { return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java
1
请完成以下Java代码
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 6, 1); } public byte color() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 3; } public boolean mutateColor(byte color) { int o = __offset(8); if (o != 0) { bb.put(o + bb_pos, color); return true; } else { return false; } } public String navigation() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } public ByteBuffer navigationAsByteBuffer() { return __vector_as_bytebuffer(10, 1); } public ByteBuffer navigationInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); } public MyGame.terrains.Effect effects(int j) { return effects(new MyGame.terrains.Effect(), j); } public MyGame.terrains.Effect effects(MyGame.terrains.Effect obj, int j) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } public int effectsLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } public MyGame.terrains.Effect.Vector effectsVector() { return effectsVector(new MyGame.terrains.Effect.Vector()); } public MyGame.terrains.Effect.Vector effectsVector(MyGame.terrains.Effect.Vector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } public static void startTerrain(FlatBufferBuilder builder) { builder.startTable(5); } public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); } public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(1, nameOffset, 0); } public static void addColor(FlatBufferBuilder builder, byte color) { builder.addByte(2, color, 3); } public static void addNavigation(FlatBufferBuilder builder, int navigationOffset) { builder.addOffset(3, navigationOffset, 0); } public static void addEffects(FlatBufferBuilder builder, int effectsOffset) { builder.addOffset(4, effectsOffset, 0); } public static int createEffectsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startEffectsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static int endTerrain(FlatBufferBuilder builder) { int o = builder.endTable(); return o; } public static void finishTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } public static void finishSizePrefixedTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); } public static final class Vector extends BaseVector { public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } public Terrain get(int j) { return get(new Terrain(), j); } public Terrain get(Terrain obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGame\terrains\Terrain.java
1
请完成以下Java代码
private static PaymentDirection extractPaymentDirection(final I_C_Payment payment) { return PaymentDirection.ofReceiptFlag(payment.isReceipt()); } private static Money extractPayAmt(@NonNull final I_C_Payment payment) { final CurrencyId currencyId = CurrencyId.ofRepoId(payment.getC_Currency_ID()); return Money.of(payment.getPayAmt(), currencyId); } @Override public BankStatementLineMultiPaymentLinkResult linkMultiPayments(@NonNull final BankStatementLineMultiPaymentLinkRequest request) { return BankStatementLineMultiPaymentLinkCommand.builder() .bankStatementBL(bankStatementBL) .bankStatementDAO(bankStatementDAO) .paymentBL(paymentBL) .bankStatementListenersService(bankStatementListenersService) .moneyService(moneyService) // .request(request) // .build() .execute(); } @NonNull private Optional<InvoiceToAllocate> getInvoiceToAllocate( @NonNull final CurrencyId paymentCurrencyId, @NonNull final InvoiceId invoiceId, @NonNull final ZonedDateTime evaluationDate)
{ final InvoiceToAllocateQuery query = InvoiceToAllocateQuery.builder() .currencyId(paymentCurrencyId) .evaluationDate(evaluationDate) .onlyInvoiceId(invoiceId) .build(); return paymentAllocationService.retrieveInvoicesToAllocate(query) .stream() .filter(invoiceToAllocate -> { // just to be sure final InvoiceId invId = invoiceToAllocate.getInvoiceId(); if (invId == null) { return false; } return invId.equals(invoiceId); }) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\BankStatementPaymentBL.java
1
请完成以下Java代码
public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } } public void traversePostOrder(Node node) { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); visit(node.value); } } public void traverseInOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current = root; while (current != null || !stack.isEmpty()) { while (current != null) { stack.push(current); current = current.left; } Node top = stack.pop(); visit(top.value); current = top.right; } } public void traversePreOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node current; stack.push(root); while(! stack.isEmpty()) { current = stack.pop(); visit(current.value); if(current.right != null) stack.push(current.right); if(current.left != null) stack.push(current.left); } }
public void traversePostOrderWithoutRecursion() { Stack<Node> stack = new Stack<>(); Node prev = root; Node current; stack.push(root); while (!stack.isEmpty()) { current = stack.peek(); boolean hasChild = (current.left != null || current.right != null); boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); if (!hasChild || isPrevLastChild) { current = stack.pop(); visit(current.value); prev = current; } else { if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } } } private void visit(int value) { System.out.print(" " + value); } static class Node { int value; Node left; Node right; Node(int value) { this.value = value; right = null; left = null; } } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\dfs\BinaryTree.java
1
请在Spring Boot框架中完成以下Java代码
public class UserRpcServiceTest implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) throws Exception { UserDTO user = userRpcService.get(1); logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user); } } @Component public class UserRpcServiceTest02 implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) throws Exception { // 获得用户 try { // 发起调用 UserDTO user = userRpcService.get(null); // 故意传入空的编号,为了校验编号不通过 logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user); } catch (Exception e) { logger.error("[run][获得用户发生异常,信息为:[{}]", e.getMessage()); } // 添加用户 try { // 创建 UserAddDTO UserAddDTO addDTO = new UserAddDTO(); addDTO.setName("yudaoyuanmayudaoyuanma"); // 故意把名字打的特别长,为了校验名字不通过 addDTO.setGender(null); // 不传递性别,为了校验性别不通过 // 发起调用 userRpcService.add(addDTO); logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO); } catch (Exception e) { logger.error("[run][添加用户发生异常,信息为:[{}]", e.getMessage());
} } } @Component public class UserRpcServiceTest03 implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) { // 添加用户 try { // 创建 UserAddDTO UserAddDTO addDTO = new UserAddDTO(); addDTO.setName("yudaoyuanma"); // 设置为 yudaoyuanma ,触发 ServiceException 异常 addDTO.setGender(1); // 发起调用 userRpcService.add(addDTO); logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO); } catch (Exception e) { logger.error("[run][添加用户发生异常({}),信息为:[{}]", e.getClass().getSimpleName(), e.getMessage()); } } } }
repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-xml-demo\user-rpc-service-consumer\src\main\java\cn\iocoder\springboot\lab30\rpc\ConsumerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public class SimpleRabbitListenerEndpoint extends AbstractRabbitListenerEndpoint { private @Nullable MessageListener messageListener; /** * Set the {@link MessageListener} to invoke when a message matching * the endpoint is received. * @param messageListener the {@link MessageListener} instance. */ public void setMessageListener(MessageListener messageListener) { this.messageListener = messageListener; } /** * @return the {@link MessageListener} to invoke when a message matching * the endpoint is received.
*/ public @Nullable MessageListener getMessageListener() { return this.messageListener; } @Override protected @Nullable MessageListener createMessageListener(MessageListenerContainer container) { return getMessageListener(); } @Override protected StringBuilder getEndpointDescription() { return super.getEndpointDescription() .append(" | messageListener='").append(this.messageListener).append("'"); } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\SimpleRabbitListenerEndpoint.java
2
请完成以下Java代码
public Flux<String> accepted(ServerHttpResponse response) { response.setStatusCode(HttpStatus.ACCEPTED); return Flux.just("accepted"); } @GetMapping(value = "/bad-request") public Mono<String> badRequest() { return Mono.error(new IllegalArgumentException()); } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments") @ExceptionHandler(IllegalArgumentException.class) public void illegalArgument() { } @GetMapping(value = "/unauthorized")
public ResponseEntity<Mono<String>> unathorized() { return ResponseEntity .status(HttpStatus.UNAUTHORIZED) .header("X-Reason", "user-invalid") .body(Mono.just("unauthorized")); } @Bean public RouterFunction<ServerResponse> notFound() { return RouterFunctions.route(GET("/statuses/not-found"), request -> ServerResponse .notFound() .build()); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\responsestatus\ResponseStatusController.java
1
请在Spring Boot框架中完成以下Java代码
public class DataSourceConfiguration { private static HikariDataSource createHikariDataSource(DataSourceProperties properties) { // 创建 HikariDataSource 对象 HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); // 设置线程池名 if (StringUtils.hasText(properties.getName())) { dataSource.setPoolName(properties.getName()); } return dataSource; } /** * 创建 quartz 数据源的配置对象 */ @Primary @Bean(name = "quartzDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.quartz") // 读取 spring.datasource.quartz 配置到 DataSourceProperties 对象 public DataSourceProperties quartzDataSourceProperties() {
return new DataSourceProperties(); } /** * 创建 quartz 数据源 */ @Bean(name = "quartzDataSource") @ConfigurationProperties(prefix = "spring.datasource.quartz.hikari") @QuartzDataSource public DataSource quartzDataSource() { // 获得 DataSourceProperties 对象 DataSourceProperties properties = this.quartzDataSourceProperties(); // 创建 HikariDataSource 对象 return createHikariDataSource(properties); } }
repos\springboot-demo-master\quartz\src\main\java\com\et\quartz\config\DataSourceConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class CostDetailQuery { @Nullable AcctSchemaId acctSchemaId; @Nullable CostElementId costElementId; @Nullable CostingDocumentRef documentRef; @Nullable CostAmountType amtType; @Nullable ProductId productId; @Nullable AttributeSetInstanceId attributeSetInstanceId; @Nullable ClientId clientId; @Nullable OrgId orgId; @Nullable CostDetailId afterCostDetailId; @Nullable Range<Instant> dateAcctRage; @NonNull @Singular ImmutableList<OrderBy> orderBys; @Getter @AllArgsConstructor public enum OrderBy { ID_ASC(I_M_CostDetail.COLUMNNAME_M_CostDetail_ID, true), ID_DESC(I_M_CostDetail.COLUMNNAME_M_CostDetail_ID, false), DATE_ACCT_ASC(I_M_CostDetail.COLUMNNAME_DateAcct, true), DATE_ACCT_DESC(I_M_CostDetail.COLUMNNAME_DateAcct, false), ; final String columnName; final boolean ascending; } public static CostDetailQueryBuilder builderFrom(@NonNull final CostSegmentAndElement costSegmentAndElement) {
return builderFrom(costSegmentAndElement.toCostSegment()) .costElementId(costSegmentAndElement.getCostElementId()); } public static CostDetailQueryBuilder builderFrom(@NonNull final CostSegment costSegment) { return builder() .acctSchemaId(costSegment.getAcctSchemaId()) .productId(costSegment.getProductId()) .attributeSetInstanceId(costSegment.getAttributeSetInstanceId().asRegularOrNull()) .clientId(costSegment.getClientId()) .orgId(costSegment.getOrgId().asRegularOrNull()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailQuery.java
2
请完成以下Java代码
public abstract class _Article extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<String> CONTENT = Property.create("content", String.class); public static final Property<String> TITLE = Property.create("title", String.class); public static final Property<Author> AUTHOR = Property.create("author", Author.class); public void setContent(String content) { writeProperty("content", content); } public String getContent() { return (String)readProperty("content"); }
public void setTitle(String title) { writeProperty("title", title); } public String getTitle() { return (String)readProperty("title"); } public void setAuthor(Author author) { setToOneTarget("author", author, true); } public Author getAuthor() { return (Author)readProperty("author"); } }
repos\tutorials-master\persistence-modules\apache-cayenne\src\main\java\com\baeldung\apachecayenne\persistent\auto\_Article.java
1
请完成以下Java代码
private HUEditorRowAttributes createRowAttributes(final ViewRowAttributesKey key) { final I_M_HU hu = extractHU(key); final IAttributeStorage attributesStorage = getAttributeStorageFactory().getAttributeStorage(hu); attributesStorage.setSaveOnChange(true); final boolean rowAttributesReadonly = readonly // readonly if the provider shall provide readonly attributes || !X_M_HU.HUSTATUS_Planning.equals(hu.getHUStatus()); // or, readonly if not Planning, see https://github.com/metasfresh/metasfresh-webui-api/issues/314 final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); final IHUStorage storage = storageFactory.getStorage(hu); return HUEditorRowAttributes.builder() .documentPath(toDocumentPath(key)) .attributesStorage(attributesStorage) .productIds(extractProductIds(storage)) .hu(hu) .readonly(rowAttributesReadonly) .isMaterialReceipt(isMaterialReceipt) .build(); } private ImmutableSet<ProductId> extractProductIds(final IHUStorage storage) { return storage.getProductStorages() .stream() .map(IHUProductStorage::getProductId) .collect(ImmutableSet.toImmutableSet()); } private I_M_HU extractHU(final ViewRowAttributesKey key) { final HuId huId = HuId.ofRepoId(key.getHuId().toInt()); final I_M_HU hu = handlingUnitsRepo.getByIdOutOfTrx(huId); if (hu == null) { throw new IllegalArgumentException("No HU found for M_HU_ID=" + huId); } return hu;
} private static DocumentPath toDocumentPath(final ViewRowAttributesKey key) { final DocumentId documentTypeId = key.getHuId(); final DocumentId huEditorRowId = key.getHuEditorRowId(); return DocumentPath.rootDocumentPath(DocumentType.ViewRecordAttributes, documentTypeId, huEditorRowId); } private IAttributeStorageFactory getAttributeStorageFactory() { return _attributeStorageFactory.get(); } private IAttributeStorageFactory createAttributeStorageFactory() { final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return attributeStorageFactoryService.createHUAttributeStorageFactory(storageFactory); } @Override public void invalidateAll() { // // Destroy AttributeStorageFactory _attributeStorageFactory.forget(); // // Destroy attribute documents rowAttributesByKey.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonRequestProductUpsertItem { @ApiModelProperty(position = 10, value = PRODUCT_IDENTIFIER_DOC) @NonNull String productIdentifier; @ApiModelProperty(position = 20, // value = "The version of the product." + EXTERNAL_VERSION_DOC) String externalVersion; @ApiModelProperty(position = 25, // value = "URL of the resource in the target external system.") @Nullable String externalReferenceUrl; @ApiModelProperty(position = 30, // value = "ID of the external system config.") @Nullable JsonMetasfreshId externalSystemConfigId; @ApiModelProperty(position = 50) @NonNull JsonRequestProduct requestProduct;
@JsonCreator public JsonRequestProductUpsertItem( @NonNull @JsonProperty("productIdentifier") final String productIdentifier, @Nullable @JsonProperty("externalVersion") final String externalVersion, @Nullable @JsonProperty("externalReferenceUrl") final String externalReferenceUrl, @Nullable @JsonProperty("externalSystemId") final JsonMetasfreshId externalSystemConfigId, @NonNull @JsonProperty("requestProduct") final JsonRequestProduct requestProduct) { this.productIdentifier = productIdentifier; this.externalVersion = externalVersion; this.requestProduct = requestProduct; this.externalReferenceUrl = externalReferenceUrl; this.externalSystemConfigId = externalSystemConfigId; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProductUpsertItem.java
2
请完成以下Java代码
public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().update("updateExecutionTenantIdForDeployment", params); } public void updateProcessInstanceLockTime(String processInstanceId) { CommandContext commandContext = Context.getCommandContext(); Date expirationTime = commandContext.getProcessEngineConfiguration().getClock().getCurrentTime(); int lockMillis = commandContext.getProcessEngineConfiguration().getAsyncExecutorAsyncJobLockTimeInMillis(); GregorianCalendar lockCal = new GregorianCalendar(); lockCal.setTime(expirationTime); lockCal.add(Calendar.MILLISECOND, lockMillis); HashMap<String, Object> params = new HashMap<>(); params.put("id", processInstanceId);
params.put("lockTime", lockCal.getTime()); params.put("expirationTime", expirationTime); int result = getDbSqlSession().update("updateProcessInstanceLockTime", params); if (result == 0) { throw new ActivitiOptimisticLockingException("Could not lock process instance"); } } public void clearProcessInstanceLockTime(String processInstanceId) { HashMap<String, Object> params = new HashMap<>(); params.put("id", processInstanceId); getDbSqlSession().update("clearProcessInstanceLockTime", params); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityManager.java
1
请完成以下Java代码
public class X_EDI_C_BPartner_Lookup_BPL_GLN_v extends org.compiere.model.PO implements I_EDI_C_BPartner_Lookup_BPL_GLN_v, org.compiere.model.I_Persistent { private static final long serialVersionUID = 948019275L; /** Standard Constructor */ public X_EDI_C_BPartner_Lookup_BPL_GLN_v (final Properties ctx, final int EDI_C_BPartner_Lookup_BPL_GLN_v_ID, @Nullable final String trxName) { super (ctx, EDI_C_BPartner_Lookup_BPL_GLN_v_ID, trxName); } /** Load Constructor */ public X_EDI_C_BPartner_Lookup_BPL_GLN_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setGLN (final @Nullable java.lang.String GLN) {
set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() { return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setLookup_Label (final @Nullable java.lang.String Lookup_Label) { set_ValueNoCheck (COLUMNNAME_Lookup_Label, Lookup_Label); } @Override public java.lang.String getLookup_Label() { return get_ValueAsString(COLUMNNAME_Lookup_Label); } @Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_Value (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Lookup_BPL_GLN_v.java
1
请完成以下Java代码
public BigDecimal getAmt() { if (list.isEmpty()) { throw new AdempiereException("No lines found"); } return list.stream() .map(I_C_PaySelectionLine::getPayAmt) .reduce(BigDecimal.ZERO, BigDecimal::add); } @NonNull public ImmutableSet<InvoiceId> getInvoiceIds() { if (list.isEmpty()) { return ImmutableSet.of(); } return list.stream() .map(line -> { final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(line.getC_Invoice_ID()); if (invoiceId == null) { throw new AdempiereException("No invoice found for paySelectionLine: " + line); } return invoiceId; }) .collect(ImmutableSet.toImmutableSet()); } @NonNull public String getAggregatedDescription(@NonNull final Function<Collection<InvoiceId>, List<I_C_Invoice>> getInvoicesByInvoiceIds) { if (getInvoiceIds().isEmpty()) { return ""; } final String aggregatedDescription = getInvoicesByInvoiceIds.apply(getInvoiceIds()) .stream() .map(I_C_Invoice::getDescription)
.filter(Check::isNotBlank) .distinct() .collect(Collectors.joining(",")); return StringUtils.trunc(aggregatedDescription, MAX_DESCRIPTION_LENGTH); } @NonNull public String getAggregatedRemittanceInfo() { if (list.isEmpty()) { return ""; } final String aggregatedRemittanceInfo = list.stream() .map(I_C_PaySelectionLine::getReference) .filter(Check::isNotBlank) .distinct() .collect(Collectors.joining(",")); return StringUtils.trunc(aggregatedRemittanceInfo, MAX_REMITTANCE_LENGTH); } public boolean isSinglePaySelectionLineGroup() {return list.size() == 1;} public boolean isMultiplePaySelectionLinesGroup() {return list.size() > 1;} @NonNull public Stream<I_C_PaySelectionLine> stream() {return list.stream();} public int size() {return list.size();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\AggregatedInvoicePaySelectionLines.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(SecurityFilter.class); private final UserAccessService userAccessService; public SecurityFilter(UserAccessService userAccessService) { this.userAccessService = userAccessService; } @Override @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest)request; String authorization = httpServletRequest.getHeader("Authorization"); if (authorization != null) { JWToken jwToken = JWToken.from(JWTUtils.extractJwtToken(authorization)); Optional<Jws<Claims>> verifiedClaims = userAccessService.validate(jwToken); if (verifiedClaims.isPresent()) { SecurityContext securityContext = SecurityContextHolder.getContext(); String userIdFromJWT = verifiedClaims.get().getBody().getSubject();
List<String> rolesFromJWT = (List<String>) verifiedClaims.get().getBody().get("roles"); Set<RoleId> setOfRoles = rolesFromJWT.stream().map(RoleId::new).collect(Collectors.toSet()); securityContext.setAuthentication(new AuthenticationImpl(userIdFromJWT, setOfRoles)); chain.doFilter(request, response); return; } else { LOG.error("not authorized !"); } } else { LOG.error("not authorized: header \"Authorization\" is missing !"); } HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value()); } }
repos\spring-examples-java-17\spring-security-jwt\src\main\java\itx\examples\springboot\security\springsecurity\jwt\config\SecurityFilter.java
2
请完成以下Java代码
public String getGraphType () { return (String)get_Value(COLUMNNAME_GraphType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintGraph.java
1
请完成以下Java代码
public IDunningCandidateSource createDunningCandidateSource() { try { final IDunningCandidateSource source = dunningCandidateSourceClass.newInstance(); return source; } catch (Exception e) { throw new DunningException("Cannot create " + IDunningCandidateSource.class + " for " + dunningCandidateSourceClass, e); } } @Override public void setDunningCandidateSourceClass(Class<? extends IDunningCandidateSource> dunningCandidateSourceClass)
{ Check.assume(dunningCandidateSourceClass != null, "dunningCandidateSourceClass is not null"); this.dunningCandidateSourceClass = dunningCandidateSourceClass; } @Override public String toString() { return "DunningConfig [" + "dunnableSourceFactory=" + dunnableSourceFactory + ", dunningCandidateProducerFactory=" + dunningCandidateProducerFactory + ", dunningCandidateSourceClass=" + dunningCandidateSourceClass + ", dunningProducerClass=" + dunningProducerClass + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningConfig.java
1
请完成以下Java代码
public void setActorTokenResolver(Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver) { Assert.notNull(actorTokenResolver, "actorTokenResolver cannot be null"); this.actorTokenResolver = actorTokenResolver; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds. * * <p> * An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew */ public void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public void setDLM_Referencing_Column(final org.compiere.model.I_AD_Column DLM_Referencing_Column) { set_ValueFromPO(COLUMNNAME_DLM_Referencing_Column_ID, org.compiere.model.I_AD_Column.class, DLM_Referencing_Column); } /** * Set Referenzierende Spalte. * * @param DLM_Referencing_Column_ID Referenzierende Spalte */ @Override public void setDLM_Referencing_Column_ID(final int DLM_Referencing_Column_ID) { if (DLM_Referencing_Column_ID < 1) { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, null); } else { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, Integer.valueOf(DLM_Referencing_Column_ID)); } } /** * Get Referenzierende Spalte. * * @return Referenzierende Spalte */ @Override public int getDLM_Referencing_Column_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Column_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partitionsgrenze.
* * @param IsPartitionBoundary * Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public void setIsPartitionBoundary(final boolean IsPartitionBoundary) { set_Value(COLUMNNAME_IsPartitionBoundary, Boolean.valueOf(IsPartitionBoundary)); } /** * Get Partitionsgrenze. * * @return Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public boolean isPartitionBoundary() { final Object oo = get_Value(COLUMNNAME_IsPartitionBoundary); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Reference.java
1
请在Spring Boot框架中完成以下Java代码
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 void validateParent(@NonNull final I_S_Issue record) { if (isParentAlreadyInHierarchy(record)) { throw new AdempiereException("The parentIssueID is already present in the hierarchy!") .appendParametersToMessage() .setParameter("ParentIssueId", record.getS_Parent_Issue_ID()) .setParameter("TargetIssueId", record.getS_Issue_ID()); } if (parentAlreadyHasAnEffortIssueAssigned(record)) { throw new AdempiereException("There is already an Effort issue created for the requested parent!") .appendParametersToMessage() .setParameter("ParentIssueId", record.getS_Parent_Issue_ID()) .setParameter("TargetIssueId", record.getS_Issue_ID()); } if (isBudgetChildForParentEffort(record)) { throw new AdempiereException("A budget issue cannot have an effort one as parent!") .appendParametersToMessage() .setParameter("ParentIssueId", record.getS_Parent_Issue_ID()) .setParameter("TargetIssueId", record.getS_Issue_ID()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = I_S_Issue.COLUMNNAME_Processed) public void setProcessedTimestamp(@NonNull final I_S_Issue record) { final I_S_Issue oldRecord = InterfaceWrapperHelper.createOld(record, I_S_Issue.class); if (oldRecord != null && oldRecord.isProcessed()) { return;//nothing to do; it means the processed timestamp was already set } if (record.isProcessed()) { record.setProcessedDate(TimeUtil.asTimestamp(Instant.now())); } } private boolean isParentAlreadyInHierarchy(@NonNull final I_S_Issue record) { final IssueId currentIssueID = IssueId.ofRepoIdOrNull(record.getS_Issue_ID()); if (currentIssueID == null) { return false; //means it's a new record so it doesn't have any children }
final IssueId parentIssueID = IssueId.ofRepoIdOrNull(record.getS_Parent_Issue_ID()); if (parentIssueID != null) { final IssueHierarchy issueHierarchy = issueRepository.buildUpStreamIssueHierarchy(parentIssueID); return issueHierarchy.hasNodeForId(currentIssueID); } return false; } private boolean parentAlreadyHasAnEffortIssueAssigned(@NonNull final I_S_Issue record) { if (record.isEffortIssue()) { final I_S_Issue parentIssue = record.getS_Parent_Issue(); if (parentIssue != null && !parentIssue.isEffortIssue()) { return issueRepository.getDirectlyLinkedSubIssues(IssueId.ofRepoId(parentIssue.getS_Issue_ID())) .stream() .anyMatch(IssueEntity::isEffortIssue); } } return false; } private boolean isBudgetChildForParentEffort(@NonNull final I_S_Issue record) { return !record.isEffortIssue() && record.getS_Parent_Issue() != null && record.getS_Parent_Issue().isEffortIssue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\interceptor\S_Issue.java
2
请完成以下Java代码
public String getWebContext(boolean full) { if (!full) return super.getURL(); String url = super.getURL(); if (url == null || url.length() == 0) url = "http://localhost"; if (url.endsWith("/")) url += url.substring(0, url.length() - 1); return url + getWebContext(); // starts with / } // getWebContext /** * String Representation * * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("WStore["); sb.append(getWebContext(true)) .append("]"); return sb.toString(); } // toString @Override protected boolean beforeSave(boolean newRecord)
{ // Context to start with / if (!getWebContext().startsWith("/")) setWebContext("/" + getWebContext()); // Org to Warehouse if (newRecord || is_ValueChanged("M_Warehouse_ID") || getAD_Org_ID() <= 0) { final I_M_Warehouse wh = Services.get(IWarehouseDAO.class).getById(WarehouseId.ofRepoId(getM_Warehouse_ID())); setAD_Org_ID(wh.getAD_Org_ID()); } String url = getURL(); if (url == null) url = ""; boolean urlOK = url.startsWith("http://") || url.startsWith("https://"); if (!urlOK) // || url.indexOf("localhost") != -1) { throw new FillMandatoryException("URL"); } return true; } // beforeSave } // MWStore
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MStore.java
1
请完成以下Java代码
public class BearerTokenAuthenticationEncoder extends AbstractEncoder<BearerTokenMetadata> { private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils .parseMimeType("message/x.rsocket.authentication.v0"); private NettyDataBufferFactory defaultBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT); public BearerTokenAuthenticationEncoder() { super(AUTHENTICATION_MIME_TYPE); } @Override public Flux<DataBuffer> encode(Publisher<? extends BearerTokenMetadata> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { return Flux.from(inputStream) .map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints)); } @Override public DataBuffer encodeValue(BearerTokenMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { String token = credentials.getToken(); NettyDataBufferFactory factory = nettyFactory(bufferFactory); ByteBufAllocator allocator = factory.getByteBufAllocator(); ByteBuf simpleAuthentication = AuthMetadataCodec.encodeBearerMetadata(allocator, token.toCharArray()); return factory.wrap(simpleAuthentication); } private NettyDataBufferFactory nettyFactory(DataBufferFactory bufferFactory) { if (bufferFactory instanceof NettyDataBufferFactory) { return (NettyDataBufferFactory) bufferFactory; } return this.defaultBufferFactory; } }
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\metadata\BearerTokenAuthenticationEncoder.java
1
请完成以下Java代码
public class ExternalWorkerJobBpmnErrorCmd extends AbstractExternalWorkerJobCmd implements Command<Void> { protected Map<String, Object> variables; protected String errorCode; public ExternalWorkerJobBpmnErrorCmd(String externalJobId, String workerId, Map<String, Object> variables, String errorCode, JobServiceConfiguration jobServiceConfiguration) { super(externalJobId, workerId, jobServiceConfiguration); this.errorCode = errorCode; this.variables = variables; } @Override protected void runJobLogic(ExternalWorkerJobEntity externalWorkerJob, CommandContext commandContext) { // We need to remove the job handler configuration String errorHandlerConfiguration; if (errorCode != null) { errorHandlerConfiguration = "error:" + errorCode; } else { errorHandlerConfiguration = "error:"; } externalWorkerJob.setJobHandlerConfiguration(errorHandlerConfiguration); if (variables != null && !variables.isEmpty()) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
VariableServiceConfiguration variableServiceConfiguration = processEngineConfiguration.getVariableServiceConfiguration(); VariableService variableService = variableServiceConfiguration.getVariableService(); for (Map.Entry<String, Object> variableEntry : variables.entrySet()) { String varName = variableEntry.getKey(); Object varValue = variableEntry.getValue(); VariableInstanceEntity variableInstance = variableService.createVariableInstance(varName); variableInstance.setScopeId(externalWorkerJob.getProcessInstanceId()); variableInstance.setSubScopeId(externalWorkerJob.getExecutionId()); variableInstance.setScopeType(ScopeTypes.BPMN_EXTERNAL_WORKER); variableService.insertVariableInstanceWithValue(variableInstance, varValue, externalWorkerJob.getTenantId()); CountingEntityUtil.handleInsertVariableInstanceEntityCount(variableInstance); } } moveExternalWorkerJobToExecutableJob(externalWorkerJob, commandContext); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ExternalWorkerJobBpmnErrorCmd.java
1
请完成以下Java代码
public class DeptrackFrontendDeploymentResource extends CRUDKubernetesDependentResource<Deployment, DeptrackResource> { public static final String COMPONENT = "frontend"; private Deployment template; public DeptrackFrontendDeploymentResource() { super(Deployment.class); this.template = BuilderHelper.loadTemplate(Deployment.class, "templates/frontend-deployment.yaml"); } @Override protected Deployment desired(DeptrackResource primary, Context<DeptrackResource> context) { ObjectMeta meta = fromPrimary(primary,COMPONENT) .build(); return new DeploymentBuilder(template).withMetadata(meta) .withSpec(buildSpec(primary, meta)) .build(); } private DeploymentSpec buildSpec(DeptrackResource primary, ObjectMeta primaryMeta) { return new DeploymentSpecBuilder().withSelector(buildSelector(primaryMeta.getLabels())) .withReplicas(1) // Dependency track does not support multiple pods (yet) .withTemplate(buildPodTemplate(primary, primaryMeta)) .build(); } private LabelSelector buildSelector(Map<String, String> labels) { return new LabelSelectorBuilder().addToMatchLabels(labels) .build(); } private PodTemplateSpec buildPodTemplate(DeptrackResource primary, ObjectMeta primaryMeta) { return new PodTemplateSpecBuilder().withMetadata(primaryMeta) .withSpec(buildPodSpec(primary)) .build(); } private PodSpec buildPodSpec(DeptrackResource primary) { // Check for version override String imageVersion = StringUtils.hasText(primary.getSpec() .getFrontendVersion()) ? ":" + primary.getSpec()
.getFrontendVersion() .trim() : ""; // Check for image override String imageName = StringUtils.hasText(primary.getSpec() .getFrontendImage()) ? primary.getSpec() .getFrontendImage() .trim() : Constants.DEFAULT_FRONTEND_IMAGE; return new PodSpecBuilder(template.getSpec().getTemplate().getSpec()) .editContainer(0) .withImage(imageName + imageVersion) .editFirstEnv() .withName("API_BASE_URL") .withValue("https://" + primary.getSpec().getIngressHostname()) .endEnv() .and() .build(); } static class Discriminator extends ResourceIDMatcherDiscriminator<Deployment,DeptrackResource> { public Discriminator() { super(COMPONENT, (p) -> new ResourceID(p.getMetadata() .getName() + "-" + COMPONENT, p.getMetadata() .getNamespace())); } } }
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackFrontendDeploymentResource.java
1
请完成以下Java代码
private IConnector getConnector() { final String className = getImpEx_ConnectorType().getClassname(); final IConnector connector = Util.getInstance(IConnector.class, className); return connector; } public IConnector useConnector() { final IConnector connector = getConnector(); final List<MImpexConnectorParam> mParams = MImpexConnectorParam.retrieve(this); final List<Parameter> connectorParams = new ArrayList<Parameter>(mParams.size()); for (final MImpexConnectorParam mParam : mParams) { final Parameter connectorParam = new Parameter( mParam.getName(), mParam.getParamName(), mParam.getDescription(), mParam .getAD_Reference_ID(), mParam.getSeqNo()); connectorParam.setValue(mParam.getParamValue()); connectorParams.add(connectorParam); } connector.open(connectorParams); return connector; } public void createParameters() { deleteParameters(); for (final Parameter param : getConnector().getParameters()) { final MImpexConnectorParam mParam = new MImpexConnectorParam( getCtx(), 0, get_TrxName()); mParam.setParamName(param.displayName);
mParam.setDescription(param.description); mParam.setAD_Reference_ID(param.displayType); mParam.setName(param.name); mParam.setSeqNo(param.seqNo); mParam.setImpEx_Connector_ID(this.get_ID()); mParam.saveEx(); } } private void deleteParameters() { for (final MImpexConnectorParam mParam : MImpexConnectorParam.retrieve(this)) { mParam.deleteEx(false); } } @Override protected boolean beforeDelete() { deleteParameters(); return true; } @Override protected boolean afterSave(boolean newRecord, boolean success) { if (success && (newRecord || is_ValueChanged(COLUMNNAME_ImpEx_ConnectorType_ID))) { createParameters(); } return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\model\MImpExConnector.java
1
请完成以下Java代码
public class CashBalanceAvailabilityDate1 { @XmlElement(name = "NbOfDays") protected String nbOfDays; @XmlElement(name = "ActlDt") @XmlSchemaType(name = "date") protected XMLGregorianCalendar actlDt; /** * Gets the value of the nbOfDays property. * * @return * possible object is * {@link String } * */ public String getNbOfDays() { return nbOfDays; } /** * Sets the value of the nbOfDays property. * * @param value * allowed object is * {@link String } * */ public void setNbOfDays(String value) { this.nbOfDays = value; } /** * Gets the value of the actlDt property. * * @return * possible object is * {@link XMLGregorianCalendar }
* */ public XMLGregorianCalendar getActlDt() { return actlDt; } /** * Sets the value of the actlDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setActlDt(XMLGregorianCalendar value) { this.actlDt = 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\CashBalanceAvailabilityDate1.java
1
请完成以下Java代码
public class SetCaseDefinitionCategoryCmd implements Command<Void> { protected String caseDefinitionId; protected String category; public SetCaseDefinitionCategoryCmd(String caseDefinitionId, String category) { this.caseDefinitionId = caseDefinitionId; this.category = category; } @Override public Void execute(CommandContext commandContext) { if (caseDefinitionId == null) { throw new FlowableIllegalArgumentException("Case definition id is null"); } CaseDefinitionEntity caseDefinition = CommandContextUtil.getCaseDefinitionEntityManager(commandContext).findById(caseDefinitionId); if (caseDefinition == null) { throw new FlowableObjectNotFoundException("No case definition found for id = '" + caseDefinitionId + "'", CaseDefinition.class); } // Update category caseDefinition.setCategory(category); // Remove case definition from cache, it will be refetch later DeploymentCache<CaseDefinitionCacheEntry> caseDefinitionCache = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getCaseDefinitionCache(); if (caseDefinitionCache != null) { caseDefinitionCache.remove(caseDefinitionId); }
return null; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetCaseDefinitionCategoryCmd.java
1
请完成以下Java代码
public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public List<OrderLine> getOrderLines() { if (orderLines == null) { orderLines = new ArrayList<>();
} return orderLines; } public void setOrderLines(List<OrderLine> orderLines) { if (orderLines == null) { orderLines = new ArrayList<>(); } this.orderLines = orderLines; } @Override public String toString() { return "Order [orderNo=" + orderNo + ", date=" + date + ", customerName=" + customerName + ", orderLines=" + orderLines + "]"; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\yaml\Order.java
1
请完成以下Java代码
public class OrderDO { /** * 订单编号 */ private Integer id; /** * 用户编号 */ private Integer userId; public Integer getId() { return id; } public OrderDO setId(Integer id) { this.id = id; return this; }
public Integer getUserId() { return userId; } public OrderDO setUserId(Integer userId) { this.userId = userId; return this; } @Override public String toString() { return "OrderDO{" + "id=" + id + ", userId=" + userId + '}'; } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\dataobject\OrderDO.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisCacheConfig { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private Environment env; @Bean public LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration(); redisConf.setHostName(env.getProperty("spring.redis.host")); redisConf.setPort(Integer.parseInt(env.getProperty("spring.redis.port"))); redisConf.setPassword(RedisPassword.of(env.getProperty("spring.redis.password"))); return new LettuceConnectionFactory(redisConf); } @Bean public RedisCacheConfiguration cacheConfiguration() { RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .disableCachingNullValues(); return cacheConfig; } @Bean public RedisCacheManager cacheManager() { RedisCacheManager rcm = RedisCacheManager.builder(redisConnectionFactory())
.cacheDefaults(cacheConfiguration()) .transactionAware() .build(); return rcm; } /** * 自定义缓存key的生成类实现 */ @Bean(name = "myKeyGenerator") public KeyGenerator myKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... params) { logger.info("自定义缓存,使用第一参数作为缓存key,params = " + Arrays.toString(params)); // 仅仅用于测试,实际不可能这么写 return params[0]; } }; } }
repos\SpringBootBucket-master\springboot-cache\src\main\java\com\xncoding\trans\config\RedisCacheConfig.java
2
请完成以下Java代码
public class MRequestAction extends X_R_RequestAction { /** * */ private static final long serialVersionUID = 2902231219773596011L; /** * Persistency Constructor * @param ctx context * @param R_RequestAction_ID id */ public MRequestAction (Properties ctx, int R_RequestAction_ID, String trxName) { super (ctx, R_RequestAction_ID, trxName); } // MRequestAction /** * Load Construtor * @param ctx context * @param rs result set */ public MRequestAction(Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MRequestAction /** * Parent Action Constructor * @param request parent */ public MRequestAction (final MRequest request) { this (request.getCtx(), 0, request.get_TrxName()); setClientOrg(request); setR_Request_ID (request.getR_Request_ID()); } // MRequestAction /** * Add Null Column * @param columnName */ public void addNullColumn (String columnName) { String nc = getNullColumns(); if (nc == null)
{ setNullColumns(columnName); } else { setNullColumns(nc + ";" + columnName); } } // addNullColumn /** * Get Name of creator * @return name */ public String getCreatedByName() { I_AD_User user = Services.get(IUserDAO.class).retrieveUserOrNull(getCtx(), getCreatedBy()); return user.getName(); } // getCreatedByName /** * Before Save * @param newRecord new * @return true */ @Override protected boolean beforeSave (boolean newRecord) { return true; } // beforeSave } // MRequestAction
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequestAction.java
1
请完成以下Spring Boot application配置
spring: application: name: demo-consumer # Spring 应用名 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 server: port: 28080 # 服务器端口。默认为 8080 ribbon: # okhttp: # enabled: true # 设置使用 OkHttp,对应 OkHttpRibbonConfiguration 配置类 restclient: enabled: true # 设置使用 Jersey Client,对应 RestClientRibbonConfiguration 配置类 # ht
tpclient: # enabled: true # 设置使用 Apache HttpClient,对应 HttpClientRibbonConfiguration 配置类 # ConnectTimeout: 1 # 请求的连接超时时间,单位:毫秒。默认为 1000 # ReadTimeout: 1 # 请求的读取超时时间,单位:毫秒。默认为 1000
repos\SpringBoot-Labs-master\labx-02-spring-cloud-netflix-ribbon\labx-02-scn-ribbon-demo05-consumer\src\main\resources\application.yaml
2
请完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // .anyRequest().permitAll() if you fix all permission values, then remove all conditions. .antMatchers("/index").permitAll() .antMatchers("/profile/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER") .antMatchers("/api/public/test1").hasAuthority("ACCESS_TEST1") .antMatchers("/api/public/test2").hasAuthority("ACCESS_TEST2") .antMatchers("/api/public/users").hasAuthority("ADMIN") .and() .httpBasic(); }
@Bean DaoAuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetialService); return daoAuthenticationProvider; } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\8. SpringAuthenticateDB\src\main\java\spring\authenticate\security\SpringSecurity.java
1
请完成以下Java代码
public void init() { // o_name and O_NAME, same jdbcTemplate.setResultsMapCaseInsensitive(true); // Convert o_c_book SYS_REFCURSOR to List<Book> simpleJdbcCallRefCursor = new SimpleJdbcCall(jdbcTemplate) .withProcedureName("get_book_by_name") .returningResultSet("o_c_book", BeanPropertyRowMapper.newInstance(Book.class)); } private static final String SQL_STORED_PROC_REF = "" + " CREATE OR REPLACE PROCEDURE get_book_by_name " + " (" + " p_name IN BOOKS.NAME%TYPE," + " o_c_book OUT SYS_REFCURSOR" + " ) AS" + " BEGIN" + " OPEN o_c_book FOR" + " SELECT * FROM BOOKS WHERE NAME LIKE '%' || p_name || '%';" + " END;"; public void start() { log.info("Creating Store Procedures and Function..."); jdbcTemplate.execute(SQL_STORED_PROC_REF); /* Test Stored Procedure RefCursor */ List<Book> books = findBookByName("Java"); // Book{id=1, name='Thinking in Java', price=46.32} // Book{id=2, name='Mkyong in Java', price=1.99} books.forEach(x -> System.out.println(x)); }
List<Book> findBookByName(String name) { SqlParameterSource paramaters = new MapSqlParameterSource() .addValue("p_name", name); Map out = simpleJdbcCallRefCursor.execute(paramaters); if (out == null) { return Collections.emptyList(); } else { return (List) out.get("o_c_book"); } } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\sp\StoredProcedure2.java
1
请完成以下Java代码
public void setQtyEntered (BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Quantity. @return The Quantity Entered is based on the selected UoM */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Tax Amount. @param TaxAmt Tax Amount for a document */ public void setTaxAmt (BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } /** Get Tax Amount. @return Tax Amount for a document */ public BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); } /** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0;
return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceBatchLine.java
1
请完成以下Java代码
public abstract class ServiceListenerFuture<S, V> implements LifecycleListener, Future<V> { protected final S serviceInstance; public ServiceListenerFuture(S serviceInstance) { this.serviceInstance = serviceInstance; } protected V value; boolean cancelled; boolean failed; @Override public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) { if(event.equals(LifecycleEvent.UP)) { serviceAvailable(); synchronized(this) { this.notifyAll(); } } else if(event.equals(LifecycleEvent.FAILED)) { synchronized (this) { failed = true; this.notifyAll(); } } else { synchronized(this) { cancelled = true; this.notifyAll(); } } } protected abstract void serviceAvailable(); public boolean cancel(boolean mayInterruptIfRunning) { // unsupported return false; } public boolean isCancelled() { // unsupported return cancelled; } public boolean isDone() { return value != null; } public V get() throws InterruptedException, ExecutionException { if (!failed && !cancelled && value == null) { synchronized (this) {
if (!failed && !cancelled && value == null) { this.wait(); } } } return value; } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!failed && !cancelled && value == null) { synchronized (this) { if (!failed && !cancelled && value == null) { this.wait(unit.convert(timeout, TimeUnit.MILLISECONDS)); } synchronized (this) { if (value == null) { throw new TimeoutException(); } } } } return value; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\util\ServiceListenerFuture.java
1
请完成以下Java代码
public class CustomsInvoice { @NonFinal CustomsInvoiceId id; @NonFinal UserId createdBy; @NonFinal UserId lastUpdatedBy; @NonNull String documentNo; @NonNull OrgId orgId; @NonNull BPartnerLocationId bpartnerAndLocationId; @NonNull String bpartnerAddress; @Nullable UserId userId; @NonNull CurrencyId currencyId; @NonNull DocTypeId docTypeId; @NonNull LocalDate invoiceDate; @NonNull String docAction;
@NonNull DocStatus docStatus; @NonNull ImmutableList<CustomsInvoiceLine> lines; public void updateLineNos() { int nextLineNo = 10; for (CustomsInvoiceLine line : lines) { line.setLineNo(nextLineNo); nextLineNo += 10; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoice.java
1
请完成以下Java代码
public void setEndDate (Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get End Date. @return Last effective date (inclusive) */ public Timestamp getEndDate () { return (Timestamp)get_Value(COLUMNNAME_EndDate); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Period No. @param PeriodNo Unique Period Number */ public void setPeriodNo (int PeriodNo) { set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo)); } /** Get Period No. @return Unique Period Number */ public int getPeriodNo () { Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo); if (ii == null) return 0; return ii.intValue(); } /** PeriodType AD_Reference_ID=115 */ public static final int PERIODTYPE_AD_Reference_ID=115; /** Standard Calendar Period = S */ public static final String PERIODTYPE_StandardCalendarPeriod = "S"; /** Adjustment Period = A */ public static final String PERIODTYPE_AdjustmentPeriod = "A"; /** Set Period Type. @param PeriodType Period Type */ public void setPeriodType (String PeriodType) { set_ValueNoCheck (COLUMNNAME_PeriodType, PeriodType); } /** Get Period Type. @return Period Type */ public String getPeriodType ()
{ return (String)get_Value(COLUMNNAME_PeriodType); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java
1
请在Spring Boot框架中完成以下Java代码
public final void preTimerJobDelete(JobEntity jobEntity, VariableScope variableScope) { InternalJobManager internalJobManager = findInternalJobManager(jobEntity); if (internalJobManager == null) { preTimerJobDeleteInternal(jobEntity, variableScope); } else { internalJobManager.preTimerJobDelete(jobEntity, variableScope); } } protected abstract void preTimerJobDeleteInternal(JobEntity jobEntity, VariableScope variableScope); @Override public final void preRepeatedTimerSchedule(TimerJobEntity timerJobEntity, VariableScope variableScope) { InternalJobManager internalJobManager = findInternalJobManager(timerJobEntity); if (internalJobManager == null) { preRepeatedTimerScheduleInternal(timerJobEntity, variableScope); } else { internalJobManager.preRepeatedTimerSchedule(timerJobEntity, variableScope); }
} protected abstract void preRepeatedTimerScheduleInternal(TimerJobEntity timerJobEntity, VariableScope variableScope); protected InternalJobManager findInternalJobManager(Job job) { if (internalJobManagerByScopeType == null || internalJobManagerByScopeType.isEmpty()) { return null; } String scopeType = job.getScopeType(); if (scopeType == null && job.getProcessInstanceId() != null) { scopeType = ScopeTypes.BPMN; } return internalJobManagerByScopeType.get(scopeType); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\ScopeAwareInternalJobManager.java
2
请在Spring Boot框架中完成以下Java代码
ReactiveGridFsTemplate reactiveGridFsTemplate(DataMongoProperties dataProperties, ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory, MappingMongoConverter mappingMongoConverter, DataBufferFactory dataBufferFactory) { return new ReactiveGridFsTemplate(dataBufferFactory, new GridFsReactiveMongoDatabaseFactory(reactiveMongoDatabaseFactory, dataProperties), mappingMongoConverter, dataProperties.getGridfs().getBucket()); } /** * {@link ReactiveMongoDatabaseFactory} decorator to use {@link Gridfs#getDatabase()} * from the {@link MongoProperties} when set. */ static class GridFsReactiveMongoDatabaseFactory implements ReactiveMongoDatabaseFactory { private final ReactiveMongoDatabaseFactory delegate; private final DataMongoProperties properties; GridFsReactiveMongoDatabaseFactory(ReactiveMongoDatabaseFactory delegate, DataMongoProperties properties) { this.delegate = delegate; this.properties = properties; } @Override public boolean hasCodecFor(Class<?> type) { return this.delegate.hasCodecFor(type); } @Override public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException { String gridFsDatabase = getGridFsDatabase(); if (StringUtils.hasText(gridFsDatabase)) { return this.delegate.getMongoDatabase(gridFsDatabase); } return this.delegate.getMongoDatabase(); } private @Nullable String getGridFsDatabase() { return this.properties.getGridfs().getDatabase(); } @Override public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException { return this.delegate.getMongoDatabase(dbName);
} @Override public <T> Optional<Codec<T>> getCodecFor(Class<T> type) { return this.delegate.getCodecFor(type); } @Override public PersistenceExceptionTranslator getExceptionTranslator() { return this.delegate.getExceptionTranslator(); } @Override public CodecRegistry getCodecRegistry() { return this.delegate.getCodecRegistry(); } @Override public Mono<ClientSession> getSession(ClientSessionOptions options) { return this.delegate.getSession(options); } @Override public ReactiveMongoDatabaseFactory withSession(ClientSession session) { return this.delegate.withSession(session); } @Override public boolean isTransactionActive() { return this.delegate.isTransactionActive(); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java
2
请完成以下Java代码
public void addTaxBaseAmt(@NonNull final Money taxBaseAmtToAdd) { if (taxBaseAmtToAdd.isZero()) { return; } this.taxBaseAmt = this.taxBaseAmt.add(taxBaseAmtToAdd); this.isTaxCalculated = false; } public Money getTaxAmt() { updateTaxAmtsIfNeeded(); return _taxAmt; } public Money getReverseChargeAmt() { updateTaxAmtsIfNeeded(); return _reverseChargeAmt; } private void updateTaxAmtsIfNeeded() { if (!isTaxCalculated) { final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt()); this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId()); this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId());
this.isTaxCalculated = true; } } public void updateDocTax(@NonNull final DocTax docTax) { if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId())) { throw new AdempiereException("TaxId not matching: " + this + ", " + docTax); } docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal()); docTax.setTaxAmt(getTaxAmt().toBigDecimal()); docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java
1
请完成以下Java代码
public class DiscoveredOperationMethod extends OperationMethod { private final List<String> producesMediaTypes; public DiscoveredOperationMethod(Method method, OperationType operationType, AnnotationAttributes annotationAttributes) { super(method, operationType); Assert.notNull(annotationAttributes, "'annotationAttributes' must not be null"); List<String> producesMediaTypes = new ArrayList<>(); producesMediaTypes.addAll(Arrays.asList(annotationAttributes.getStringArray("produces"))); producesMediaTypes.addAll(getProducesFromProducible(annotationAttributes)); this.producesMediaTypes = Collections.unmodifiableList(producesMediaTypes); } private <E extends Enum<E> & Producible<E>> List<String> getProducesFromProducible( AnnotationAttributes annotationAttributes) { Class<?> type = getProducesFrom(annotationAttributes); if (type == Producible.class) { return Collections.emptyList(); } List<String> produces = new ArrayList<>(); for (Object value : type.getEnumConstants()) {
produces.add(((Producible<?>) value).getProducedMimeType().toString()); } return produces; } private Class<?> getProducesFrom(AnnotationAttributes annotationAttributes) { try { return annotationAttributes.getClass("producesFrom"); } catch (IllegalArgumentException ex) { return Producible.class; } } public List<String> getProducesMediaTypes() { return this.producesMediaTypes; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\annotation\DiscoveredOperationMethod.java
1
请完成以下Java代码
public class Queue extends BaseDataWithAdditionalInfo<QueueId> implements HasName, HasTenantId, QueueConfig { private TenantId tenantId; @NoXss @Length(fieldName = "name") private String name; @NoXss @Length(fieldName = "topic") private String topic; private int pollInterval; private int partitions; private boolean consumerPerPartition; private long packProcessingTimeout; private SubmitStrategy submitStrategy; private ProcessingStrategy processingStrategy; public Queue() { } public Queue(QueueId id) { super(id); } public Queue(TenantId tenantId, TenantProfileQueueConfiguration queueConfiguration) { this.tenantId = tenantId; this.name = queueConfiguration.getName(); this.topic = queueConfiguration.getTopic(); this.pollInterval = queueConfiguration.getPollInterval(); this.partitions = queueConfiguration.getPartitions(); this.consumerPerPartition = queueConfiguration.isConsumerPerPartition(); this.packProcessingTimeout = queueConfiguration.getPackProcessingTimeout(); this.submitStrategy = queueConfiguration.getSubmitStrategy(); this.processingStrategy = queueConfiguration.getProcessingStrategy(); setAdditionalInfo(queueConfiguration.getAdditionalInfo()); }
@JsonIgnore public String getCustomProperties() { return Optional.ofNullable(getAdditionalInfo()) .map(info -> info.get("customProperties")) .filter(JsonNode::isTextual).map(JsonNode::asText).orElse(null); } @JsonIgnore public boolean isDuplicateMsgToAllPartitions() { return Optional.ofNullable(getAdditionalInfo()) .map(info -> info.get("duplicateMsgToAllPartitions")) .filter(JsonNode::isBoolean).map(JsonNode::asBoolean).orElse(false); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\queue\Queue.java
1
请完成以下Java代码
protected void initializeResultVariable(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask decisionTask = getDefinition(element); DmnDecisionTaskActivityBehavior behavior = getActivityBehavior(activity); String resultVariable = decisionTask.getCamundaResultVariable(); behavior.setResultVariable(resultVariable); } protected void initializeDecisionTableResultMapper(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask decisionTask = getDefinition(element); DmnDecisionTaskActivityBehavior behavior = getActivityBehavior(activity); String mapper = decisionTask.getCamundaMapDecisionResult(); DecisionResultMapper decisionResultMapper = getDecisionResultMapperForName(mapper); behavior.setDecisionTableResultMapper(decisionResultMapper); } protected BaseCallableElement createCallableElement() { return new BaseCallableElement(); } protected CmmnActivityBehavior getActivityBehavior() { return new DmnDecisionTaskActivityBehavior(); } protected DmnDecisionTaskActivityBehavior getActivityBehavior(CmmnActivity activity) { return (DmnDecisionTaskActivityBehavior) activity.getActivityBehavior(); } protected String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); String decision = definition.getDecision(); if (decision == null) { DecisionRefExpression decisionExpression = definition.getDecisionExpression(); if (decisionExpression != null) { decision = decisionExpression.getText(); }
} return decision; } protected String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionBinding(); } protected String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionVersion(); } protected String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { DecisionTask definition = getDefinition(element); return definition.getCamundaDecisionTenantId(); } protected DecisionTask getDefinition(CmmnElement element) { return (DecisionTask) super.getDefinition(element); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\DecisionTaskItemHandler.java
1
请完成以下Java代码
private BPartnerLocationId computeAddressToUse( @Nullable final BPartnerId bpartnerId, @Nullable final DefaultAddressType defaultAddressType) { if (bpartnerId == null) { // no address found return null; } // Keep as before, and consider Billing address as default return DefaultAddressType.ShipToDefault.equals(defaultAddressType) ? bpartnerDAO.getShiptoDefaultLocationIdByBpartnerId(bpartnerId) : bpartnerDAO.getBilltoDefaultLocationIdByBpartnerId(bpartnerId); } public void removeUserFromCampaign( @NonNull final User user, @NonNull final CampaignId campaignId) { final Campaign campaign = campaignRepository.getById(campaignId); BPartnerLocationId billToDefaultLocationId = null; if (user.getBpartnerId() != null) { billToDefaultLocationId = bpartnerDAO.getBilltoDefaultLocationIdByBpartnerId(user.getBpartnerId()); } final ContactPerson contactPerson = ContactPerson.newForUserPlatformAndLocation(user, campaign.getPlatformId(), billToDefaultLocationId); final ContactPerson savedContactPerson = contactPersonRepository.save(contactPerson);
contactPersonRepository.revokeConsent(savedContactPerson); campaignRepository.removeContactPersonFromCampaign(savedContactPerson, campaign); } public void saveSyncResults(@NonNull final List<? extends SyncResult> syncResults) { for (final SyncResult syncResult : syncResults) { campaignRepository.saveCampaignSyncResult(syncResult); } } public Campaign saveSyncResult(@NonNull final SyncResult syncResult) { return campaignRepository.saveCampaignSyncResult(syncResult); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\CampaignService.java
1
请完成以下Java代码
protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) { final Module module = deploymentUnit.getAttachment(MODULE); Map<String, byte[]> resources = new HashMap<>(); // first, add all resources listed in the processes.xml List<String> process = processArchive.getProcessResourceNames(); ModuleClassLoader classLoader = module.getClassLoader(); for (String resource : process) { InputStream inputStream = null; try { inputStream = classLoader.getResourceAsStream(resource); resources.put(resource, IoUtil.readInputStream(inputStream, resource)); } finally { IoUtil.closeSilently(inputStream); } } // scan for process definitions if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) { //always use VFS scanner on JBoss final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner(); String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH); String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR); URL processesXmlUrl = vfsFileAsUrl(processesXmlFile);
resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes)); } return resources; } protected URL vfsFileAsUrl(VirtualFile processesXmlFile) { try { return processesXmlFile.toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class ResourceController { private static Logger logger = LoggerFactory.getLogger(ResourceController.class); @Autowired private SentinelApiClient httpFetcher; /** * Fetch real time statistics info of the machine. * * @param ip ip to fetch * @param port port of the ip * @param type one of [root, default, cluster], 'root' means fetching from tree root node, 'default' means * fetching from tree default node, 'cluster' means fetching from cluster node. * @param searchKey key to search * @return node statistics info. */ @GetMapping("/machineResource.json") public Result<List<ResourceVo>> fetchResourceChainListOfMachine(String ip, Integer port, String type, String searchKey) { if (StringUtil.isEmpty(ip) || port == null) { return Result.ofFail(-1, "invalid param, give ip, port"); } final String ROOT = "root"; final String DEFAULT = "default"; if (StringUtil.isEmpty(type)) { type = ROOT; } if (ROOT.equalsIgnoreCase(type) || DEFAULT.equalsIgnoreCase(type)) { List<NodeVo> nodeVos = httpFetcher.fetchResourceOfMachine(ip, port, type); if (nodeVos == null) { return Result.ofSuccess(null); }
ResourceTreeNode treeNode = ResourceTreeNode.fromNodeVoList(nodeVos); treeNode.searchIgnoreCase(searchKey); return Result.ofSuccess(ResourceVo.fromResourceTreeNode(treeNode)); } else { // Normal (cluster node). List<NodeVo> nodeVos = httpFetcher.fetchClusterNodeOfMachine(ip, port, true); if (nodeVos == null) { return Result.ofSuccess(null); } if (StringUtil.isNotEmpty(searchKey)) { nodeVos = nodeVos.stream().filter(node -> node.getResource() .toLowerCase().contains(searchKey.toLowerCase())) .collect(Collectors.toList()); } return Result.ofSuccess(ResourceVo.fromNodeVoList(nodeVos)); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\ResourceController.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DmnEvaluatedOutputImpl that = (DmnEvaluatedOutputImpl) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (outputName != null ? !outputName.equals(that.outputName) : that.outputName != null) return false; return !(value != null ? !value.equals(that.value) : that.value != null); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (outputName != null ? outputName.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public String toString() { return "DmnEvaluatedOutputImpl{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", outputName='" + outputName + '\'' + ", value=" + value + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedOutputImpl.java
1
请完成以下Java代码
public class InSubQueryFilterClause<ModelType, ParentType> implements IInSubQueryFilterClause<ModelType, ParentType> { private final ParentType parent; private final Consumer<InSubQueryFilter<ModelType>> finisher; private final InSubQueryFilter.Builder<ModelType> inSubQueryBuilder; private boolean destroyed = false; public InSubQueryFilterClause(@NonNull final String tableName, @NonNull final ParentType parent, @NonNull final Consumer<InSubQueryFilter<ModelType>> finisher) { this.parent = parent; this.finisher = finisher; inSubQueryBuilder = InSubQueryFilter.<ModelType> builder() .tableName(tableName); } private void asserNotDestroyed() { if (destroyed) { throw new AdempiereException("already destroyed: " + this); } } private void markAsDestroyed() { asserNotDestroyed(); destroyed = true; } @Override public ParentType end() { markAsDestroyed(); final InSubQueryFilter<ModelType> inSubQueryFilter = inSubQueryBuilder.build(); finisher.accept(inSubQueryFilter); return parent; } @Override public IInSubQueryFilterClause<ModelType, ParentType> subQuery(final IQuery<?> subQuery) {
asserNotDestroyed(); inSubQueryBuilder.subQuery(subQuery); return this; } @Override public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier) { asserNotDestroyed(); inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName, modifier); return this; } @Override public IInSubQueryFilterClause<ModelType, ParentType> matchingColumnNames(final String columnName, final String subQueryColumnName) { asserNotDestroyed(); inSubQueryBuilder.matchingColumnNames(columnName, subQueryColumnName); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilterClause.java
1
请完成以下Java代码
private List<Resource> doGetResources(String location, ScriptLocationResolver locationResolver) { try { return locationResolver.resolve(location); } catch (Exception ex) { throw new IllegalStateException("Unable to load resources from " + location, ex); } } private void runScripts(List<Resource> resources) { runScripts(new Scripts(resources).continueOnError(this.settings.isContinueOnError()) .separator(this.settings.getSeparator()) .encoding(this.settings.getEncoding())); } /** * Initialize the database by running the given {@code scripts}. * @param scripts the scripts to run * @since 3.0.0 */ protected abstract void runScripts(Scripts scripts); private static class ScriptLocationResolver { private final ResourcePatternResolver resourcePatternResolver; ScriptLocationResolver(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); } private List<Resource> resolve(String location) throws IOException { List<Resource> resources = new ArrayList<>( Arrays.asList(this.resourcePatternResolver.getResources(location))); resources.sort((r1, r2) -> { try { return r1.getURL().toString().compareTo(r2.getURL().toString()); } catch (IOException ex) { return 0; } }); return resources; } } /** * Scripts to be used to initialize the database. * * @since 3.0.0 */ public static class Scripts implements Iterable<Resource> { private final List<Resource> resources;
private boolean continueOnError; private String separator = ";"; private @Nullable Charset encoding; public Scripts(List<Resource> resources) { this.resources = resources; } @Override public Iterator<Resource> iterator() { return this.resources.iterator(); } public Scripts continueOnError(boolean continueOnError) { this.continueOnError = continueOnError; return this; } public boolean isContinueOnError() { return this.continueOnError; } public Scripts separator(String separator) { this.separator = separator; return this; } public String getSeparator() { return this.separator; } public Scripts encoding(@Nullable Charset encoding) { this.encoding = encoding; return this; } public @Nullable Charset getEncoding() { return this.encoding; } } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
1
请在Spring Boot框架中完成以下Java代码
public class QiNiuServiceImpl implements IQiNiuService, InitializingBean { private final UploadManager uploadManager; private final Auth auth; @Value("${qiniu.bucket}") private String bucket; private StringMap putPolicy; @Autowired public QiNiuServiceImpl(UploadManager uploadManager, Auth auth) { this.uploadManager = uploadManager; this.auth = auth; } /** * 七牛云上传文件 * * @param file 文件 * @return 七牛上传Response * @throws QiniuException 七牛异常 */ @Override public Response uploadFile(File file) throws QiniuException { Response response = this.uploadManager.put(file, file.getName(), getUploadToken()); int retry = 0; while (response.needRetry() && retry < 3) { response = this.uploadManager.put(file, file.getName(), getUploadToken());
retry++; } return response; } @Override public void afterPropertiesSet() { this.putPolicy = new StringMap(); putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}"); } /** * 获取上传凭证 * * @return 上传凭证 */ private String getUploadToken() { return this.auth.uploadToken(bucket, null, 3600, putPolicy); } }
repos\spring-boot-demo-master\demo-upload\src\main\java\com\xkcoding\upload\service\impl\QiNiuServiceImpl.java
2
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public boolean isClosed() { return isClosedAttribute.getValue(this); } public void setClosed(boolean isClosed) { isClosedAttribute.setValue(this, isClosed); } public Collection<Participant> getParticipants() { return participantCollection.get(this); } public Collection<MessageFlow> getMessageFlows() { return messageFlowCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } public Collection<ConversationNode> getConversationNodes() {
return conversationNodeCollection.get(this); } public Collection<ConversationAssociation> getConversationAssociations() { return conversationAssociationCollection.get(this); } public Collection<ParticipantAssociation> getParticipantAssociations() { return participantAssociationCollection.get(this); } public Collection<MessageFlowAssociation> getMessageFlowAssociations() { return messageFlowAssociationCollection.get(this); } public Collection<CorrelationKey> getCorrelationKeys() { return correlationKeyCollection.get(this); } public Collection<ConversationLink> getConversationLinks() { return conversationLinkCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CollaborationImpl.java
1
请完成以下Java代码
public class StartJobAcquisitionStep extends DeploymentOperationStep { protected final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER; protected final JobAcquisitionXml jobAcquisitionXml; public StartJobAcquisitionStep(JobAcquisitionXml jobAcquisitionXml) { this.jobAcquisitionXml = jobAcquisitionXml; } public String getName() { return "Start job acquisition '"+jobAcquisitionXml.getName()+"'"; } public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final AbstractProcessApplication processApplication = operationContext.getAttachment(PROCESS_APPLICATION); ClassLoader configurationClassloader = null; if(processApplication != null) { configurationClassloader = processApplication.getProcessApplicationClassloader(); } else { configurationClassloader = ProcessEngineConfiguration.class.getClassLoader(); } String configurationClassName = jobAcquisitionXml.getJobExecutorClassName(); if(configurationClassName == null || configurationClassName.isEmpty()) { configurationClassName = RuntimeContainerJobExecutor.class.getName(); } // create & instantiate the job executor class Class<? extends JobExecutor> jobExecutorClass = loadJobExecutorClass(configurationClassloader, configurationClassName); JobExecutor jobExecutor = instantiateJobExecutor(jobExecutorClass); // apply properties Map<String, String> properties = jobAcquisitionXml.getProperties(); PropertyHelper.applyProperties(jobExecutor, properties); // construct service for job executor JmxManagedJobExecutor jmxManagedJobExecutor = new JmxManagedJobExecutor(jobExecutor);
// deploy the job executor service into the container serviceContainer.startService(ServiceTypes.JOB_EXECUTOR, jobAcquisitionXml.getName(), jmxManagedJobExecutor); } protected JobExecutor instantiateJobExecutor(Class<? extends JobExecutor> configurationClass) { try { return configurationClass.newInstance(); } catch (Exception e) { throw LOG.couldNotInstantiateJobExecutorClass(e); } } @SuppressWarnings("unchecked") protected Class<? extends JobExecutor> loadJobExecutorClass(ClassLoader processApplicationClassloader, String jobExecutorClassname) { try { return (Class<? extends JobExecutor>) processApplicationClassloader.loadClass(jobExecutorClassname); } catch (ClassNotFoundException e) { throw LOG.couldNotLoadJobExecutorClass(e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartJobAcquisitionStep.java
1
请完成以下Java代码
public void setA_State (String A_State) { set_Value (COLUMNNAME_A_State, A_State); } /** Get Account State. @return State of the Credit Card or Account holder */ public String getA_State () { return (String)get_Value(COLUMNNAME_A_State); } /** Set Tax Entity. @param A_Tax_Entity Tax Entity */ public void setA_Tax_Entity (String A_Tax_Entity) { set_Value (COLUMNNAME_A_Tax_Entity, A_Tax_Entity); } /** Get Tax Entity. @return Tax Entity */ public String getA_Tax_Entity () { return (String)get_Value(COLUMNNAME_A_Tax_Entity); }
/** 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_A_Asset_Info_Tax.java
1
请完成以下Java代码
private void handleIfBindException(String dn, String username, org.springframework.ldap.NamingException naming) { if ((naming instanceof org.springframework.ldap.AuthenticationException) || (naming instanceof org.springframework.ldap.OperationNotSupportedException)) { handleBindException(dn, username, naming); } else { throw naming; } } /** * Allows subclasses to inspect the exception thrown by an attempt to bind with a * particular DN. The default implementation just reports the failure to the debug * logger. */ protected void handleBindException(String userDn, String username, Throwable cause) { logger.trace(LogMessage.format("Failed to bind as %s", userDn), cause); }
/** * Set whether javax-based bind exceptions should also be delegated to * {@code #handleBindException} (only Spring-based bind exceptions are handled by * default) * * <p> * For passivity reasons, defaults to {@code false}, though may change to {@code true} * in future releases. * @param alsoHandleJavaxNamingBindExceptions - whether to delegate javax-based bind * exceptions to #handleBindException * @since 6.4 */ public void setAlsoHandleJavaxNamingBindExceptions(boolean alsoHandleJavaxNamingBindExceptions) { this.alsoHandleJavaxNamingBindExceptions = alsoHandleJavaxNamingBindExceptions; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\BindAuthenticator.java
1
请完成以下Java代码
public String getKey() { return this.key; } public void setTokenValiditySeconds(int tokenValiditySeconds) { this.tokenValiditySeconds = tokenValiditySeconds; } protected int getTokenValiditySeconds() { return this.tokenValiditySeconds; } /** * Whether the cookie should be flagged as secure or not. Secure cookies can only be * sent over an HTTPS connection and thus cannot be accidentally submitted over HTTP * where they could be intercepted. * <p> * By default the cookie will be secure if the request is secure. If you only want to * use remember-me over HTTPS (recommended) you should set this property to * {@code true}. * @param useSecureCookie set to {@code true} to always user secure cookies, * {@code false} to disable their use. */ public void setUseSecureCookie(boolean useSecureCookie) { this.useSecureCookie = useSecureCookie; } protected AuthenticationDetailsSource<HttpServletRequest, ?> getAuthenticationDetailsSource() { return this.authenticationDetailsSource; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource cannot be null"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * Sets the strategy to be used to validate the {@code UserDetails} object obtained * for the user when processing a remember-me cookie to automatically log in a user. * @param userDetailsChecker the strategy which will be passed the user object to * allow it to be rejected if account should not be allowed to authenticate (if it is * locked, for example). Defaults to a {@code AccountStatusUserDetailsChecker}
* instance. * */ public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { this.userDetailsChecker = userDetailsChecker; } public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { this.authoritiesMapper = authoritiesMapper; } /** * @since 5.5 */ @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the {@link Consumer}, allowing customization of cookie. * @param cookieCustomizer customize for cookie * @since 6.4 */ public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) { Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null"); this.cookieCustomizer = cookieCustomizer; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\AbstractRememberMeServices.java
1
请完成以下Java代码
private I_M_HU getOrCreateCurrentTU() { if (_currentTU == null) { _currentTU = newHUBuilder().create(tuPI); } return _currentTU; } private void closeCurrentTUIfCapacityExceeded() { if (_currentTU != null && getCurrentTURemainingQty().signum() <= 0) { closeCurrentTU(); } } void closeCurrentTU() { if (_currentTU != null && _currentAttributes != null) { final IAttributeStorage tuAttributes = getAttributeStorage(_currentTU); tuAttributes.setSaveOnChange(true); _currentAttributes.updateAggregatedValuesTo(tuAttributes); } _currentTU = null; _currentTUQty = null; _currentAttributes = null; } private void addToCurrentTUQty(final Quantity qtyToAdd) { Check.assumeNotNull(_currentTU, "current TU is created"); if (this._currentTUQty == null) { this._currentTUQty = Quantity.zero(capacity.getC_UOM()); } this._currentTUQty = this._currentTUQty.add(qtyToAdd); } private IHUBuilder newHUBuilder() { final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext); huBuilder.setLocatorId(locatorId); if (!Check.isEmpty(huStatus, true)) {
huBuilder.setHUStatus(huStatus); } if (bpartnerId != null) { huBuilder.setBPartnerId(bpartnerId); } if (bpartnerLocationRepoId > 0) { huBuilder.setC_BPartner_Location_ID(bpartnerLocationRepoId); } huBuilder.setHUPlanningReceiptOwnerPM(true); huBuilder.setHUClearanceStatusInfo(clearanceStatusInfo); return huBuilder; } private I_M_HU splitCU(final I_M_HU fromCU, final ProductId cuProductId, final Quantity qtyToSplit) { Check.assume(qtyToSplit.signum() > 0, "qtyToSplit shall be greater than zero but it was {}", qtyToSplit); final HUProducerDestination destination = HUProducerDestination.ofVirtualPI(); HULoader.builder() .source(HUListAllocationSourceDestination.of(fromCU)) .destination(destination) .load(AllocationUtils.builder() .setHUContext(huContext) .setProduct(cuProductId) .setQuantity(qtyToSplit) .setForceQtyAllocation(false) // no need to force .setClearanceStatusInfo(clearanceStatusInfo) .create()); return CollectionUtils.singleElement(destination.getCreatedHUs()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoaderInstance.java
1
请完成以下Java代码
public void setM_HU_Storage_ID (final int M_HU_Storage_ID) { if (M_HU_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID); } @Override public int getM_HU_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); }
@Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Stock_Detail_V.java
1
请在Spring Boot框架中完成以下Java代码
public static class Singlesignon { /** * Remote endpoint to send authentication requests to. */ private @Nullable String url; /** * Whether to redirect or post authentication requests. */ private @Nullable Saml2MessageBinding binding; /** * Whether to sign authentication requests. */ private @Nullable Boolean signRequest; public @Nullable String getUrl() { return this.url; } public void setUrl(@Nullable String url) { this.url = url; } public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } public @Nullable Boolean getSignRequest() { return this.signRequest; } public void setSignRequest(@Nullable Boolean signRequest) { this.signRequest = signRequest; } } /** * Verification details for an Identity Provider. */ public static class Verification { /** * Credentials used for verification of incoming SAML messages. */ private List<Credential> credentials = new ArrayList<>(); public List<Credential> getCredentials() { return this.credentials; } public void setCredentials(List<Credential> credentials) { this.credentials = credentials; } public static class Credential { /** * Locations of the X.509 certificate used for verification of incoming * SAML messages. */ private @Nullable Resource certificate; public @Nullable Resource getCertificateLocation() { return this.certificate; } public void setCertificateLocation(@Nullable Resource certificate) { this.certificate = certificate; } }
} } /** * Single logout details. */ public static class Singlelogout { /** * Location where SAML2 LogoutRequest gets sent to. */ private @Nullable String url; /** * Location where SAML2 LogoutResponse gets sent to. */ private @Nullable String responseUrl; /** * Whether to redirect or post logout requests. */ private @Nullable Saml2MessageBinding binding; public @Nullable String getUrl() { return this.url; } public void setUrl(@Nullable String url) { this.url = url; } public @Nullable String getResponseUrl() { return this.responseUrl; } public void setResponseUrl(@Nullable String responseUrl) { this.responseUrl = responseUrl; } public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java
2
请完成以下Java代码
public int getGeodb_loc_id() { return geodb_loc_id; } public String getCity() { return city; } public String getZip() { return zip; } public double getLon() { return lon; } public double getLat() { return lat; } public int getC_Country_ID() { return C_Country_ID; } public void setC_Country_ID(int cCountryID) { C_Country_ID = cCountryID; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCity_7bitlc() { return city_7bitlc; }
public void setCity_7bitlc(String city_7bitlc) { this.city_7bitlc = city_7bitlc; } public String getStringRepresentation() { return stringRepresentation; } public void setStringRepresentation(String stringRepresentation) { this.stringRepresentation = stringRepresentation; } @Override public boolean equals(Object obj) { if (! (obj instanceof GeodbObject)) return false; if (this == obj) return true; // GeodbObject go = (GeodbObject)obj; return this.geodb_loc_id == go.geodb_loc_id && this.zip.equals(go.zip) ; } @Override public String toString() { String str = getStringRepresentation(); if (str != null) return str; return city+", "+zip+" - "+countryName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\GeodbObject.java
1
请完成以下Java代码
public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public boolean isHasExistingInstancesForUniqueCorrelation() { return hasExistingInstancesForUniqueCorrelation; }
public void setHasExistingInstancesForUniqueCorrelation(boolean hasExistingInstancesForUniqueCorrelation) { this.hasExistingInstancesForUniqueCorrelation = hasExistingInstancesForUniqueCorrelation; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("eventSubscriptionId='" + eventSubscriptionId + "'") .add("subScopeId='" + subScopeId + "'") .add("scopeType='" + scopeType + "'") .add("scopeDefinitionId='" + scopeDefinitionId + "'") .add("hasExistingInstancesForUniqueCorrelation=" + hasExistingInstancesForUniqueCorrelation) .toString(); } }
repos\flowable-engine-main\modules\flowable-event-registry-api\src\main\java\org\flowable\eventregistry\api\EventConsumerInfo.java
1
请完成以下Java代码
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { orderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return orderLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { values.setC_UOM_ID(uomId); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { orderLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return orderLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { orderLine.setQtyEnteredTU(qtyPacks); values.setQtyTU(qtyPacks); } @Override public void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { orderLine.setQtyItemCapacity(qtyCUsPerTU); values.setQtyCUsPerTU(qtyCUsPerTU); } @Override public Optional<BigDecimal> getQtyCUsPerTU() { return Optional.of(orderLine.getQtyItemCapacity()); } @Override public int getC_BPartner_ID() { return orderLine.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int bpartnerId) { orderLine.setC_BPartner_ID(bpartnerId); values.setC_BPartner_ID(bpartnerId); } public void setQtyLU(@NonNull final BigDecimal qtyLU) { orderLine.setQtyLU(qtyLU); } public BigDecimal getQtyLU() { return orderLine.getQtyLU(); }
@Override public void setLuId(@Nullable final HuPackingInstructionsId luId) { orderLine.setM_LU_HU_PI_ID(HuPackingInstructionsId.toRepoId(luId)); } @Override public HuPackingInstructionsId getLuId() { return HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID()); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public String toString() { return String .format("OrderLineHUPackingAware [orderLine=%s, getM_Product_ID()=%s, getM_Product()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, qtyLU()=%s, luId()=%s, isInDispute()=%s]", orderLine, getM_Product_ID(), getM_Product_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQtyTU(), getC_BPartner_ID(), getM_HU_PI_Item_Product_ID(), getQtyLU(), getLuId(), isInDispute()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); /** * 添加jwt过滤器,并在下面注册 * 也就是将jwtFilter注册到shiro的Filter中 * 指定除了login和logout之外的请求都先经过jwtFilter */ Map<String, Filter> filterMap = new HashMap<>(); //这个地方其实另外两个filter可以不设置,默认就是 filterMap.put("hf", new HeaderFilter()); factoryBean.setFilters(filterMap); factoryBean.setSecurityManager(securityManager); factoryBean.setLoginUrl("/login"); factoryBean.setSuccessUrl("/index"); factoryBean.setUnauthorizedUrl("/unauthorized"); Map<String, String> map = new LinkedHashMap<>(); /** * {@link DefaultFilter} */ map.put("/doLogin", "anon"); map.put("/getLogin/**", "anon"); map.put("/anno/hello1", "anon"); map.put("/vip", "roles[admin]"); map.put("/common", "roles[user]"); // 登陆鉴权 map.put("/**", "hf,authc"); // header 鉴权 factoryBean.setFilterChainDefinitionMap(map); return factoryBean; } /** * 一下三个bean是为了让@RequiresRoles({"admin"}) 生效 * 这两个是 Shiro 的注解,我们需要借助 SpringAOP 扫描到它们 *
* @return */ @Bean public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public static DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\config\ShiroConfig.java
2
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { if (base == null) { // according to javadoc, can only be a String String key = (String) property; for (String componentId : (Set<String>) blueprintContainer.getComponentIds()) { if (componentId.equals(key)) { context.setPropertyResolved(true); return blueprintContainer.getComponentInstance(key); } } } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) {
return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { } @Override public Class<?> getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Class<?> getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BlueprintContextELResolver.java
1
请完成以下Java代码
public RefreshTokenGrantBuilder eventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; return this; } /** * Sets the maximum acceptable clock skew, which is used when checking the access * token expiry. An access token is considered expired if * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link RefreshTokenGrantBuilder} * @see RefreshTokenOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; return this; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the * access token expiry. * @param clock the clock * @return the {@link RefreshTokenGrantBuilder} */ public RefreshTokenGrantBuilder clock(Clock clock) { this.clock = clock; return this;
} /** * Builds an instance of {@link RefreshTokenOAuth2AuthorizedClientProvider}. * @return the {@link RefreshTokenOAuth2AuthorizedClientProvider} */ @Override public OAuth2AuthorizedClientProvider build() { RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider(); if (this.accessTokenResponseClient != null) { authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient); } if (this.eventPublisher != null) { authorizedClientProvider.setApplicationEventPublisher(this.eventPublisher); } if (this.clockSkew != null) { authorizedClientProvider.setClockSkew(this.clockSkew); } if (this.clock != null) { authorizedClientProvider.setClock(this.clock); } return authorizedClientProvider; } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizedClientProviderBuilder.java
1
请完成以下Java代码
public final void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { if (!this.alwaysRemember && !rememberMeRequested(request, this.rememberMeParameterName)) { logger.debug("Remember-me login not requested."); return; } request.setAttribute(REMEMBER_ME_LOGIN_ATTR, true); request.getSession().setMaxInactiveInterval(this.validitySeconds); } /** * Allows customization of whether a remember-me login has been requested. The default * is to return {@code true} if the configured parameter name has been included in the * request and is set to the value {@code true}. * @param request the request submitted from an interactive login, which may include * additional information indicating that a persistent login is desired. * @param parameter the configured remember-me parameter name. * @return true if the request includes information indicating that a persistent login * has been requested. */ protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { String rememberMe = request.getParameter(parameter); if (rememberMe != null) { if (rememberMe.equalsIgnoreCase("true") || rememberMe.equalsIgnoreCase("on") || rememberMe.equalsIgnoreCase("yes") || rememberMe.equals("1")) { return true; } } if (logger.isDebugEnabled()) { logger.debug("Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')"); } return false; } /** * Set the name of the parameter which should be checked for to see if a remember-me * has been requested during a login request. This should be the same name you assign * to the checkbox in your login form. * @param rememberMeParameterName the request parameter */ public void setRememberMeParameterName(String rememberMeParameterName) {
Assert.hasText(rememberMeParameterName, "rememberMeParameterName cannot be empty or null"); this.rememberMeParameterName = rememberMeParameterName; } public void setAlwaysRemember(boolean alwaysRemember) { this.alwaysRemember = alwaysRemember; } public void setValiditySeconds(int validitySeconds) { this.validitySeconds = validitySeconds; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { logout(request); } private void logout(HttpServletRequest request) { logger.debug("Interactive login attempt was unsuccessful."); HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\web\authentication\SpringSessionRememberMeServices.java
1
请完成以下Java代码
public void setAsynchronousLeaveExclusive(boolean exclusive) { this.asynchronousLeaveNotExclusive = !exclusive; } public boolean isAsynchronousLeaveNotExclusive() { return asynchronousLeaveNotExclusive; } public void setAsynchronousLeaveNotExclusive(boolean asynchronousLeaveNotExclusive) { this.asynchronousLeaveNotExclusive = asynchronousLeaveNotExclusive; } public Object getBehavior() { return behavior; } public void setBehavior(Object behavior) { this.behavior = behavior; } public List<SequenceFlow> getIncomingFlows() { return incomingFlows; } public void setIncomingFlows(List<SequenceFlow> incomingFlows) { this.incomingFlows = incomingFlows; } public List<SequenceFlow> getOutgoingFlows() { return outgoingFlows; } public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) { this.outgoingFlows = outgoingFlows; } public void setValues(FlowNode otherNode) { super.setValues(otherNode); setAsynchronous(otherNode.isAsynchronous()); setNotExclusive(otherNode.isNotExclusive());
setAsynchronousLeave(otherNode.isAsynchronousLeave()); setAsynchronousLeaveNotExclusive(otherNode.isAsynchronousLeaveNotExclusive()); if (otherNode.getIncomingFlows() != null) { setIncomingFlows(otherNode.getIncomingFlows() .stream() .map(SequenceFlow::clone) .collect(Collectors.toList())); } if (otherNode.getOutgoingFlows() != null) { setOutgoingFlows(otherNode.getOutgoingFlows() .stream() .map(SequenceFlow::clone) .collect(Collectors.toList())); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowNode.java
1
请完成以下Java代码
public void packagePickup(Instant pickupTime) { Workflow.await(() -> shipping != null); shipping = shipping.toStatus(ShippingStatus.SHIPPED, pickupTime, "Package picked up"); } @Override public void packageDelivered(Instant pickupTime) { Workflow.await(() -> shipping != null); shipping = shipping.toStatus(ShippingStatus.DELIVERED, pickupTime, "Package delivered"); } @Override public void packageReturned(Instant pickupTime) { shipping = shipping.toStatus(ShippingStatus.RETURNED, pickupTime, "Package returned"); } @Override public Order getOrder() { return order;
} @Override public Shipping getShipping() { return shipping; } @Override public PaymentAuthorization getPayment() { return payment; } @Override public RefundRequest getRefund() { return refund; } }
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\workflow\OrderWorkflowImpl.java
1
请完成以下Java代码
public void setFrom(final I_C_Invoice from) { final DocumentLocation fromDocumentLocationAdapter = new InvoiceDocumentLocationAdapter(from).toDocumentLocation(); final BPartnerContactId fromContactId = fromDocumentLocationAdapter.getContactId(); final BPartnerContactId invoiceContactId = getBPartnerContactId().orElse(null); if(invoiceContactId != null && !BPartnerContactId.equals(invoiceContactId, fromContactId)) { setFrom(fromDocumentLocationAdapter.withContactId(null)); } else { setFrom(fromDocumentLocationAdapter); } } @Override public I_C_Invoice getWrappedRecord() { return delegate;
} @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public InvoiceDocumentLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new InvoiceDocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Invoice.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\location\adapter\InvoiceDocumentLocationAdapter.java
1
请完成以下Java代码
public String toString() {return getAsString();} public String getAsString() {return type + "-" + last4Digits;} } // // // // // // @RequiredArgsConstructor @Getter public enum LastSyncStatus implements ReferenceListAwareEnum { OK(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_OK), Error(X_SUMUP_Transaction.SUMUP_LASTSYNC_STATUS_Error), ; private static final ValuesIndex<LastSyncStatus> index = ReferenceListAwareEnums.index(values()); @NonNull private final String code; public static LastSyncStatus ofCode(@NonNull String code) {return index.ofCode(code);} public static LastSyncStatus ofNullableCode(@Nullable String code) {return index.ofNullableCode(code);} } // // // // // //
@Value @Builder @Jacksonized @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public static class LastSync { @NonNull LastSyncStatus status; @Nullable Instant timestamp; @Nullable AdIssueId errorId; public static LastSync ok() { return builder() .status(LastSyncStatus.OK) .timestamp(SystemTime.asInstant()) .build(); } public static LastSync error(@NonNull final AdIssueId errorId) { return builder() .status(LastSyncStatus.Error) .timestamp(SystemTime.asInstant()) .errorId(errorId) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpTransaction.java
1
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setT_Amount (final @Nullable BigDecimal T_Amount) { set_Value (COLUMNNAME_T_Amount, T_Amount); } @Override public BigDecimal getT_Amount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Amount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Date (final @Nullable java.sql.Timestamp T_Date) { set_Value (COLUMNNAME_T_Date, T_Date); } @Override public java.sql.Timestamp getT_Date() { return get_ValueAsTimestamp(COLUMNNAME_T_Date); } @Override public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime) { set_Value (COLUMNNAME_T_DateTime, T_DateTime); } @Override public java.sql.Timestamp getT_DateTime() { return get_ValueAsTimestamp(COLUMNNAME_T_DateTime); } @Override public void setT_Integer (final int T_Integer) { set_Value (COLUMNNAME_T_Integer, T_Integer); } @Override public int getT_Integer() { return get_ValueAsInt(COLUMNNAME_T_Integer); } @Override public void setT_Number (final @Nullable BigDecimal T_Number) { set_Value (COLUMNNAME_T_Number, T_Number); } @Override public BigDecimal getT_Number() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Qty (final @Nullable BigDecimal T_Qty) { set_Value (COLUMNNAME_T_Qty, T_Qty); } @Override public BigDecimal getT_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Time (final @Nullable java.sql.Timestamp T_Time) { set_Value (COLUMNNAME_T_Time, T_Time); } @Override public java.sql.Timestamp getT_Time() { return get_ValueAsTimestamp(COLUMNNAME_T_Time); } @Override public void setTest_ID (final int Test_ID) { if (Test_ID < 1) set_ValueNoCheck (COLUMNNAME_Test_ID, null); else set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID); } @Override public int getTest_ID() { return get_ValueAsInt(COLUMNNAME_Test_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java
1
请完成以下Java代码
public final class DevToolsEnablementDeducer { private static final Set<String> SKIPPED_STACK_ELEMENTS; static { Set<String> skipped = new LinkedHashSet<>(); skipped.add("org.junit.runners."); skipped.add("org.junit.platform."); skipped.add("org.springframework.boot.test."); skipped.add(SpringApplicationAotProcessor.class.getName()); skipped.add("cucumber.runtime."); SKIPPED_STACK_ELEMENTS = Collections.unmodifiableSet(skipped); } private DevToolsEnablementDeducer() { } /** * Checks if a specific {@link StackTraceElement} in the current thread's stacktrace * should cause devtools to be disabled. Devtools will also be disabled if running in * a native image. * @param thread the current thread * @return {@code true} if devtools should be enabled */ public static boolean shouldEnable(Thread thread) { if (NativeDetector.inNativeImage()) { return false; }
for (StackTraceElement element : thread.getStackTrace()) { if (isSkippedStackElement(element)) { return false; } } return true; } private static boolean isSkippedStackElement(StackTraceElement element) { for (String skipped : SKIPPED_STACK_ELEMENTS) { if (element.getClassName().startsWith(skipped)) { return true; } } return false; } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\system\DevToolsEnablementDeducer.java
1
请完成以下Java代码
public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } public I_GL_Category getGL_Category() throws RuntimeException { return (I_GL_Category)MTable.get(getCtx(), I_GL_Category.Table_Name) .getPO(getGL_Category_ID(), get_TrxName()); } /** Set GL Category. @param GL_Category_ID General Ledger Category */ public void setGL_Category_ID (int GL_Category_ID) { if (GL_Category_ID < 1) set_Value (COLUMNNAME_GL_Category_ID, null); else set_Value (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID)); } /** Get GL Category. @return General Ledger Category */ public int getGL_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed
*/ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Reval_Entry.java
1
请完成以下Java代码
public static CoNLLSentence compute(String sentence) { return new MaxEntDependencyParser().parse(sentence); } @Override protected Edge makeEdge(Node[] nodeArray, int from, int to) { LinkedList<String> context = new LinkedList<String>(); int index = from; for (int i = index - 2; i < index + 2 + 1; ++i) { Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL; context.add(w.compiledWord + "i" + (i - index)); // 在尾巴上做个标记,不然特征冲突了 context.add(w.label + "i" + (i - index)); } index = to; for (int i = index - 2; i < index + 2 + 1; ++i) { Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL; context.add(w.compiledWord + "j" + (i - index)); // 在尾巴上做个标记,不然特征冲突了 context.add(w.label + "j" + (i - index)); } context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord); context.add(nodeArray[from].label + '→' + nodeArray[to].label); context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord + (from - to)); context.add(nodeArray[from].label + '→' + nodeArray[to].label + (from - to)); Node wordBeforeI = from - 1 >= 0 ? nodeArray[from - 1] : Node.NULL; Node wordBeforeJ = to - 1 >= 0 ? nodeArray[to - 1] : Node.NULL; context.add(wordBeforeI.compiledWord + '@' + nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord);
context.add(nodeArray[from].compiledWord + '→' + wordBeforeJ.compiledWord + '@' + nodeArray[to].compiledWord); context.add(wordBeforeI.label + '@' + nodeArray[from].label + '→' + nodeArray[to].label); context.add(nodeArray[from].label + '→' + wordBeforeJ.label + '@' + nodeArray[to].label); List<Pair<String, Double>> pairList = model.predict(context.toArray(new String[0])); Pair<String, Double> maxPair = new Pair<String, Double>("null", -1.0); // System.out.println(context); // System.out.println(pairList); for (Pair<String, Double> pair : pairList) { if (pair.getValue() > maxPair.getValue() && !"null".equals(pair.getKey())) { maxPair = pair; } } // System.out.println(nodeArray[from].word + "→" + nodeArray[to].word + " : " + maxPair); return new Edge(from, to, maxPair.getKey(), (float) - Math.log(maxPair.getValue())); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\MaxEntDependencyParser.java
1
请完成以下Java代码
public iframe setAlign(String align) { addAttribute("align",align); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public iframe addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public iframe addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public iframe addElement(Element element) {
addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public iframe addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public iframe removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\iframe.java
1
请完成以下Java代码
public class MeteredCalculatorDecorator implements Calculator { private final Calculator wrappedCalculator; private final Map<String, Integer> methodCalls; public MeteredCalculatorDecorator(Calculator calculator) { this.wrappedCalculator = calculator; this.methodCalls = new HashMap<>(); // Initialize counts for clarity methodCalls.put("add", 0); methodCalls.put("subtract", 0); } @Override public int add(int a, int b) { // Track the call count methodCalls.merge("add", 1, Integer::sum);
return wrappedCalculator.add(a, b); // Delegation } @Override public int subtract(int a, int b) { // Track the call count methodCalls.merge("subtract", 1, Integer::sum); return wrappedCalculator.subtract(a, b); // Delegation } // Public method to expose the call counts for testing public int getCallCount(String methodName) { return methodCalls.getOrDefault(methodName, 0); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\overridemethod\decorator\MeteredCalculatorDecorator.java
1
请完成以下Java代码
public String getValidateFormFields() { return validateFormFields; } public void setValidateFormFields(String validateFormFields) { this.validateFormFields = validateFormFields; } @Override public StartEvent clone() { StartEvent clone = new StartEvent(); clone.setValues(this); return clone; } public void setValues(StartEvent otherEvent) {
super.setValues(otherEvent); setInitiator(otherEvent.getInitiator()); setFormKey(otherEvent.getFormKey()); setSameDeployment(otherEvent.isInterrupting); setInterrupting(otherEvent.isInterrupting); setValidateFormFields(otherEvent.validateFormFields); formProperties = new ArrayList<>(); if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) { for (FormProperty property : otherEvent.getFormProperties()) { formProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\StartEvent.java
1
请完成以下Spring Boot application配置
server: port: 8088 spring: data: mongodb: uri: mongodb://admin:123456@127.0.0.1:27017/test # 需要用户名和密码认证 #uri: mongodb://username:password@ip:port/admin #不需要用户名和密码认证 #uri: mongodb://ip:port/admin kafka: bootstrap-servers: localhost:9092 consumer: group-id: your-group-id auto-offset-reset: earliest key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.
common.serialization.StringDeserializer producer: key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.apache.kafka.common.serialization.StringSerializer
repos\springboot-demo-master\mongodb\src\main\resources\application.yaml
2
请完成以下Java代码
public class MyDtoIgnoreNull { private String stringValue; private int intValue; private boolean booleanValue; public MyDtoIgnoreNull() { super(); } public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) { super(); this.stringValue = stringValue; this.intValue = intValue; this.booleanValue = booleanValue; } // API public String getStringValue() { return stringValue; } public void setStringValue(final String stringValue) { this.stringValue = stringValue; } public int getIntValue() { return intValue;
} public void setIntValue(final int intValue) { this.intValue = intValue; } public boolean isBooleanValue() { return booleanValue; } public void setBooleanValue(final boolean booleanValue) { this.booleanValue = booleanValue; } }
repos\tutorials-master\jackson-modules\jackson-core-2\src\main\java\com\baeldung\jackson\ignorenullfields\MyDtoIgnoreNull.java
1
请完成以下Java代码
public void setShipper_City (final @Nullable java.lang.String Shipper_City) { set_Value (COLUMNNAME_Shipper_City, Shipper_City); } @Override public java.lang.String getShipper_City() { return get_ValueAsString(COLUMNNAME_Shipper_City); } @Override public void setShipper_CountryISO2Code (final @Nullable java.lang.String Shipper_CountryISO2Code) { set_Value (COLUMNNAME_Shipper_CountryISO2Code, Shipper_CountryISO2Code); } @Override public java.lang.String getShipper_CountryISO2Code() { return get_ValueAsString(COLUMNNAME_Shipper_CountryISO2Code); } @Override public void setShipper_EORI (final @Nullable java.lang.String Shipper_EORI) { set_Value (COLUMNNAME_Shipper_EORI, Shipper_EORI); } @Override public java.lang.String getShipper_EORI() { return get_ValueAsString(COLUMNNAME_Shipper_EORI); } @Override public void setShipper_Name1 (final @Nullable java.lang.String Shipper_Name1) { set_Value (COLUMNNAME_Shipper_Name1, Shipper_Name1); } @Override public java.lang.String getShipper_Name1() { return get_ValueAsString(COLUMNNAME_Shipper_Name1); } @Override public void setShipper_Name2 (final @Nullable java.lang.String Shipper_Name2) { set_Value (COLUMNNAME_Shipper_Name2, Shipper_Name2); } @Override public java.lang.String getShipper_Name2()
{ return get_ValueAsString(COLUMNNAME_Shipper_Name2); } @Override public void setShipper_StreetName1 (final @Nullable java.lang.String Shipper_StreetName1) { set_Value (COLUMNNAME_Shipper_StreetName1, Shipper_StreetName1); } @Override public java.lang.String getShipper_StreetName1() { return get_ValueAsString(COLUMNNAME_Shipper_StreetName1); } @Override public void setShipper_StreetName2 (final @Nullable java.lang.String Shipper_StreetName2) { set_Value (COLUMNNAME_Shipper_StreetName2, Shipper_StreetName2); } @Override public java.lang.String getShipper_StreetName2() { return get_ValueAsString(COLUMNNAME_Shipper_StreetName2); } @Override public void setShipper_StreetNumber (final @Nullable java.lang.String Shipper_StreetNumber) { set_Value (COLUMNNAME_Shipper_StreetNumber, Shipper_StreetNumber); } @Override public java.lang.String getShipper_StreetNumber() { return get_ValueAsString(COLUMNNAME_Shipper_StreetNumber); } @Override public void setShipper_ZipCode (final @Nullable java.lang.String Shipper_ZipCode) { set_Value (COLUMNNAME_Shipper_ZipCode, Shipper_ZipCode); } @Override public java.lang.String getShipper_ZipCode() { return get_ValueAsString(COLUMNNAME_Shipper_ZipCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder.java
1
请完成以下Java代码
public int getLogo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Logo_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Image getLogoReport() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_LogoReport_ID, org.compiere.model.I_AD_Image.class); } @Override public void setLogoReport(org.compiere.model.I_AD_Image LogoReport) { set_ValueFromPO(COLUMNNAME_LogoReport_ID, org.compiere.model.I_AD_Image.class, LogoReport); } /** Set Logo Report. @param LogoReport_ID Logo Report */ @Override public void setLogoReport_ID (int LogoReport_ID) { if (LogoReport_ID < 1) set_Value (COLUMNNAME_LogoReport_ID, null); else set_Value (COLUMNNAME_LogoReport_ID, Integer.valueOf(LogoReport_ID)); } /** Get Logo Report. @return Logo Report */ @Override public int getLogoReport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LogoReport_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Image getLogoWeb() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_LogoWeb_ID, org.compiere.model.I_AD_Image.class); } @Override public void setLogoWeb(org.compiere.model.I_AD_Image LogoWeb) { set_ValueFromPO(COLUMNNAME_LogoWeb_ID, org.compiere.model.I_AD_Image.class, LogoWeb); } /** Set Logo Web. @param LogoWeb_ID Logo Web */ @Override
public void setLogoWeb_ID (int LogoWeb_ID) { if (LogoWeb_ID < 1) set_Value (COLUMNNAME_LogoWeb_ID, null); else set_Value (COLUMNNAME_LogoWeb_ID, Integer.valueOf(LogoWeb_ID)); } /** Get Logo Web. @return Logo Web */ @Override public int getLogoWeb_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LogoWeb_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight) { set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight); } /** Set Produkt für Fracht. @param M_ProductFreight_ID Produkt für Fracht */ @Override public void setM_ProductFreight_ID (int M_ProductFreight_ID) { if (M_ProductFreight_ID < 1) set_Value (COLUMNNAME_M_ProductFreight_ID, null); else set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID)); } /** Get Produkt für Fracht. @return Produkt für Fracht */ @Override public int getM_ProductFreight_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ClientInfo.java
1
请完成以下Java代码
private IHUDocumentFactory getHUDocumentFactoryOrNull(final String tableName) { return factories.get(tableName); } @Override public void registerHUDocumentFactory(final String tableName, final IHUDocumentFactory factory) { Check.assumeNotEmpty(tableName, "tableName not empty"); Check.assumeNotNull(factory, "factory not null"); factories.put(tableName, factory); } @Override public List<IHUDocument> createHUDocuments(final ProcessInfo pi) { Check.assumeNotNull(pi, "process info not null"); final String tableName = pi.getTableNameOrNull(); Check.assumeNotNull(tableName, "tableName not null ({})", pi); final IHUDocumentFactory factory = getHUDocumentFactory(tableName); return factory.createHUDocuments(pi); } @Override
public <T> List<IHUDocument> createHUDocuments(final Properties ctx, final Class<T> modelClass, final Iterator<T> records) { final String tableName = InterfaceWrapperHelper.getTableName(modelClass); final IHUDocumentFactory factory = getHUDocumentFactory(tableName); return factory.createHUDocuments(ctx, modelClass, records); } @Override public List<IHUDocument> createHUDocumentsFromModel(final Object model) { Check.assumeNotNull(model, "model not null"); final String tableName = InterfaceWrapperHelper.getModelTableName(model); final IHUDocumentFactory factory = getHUDocumentFactory(tableName); return factory.createHUDocumentsFromModel(model); } @Override public boolean isSupported(final String tableName) { final IHUDocumentFactory factory = getHUDocumentFactoryOrNull(tableName); return factory != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\HUDocumentFactoryService.java
1
请完成以下Java代码
public void removeTransientVariables() { removeTransientVariablesLocal(); VariableScopeImpl parentVariableScope = getParentVariableScope(); if (parentVariableScope != null) { parentVariableScope.removeTransientVariablesLocal(); } } // getters and setters ////////////////////////////////////////////////////// public ELContext getCachedElContext() { return cachedElContext; } public void setCachedElContext(ELContext cachedElContext) { this.cachedElContext = cachedElContext; }
public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public <T> T getVariable(String variableName, Class<T> variableClass) { return variableClass.cast(getVariable(variableName)); } @Override public <T> T getVariableLocal(String variableName, Class<T> variableClass) { return variableClass.cast(getVariableLocal(variableName)); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableScopeImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getAuthor() {
return author; } public void setAuthor(String author) { this.author = author; } public Integer getPages() { return pages; } public void setPages(Integer pages) { this.pages = pages; } }
repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\model\Book.java
2
请完成以下Java代码
public void setByteArrayId(String id) { byteArrayField.setByteArrayId(id); } @Override public String getSerializerName() { return typedValueField.getSerializerName(); } @Override public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getByteArrayValueId() { return byteArrayField.getByteArrayId(); } public byte[] getByteArrayValue() { return byteArrayField.getByteArrayValue(); } public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public String getName() { return getVariableName(); } // entity lifecycle ///////////////////////////////////////////////////////// public void postLoad() { // make sure the serializer is initialized typedValueField.postLoad(); } // getters and setters //////////////////////////////////////////////////////
public String getTypeName() { return typedValueField.getTypeName(); } public String getVariableTypeName() { return getTypeName(); } public Date getTime() { return timestamp; } @Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
1
请完成以下Java代码
public void setMinQty (BigDecimal MinQty) { set_Value (COLUMNNAME_MinQty, MinQty); } /** Get Minimum Quantity. @return Minimum quantity for the business partner */ public BigDecimal getMinQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty); if (bd == null) return Env.ZERO; return bd; } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Total Quantity. @param TotalQty Total Quantity */ public void setTotalQty (BigDecimal TotalQty) { set_Value (COLUMNNAME_TotalQty, TotalQty); } /** Get Total Quantity. @return Total Quantity */ public BigDecimal getTotalQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalQty); 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_DistributionRunLine.java
1
请在Spring Boot框架中完成以下Java代码
private BigDecimal getQtyInProductPriceUOM(@NonNull final I_M_ProductPrice productPrice, @NonNull final Quantity quantity) { final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID()); final UomId productPriceUomId = UomId.ofRepoId(productPrice.getC_UOM_ID()); return uomConversionBL.convertQty(productId, quantity.toBigDecimal(), quantity.getUomId(), productPriceUomId); } @Value public static class ProductPriceSettings { @NonNull BigDecimal priceStd; @NonNull
BigDecimal priceLimit; @NonNull BigDecimal priceList; public static ProductPriceSettings of(@NonNull final I_M_ProductPrice productPrice) { return new ProductPriceSettings(productPrice.getPriceStd(), productPrice.getPriceLimit(), productPrice.getPriceList()); } public static ProductPriceSettings of(@NonNull final I_M_ProductScalePrice productScalePrice) { return new ProductPriceSettings(productScalePrice.getPriceStd(), productScalePrice.getPriceLimit(), productScalePrice.getPriceList()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductScalePriceService.java
2
请完成以下Java代码
public void addAsync(final Properties ctx, final int M_Warehouse_ID, final int M_Locator_ID, final int M_Product_ID, final int M_AttributeSetInstance_ID, final int reservationAttributeSetInstance_ID, final BigDecimal diffQtyOnHand, final BigDecimal diffQtyReserved, final BigDecimal diffQtyOrdered, final String trxName) { if (isMStorageDisabled()) { return; } // @formatter:off Services.get(IWorkPackageQueueFactory.class).getQueueForEnqueuing(ctx, M_Storage_Add.class) .newWorkPackage() .bindToTrxName(trxName) .parameters() .setParameter(M_Storage_Add.WP_PARAM_M_Warehouse_ID, M_Warehouse_ID) .setParameter(M_Storage_Add.WP_PARAM_M_Locator_ID, M_Locator_ID) .setParameter(M_Storage_Add.WP_PARAM_M_Product_ID, M_Product_ID) .setParameter(M_Storage_Add.WP_PARAM_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID) .setParameter(M_Storage_Add.WP_PARAM_reservationAttributeSetInstance_ID, reservationAttributeSetInstance_ID) .setParameter(M_Storage_Add.WP_PARAM_diffQtyOnHand, diffQtyOnHand) .setParameter(M_Storage_Add.WP_PARAM_diffQtyReserved, diffQtyReserved) .setParameter(M_Storage_Add.WP_PARAM_diffQtyOrdered, diffQtyOrdered) .end() .buildAndEnqueue(); // @formatter:on } @Override public void add( final Properties ctx, final int M_Warehouse_ID, final int M_Locator_ID, final int M_Product_ID, final int M_AttributeSetInstance_ID,
final int reservationAttributeSetInstance_ID, final BigDecimal diffQtyOnHand, final BigDecimal diffQtyReserved, final BigDecimal diffQtyOrdered, final String trxName) { if (isMStorageDisabled()) { return; } MStorage.add(ctx, M_Warehouse_ID, M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID, reservationAttributeSetInstance_ID, diffQtyOnHand, diffQtyReserved, diffQtyOrdered, trxName); } private boolean isMStorageDisabled() { return Services.get(ISysConfigBL.class).getBooleanValue(CFG_M_STORAGE_DISABLED, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StorageBL.java
1
请完成以下Java代码
public void setDLM_Partition_Workqueue_ID(final int DLM_Partition_Workqueue_ID) { if (DLM_Partition_Workqueue_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Workqueue_ID, Integer.valueOf(DLM_Partition_Workqueue_ID)); } } /** * Get Partitionierungswarteschlange. * * @return Partitionierungswarteschlange */ @Override public int getDLM_Partition_Workqueue_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Workqueue_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Datensatz-ID. * * @param Record_ID * Direct internal record ID */ @Override public void setRecord_ID(final int Record_ID) { if (Record_ID < 0) { set_Value(COLUMNNAME_Record_ID, null); } else { set_Value(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } } /**
* Get Datensatz-ID. * * @return Direct internal record ID */ @Override public int getRecord_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { throw new IllegalArgumentException("TableName is virtual column"); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Workqueue.java
1
请完成以下Java代码
private List<JsonPurchaseOrder> retrievePurchaseOrderInfo(final PurchaseCandidateId candidate) { final Collection<OrderId> orderIds = purchaseCandidateRepo.getOrderIdsForPurchaseCandidates(candidate); return Services.get(IOrderDAO.class).getByIds(orderIds) .stream() .map(this::toJsonOrder) .collect(ImmutableList.toImmutableList()); } @NonNull private JsonPurchaseCandidate.JsonPurchaseCandidateBuilder preparePurchaseCandidateStatus(@NonNull final PurchaseCandidate candidate) { return JsonPurchaseCandidate.builder() .externalSystemCode(poJsonConverters.getExternalSystemTypeById(candidate)) .externalHeaderId(JsonExternalIds.ofOrNull(candidate.getExternalHeaderId())) .externalLineId(JsonExternalIds.ofOrNull(candidate.getExternalLineId())) .purchaseDateOrdered(candidate.getPurchaseDateOrdered()) .purchaseDatePromised(candidate.getPurchaseDatePromised()) .metasfreshId(JsonMetasfreshId.of(candidate.getId().getRepoId())) .externalPurchaseOrderUrl(candidate.getExternalPurchaseOrderUrl()) .processed(candidate.isProcessed()); } private JsonPurchaseOrder toJsonOrder(@NonNull final I_C_Order order) { final boolean hasArchive = hasArchive(order); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); return JsonPurchaseOrder.builder()
.dateOrdered(TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone)) .datePromised(TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone)) .docStatus(order.getDocStatus()) .documentNo(order.getDocumentNo()) .metasfreshId(JsonMetasfreshId.of(order.getC_Order_ID())) .pdfAvailable(hasArchive) .build(); } private boolean hasArchive(final I_C_Order order) { return archiveBL.getLastArchive(TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID())).isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidatesStatusService.java
1
请在Spring Boot框架中完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone;
} public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } @Override public String toString() { return "AdminCreateReq{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", roleId='" + roleId + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\AdminCreateReq.java
2
请在Spring Boot框架中完成以下Java代码
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } public ShiroFormAuthenticationFilter formAuthenticationFilter() { ShiroFormAuthenticationFilter filter = new ShiroFormAuthenticationFilter(); filter.setUsernameParam("username"); filter.setPasswordParam("password"); filter.setRememberMeParam("rememberMe"); filter.setLoginUrl("/login"); filter.setSuccessUrl("/index"); return filter; } /** * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类, * 并在必要时进行安全逻辑验证 * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor) * 即可实现此功能 * * @return */ @Bean @DependsOn({"lifecycleBeanPostProcessor"}) public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; } /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; * 需要aspectj支持 * * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroConfig.java
2
请完成以下Java代码
private static int getBPartnerLocationId(@NonNull final IViewRow row) { return row.getFieldValueAsInt(I_M_Packageable_V.COLUMNNAME_C_BPartner_Location_ID, -1); } private long getSelectionSize(final DocumentIdsSelection rowIds) { if (rowIds.isAll()) { return getView().size(); } else { return rowIds.size(); } } private DocumentIdsSelection getSelectedRootDocumentIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isAll()) { return selectedRowIds; } else if (selectedRowIds.isEmpty()) { return selectedRowIds; } else
{ return selectedRowIds.stream().filter(DocumentId::isInt).collect(DocumentIdsSelection.toDocumentIdsSelection()); } } private Optional<ProductBarcodeFilterData> getProductBarcodeFilterData() { return PackageableFilterDescriptorProvider.extractProductBarcodeFilterData(getView()); } private List<ShipmentScheduleId> getShipmentScheduleIds() { final DocumentIdsSelection selectedRowIds = getSelectedRootDocumentIds(); return getView().streamByIds(selectedRowIds) .flatMap(selectedRow -> selectedRow.getIncludedRows().stream()) .map(IViewRow::getId) .distinct() .map(DocumentId::removeDocumentPrefixAndConvertToInt) .map(ShipmentScheduleId::ofRepoIdOrNull) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\process\WEBUI_Picking_Launcher.java
1
请完成以下Java代码
public class JSONProcessLayout { public static JSONProcessLayout of(final ProcessLayout layout, final JSONDocumentLayoutOptions jsonOpts) { return new JSONProcessLayout(layout, jsonOpts); } @JsonProperty("layoutType") private final PanelLayoutType layoutType; @JsonProperty("barcodeScannerType") @JsonInclude(JsonInclude.Include.NON_NULL) private final BarcodeScannerType barcodeScannerType; @JsonProperty("caption") private final String caption; @JsonProperty("description") private final String description;
@JsonProperty("elements") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final List<JSONDocumentLayoutElement> elements; private JSONProcessLayout(final ProcessLayout layout, final JSONDocumentLayoutOptions jsonOpts) { layoutType = layout.getLayoutType(); barcodeScannerType = layout.getBarcodeScannerType(); final String adLanguage = jsonOpts.getAdLanguage(); caption = layout.getCaption(adLanguage); description = layout.getDescription(adLanguage); elements = JSONDocumentLayoutElement.ofList(layout.getElements(), jsonOpts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONProcessLayout.java
1
请完成以下Java代码
private void checkProductCount(Collection<Integer> counts) { for (Integer count : counts) { if (count <= 0) { throw new CommonBizException(ExpCodeEnum.PRODUCTIDCOUNT_ERROR); } } } /** * 检查产品ID列表对应的卖家是否是同一个 * @param prodIdCountMap 产品ID-数量 的map */ private void checkIsSameSeller(Map<String, Integer> prodIdCountMap) { // 获取prodcutID集合 Set<String> productIdSet = prodIdCountMap.keySet(); // 构造查询请求 List<ProdQueryReq> prodQueryReqList = buildOrderQueryReq(productIdSet); // 查询 Set<String> companyIdSet = query(prodQueryReqList); // 校验 if (companyIdSet.size() > 1) { throw new CommonBizException(ExpCodeEnum.SELLER_DIFFERENT); } } /** * 构造查询请求 * @param productIdSet 产品ID集合 * @return 查询请求列表 */ private List<ProdQueryReq> buildOrderQueryReq(Set<String> productIdSet) { List<ProdQueryReq> prodQueryReqList = Lists.newArrayList(); for (String productId : productIdSet) { ProdQueryReq prodQueryReq = new ProdQueryReq(); prodQueryReq.setId(productId); prodQueryReqList.add(prodQueryReq);
} return prodQueryReqList; } /** * 根据产品ID查询产品列表 * @param prodQueryReqList 产品查询请求 * @return 产品所属公司的ID */ private Set<String> query(List<ProdQueryReq> prodQueryReqList) { Set<String> companyIdSet = Sets.newHashSet(); for (ProdQueryReq prodQueryReq : prodQueryReqList) { ProductEntity productEntity = productService.findProducts(prodQueryReq).getData().get(0); companyIdSet.add(productEntity.getCompanyEntity().getId()); } return companyIdSet; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\checkparam\PlaceOrderCheckParamComponent.java
1
请在Spring Boot框架中完成以下Java代码
public class CallOrderDetailQuery { @NonNull CallOrderSummaryId summaryId; @Nullable OrderLineId orderLineId; @Nullable InOutLineId inOutLineId; @Nullable InvoiceAndLineId invoiceAndLineId; @Builder public CallOrderDetailQuery( @NonNull final CallOrderSummaryId summaryId, @Nullable final OrderLineId orderLineId, @Nullable final InOutLineId inOutLineId, @Nullable final InvoiceAndLineId invoiceAndLineId) {
final long nonNullSources = Stream.of(orderLineId, inOutLineId, invoiceAndLineId) .filter(Objects::nonNull) .count(); if (nonNullSources == 0) { throw new AdempiereException("One of orderLineId, inOutLineId, invoiceLineId must be provided!"); } if (nonNullSources > 1) { throw new AdempiereException("Only one of orderLineId, inOutLineId, invoiceLineId must be provided!"); } this.summaryId = summaryId; this.orderLineId = orderLineId; this.inOutLineId = inOutLineId; this.invoiceAndLineId = invoiceAndLineId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\CallOrderDetailQuery.java
2
请完成以下Java代码
public class ReadWriteBlockingQueue { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> queue = new LinkedBlockingQueue<>(); String readFileName = "src/main/resources/read_file.txt"; String writeFileName = "src/main/resources/write_file.txt"; Thread producerThread = new Thread(new FileProducer(queue, readFileName)); Thread consumerThread1 = new Thread(new FileConsumer(queue, writeFileName)); producerThread.start(); Thread.sleep(100); // Give producer a head start consumerThread1.start(); try { producerThread.join(); consumerThread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } class FileProducer implements Runnable { private final BlockingQueue<String> queue; private final String inputFileName; public FileProducer(BlockingQueue<String> queue, String inputFileName) { this.queue = queue; this.inputFileName = inputFileName; } @Override public void run() { try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) { String line; while ((line = reader.readLine()) != null) { queue.offer(line); System.out.println("Producer added line: " + line);
System.out.println("Queue size: " + queue.size()); } } catch (IOException e) { e.printStackTrace(); } } } class FileConsumer implements Runnable { private final BlockingQueue<String> queue; private final String outputFileName; public FileConsumer(BlockingQueue queue, String outputFileName) { this.queue = queue; this.outputFileName = outputFileName; } @Override public void run() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) { String line; while ((line = queue.poll()) != null) { writer.write(line); writer.newLine(); System.out.println(Thread.currentThread() .getId() + " - Consumer processed line: " + line); System.out.println("Queue size: " + queue.size()); } } catch (IOException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\readwritethread\ReadWriteBlockingQueue.java
1