instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getPartnerBlz() { return partnerBlz; } public void setPartnerBlz(String partnerBlz) { this.partnerBlz = partnerBlz; } public String getPartnerKtoNr() { return partnerKtoNr; } public void setPartnerKtoNr(String partnerKtoNr) { this.partnerKtoNr = partnerKtoNr; } public String getPartnerName() { return partnerName;
} public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public String getTextschluessel() { return textschluessel; } public void setTextschluessel(String textschluessel) { this.textschluessel = textschluessel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
1
请完成以下Java代码
public void close() throws IOException { // nothing } public void append(final JdbcExportDataSource source) { final StringBuilder sqlInsert = new StringBuilder(); final StringBuilder sqlSelect = new StringBuilder(); final List<Object> sqlSelectParams = new ArrayList<Object>(); for (final Column field : fields.values()) { final String columnName = field.getColumnName(); // // INSERT part if (sqlInsert.length() > 0) { sqlInsert.append(", "); } sqlInsert.append(columnName); if (sqlSelect.length() > 0) { sqlSelect.append("\n, "); } // // SELECT part final String sourceColumnName = field.getSourceColumnName(); if (!Check.isEmpty(sourceColumnName)) { sqlSelect.append(sourceColumnName).append(" AS ").append(columnName); } // Constant else { sqlSelect.append("? AS ").append(columnName); sqlSelectParams.add(field.getConstantValue());
} } final String sql = new StringBuilder() .append("INSERT INTO ").append(tableName).append(" (").append(sqlInsert).append(")") .append("\nSELECT ").append(sqlSelect) .append("\nFROM (").append(source.getSqlSelect()).append(") t") .toString(); final List<Object> sqlParams = new ArrayList<Object>(); sqlParams.addAll(sqlSelectParams); sqlParams.addAll(source.getSqlParams()); final String trxName = Trx.TRXNAME_None; final int count = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), trxName); logger.info("Inserted {} records into {} from {}", new Object[] { count, tableName, source }); } public void addField(final String fieldName, final String sourceFieldName) { final Column field = new Column(fieldName, sourceFieldName, null); fields.put(fieldName, field); } public void addConstant(final String fieldName, final Object value) { final Column field = new Column(fieldName, null, value); fields.put(fieldName, field); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcTableExportDataDestination.java
1
请在Spring Boot框架中完成以下Java代码
public Long bookTicket(BookTicket booking) { log.info("Received booking command for movie ID: {}, seat: {}. checking availability...", booking.movieId(), booking.seat()); validateSeatNumber(booking.seat()); bookedTickets.findLatestByMovieIdAndSeatNumber(booking.movieId(), booking.seat()) .filter(BookedTicket::isBooked) .ifPresent(it -> { log.error("Seat {} is already booked for movie ID: {}. Booking cannot proceed.", booking.seat(), booking.movieId()); throw new IllegalStateException("Seat %s is already booked for movie ID: %s".formatted(booking.seat(), booking.movieId())); }); log.info("Seat: {} is available for movie ID: {}. Proceeding with booking.", booking.seat(), booking.movieId()); BookedTicket bookedTicket = new BookedTicket(booking.movieId(), booking.seat()); bookedTicket = bookedTickets.save(bookedTicket); eventPublisher.publishEvent( new BookingCreated(bookedTicket.movieId(), bookedTicket.seatNumber())); return bookedTicket.id(); } @Transactional public Long cancelTicket(CancelTicket cancellation) { log.info("Received cancellation command for bookingId: {}. Validating the Booking", cancellation.bookingId()); BookedTicket booking = bookedTickets.findById(cancellation.bookingId()) .orElseThrow(() -> new IllegalArgumentException("Booking not found for ID: " + cancellation.bookingId())); if (booking.isCancelled()) { log.warn("Booking with ID: {} is already cancelled. No action taken.", cancellation.bookingId()); throw new IllegalStateException("Booking with ID: " + cancellation.bookingId() + " is already cancelled."); } log.info("Proceeding with cancellation for {}", cancellation.bookingId()); BookedTicket cancelledTicket = booking.cancelledBooking(); bookedTickets.save(cancelledTicket); eventPublisher.publishEvent( new BookingCancelled(cancelledTicket.movieId(), cancelledTicket.seatNumber())); return cancelledTicket.id();
} private static void validateSeatNumber(String seat) { if (seat == null || seat.isBlank()) { throw new IllegalArgumentException("Seat number cannot be null or empty"); } char col = seat.charAt(0); if (col < 'A' || col > 'J') { throw new IllegalArgumentException("Invalid seat number: " + seat); } int rowPart = Integer.parseInt(seat.substring(1)); if (rowPart < 1 || rowPart > 20) { throw new IllegalArgumentException("Invalid seat number: " + seat); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\spring\modulith\cqrs\ticket\TicketBookingCommandHandler.java
2
请完成以下Java代码
public HUConsolidationJob startJob( @NonNull final HUConsolidationJobReference reference, @NonNull final UserId responsibleId) { return jobRepository.create(reference, responsibleId); } public HUConsolidationJob complete(@NonNull final HUConsolidationJob job) { return CompleteCommand.builder() .jobRepository(jobRepository) .targetCloser(targetCloser) // .job(job) // .build().execute(); } public HUConsolidationJob assignJob(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId) { return jobRepository.updateById(jobId, job -> job.withResponsibleId(callerId)); } public void abort(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId) { AbortCommand.builder() .jobRepository(jobRepository) .targetCloser(targetCloser) // .jobId(jobId) .callerId(callerId) // .build().execute(); } public void abortAll(@NonNull final UserId callerId) { // TODO } public List<HUConsolidationTarget> getAvailableTargets(@NonNull final HUConsolidationJob job) { return availableTargetsFinder.getAvailableTargets(job.getCustomerId()); } public HUConsolidationJob setTarget(@NonNull final HUConsolidationJobId jobId, @Nullable final HUConsolidationTarget target, @NonNull UserId callerId) { return SetTargetCommand.builder() .jobRepository(jobRepository) // .callerId(callerId) .jobId(jobId) .target(target) // .build().execute();
} public HUConsolidationJob closeTarget(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId) { return jobRepository.updateById(jobId, job -> { job.assertUserCanEdit(callerId); return targetCloser.closeTarget(job); }); } public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId) { final HUConsolidationJob job = jobRepository.getById(jobId); final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull(); labelPrinter.printLabel(currentTarget); } public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request) { return ConsolidateCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService) .pickingSlotService(pickingSlotService) .request(request) .build() .execute(); } public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId) { return GetPickingSlotContentCommand.builder() .jobRepository(jobRepository) .huQRCodesService(huQRCodesService) .pickingSlotService(pickingSlotService) .jobId(jobId) .pickingSlotId(pickingSlotId) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java
1
请完成以下Java代码
public void setFullPaymentString (java.lang.String FullPaymentString) { set_Value (COLUMNNAME_FullPaymentString, FullPaymentString); } /** Get Eingelesene Zeichenkette. @return Im Fall von ESR oder anderen von Zahlschein gelesenen Zahlungsaufforderungen ist dies der komplette vom Schein eingelesene String */ @Override public java.lang.String getFullPaymentString () { return (java.lang.String)get_Value(COLUMNNAME_FullPaymentString); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenz. @param Reference Bezug für diesen Eintrag */ @Override public void setReference (java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Referenz. @return Bezug für diesen Eintrag */ @Override public java.lang.String getReference () { return (java.lang.String)get_Value(COLUMNNAME_Reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_Payment_Request.java
1
请在Spring Boot框架中完成以下Java代码
public class ChatController { Map<String, String> msgMap = new ConcurrentHashMap<>(); /** * send meaaage * @param msg * @return */ @ResponseBody @PostMapping("/sendMsg") public String sendMsg(String msg) { String msgId = IdUtil.simpleUUID(); msgMap.put(msgId, msg); return msgId; } /** * conversation * @param msgId mapper with sendmsg * @return */ @GetMapping(value = "/conversation/{msgId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter conversation(@PathVariable("msgId") String msgId) { SseEmitter emitter = new SseEmitter();
String msg = msgMap.remove(msgId); //mock chatgpt response new Thread(() -> { try { for (int i = 0; i < 10; i++) { ChatMessage chatMessage = new ChatMessage("test", new String(i+"")); emitter.send(chatMessage); Thread.sleep(1000); } emitter.send(SseEmitter.event().name("stop").data("")); emitter.complete(); // close connection } catch (IOException | InterruptedException e) { emitter.completeWithError(e); // error finish } }).start(); return emitter; } }
repos\springboot-demo-master\sse\src\main\java\com\et\sse\controller\ChatController.java
2
请完成以下Java代码
public class SysRoleIndex { /**id*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "id") private java.lang.String id; /**角色编码*/ @Excel(name = "角色编码", width = 15) @Schema(description = "角色编码") private java.lang.String roleCode; /**路由地址*/ @Excel(name = "路由地址", width = 15) @Schema(description = "路由地址") private java.lang.String url; /**路由地址*/ @Excel(name = "路由地址", width = 15) @Schema(description = "组件") private java.lang.String component; /** * 是否路由菜单: 0:不是 1:是(默认值1) */ @Excel(name = "是否路由菜单", width = 15) @Schema(description = "是否路由菜单") @TableField(value="is_route") private Boolean route; /**优先级*/ @Excel(name = "优先级", width = 15) @Schema(description = "优先级") private java.lang.Integer priority; /**路由地址*/ @Excel(name = "状态", width = 15) @Schema(description = "状态") private java.lang.String status; /**创建人登录名称*/ @Excel(name = "创建人登录名称", width = 15) @Schema(description = "创建人登录名称") private java.lang.String createBy; /**创建日期*/
@Excel(name = "创建日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "创建日期") private java.util.Date createTime; /**更新人登录名称*/ @Excel(name = "更新人登录名称", width = 15) @Schema(description = "更新人登录名称") private java.lang.String updateBy; /**更新日期*/ @Excel(name = "更新日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "更新日期") private java.util.Date updateTime; /**所属部门*/ @Excel(name = "所属部门", width = 15) @Schema(description = "所属部门") private java.lang.String sysOrgCode; /**关联类型(ROLE:角色 USER:表示用户)*/ @Schema(description = "关联类型") @Excel(name = "关联类型", width = 15, dicCode = "relation_type") @Dict(dicCode = "relation_type") private java.lang.String relationType; public SysRoleIndex() { } public SysRoleIndex(String componentUrl){ this.component = componentUrl; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysRoleIndex.java
1
请完成以下Java代码
public String getCaseDefinitionIdLike() { return caseDefinitionKey + ":%:%"; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseDefinitionNameLike() { return caseDefinitionNameLike; } public String getCaseInstanceId() { return caseInstanceId; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public String getStartedBy() { return createdBy; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public void setSuperCaseInstanceId(String superCaseInstanceId) { this.superCaseInstanceId = superCaseInstanceId; } public List<String> getCaseKeyNotIn() { return caseKeyNotIn; } public Date getCreatedAfter() { return createdAfter; }
public Date getCreatedBefore() { return createdBefore; } public Date getClosedAfter() { return closedAfter; } public Date getClosedBefore() { return closedBefore; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java
1
请完成以下Java代码
public static boolean isForeignKeyViolation(final Throwable e) { if (DB.isPostgreSQL()) { return isSQLState(e, PG_SQLSTATE_foreign_key_violation); } // NOTE: on oracle there are many ORA-codes for foreign key violation // below i am adding a few of them, but pls note that it's not tested at all return isErrorCode(e, 2291) // integrity constraint (string.string) violated - parent key not found || isErrorCode(e, 2292) // integrity constraint (string.string) violated - child record found // ; } /** * Check if "invalid identifier" exception (aka ORA-00904) * * @param e exception */ public static boolean isInvalidIdentifierError(final Exception e) { return isErrorCode(e, 904); } /** * Check if "invalid username/password" exception (aka ORA-01017) * * @param e exception */ public static boolean isInvalidUserPassError(final Exception e) { return isErrorCode(e, 1017); } /** * Check if "time out" exception (aka ORA-01013) */ public static boolean isTimeout(final Exception e) {
if (DB.isPostgreSQL()) { return isSQLState(e, PG_SQLSTATE_query_canceled); } return isErrorCode(e, 1013); } /** * Task 08353 */ public static boolean isDeadLockDetected(final Throwable e) { if (DB.isPostgreSQL()) { return isSQLState(e, PG_SQLSTATE_deadlock_detected); } return isErrorCode(e, 40001); // not tested for oracle, just did a brief googling } } // DBException
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DBException.java
1
请完成以下Java代码
public User getUser(@PathVariable Long id) { // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id); } /** * 处理"/users/{id}"的PUT请求,用来更新User信息 * * @param id * @param user * @return */ @PutMapping("/{id}") public String putUser(@PathVariable Long id, @RequestBody User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u);
return "success"; } /** * 处理"/users/{id}"的DELETE请求,用来删除User * * @param id * @return */ @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; } }
repos\SpringBoot-Learning-master\2.x\chapter2-1\src\main\java\com\didispace\chapter21\UserController.java
1
请完成以下Java代码
public ModelElementType getType(Class<? extends ModelElementInstance> instanceClass) { return typesByClass.get(instanceClass); } public ModelElementType getTypeForName(String typeName) { return getTypeForName(null, typeName); } public ModelElementType getTypeForName(String namespaceUri, String typeName) { return typesByName.get(ModelUtil.getQName(namespaceUri, typeName)); } /** * Registers a {@link ModelElementType} in this {@link Model}. * * @param modelElementType the element type to register * @param instanceType the instance class of the type to register */ public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) { QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName()); typesByName.put(qName, modelElementType); typesByClass.put(instanceType, modelElementType); } public String getModelName() { return modelName; } @Override public int hashCode() { int prime = 31; int result = 1;
result = prime * result + ((modelName == null) ? 0 : modelName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ModelImpl other = (ModelImpl) obj; if (modelName == null) { if (other.modelName != null) { return false; } } else if (!modelName.equals(other.modelName)) { return false; } return true; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelImpl.java
1
请完成以下Java代码
private Method getFactoryMethod(final Class<?> objClass) throws JAXBException { Method method = factoryMethods.get(objClass); if (method == null) { method = findFactoryMethod(objClass); factoryMethods.put(objClass, method); } return method; } private Method findFactoryMethod(final Class<?> objClass) throws JAXBException { for (final Method method : objectFactory.getClass().getDeclaredMethods()) { if (!method.getName().startsWith("create")) { continue; } if (method.getParameterTypes().length != 1) {
continue; } if (!method.getParameterTypes()[0].equals(objClass)) { continue; } if (!method.getReturnType().equals(JAXBElement.class)) { continue; } return method; } throw new JAXBException("No converter method found in factory: " + objectFactory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\util\jaxb\DynamicObjectFactory.java
1
请完成以下Java代码
private void updateBestBeforePolicy(@NonNull final QuickInput quickInput) { if (!quickInput.hasField(IOrderLineQuickInput.COLUMNNAME_ShipmentAllocation_BestBefore_Policy)) { return; } final I_C_Order order = quickInput.getRootDocumentAs(I_C_Order.class); final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(order.getC_BPartner_ID()); if (bpartnerId == null) { return; } final ShipmentAllocationBestBeforePolicy bestBeforePolicy = bpartnersService.getBestBeforePolicy(bpartnerId); final IOrderLineQuickInput quickInputModel = quickInput.getQuickInputDocumentAs(IOrderLineQuickInput.class); quickInputModel.setShipmentAllocation_BestBefore_Policy(bestBeforePolicy.getCode()); } private void updateCompensationGroup(@NonNull final QuickInput quickInput) { if (!quickInput.hasField(IOrderLineQuickInput.COLUMNNAME_C_CompensationGroup_Schema_ID)) { return; } final IOrderLineQuickInput quickInputModel = quickInput.getQuickInputDocumentAs(IOrderLineQuickInput.class); final ProductAndAttributes productAndAttributes = getProductAndAttributes(quickInputModel); final GroupTemplateId groupTemplateId = getGroupTemplateId(productAndAttributes).orElse(null); quickInputModel.setC_CompensationGroup_Schema_ID(GroupTemplateId.toRepoId(groupTemplateId)); if (groupTemplateId != null) { quickInputModel.setQty(BigDecimal.ONE); } else { quickInputModel.setC_Flatrate_Conditions_ID(-1);
} } @Nullable private static ProductAndAttributes getProductAndAttributes(@NonNull final IOrderLineQuickInput quickInputModel) { return quickInputModel.getM_Product_ID() != null ? ProductLookupDescriptor.toProductAndAttributes(quickInputModel.getM_Product_ID()) : null; } private Optional<GroupTemplateId> getGroupTemplateId(@Nullable final ProductAndAttributes productAndAttributes) { return productAndAttributes != null ? productDAO.getGroupTemplateIdByProductId(productAndAttributes.getProductId()) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\orderline\OrderLineQuickInputCallout.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}") private int batchSize; private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public void batchAuthors() { List<Author> authors = new ArrayList<>(); for (int i = 0; i < 1000; i++) { Author author = new Author(); author.setId((long) i + 1); author.setName("Name_" + i); author.setGenre("Genre_" + i);
author.setAge(18 + i); authors.add(author); if (i % batchSize == 0 && i > 0) { authorRepository.saveAll(authors); authors.clear(); } } if (authors.size() > 0) { authorRepository.saveAll(authors); authors.clear(); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsJpaRepository\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public class SyncBPartner implements IConfirmableDTO { String uuid; boolean deleted; long syncConfirmationId; String name; List<SyncUser> users; boolean syncContracts; List<SyncContract> contracts; List<SyncRfQ> rfqs; @Builder(toBuilder = true) @JsonCreator private SyncBPartner( @JsonProperty("uuid") final String uuid, @JsonProperty("deleted") final boolean deleted, @JsonProperty("syncConfirmationId") final long syncConfirmationId, @JsonProperty("name") final String name, @JsonProperty("users") @Singular final List<SyncUser> users, @JsonProperty("syncContracts") final Boolean syncContracts, @JsonProperty("contracts") @Singular final List<SyncContract> contracts, @JsonProperty("rfqs") @Singular final List<SyncRfQ> rfqs) { this.uuid = uuid; this.deleted = deleted;
this.syncConfirmationId = syncConfirmationId; this.name = name; this.users = users; this.syncContracts = syncContracts != null ? syncContracts : false; this.contracts = contracts; this.rfqs = rfqs; } @Override public String toString() { return "SyncBPartner [name=" + name + ", users=" + users + ", syncContracts=" + syncContracts + ", contracts=" + contracts + ", rfqs=" + rfqs + "]"; } @Override public IConfirmableDTO withNotDeleted() { return toBuilder().deleted(false).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncBPartner.java
2
请完成以下Java代码
public void setC_Currency_ID (int C_Currency_ID) { throw new IllegalArgumentException ("C_Currency_ID is virtual column"); } /** Get Währung. @return Die Währung für diesen Eintrag */ @Override public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Credit limit indicator %. @param CreditLimitIndicator Percent of Credit used from the limit */ @Override public void setCreditLimitIndicator (java.lang.String CreditLimitIndicator) { set_Value (COLUMNNAME_CreditLimitIndicator, CreditLimitIndicator); } /** Get Credit limit indicator %. @return Percent of Credit used from the limit */ @Override public java.lang.String getCreditLimitIndicator () { return (java.lang.String)get_Value(COLUMNNAME_CreditLimitIndicator); } /** Set Offene Posten. @param OpenItems Offene Posten */ @Override public void setOpenItems (java.math.BigDecimal OpenItems) { set_Value (COLUMNNAME_OpenItems, OpenItems); } /** Get Offene Posten. @return Offene Posten */ @Override public java.math.BigDecimal getOpenItems () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenItems); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Kredit gewährt. @param SO_CreditUsed Gegenwärtiger Aussenstand */ @Override public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed) { set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed); } /** Get Kredit gewährt. @return Gegenwärtiger Aussenstand */ @Override public java.math.BigDecimal getSO_CreditUsed () {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed); if (bd == null) return BigDecimal.ZERO; return bd; } /** * SOCreditStatus AD_Reference_ID=289 * Reference name: C_BPartner SOCreditStatus */ public static final int SOCREDITSTATUS_AD_Reference_ID=289; /** CreditStop = S */ public static final String SOCREDITSTATUS_CreditStop = "S"; /** CreditHold = H */ public static final String SOCREDITSTATUS_CreditHold = "H"; /** CreditWatch = W */ public static final String SOCREDITSTATUS_CreditWatch = "W"; /** NoCreditCheck = X */ public static final String SOCREDITSTATUS_NoCreditCheck = "X"; /** CreditOK = O */ public static final String SOCREDITSTATUS_CreditOK = "O"; /** NurEineRechnung = I */ public static final String SOCREDITSTATUS_NurEineRechnung = "I"; /** Set Kreditstatus. @param SOCreditStatus Kreditstatus des Geschäftspartners */ @Override public void setSOCreditStatus (java.lang.String SOCreditStatus) { set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus); } /** Get Kreditstatus. @return Kreditstatus des Geschäftspartners */ @Override public java.lang.String getSOCreditStatus () { return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java
1
请完成以下Java代码
public class Order { private Long id; private String symbol; private OrderType orderType; private BigDecimal price; private BigDecimal quantity; public Order() {} public Order(Long id, String symbol, OrderType orderType, BigDecimal price, BigDecimal quantity) { this.id = id; this.symbol = symbol; this.orderType = orderType; this.price = price; this.quantity = quantity; } /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the symbol */ public String getSymbol() { return symbol; } /** * @param symbol the symbol to set */ public void setSymbol(String symbol) { this.symbol = symbol; } /** * @return the orderType */ public OrderType getOrderType() { return orderType; } /** * @param orderType the orderType to set */ public void setOrderType(OrderType orderType) { this.orderType = orderType; } /**
* @return the price */ public BigDecimal getPrice() { return price; } /** * @param price the price to set */ public void setPrice(BigDecimal price) { this.price = price; } /** * @return the quantity */ public BigDecimal getQuantity() { return quantity; } /** * @param quantity the quantity to set */ public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\domain\Order.java
1
请在Spring Boot框架中完成以下Java代码
public V remove(Object key) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { this.loaded.clear(); } @Override public boolean containsValue(Object value) { return this.loaded.containsValue(value); } @Override public Collection<V> values() { return this.loaded.values(); } @Override public Set<Entry<K, V>> entrySet() { return this.loaded.entrySet(); } @Override
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoadingMap<?, ?> that = (LoadingMap<?, ?>) o; return this.loaded.equals(that.loaded); } @Override public int hashCode() { return this.loaded.hashCode(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java
2
请完成以下Java代码
public int getOrder() { return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 3; } private Mono<Void> filterWithCache(ServerWebExchange exchange, GatewayFilterChain chain) { final String metadataKey = responseCacheManager.resolveMetadataKey(exchange); Optional<CachedResponse> cached = getCachedResponse(exchange, metadataKey); if (cached.isPresent()) { return responseCacheManager.processFromCache(exchange, metadataKey, cached.get()); } else { return chain .filter(exchange.mutate().response(new CachingResponseDecorator(metadataKey, exchange)).build()); } } private Optional<CachedResponse> getCachedResponse(ServerWebExchange exchange, String metadataKey) { Optional<CachedResponse> cached; if (shouldRevalidate(exchange)) { cached = Optional.empty(); } else { cached = responseCacheManager.getFromCache(exchange.getRequest(), metadataKey); } return cached; } private boolean shouldRevalidate(ServerWebExchange exchange) { return LocalResponseCacheUtils.isNoCacheRequest(exchange.getRequest()); } private class CachingResponseDecorator extends ServerHttpResponseDecorator { private final String metadataKey; private final ServerWebExchange exchange;
CachingResponseDecorator(String metadataKey, ServerWebExchange exchange) { super(exchange.getResponse()); this.metadataKey = metadataKey; this.exchange = exchange; } @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { final ServerHttpResponse response = exchange.getResponse(); Flux<DataBuffer> decoratedBody; if (responseCacheManager.isResponseCacheable(response) && !responseCacheManager.isNoCacheRequestWithoutUpdate(exchange.getRequest())) { decoratedBody = responseCacheManager.processFromUpstream(metadataKey, exchange, Flux.from(body)); } else { decoratedBody = Flux.from(body); } return super.writeWith(decoratedBody); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheGatewayFilter.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getView().hasEditableRow()) { return ProcessPreconditionsResolution.rejectWithInternalReason("view does not have an editable row"); } if (!isSingleSelectedRow()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selected row"); } final PricingConditionsRow row = getSingleSelectedRow(); if (!row.isEditable()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the editable row"); } if (row.getPricingConditionsId() == null) { final ITranslatableString msg = msgBL.getTranslatableMsgText(MSG_BPARTNER_HAS_NO_PRICING_CONDITIONS); return ProcessPreconditionsResolution.reject(msg); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final PricingConditionsBreak pricingConditionsBreak = pricingConditionsRepo.changePricingConditionsBreak(createPricingConditionsBreakChangeRequest(getEditableRow())); patchEditableRow(PricingConditionsRowActions.saved(pricingConditionsBreak)); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); } private static PricingConditionsBreakChangeRequest createPricingConditionsBreakChangeRequest(final PricingConditionsRow row) { if (!row.isEditable()) { throw new AdempiereException("Saving not editable rows is not allowed") .setParameter("row", row); } final PricingConditionsId pricingConditionsId = row.getPricingConditionsId();
final PricingConditionsBreak pricingConditionsBreak = row.getPricingConditionsBreak(); final PricingConditionsBreakId updateFromPricingConditionsBreakId = row.getCopiedFromPricingConditionsBreakId(); return preparePricingConditionsBreakChangeRequest(pricingConditionsBreak) .pricingConditionsId(pricingConditionsId) .updateFromPricingConditionsBreakId(updateFromPricingConditionsBreakId) .build(); } private static PricingConditionsBreakChangeRequestBuilder preparePricingConditionsBreakChangeRequest( @NonNull final PricingConditionsBreak pricingConditionsBreak) { return PricingConditionsBreakChangeRequest.builder() .pricingConditionsBreakId(pricingConditionsBreak.getId()) .matchCriteria(pricingConditionsBreak.getMatchCriteria()) .price(pricingConditionsBreak.getPriceSpecification()) .discount(pricingConditionsBreak.getDiscount()) .paymentTermId(Optional.ofNullable(pricingConditionsBreak.getPaymentTermIdOrNull())) .paymentDiscount(Optional.ofNullable(pricingConditionsBreak.getPaymentDiscountOverrideOrNull())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\PricingConditionsView_SaveEditableRow.java
1
请完成以下Java代码
protected ExecutionEntity getScopeExecutionForActivityInstance(ExecutionEntity processInstance, ActivityExecutionTreeMapping mapping, ActivityInstance activityInstance) { ensureNotNull("activityInstance", activityInstance); ProcessDefinitionImpl processDefinition = processInstance.getProcessDefinition(); ScopeImpl scope = getScopeForActivityInstance(processDefinition, activityInstance); Set<ExecutionEntity> executions = mapping.getExecutions(scope); Set<String> activityInstanceExecutions = new HashSet<String>(Arrays.asList(activityInstance.getExecutionIds())); // TODO: this is a hack around the activity instance tree // remove with fix of CAM-3574 for (String activityInstanceExecutionId : activityInstance.getExecutionIds()) { ExecutionEntity execution = Context.getCommandContext() .getExecutionManager() .findExecutionById(activityInstanceExecutionId); if (execution.isConcurrent() && execution.hasChildren()) { // concurrent executions have at most one child ExecutionEntity child = execution.getExecutions().get(0); activityInstanceExecutions.add(child.getId()); } } // find the scope execution for the given activity instance Set<ExecutionEntity> retainedExecutionsForInstance = new HashSet<ExecutionEntity>(); for (ExecutionEntity execution : executions) { if (activityInstanceExecutions.contains(execution.getId())) { retainedExecutionsForInstance.add(execution); } } if (retainedExecutionsForInstance.size() != 1) {
throw new ProcessEngineException("There are " + retainedExecutionsForInstance.size() + " (!= 1) executions for activity instance " + activityInstance.getId()); } return retainedExecutionsForInstance.iterator().next(); } protected String describeFailure(String detailMessage) { return "Cannot perform instruction: " + describe() + "; " + detailMessage; } protected abstract String describe(); public String toString() { return describe(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractProcessInstanceModificationCommand.java
1
请完成以下Java代码
public void setAttributeName (final @Nullable java.lang.String AttributeName) { set_ValueNoCheck (COLUMNNAME_AttributeName, AttributeName); } @Override public java.lang.String getAttributeName() { return get_ValueAsString(COLUMNNAME_AttributeName); } /** * DocumentName AD_Reference_ID=53258 * Reference name: A_Asset_ID */ public static final int DOCUMENTNAME_AD_Reference_ID=53258; @Override public void setDocumentName (final @Nullable java.lang.String DocumentName) { set_ValueNoCheck (COLUMNNAME_DocumentName, DocumentName); } @Override public java.lang.String getDocumentName() { return get_ValueAsString(COLUMNNAME_DocumentName); } @Override public void setDocumentNo (final @Nullable java.lang.String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setPIName (final @Nullable java.lang.String PIName)
{ set_ValueNoCheck (COLUMNNAME_PIName, PIName); } @Override public java.lang.String getPIName() { return get_ValueAsString(COLUMNNAME_PIName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); 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_Instance_Properties_v.java
1
请完成以下Spring Boot application配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/cg?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.configuration.auto-mapping-behavior=full mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.s
tdout.StdOutImpl mybatis-plus.mapper-locations=classpath*:mapper/**/*Mapper.xml mybatis-plus.global-config.db-config.logic-not-delete-value=0 mybatis-plus.global-config.db-config.logic-delete-value=1
repos\spring-boot-quick-master\quick-sample-server\sample-server\src\main\resources\application-jdbc.properties
2
请完成以下Java代码
public ExtensionOutput getOutput() { return this.output; } /** * The output for {@link CredentialPropertiesOutput} * * @author Rob Winch * @since 6.4 * @see #getOutput() */ public static final class ExtensionOutput implements Serializable { @Serial private static final long serialVersionUID = 4557406414847424019L; private final boolean rk; private ExtensionOutput(boolean rk) { this.rk = rk; }
/** * This OPTIONAL property, known abstractly as the resident key credential * property (i.e., client-side discoverable credential property), is a Boolean * value indicating whether the PublicKeyCredential returned as a result of a * registration ceremony is a client-side discoverable credential. * @return is resident key credential property */ public boolean isRk() { return this.rk; } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\CredentialPropertiesOutput.java
1
请完成以下Java代码
public int getPageFrom() { return pageFrom; } /** * @param pageFrom the pageFrom to set */ public void setPageFrom(int pageFrom) { this.pageFrom = pageFrom; } public int getPageTo() { return pageTo; } /** * @param pageTo the pageTo to set */ public void setPageTo(int pageTo) { this.pageTo = pageTo; } @Override public String toString() { return "PrintPackageInfo [printService=" + printService + ", tray=" + tray + ", pageFrom=" + pageFrom + ", pageTo=" + pageTo + ", calX=" + calX + ", calY=" + calY + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + calX; result = prime * result + calY; result = prime * result + pageFrom; result = prime * result + pageTo; result = prime * result + ((printService == null) ? 0 : printService.hashCode()); result = prime * result + ((tray == null) ? 0 : tray.hashCode()); result = prime * result + trayNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null)
return false; if (getClass() != obj.getClass()) return false; PrintPackageInfo other = (PrintPackageInfo)obj; if (calX != other.calX) return false; if (calY != other.calY) return false; if (pageFrom != other.pageFrom) return false; if (pageTo != other.pageTo) return false; if (printService == null) { if (other.printService != null) return false; } else if (!printService.equals(other.printService)) return false; if (tray == null) { if (other.tray != null) return false; } else if (!tray.equals(other.tray)) return false; if (trayNumber != other.trayNumber) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java
1
请完成以下Java代码
public void init() { // nothing to do here } @Override public Properties getContext() { return ctxProxy; } private Properties getActualContext() { // // IMPORTANT: this method will be called very often, so please make sure it's FAST! // // // If there is currently a temporary context active, return it first final Properties temporaryCtx = temporaryCtxHolder.get(); if (temporaryCtx != null) { logger.trace("Returning temporary context: {}", temporaryCtx); return temporaryCtx; } // // Get the context from current session final UserSession userSession = UserSession.getCurrentOrNull(); if (userSession != null) { final Properties userSessionCtx = userSession.getCtx(); logger.trace("Returning user session context: {}", userSessionCtx); return userSessionCtx; } // // If there was no current session it means we are running on server side, so return the server context logger.trace("Returning server context: {}", serverCtx); return serverCtx; } @Override public IAutoCloseable switchContext(@NonNull final Properties ctx) { // If we were asked to set the context proxy (the one which we are returning everytime), // then it's better to do nothing because this could end in a StackOverflowException. if (ctx == ctxProxy) { logger.trace("Not switching context because the given temporary context it's actually our context proxy: {}", ctx);
return NullAutoCloseable.instance; } final Properties previousTempCtx = temporaryCtxHolder.get(); temporaryCtxHolder.set(ctx); logger.trace("Switched to temporary context. \n New temporary context: {} \n Previous temporary context: {}", ctx, previousTempCtx); return new IAutoCloseable() { private boolean closed = false; @Override public void close() { if (closed) { return; } if (previousTempCtx != null) { temporaryCtxHolder.set(previousTempCtx); } else { temporaryCtxHolder.remove(); } closed = true; logger.trace("Switched back from temporary context"); } }; } @Override public void reset() { temporaryCtxHolder.remove(); serverCtx.clear(); logger.debug("Reset done"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\WebRestApiContextProvider.java
1
请完成以下Java代码
public void onSuccess(InvokeRequest request, InvokeResult invokeResult) { try { if (config.isTellFailureIfFuncThrowsExc() && invokeResult.getFunctionError() != null) { throw new RuntimeException(getPayload(invokeResult)); } tellSuccess(ctx, getResponseMsg(tbMsg, invokeResult)); } catch (Exception e) { tellFailure(ctx, processException(tbMsg, invokeResult, e), e); } } }); } private InvokeRequest toRequest(String requestBody, String functionName, String qualifier) { return new InvokeRequest() .withFunctionName(functionName) .withPayload(requestBody) .withQualifier(qualifier); } private String getPayload(InvokeResult invokeResult) { ByteBuffer buf = invokeResult.getPayload(); if (buf == null) { throw new RuntimeException("Payload from result of AWS Lambda function execution is null."); } byte[] responseBytes = new byte[buf.remaining()]; buf.get(responseBytes); return new String(responseBytes); } private TbMsg getResponseMsg(TbMsg originalMsg, InvokeResult invokeResult) { TbMsgMetaData metaData = originalMsg.getMetaData().copy();
metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId()); String data = getPayload(invokeResult); return originalMsg.transform() .metaData(metaData) .data(data) .build(); } private TbMsg processException(TbMsg origMsg, InvokeResult invokeResult, Throwable t) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue("error", t.getClass() + ": " + t.getMessage()); metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId()); return origMsg.transform() .metaData(metaData) .build(); } @Override public void destroy() { if (client != null) { try { client.shutdown(); } catch (Exception e) { log.error("Failed to shutdown Lambda client during destroy", e); } } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\lambda\TbAwsLambdaNode.java
1
请完成以下Java代码
public final void setCsrfRequestAttributeName(String csrfRequestAttributeName) { this.csrfRequestAttributeName = csrfRequestAttributeName; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> deferredCsrfToken) { Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); Assert.notNull(deferredCsrfToken, "deferredCsrfToken cannot be null"); CsrfToken csrfToken = new SupplierCsrfToken(deferredCsrfToken); request.setAttribute(CsrfToken.class.getName(), csrfToken); String csrfAttrName = (this.csrfRequestAttributeName != null) ? this.csrfRequestAttributeName : csrfToken.getParameterName(); request.setAttribute(csrfAttrName, csrfToken); logger.trace(LogMessage.format("Wrote a CSRF token to the following request attributes: [%s, %s]", csrfAttrName, CsrfToken.class.getName())); } @SuppressWarnings("serial") private static final class SupplierCsrfToken implements CsrfToken { private final Supplier<CsrfToken> csrfTokenSupplier; private SupplierCsrfToken(Supplier<CsrfToken> csrfTokenSupplier) { this.csrfTokenSupplier = csrfTokenSupplier; } @Override public String getHeaderName() { return getDelegate().getHeaderName(); }
@Override public String getParameterName() { return getDelegate().getParameterName(); } @Override public String getToken() { return getDelegate().getToken(); } private CsrfToken getDelegate() { CsrfToken delegate = this.csrfTokenSupplier.get(); if (delegate == null) { throw new IllegalStateException("csrfTokenSupplier returned null delegate"); } return delegate; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfTokenRequestAttributeHandler.java
1
请完成以下Java代码
public class CaseReactivationBuilderImpl implements CaseReactivationBuilder { protected final CommandExecutor commandExecutor; protected final String caseInstanceId; protected List<String> terminatedPlanItemDefinitionIds = new ArrayList<>(); protected Map<String, Object> variables; protected Map<String, Object> transientVariables; public CaseReactivationBuilderImpl(CommandExecutor commandExecutor, String caseInstanceId) { this.commandExecutor = commandExecutor; this.caseInstanceId = caseInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public List<String> getTerminatedPlanItemDefinitionIds() { return terminatedPlanItemDefinitionIds; } public boolean hasVariables() { return variables != null && variables.size() > 0; } public Map<String, Object> getVariables() { return variables; } public boolean hasTransientVariables() { return transientVariables != null && transientVariables.size() > 0; } public Map<String, Object> getTransientVariables() { return transientVariables; } @Override public CaseReactivationBuilder addTerminatedPlanItemInstanceForPlanItemDefinition(String planItemDefinitionId) { this.terminatedPlanItemDefinitionIds.add(planItemDefinitionId); return this; } @Override public CaseReactivationBuilder variable(String name, Object value) { if (variables == null) {
variables = new HashMap<>(); } variables.put(name, value); return this; } @Override public CaseReactivationBuilder variables(Map<String, Object> variables) { if (this.variables == null) { this.variables = new HashMap<>(); } this.variables.putAll(variables); return this; } @Override public CaseReactivationBuilder transientVariable(String name, Object value) { if (transientVariables == null) { transientVariables = new HashMap<>(); } transientVariables.put(name, value); return this; } @Override public CaseReactivationBuilder transientVariables(Map<String, Object> variables) { if (transientVariables == null) { transientVariables = new HashMap<>(); } transientVariables.putAll(variables); return this; } @Override public CaseInstance reactivate() { return commandExecutor.execute(new ReactivateHistoricCaseInstanceCmd(this)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\reactivation\CaseReactivationBuilderImpl.java
1
请完成以下Java代码
public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM) { set_ValueNoCheck (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM); } @Override public BigDecimal getQtyEnteredInBPartnerUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoiced (final @Nullable BigDecimal QtyInvoiced) { set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced); } @Override public BigDecimal getQtyInvoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoicedInOrderedUOM (final @Nullable BigDecimal QtyInvoicedInOrderedUOM) { set_ValueNoCheck (COLUMNNAME_QtyInvoicedInOrderedUOM, QtyInvoicedInOrderedUOM); } @Override public BigDecimal getQtyInvoicedInOrderedUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInOrderedUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSupplier_GTIN_CU (final @Nullable java.lang.String Supplier_GTIN_CU) { set_ValueNoCheck (COLUMNNAME_Supplier_GTIN_CU, Supplier_GTIN_CU); } @Override public java.lang.String getSupplier_GTIN_CU() { return get_ValueAsString(COLUMNNAME_Supplier_GTIN_CU); } @Override public void setTaxAmtInfo (final @Nullable BigDecimal TaxAmtInfo) { set_Value (COLUMNNAME_TaxAmtInfo, TaxAmtInfo); }
@Override public BigDecimal getTaxAmtInfo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtInfo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void settaxfree (final boolean taxfree) { set_Value (COLUMNNAME_taxfree, taxfree); } @Override public boolean istaxfree() { return get_ValueAsBoolean(COLUMNNAME_taxfree); } @Override public void setUPC_CU (final @Nullable java.lang.String UPC_CU) { set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU); } @Override public java.lang.String getUPC_CU() { return get_ValueAsString(COLUMNNAME_UPC_CU); } @Override public void setUPC_TU (final @Nullable java.lang.String UPC_TU) { set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU); } @Override public java.lang.String getUPC_TU() { return get_ValueAsString(COLUMNNAME_UPC_TU); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java
1
请完成以下Java代码
void jbInit() throws Exception { this.setLayout(borderLayout1); textF.setEditable(false); textF.setText(text); cancelB.setMaximumSize(new Dimension(120, 26)); cancelB.setMinimumSize(new Dimension(80, 26)); cancelB.setPreferredSize(new Dimension(120, 26)); cancelB.setText(Local.getString("Cancel")); cancelB.setFocusable(false); cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); continueB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { continueB_actionPerformed(e); } }); continueB.setText(Local.getString("Find next")); continueB.setPreferredSize(new Dimension(120, 26)); continueB.setMinimumSize(new Dimension(80, 26)); continueB.setMaximumSize(new Dimension(120, 26)); continueB.setFocusable(false); flowLayout1.setAlignment(FlowLayout.RIGHT); buttonsPanel.setLayout(flowLayout1); jLabel1.setText(" "+Local.getString("Search for")+": ");
jLabel1.setIcon(new ImageIcon(HTMLEditor.class.getResource("resources/icons/findbig.png"))) ; this.add(jLabel1, BorderLayout.WEST); this.add(textF,BorderLayout.CENTER); buttonsPanel.add(continueB, null); buttonsPanel.add(cancelB, null); this.add(buttonsPanel, BorderLayout.EAST); } void cancelB_actionPerformed(ActionEvent e) { cont = true; cancel = true; thread.resume(); } void continueB_actionPerformed(ActionEvent e) { cont = true; thread.resume(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\ContinueSearchDialog.java
1
请完成以下Java代码
public MultiCustomerHUReturnsInOutProducer setMovementDate(final Timestamp movementDate) { _movementDate = movementDate; return this; } private Timestamp getMovementDate() { if (_movementDate == null) { _movementDate = Env.getDate(); // use login date by default } return _movementDate; } @NonNull private I_C_BPartner_Location retrieveShipFromLocation(@NonNull final BPartnerId bpartnerId)
{ final IBPartnerDAO.BPartnerLocationQuery query = IBPartnerDAO.BPartnerLocationQuery.builder() .bpartnerId(bpartnerId) .type(IBPartnerDAO.BPartnerLocationQuery.Type.SHIP_TO) .build(); final I_C_BPartner_Location shipFromLocation = bpartnerDAO.retrieveBPartnerLocation(query); if (shipFromLocation == null) { final I_C_BPartner bPartner = bpartnerDAO.getById(bpartnerId); throw new AdempiereException(MSG_ERR_NO_BUSINESS_PARTNER_SHIP_TO_LOCATION, bPartner.getName(), bPartner.getValue()).markAsUserValidationError(); } return shipFromLocation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\MultiCustomerHUReturnsInOutProducer.java
1
请完成以下Java代码
public void consumeForChangedFieldName(final String changedFieldName, final IDependencyConsumer consumer) { for (final DependencyType dependencyType : DependencyType.values()) { final Multimap<String, String> name2dependencies = type2name2dependencies.get(dependencyType); if (name2dependencies == null || name2dependencies.isEmpty()) { continue; } for (final String dependentFieldName : name2dependencies.get(changedFieldName)) { consumer.consume(dependentFieldName, dependencyType); } } } // // // // // public static final class Builder { private final Map<DependencyType, ImmutableSetMultimap.Builder<String, String>> type2name2dependencies = new HashMap<>(); private Builder() { super(); } public DocumentFieldDependencyMap build() { if (type2name2dependencies.isEmpty()) { return EMPTY; } return new DocumentFieldDependencyMap(this); } private ImmutableMap<DependencyType, Multimap<String, String>> getType2Name2DependenciesMap() { final ImmutableMap.Builder<DependencyType, Multimap<String, String>> builder = ImmutableMap.builder(); for (final Entry<DependencyType, ImmutableSetMultimap.Builder<String, String>> e : type2name2dependencies.entrySet()) { final DependencyType dependencyType = e.getKey(); final Multimap<String, String> name2dependencies = e.getValue().build(); if (name2dependencies.isEmpty()) { continue; } builder.put(dependencyType, name2dependencies); } return builder.build(); } public Builder add( @NonNull final String fieldName, @Nullable final Collection<String> dependsOnFieldNames, @NonNull final DependencyType dependencyType) { if (dependsOnFieldNames == null || dependsOnFieldNames.isEmpty()) {
return this; } final ImmutableSetMultimap.Builder<String, String> fieldName2dependsOnFieldNames = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder()); for (final String dependsOnFieldName : dependsOnFieldNames) { fieldName2dependsOnFieldNames.put(dependsOnFieldName, fieldName); } return this; } public Builder add(@Nullable final DocumentFieldDependencyMap dependencies) { if (dependencies == null || dependencies == EMPTY) { return this; } for (final Map.Entry<DependencyType, Multimap<String, String>> l1 : dependencies.type2name2dependencies.entrySet()) { final DependencyType dependencyType = l1.getKey(); final ImmutableSetMultimap.Builder<String, String> name2dependencies = type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder()); name2dependencies.putAll(l1.getValue()); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDependencyMap.java
1
请完成以下Java代码
public ViewQuery findAll() { return ViewQuery.from("studentGrades", "findByCourse"); } public ViewQuery findByCourse(String course) { return ViewQuery.from("studentGrades", "findByCourse") .key(course); } public ViewQuery findByCourses(String... courses) { return ViewQuery.from("studentGrades", "findByCourse") .keys(JsonArray.from(courses)); } public ViewQuery findByGradeInRange(int lower, int upper, boolean inclusiveEnd) { return ViewQuery.from("studentGrades", "findByGrade") .startKey(lower) .endKey(upper) .inclusiveEnd(inclusiveEnd); } public ViewQuery findByGradeLessThan(int upper) { return ViewQuery.from("studentGrades", "findByGrade") .endKey(upper) .inclusiveEnd(false); } public ViewQuery findByGradeGreaterThan(int lower) { return ViewQuery.from("studentGrades", "findByGrade") .startKey(lower); }
public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) { return ViewQuery.from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from(course, minGrade)) .endKey(JsonArray.from(course, maxGrade)) .inclusiveEnd(inclusiveEnd); } public ViewQuery findTopGradesByCourse(String course, int limit) { return ViewQuery.from("studentGrades", "findByCourseAndGrade") .startKey(JsonArray.from(course, 100)) .endKey(JsonArray.from(course, 0)) .inclusiveEnd(true) .descending() .limit(limit); } public ViewQuery countStudentsByCourse() { return ViewQuery.from("studentGrades", "countStudentsByCourse") .reduce() .groupLevel(1); } public ViewQuery sumCreditsByStudent() { return ViewQuery.from("studentGrades", "sumCreditsByStudent") .reduce() .groupLevel(1); } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\mapreduce\StudentGradeQueryBuilder.java
1
请完成以下Java代码
static String canonicalize(String path) { path = removeEmbeddedSlashDotDotSlash(path); path = removeEmbeddedSlashDotSlash(path); path = removeTrailingSlashDotDot(path); path = removeTrailingSlashDot(path); return path; } private static String removeEmbeddedSlashDotDotSlash(String path) { int index; while ((index = path.indexOf("/../")) >= 0) { int priorSlash = path.lastIndexOf('/', index - 1); String after = path.substring(index + 3); path = (priorSlash >= 0) ? path.substring(0, priorSlash) + after : after; } return path; } private static String removeEmbeddedSlashDotSlash(String path) { int index; while ((index = path.indexOf("/./")) >= 0) { String before = path.substring(0, index); String after = path.substring(index + 2); path = before + after; } return path; }
private static String removeTrailingSlashDot(String path) { return (!path.endsWith("/.")) ? path : path.substring(0, path.length() - 1); } private static String removeTrailingSlashDotDot(String path) { int index; while (path.endsWith("/..")) { index = path.indexOf("/.."); int priorSlash = path.lastIndexOf('/', index - 1); path = (priorSlash >= 0) ? path.substring(0, priorSlash + 1) : path.substring(0, index); } return path; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\Canonicalizer.java
1
请完成以下Java代码
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findAlarmById(tenantId, new AlarmId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findAlarmByIdAsync(tenantId, new AlarmId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.ALARM; } //TODO: refactor to use efficient caching. private AlarmApiCallResult withPropagated(AlarmApiCallResult result) { if (result.isSuccessful() && result.getAlarm() != null) { List<EntityId> propagationEntities; if (result.isPropagationChanged()) { try { propagationEntities = createEntityAlarmRecords(result.getAlarm()); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } else { propagationEntities = getPropagationEntityIdsList(result.getAlarm()); } return new AlarmApiCallResult(result, propagationEntities); } else { return result; } }
private void validateAlarmRequest(AlarmModificationRequest request) { ConstraintValidator.validateFields(request); if (request.getEndTs() > 0 && request.getStartTs() > request.getEndTs()) { throw new DataValidationException("Alarm start ts can't be greater then alarm end ts!"); } if (!tenantService.tenantExists(request.getTenantId())) { throw new DataValidationException("Alarm is referencing to non-existent tenant!"); } if (request.getStartTs() == 0L) { request.setStartTs(System.currentTimeMillis()); } if (request.getEndTs() == 0L) { request.setEndTs(request.getStartTs()); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\alarm\BaseAlarmService.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void setResources(Map<String, ResourceEntity> resources) { this.resources = resources; } public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public boolean isNew() { return isNew; } public void setNew(boolean isNew) { this.isNew = isNew;
} public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getProjectReleaseVersion() { return projectReleaseVersion; } public void setProjectReleaseVersion(String projectReleaseVersion) { this.projectReleaseVersion = projectReleaseVersion; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static void updateContextFromRecord(final ProcessInfo processInfo) { if (!processInfo.isRecordSet()) { return; } try { final Properties ctx = processInfo.getCtx(); final Object record = processInfo.getRecord(Object.class); final Integer adClientId = InterfaceWrapperHelper.getValueOrNull(record, "AD_Client_ID"); if (adClientId != null) { Env.setContext(ctx, Env.CTXNAME_AD_Client_ID, adClientId); } final Integer adOrgId = InterfaceWrapperHelper.getValueOrNull(record, "AD_Org_ID"); if (adOrgId != null) {
Env.setContext(ctx, Env.CTXNAME_AD_Org_ID, adOrgId); } } catch (final Exception ex) { logger.warn("Failed while populating the context from record. Ignored. \n ProcessInfo: {}", processInfo, ex); } } @Override public void cacheReset() { // nothing to do. In case of LocalJasperServer, the "server" is running in same JVM as ADempiere application // CacheMgt.get().reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\LocalReportServer.java
2
请完成以下Java代码
private void destroy() { if (coreAdmin != null) { coreAdmin.destroy(); } if (ruleEngineAdmin != null) { ruleEngineAdmin.destroy(); } if (jsExecutorRequestAdmin != null) { jsExecutorRequestAdmin.destroy(); } if (jsExecutorResponseAdmin != null) { jsExecutorResponseAdmin.destroy(); } if (transportApiRequestAdmin != null) { transportApiRequestAdmin.destroy(); } if (transportApiResponseAdmin != null) { transportApiResponseAdmin.destroy(); }
if (notificationAdmin != null) { notificationAdmin.destroy(); } if (fwUpdatesAdmin != null) { fwUpdatesAdmin.destroy(); } if (vcAdmin != null) { vcAdmin.destroy(); } if (cfAdmin != null) { cfAdmin.destroy(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\KafkaTbCoreQueueFactory.java
1
请完成以下Java代码
public class SysDateDateExpression implements IExpression<java.util.Date> { public static final transient SysDateDateExpression instance = new SysDateDateExpression(); public static final transient Optional<IExpression<?>> optionalInstance = Optional.of(instance); public static final String EXPRESSION_STRING = "@SysDate@"; private SysDateDateExpression() { } @Override public Class<Date> getValueClass() { return java.util.Date.class; } @Override public String getExpressionString() { return EXPRESSION_STRING; } @Override public String getFormatedExpressionString() { return EXPRESSION_STRING; } @Override public Set<CtxName> getParameters() { return ImmutableSet.of();
} @Override public Date evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { return de.metas.common.util.time.SystemTime.asDate(); } @Override public boolean isNoResult(final Object result) { return result == null; } @Override public boolean isNullExpression() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SysDateDateExpression.java
1
请完成以下Java代码
public void setMetrics(List<String> metrics) { boolean valid = new HashSet<>(VALID_METRIC_VALUES).containsAll(metrics); if (!valid) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "metrics parameter has invalid value: " + metrics); } this.metrics = new HashSet<>(metrics); } public Set<String> getMetrics() { return metrics; } @CamundaQueryParam(value = "subscriptionStartDate", converter = DateConverter.class) public void setSubscriptionStartDate(Date subscriptionStartDate) { this.subscriptionStartDate = subscriptionStartDate; if (subscriptionStartDate != null) { // calculate subscription year and month Calendar cal = Calendar.getInstance(); cal.setTime(subscriptionStartDate); subscriptionMonth = cal.get(Calendar.MONTH) + 1; subscriptionDay = cal.get(Calendar.DAY_OF_MONTH); } } @CamundaQueryParam(value = "startDate", converter = DateConverter.class) public void setStartDate(Date startDate) { this.startDate = startDate; } @CamundaQueryParam(value = "endDate", converter = DateConverter.class) public void setEndDate(Date endDate) { this.endDate = endDate; } @Override protected String getOrderByValue(String sortBy) { return null; }
@Override protected boolean isValidSortByValue(String value) { return false; } public void validateAndPrepareQuery() { if (subscriptionStartDate == null || !subscriptionStartDate.before(ClockUtil.now())) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "subscriptionStartDate parameter has invalid value: " + subscriptionStartDate); } if (startDate != null && endDate != null && !endDate.after(startDate)) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "endDate parameter must be after startDate"); } if (!VALID_GROUP_BY_VALUES.contains(groupBy)) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupBy); } if (metrics == null || metrics.isEmpty()) { metrics = VALID_METRIC_VALUES; } // convert metrics to internal names this.metrics = metrics.stream() .map(MetricsUtil::resolveInternalName) .collect(Collectors.toSet()); } public int getSubscriptionMonth() { return subscriptionMonth; } public int getSubscriptionDay() { return subscriptionDay; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\plugin\base\dto\MetricsAggregatedQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult close(@RequestParam("ids") List<Long> ids, @RequestParam String note) { int count = orderService.close(ids, note); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除订单") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取订单详情:订单信息、商品信息、操作记录") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) { OmsOrderDetail orderDetailResult = orderService.detail(id); return CommonResult.success(orderDetailResult); } @ApiOperation("修改收货人信息") @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) { int count = orderService.updateReceiverInfo(receiverInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改订单费用信息") @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) { int count = orderService.updateMoneyInfo(moneyInfoParam);
if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("备注订单") @RequestMapping(value = "/update/note", method = RequestMethod.POST) @ResponseBody public CommonResult updateNote(@RequestParam("id") Long id, @RequestParam("note") String note, @RequestParam("status") Integer status) { int count = orderService.updateNote(id, note, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderController.java
2
请完成以下Java代码
public class EncryptionUtil { private EncryptionUtil() { } public static String certTrimNewLines(String input) { return input.replaceAll("-----BEGIN CERTIFICATE-----", "") .replaceAll("\n", "") .replaceAll("\r", "") .replaceAll("-----END CERTIFICATE-----", ""); } public static String certTrimNewLinesForChainInDeviceProfile(String input) { return input.replaceAll("\n", "") .replaceAll("\r", "") .replaceAll("-----BEGIN CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n") .replaceAll("-----END CERTIFICATE-----", "\n-----END CERTIFICATE-----\n") .trim(); } public static String pubkTrimNewLines(String input) { return input.replaceAll("-----BEGIN PUBLIC KEY-----", "") .replaceAll("\n", "") .replaceAll("\r", "") .replaceAll("-----END PUBLIC KEY-----", ""); } public static String prikTrimNewLines(String input) { return input.replaceAll("-----BEGIN EC PRIVATE KEY-----", "") .replaceAll("\n", "") .replaceAll("\r", "") .replaceAll("-----END EC PRIVATE KEY-----", ""); } public static String getSha3Hash(String data) { String trimmedData = certTrimNewLines(data); byte[] dataBytes = trimmedData.getBytes();
SHA3Digest md = new SHA3Digest(256); md.reset(); md.update(dataBytes, 0, dataBytes.length); byte[] hashedBytes = new byte[256 / 8]; md.doFinal(hashedBytes, 0); String sha3Hash = ByteUtils.toHexString(hashedBytes); return sha3Hash; } public static String getSha3Hash(String delim, String... tokens) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String token : tokens) { if (token != null && !token.isEmpty()) { if (first) { first = false; } else { sb.append(delim); } sb.append(token); } } return getSha3Hash(sb.toString()); } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\EncryptionUtil.java
1
请在Spring Boot框架中完成以下Java代码
public String type() { return "redis"; } public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } private StringRedisTemplate stringRedisTemplate; @Override public void set(String key, String value, long expiresInSeconds) { stringRedisTemplate.opsForValue().set(key, value, expiresInSeconds, TimeUnit.SECONDS); } @Override public boolean exists(String key) { return stringRedisTemplate.hasKey(key); }
@Override public void delete(String key) { stringRedisTemplate.delete(key); } @Override public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } @Override public Long increment(String key, long val) { return stringRedisTemplate.opsForValue().increment(key,val); } }
repos\springboot-demo-master\Captcha\src\main\java\com\et\captcha\service\CaptchaCacheServiceRedisImpl.java
2
请完成以下Java代码
public void addCDataSection(String data) { synchronized (document) { CDATASection cdataSection = document.createCDATASection(data); element.appendChild(cdataSection); } } public ModelElementInstance getModelElementInstance() { synchronized(document) { return (ModelElementInstance) element.getUserData(MODEL_ELEMENT_KEY); } } public void setModelElementInstance(ModelElementInstance modelElementInstance) { synchronized(document) { element.setUserData(MODEL_ELEMENT_KEY, modelElementInstance, null); } } public String registerNamespace(String namespaceUri) { synchronized(document) { String lookupPrefix = lookupPrefix(namespaceUri); if (lookupPrefix == null) { // check if a prefix is known String prefix = XmlQName.KNOWN_PREFIXES.get(namespaceUri); // check if prefix is not already used if (prefix != null && getRootElement() != null && getRootElement().hasAttribute(XMLNS_ATTRIBUTE_NS_URI, prefix)) { prefix = null; } if (prefix == null) { // generate prefix prefix = ((DomDocumentImpl) getDocument()).getUnusedGenericNsPrefix(); } registerNamespace(prefix, namespaceUri); return prefix; } else {
return lookupPrefix; } } } public void registerNamespace(String prefix, String namespaceUri) { synchronized(document) { element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE + ":" + prefix, namespaceUri); } } public String lookupPrefix(String namespaceUri) { synchronized(document) { return element.lookupPrefix(namespaceUri); } } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DomElementImpl that = (DomElementImpl) o; return element.equals(that.element); } public int hashCode() { return element.hashCode(); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomElementImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WebServicesConfig extends WsConfigurerAdapter { public static final String NAMESPACE_URI = "https://github.com/YunaiV/SpringBoot-Labs/tree/master/lab-65/lab-65-spring-ws-demo"; @Bean public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); servlet.setTransformWsdlLocations(true); return new ServletRegistrationBean<>(servlet, "/ws/*"); } @Bean public XsdSchema usersSchema() { return new SimpleXsdSchema(new ClassPathResource("users.xsd")); } @Bean(name = "users")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema usersSchema) { DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); wsdl11Definition.setLocationUri("/ws"); wsdl11Definition.setTargetNamespace(NAMESPACE_URI); wsdl11Definition.setSchema(usersSchema); wsdl11Definition.setPortTypeName("UsersPort"); return wsdl11Definition; } @Override public void addInterceptors(List<EndpointInterceptor> interceptors) { // 可自定义附加拦截器 } }
repos\SpringBoot-Labs-master\lab-65\lab-65-spring-ws-demo\lab-65-spring-ws-demo-user-service\src\main\java\cn\iocoder\springboot\lab65\userservice\config\WebServicesConfig.java
2
请完成以下Java代码
public static CmmnEngine getCmmnEngine(String cmmnEngineName) { if (!isInitialized()) { init(); } return cmmnEngines.get(cmmnEngineName); } /** * retries to initialize a cmmn engine that previously failed. */ public static EngineInfo retry(String resourceUrl) { LOGGER.debug("retying initializing of resource {}", resourceUrl); try { return initCmmnEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new FlowableException("invalid url: " + resourceUrl, e); } } /** * provides access to cmmn engine to application clients in a managed server environment. */ public static Map<String, CmmnEngine> getCmmnEngines() { return cmmnEngines; } /** * closes all cmmn engines. This method should be called when the server shuts down. */ public static synchronized void destroy() { if (isInitialized()) { Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines); cmmnEngines = new HashMap<>(); for (String cmmnEngineName : engines.keySet()) { CmmnEngine cmmnEngine = engines.get(cmmnEngineName);
try { cmmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e); } } cmmnEngineInfosByName.clear(); cmmnEngineInfosByResourceUrl.clear(); cmmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { CmmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java
1
请完成以下Java代码
public static boolean isRotationUsingQueue(String origin, String rotation) { if (origin.length() == rotation.length()) { return checkWithQueue(origin, rotation); } return false; } static boolean checkWithQueue(String origin, String rotation) { if (origin.length() == rotation.length()) { Queue<Character> originQueue = getCharactersQueue(origin); Queue<Character> rotationQueue = getCharactersQueue(rotation); int k = rotation.length(); while (k > 0 && null != rotationQueue.peek()) { k--; char ch = rotationQueue.peek(); rotationQueue.remove(); rotationQueue.add(ch); if (rotationQueue.equals(originQueue)) { return true; } } } return false; } static Queue<Character> getCharactersQueue(String origin) { return origin.chars() .mapToObj(c -> (char) c) .collect(Collectors.toCollection(LinkedList::new)); }
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) { if (origin.length() == rotation.length()) { return checkPrefixAndSuffix(origin, rotation); } return false; } static boolean checkPrefixAndSuffix(String origin, String rotation) { if (origin.length() == rotation.length()) { for (int i = 0; i < origin.length(); i++) { if (origin.charAt(i) == rotation.charAt(0)) { if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) { if (checkOriginPrefixWithRotationSuffix(origin, rotation, i)) return true; } } } } return false; } private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) { return origin.substring(i) .equals(rotation.substring(0, origin.length() - i)); } private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) { return origin.substring(0, i) .equals(rotation.substring(origin.length() - i)); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\stringrotation\StringRotation.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Autowired private IgnoreUrlsConfig ignoreUrlsConfig; @Autowired private RestfulAccessDeniedHandler restfulAccessDeniedHandler; @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Autowired private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; @Autowired(required = false) private DynamicSecurityService dynamicSecurityService; @Autowired(required = false) private DynamicSecurityFilter dynamicSecurityFilter; @Bean SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity .authorizeRequests(); //不需要保护的资源路径允许访问 for (String url : ignoreUrlsConfig.getUrls()) { registry.antMatchers(url).permitAll(); } //允许跨域请求的OPTIONS请求 registry.antMatchers(HttpMethod.OPTIONS) .permitAll(); //任何请求都需要身份认证 registry.and() .authorizeRequests() .anyRequest() .authenticated() //关闭跨站请求防护及不使用session
.and() .csrf() .disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //自定义权限拒绝处理类 .and() .exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler) .authenticationEntryPoint(restAuthenticationEntryPoint) //自定义权限拦截器JWT过滤器 .and() .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); //有动态权限配置时添加动态权限校验过滤器 if(dynamicSecurityService!=null){ registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class); } return httpSecurity.build(); } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\config\SecurityConfig.java
2
请完成以下Java代码
public void registerClientGroup(String groupId) { if (statsConfig.getEnabled() && !StringUtils.isEmpty(groupId)) { monitoredGroups.add(groupId); } } public void unregisterClientGroup(String groupId) { if (statsConfig.getEnabled() && !StringUtils.isEmpty(groupId)) { monitoredGroups.remove(groupId); } } @PreDestroy public void destroy() { if (statsPrintScheduler != null) { statsPrintScheduler.shutdownNow(); } if (consumer != null) { consumer.close(); } } @Builder @Data private static class GroupTopicStats {
private String topic; private int partition; private long committedOffset; private long endOffset; private long lag; @Override public String toString() { return "[" + "topic=[" + topic + ']' + ", partition=[" + partition + "]" + ", committedOffset=[" + committedOffset + "]" + ", endOffset=[" + endOffset + "]" + ", lag=[" + lag + "]" + "]"; } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaConsumerStatsService.java
1
请完成以下Java代码
private <T> boolean canConvertFromStringTo(Class<T> targetType) { return this.conversionService.canConvert(String.class, targetType); } private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) { return this.conversionService.convert(identifier, targetType); } /** * Converts to a {@link Long}, attempting to use the {@link ConversionService} if * available. * @param identifier The identifier * @return Long version of the identifier * @throws NumberFormatException if the string cannot be parsed to a long. * @throws org.springframework.core.convert.ConversionException if a conversion * exception occurred * @throws IllegalArgumentException if targetType is null */ private Long convertToLong(Serializable identifier) { if (this.conversionService.canConvert(identifier.getClass(), Long.class)) { return this.conversionService.convert(identifier, Long.class); } return Long.valueOf(identifier.toString()); } private boolean isString(Serializable object) { return object.getClass().isAssignableFrom(String.class); } void setConversionService(ConversionService conversionService) { Assert.notNull(conversionService, "conversionService must not be null"); this.conversionService = conversionService; } private static class StringToLongConverter implements Converter<String, Long> { @Override public Long convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Long.class), null, null); } return Long.parseLong(identifierAsString);
} } private static class StringToUUIDConverter implements Converter<String, UUID> { @Override public UUID convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(UUID.class), null, null); } return UUID.fromString(identifierAsString); } } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\AclClassIdUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingSlotRepository { @NonNull private final IPickingSlotDAO pickingSlotDAO = Services.get(IPickingSlotDAO.class); public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class); } public List<I_M_PickingSlot> getByIds(@NonNull final Set<PickingSlotId> pickingSlotIds) { return pickingSlotDAO.getByIds(pickingSlotIds, I_M_PickingSlot.class); } public List<I_M_PickingSlot> list(@NonNull final PickingSlotQuery query) { return pickingSlotDAO.retrievePickingSlots(query);
} public void save(final @NonNull I_M_PickingSlot pickingSlot) { pickingSlotDAO.save(pickingSlot); } public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId); } public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final Set<PickingSlotId> pickingSlotIds) { return pickingSlotDAO.getPickingSlotIdAndCaptions(pickingSlotIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotRepository.java
2
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * MarketingPlatformGatewayId AD_Reference_ID=540858 * Reference name: MarketingPlatformGatewayId */ public static final int MARKETINGPLATFORMGATEWAYID_AD_Reference_ID=540858; /** CleverReach = CleverReach */ public static final String MARKETINGPLATFORMGATEWAYID_CleverReach = "CleverReach"; /** Set Marketing Platform GatewayId. @param MarketingPlatformGatewayId Marketing Platform GatewayId */ @Override public void setMarketingPlatformGatewayId (java.lang.String MarketingPlatformGatewayId) { set_Value (COLUMNNAME_MarketingPlatformGatewayId, MarketingPlatformGatewayId); } /** Get Marketing Platform GatewayId. @return Marketing Platform GatewayId */ @Override public java.lang.String getMarketingPlatformGatewayId () { return (java.lang.String)get_Value(COLUMNNAME_MarketingPlatformGatewayId); } /** Set MKTG_Consent. @param MKTG_Consent_ID MKTG_Consent */ @Override public void setMKTG_Consent_ID (int MKTG_Consent_ID) { if (MKTG_Consent_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Consent_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Consent_ID, Integer.valueOf(MKTG_Consent_ID)); } /** Get MKTG_Consent. @return MKTG_Consent */ @Override public int getMKTG_Consent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Consent_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class);
} @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_Value (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_Value (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Consent.java
1
请完成以下Java代码
public void setHUAttributeStorageFactory(final IAttributeStorageFactory attributesStorageFactory) { Check.assumeNotNull(attributesStorageFactory, "attributesStorageFactory not null"); Check.assume(!_attributesStorageFactoryInitialized, "attributesStorageFactory not already initialized"); _attributesStorageFactory = attributesStorageFactory; } @Override public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> getHUPackingMaterialsCollector() { return _huPackingMaterialsCollector; } @Override public IMutableHUContext setHUPackingMaterialsCollector(@NonNull final IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> huPackingMaterialsCollector) { this._huPackingMaterialsCollector = huPackingMaterialsCollector; return this; } @Override public CompositeHUTrxListener getTrxListeners() { if (_trxListeners == null) { final CompositeHUTrxListener trxListeners = new CompositeHUTrxListener(); // Add system registered listeners final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); trxListeners.addListeners(huTrxBL.getHUTrxListenersList()); _trxListeners = trxListeners; } return _trxListeners; } @Override public void addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener)
{ emptyHUListeners.add(emptyHUListener); } @Override public List<EmptyHUListener> getEmptyHUListeners() { return ImmutableList.copyOf(emptyHUListeners); } @Override public void flush() { final IAttributeStorageFactory attributesStorageFactory = _attributesStorageFactory; if(attributesStorageFactory != null) { attributesStorageFactory.flush(); } } @Override public IAutoCloseable temporarilyDontDestroyHU(@NonNull final HuId huId) { huIdsToNotDestroy.add(huId); return () -> huIdsToNotDestroy.remove(huId); } @Override public boolean isDontDestroyHu(@NonNull final HuId huId) { return huIdsToNotDestroy.contains(huId); } @Override public boolean isPropertyTrue(@NonNull final String propertyName) { final Boolean isPropertyTrue = getProperty(propertyName); return isPropertyTrue != null && isPropertyTrue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\MutableHUContext.java
1
请完成以下Java代码
public int getAD_Task_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); }
/** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); 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_AD_Task_Access.java
1
请完成以下Java代码
public org.activiti.engine.runtime.ProcessInstance internalProcessInstance(String processInstanceId) { org.activiti.engine.runtime.ProcessInstance internalProcessInstance = runtimeService .createProcessInstanceQuery() .processInstanceId(processInstanceId) .singleResult(); if (internalProcessInstance == null) { throw new NotFoundException("Unable to find process instance for the given id:'" + processInstanceId + "'"); } return internalProcessInstance; } private boolean canReadProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) { return ( securityPoliciesManager.canRead(processInstance.getProcessDefinitionKey()) && (securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId()) || isATaskAssigneeOrACandidate(processInstance.getProcessInstanceId())) ); } private boolean canWriteProcessInstance(org.activiti.engine.runtime.ProcessInstance processInstance) { return ( securityPoliciesManager.canWrite(processInstance.getProcessDefinitionKey()) && securityManager.getAuthenticatedUserId().equals(processInstance.getStartUserId()) ); }
private boolean isATaskAssigneeOrACandidate(String processInstanceId) { String authenticatedUserId = securityManager.getAuthenticatedUserId(); TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processInstanceId); taskQuery .or() .taskCandidateOrAssigned( securityManager.getAuthenticatedUserId(), securityManager.getAuthenticatedUserGroups() ) .taskOwner(authenticatedUserId) .endOr(); return taskQuery.count() > 0; } private List<String> getCurrentUserGroupsIncludingEveryOneGroup() { List<String> groups = new ArrayList<>(securityManager.getAuthenticatedUserGroups()); groups.add(EVERYONE_GROUP); return groups; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ProcessRuntimeImpl.java
1
请完成以下Java代码
public void setLoopCardinality(String loopCardinality) { this.loopCardinality = loopCardinality; } public String getCompletionCondition() { return completionCondition; } public void setCompletionCondition(String completionCondition) { this.completionCondition = completionCondition; } public String getElementVariable() { return elementVariable; } public void setElementVariable(String elementVariable) { this.elementVariable = elementVariable; } public String getElementIndexVariable() { return elementIndexVariable; } public void setElementIndexVariable(String elementIndexVariable) { this.elementIndexVariable = elementIndexVariable; } public boolean isSequential() { return sequential; } public void setSequential(boolean sequential) { this.sequential = sequential; } public boolean isNoWaitStatesAsyncLeave() { return noWaitStatesAsyncLeave; } public void setNoWaitStatesAsyncLeave(boolean noWaitStatesAsyncLeave) { this.noWaitStatesAsyncLeave = noWaitStatesAsyncLeave; } public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) { if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions(); } this.aggregations.getAggregations().add(aggregation); }
@Override public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { super.setValues(otherLoopCharacteristics); setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setCollectionString(otherLoopCharacteristics.getCollectionString()); if (otherLoopCharacteristics.getHandler() != null) { setHandler(otherLoopCharacteristics.getHandler().clone()); } setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave()); if (otherLoopCharacteristics.getAggregations() != null) { setAggregations(otherLoopCharacteristics.getAggregations().clone()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请在Spring Boot框架中完成以下Java代码
public class RecordChangeLogRepository implements LogEntriesRepository { public RecordChangeLog getByRecord(@NonNull final TableRecordReference recordRef) { final String tableName = recordRef.getTableName(); final int recordId = recordRef.getRecord_ID(); final String singleKeyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName); return RecordChangeLogLoader.ofAdTableId(recordRef.getAD_Table_ID()) .getByRecordId(ComposedRecordId.singleKey(singleKeyColumnName, recordId)); } public RecordChangeLog getByRecord(final int adTableId, final ComposedRecordId recordId) { return RecordChangeLogLoader .ofAdTableId(adTableId) .getByRecordId(recordId); } public RecordChangeLog getSummaryByRecord(@NonNull final TableRecordReference recordRef) { final String tableName = recordRef.getTableName();
final int recordId = recordRef.getRecord_ID(); final int adTableId = recordRef.getAD_Table_ID(); final String singleKeyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName); return RecordChangeLogLoader.ofAdTableId(adTableId) .getSummaryByRecordId(ComposedRecordId.singleKey(singleKeyColumnName, recordId)); } @Override public ImmutableListMultimap<TableRecordReference, RecordChangeLogEntry> getLogEntriesForRecordReferences( @NonNull final LogEntriesQuery logEntriesQuery) { return RecordChangeLogEntryLoader.retrieveLogEntries(logEntriesQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogRepository.java
2
请完成以下Java代码
@Override public void exitPrintExpr(LabeledExprParser.PrintExprContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAssign(LabeledExprParser.AssignContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAssign(LabeledExprParser.AssignContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterBlank(LabeledExprParser.BlankContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitBlank(LabeledExprParser.BlankContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterParens(LabeledExprParser.ParensContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitParens(LabeledExprParser.ParensContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterMulDiv(LabeledExprParser.MulDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitMulDiv(LabeledExprParser.MulDivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAddSub(LabeledExprParser.AddSubContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAddSub(LabeledExprParser.AddSubContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterId(LabeledExprParser.IdContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p>
*/ @Override public void exitId(LabeledExprParser.IdContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprBaseListener.java
1
请完成以下Java代码
public void setAD_WF_Responsible_Name (java.lang.String AD_WF_Responsible_Name) { set_Value (COLUMNNAME_AD_WF_Responsible_Name, AD_WF_Responsible_Name); } /** Get Workflow - Verantwortlicher (text). @return Workflow - Verantwortlicher (text) */ @Override public java.lang.String getAD_WF_Responsible_Name () { return (java.lang.String)get_Value(COLUMNNAME_AD_WF_Responsible_Name); } /** Set Document Responsible. @param C_Doc_Responsible_ID Document Responsible */ @Override public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID) { if (C_Doc_Responsible_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID)); } /** Get Document Responsible. @return Document Responsible */ @Override public int getC_Doc_Responsible_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID.
@param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java
1
请完成以下Java代码
public static GraphQlWebSocketMessage subscribe(String id, GraphQlRequest request) { Assert.notNull(request, "GraphQlRequest is required"); return new GraphQlWebSocketMessage(id, GraphQlWebSocketMessageType.SUBSCRIBE, request.toMap()); } /** * Create a {@code "next"} server message. * @param id unique request id * @param responseMap the response map */ public static GraphQlWebSocketMessage next(String id, Map<String, Object> responseMap) { Assert.notNull(responseMap, "'responseMap' is required"); return new GraphQlWebSocketMessage(id, GraphQlWebSocketMessageType.NEXT, responseMap); } /** * Create an {@code "error"} server message. * @param id unique request id * @param errors the error to add as the message payload */ public static GraphQlWebSocketMessage error(String id, List<GraphQLError> errors) { Assert.notNull(errors, "GraphQlError's are required"); return new GraphQlWebSocketMessage(id, GraphQlWebSocketMessageType.ERROR, errors.stream().map(GraphQLError::toSpecification).collect(Collectors.toList())); } /** * Create a {@code "complete"} server message.
* @param id unique request id */ public static GraphQlWebSocketMessage complete(String id) { return new GraphQlWebSocketMessage(id, GraphQlWebSocketMessageType.COMPLETE, null); } /** * Create a {@code "ping"} client or server message. * @param payload an optional payload */ public static GraphQlWebSocketMessage ping(@Nullable Object payload) { return new GraphQlWebSocketMessage(null, GraphQlWebSocketMessageType.PING, payload); } /** * Create a {@code "pong"} client or server message. * @param payload an optional payload */ public static GraphQlWebSocketMessage pong(@Nullable Object payload) { return new GraphQlWebSocketMessage(null, GraphQlWebSocketMessageType.PONG, payload); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\GraphQlWebSocketMessage.java
1
请完成以下Java代码
public String getDiagramResourceName() { throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms"); } @Override public void setDiagramResourceName(String diagramResourceName) { throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms"); } @Override public Integer getHistoryTimeToLive() { throw new UnsupportedOperationException("history time to live not supported for Camunda Forms"); } @Override public void setHistoryTimeToLive(Integer historyTimeToLive) { throw new UnsupportedOperationException("history time to live not supported for Camunda Forms"); } @Override public Object getPersistentState() { // properties of this entity are immutable return CamundaFormDefinitionEntity.class;
} @Override public void updateModifiableFieldsFromEntity(CamundaFormDefinitionEntity updatingDefinition) { throw new UnsupportedOperationException("properties of Camunda Form Definitions are immutable"); } @Override public String getName() { throw new UnsupportedOperationException("name property not supported for Camunda Forms"); } @Override public void setName(String name) { throw new UnsupportedOperationException("name property not supported for Camunda Forms"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CamundaFormDefinitionEntity.java
1
请完成以下Java代码
public String getProcessEngineName() { return processEngineName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identityId == null) ? 0 : identityId.hashCode()); result = prime * result + ((processEngineName == null) ? 0 : processEngineName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null)
return false; if (getClass() != obj.getClass()) return false; Authentication other = (Authentication) obj; if (identityId == null) { if (other.identityId != null) return false; } else if (!identityId.equals(other.identityId)) return false; if (processEngineName == null) { if (other.processEngineName != null) return false; } else if (!processEngineName.equals(other.processEngineName)) return false; return true; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\Authentication.java
1
请完成以下Java代码
protected void writeTextContent(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write(" "); // add additional whitespace writer.write(textContent); } protected void writeStartTagOpen(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write("<"); writer.write(tagName); } protected void writeAttributes(HtmlWriteContext context) { StringWriter writer = context.getWriter(); for (Entry<String, String> attribute : attributes.entrySet()) { writer.write(" "); writer.write(attribute.getKey()); if(attribute.getValue() != null) { writer.write("=\""); String attributeValue = escapeQuotes(attribute.getValue()); writer.write(attributeValue); writer.write("\""); } } } protected String escapeQuotes(String attributeValue){ String escapedHtmlQuote = "&quot;"; String escapedJavaQuote = "\""; return attributeValue.replaceAll(escapedJavaQuote, escapedHtmlQuote); } protected void writeEndLine(HtmlWriteContext context) { StringWriter writer = context.getWriter();
writer.write("\n"); } protected void writeStartTagClose(HtmlWriteContext context) { StringWriter writer = context.getWriter(); if(isSelfClosing) { writer.write(" /"); } writer.write(">"); } protected void writeLeadingWhitespace(HtmlWriteContext context) { int stackSize = context.getElementStackSize(); StringWriter writer = context.getWriter(); for (int i = 0; i < stackSize; i++) { writer.write(" "); } } // builder ///////////////////////////////////// public HtmlElementWriter attribute(String name, String value) { attributes.put(name, value); return this; } public HtmlElementWriter textContent(String text) { if(isSelfClosing) { throw new IllegalStateException("Self-closing element cannot have text content."); } this.textContent = text; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlElementWriter.java
1
请在Spring Boot框架中完成以下Java代码
protected void sleep(long millisToWait) { if (millisToWait > 0) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("timer job acquisition thread for engine {} sleeping for {} millis", getEngineName(), millisToWait); } synchronized (MONITOR) { if (!isInterrupted) { isWaiting.set(true); lifecycleListener.startWaiting(getEngineName(), millisToWait); MONITOR.wait(millisToWait); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("timer job acquisition thread for engine {} woke up", getEngineName()); } } catch (InterruptedException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("timer job acquisition wait for engine {} interrupted", getEngineName()); } } finally { isWaiting.set(false); } } } protected String getEngineName() { return asyncExecutor.getJobServiceConfiguration().getEngineName(); } protected void unlockTimerJobs(Collection<TimerJobEntity> timerJobs) { try { if (!timerJobs.isEmpty()) { commandExecutor.execute(new UnlockTimerJobsCmd(timerJobs, asyncExecutor.getJobServiceConfiguration())); } } catch (Throwable e) {
if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed to unlock timer jobs during acquiring for engine {}. This is OK since they will be unlocked when the reset expired jobs thread runs", getEngineName(), e); } } } public void stop() { synchronized (MONITOR) { isInterrupted = true; if (isWaiting.compareAndSet(true, false)) { MONITOR.notifyAll(); } } } public void setConfiguration(AcquireJobsRunnableConfiguration configuration) { this.configuration = configuration; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AcquireTimerJobsRunnable.java
2
请完成以下Java代码
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set User Element 1. @param UserElement1_ID User defined accounting Element */ public void setUserElement1_ID (int UserElement1_ID) { if (UserElement1_ID < 1) set_Value (COLUMNNAME_UserElement1_ID, null); else set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID)); } /** Get User Element 1. @return User defined accounting Element */ public int getUserElement1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set User Element 2. @param UserElement2_ID User defined accounting Element */ public void setUserElement2_ID (int UserElement2_ID) { if (UserElement2_ID < 1) set_Value (COLUMNNAME_UserElement2_ID, null); else set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID)); } /** Get User Element 2. @return User defined accounting Element */ public int getUserElement2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_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_PA_ReportColumn.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param QtyEntered Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity Invoiced.
@param QtyInvoiced Invoiced Quantity */ public void setQtyInvoiced (BigDecimal QtyInvoiced) { set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Quantity Invoiced. @return Invoiced Quantity */ public BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java
1
请完成以下Java代码
public void setPathMatcher(PathMatcher pathMatcher) { this.pathMatcher = pathMatcher; } /* for testing */ void setIncludePort(boolean includePort) { this.includePort = includePort; } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList("patterns"); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST; } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { String host; if (includePort) { host = exchange.getRequest().getHeaders().getFirst("Host"); } else { InetSocketAddress address = exchange.getRequest().getHeaders().getHost(); if (address != null) { host = address.getHostString(); } else { return false; } } if (host == null) { return false; } String match = null; for (int i = 0; i < config.getPatterns().size(); i++) { String pattern = config.getPatterns().get(i); if (pathMatcher.match(pattern, host)) { match = pattern; break; } } if (match != null) {
Map<String, String> variables = pathMatcher.extractUriTemplateVariables(match, host); ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables); return true; } return false; } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Hosts: %s", config.getPatterns()); } }; } public static class Config { private List<String> patterns = new ArrayList<>(); public List<String> getPatterns() { return patterns; } public Config setPatterns(List<String> patterns) { this.patterns = patterns; return this; } @Override public String toString() { return new ToStringCreator(this).append("patterns", patterns).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HostRoutePredicateFactory.java
1
请完成以下Java代码
private void assignInventoryLinesToCounterIdentifiers(final List<I_M_InventoryLine> list, final char counterIdentifier) { list.forEach(inventoryLine -> { inventoryLine.setAssignedTo(Character.toString(counterIdentifier)); save(inventoryLine); }); } @Override public void setDefaultInternalChargeId(final I_M_InventoryLine inventoryLine) { final int defaultChargeId = getDefaultInternalChargeId(); inventoryLine.setC_Charge_ID(defaultChargeId);
} @Override public void markInventoryLinesAsCounted(@NonNull final InventoryId inventoryId) { inventoryDAO.retrieveLinesForInventoryId(inventoryId) .forEach(this::markInventoryLineAsCounted); } private void markInventoryLineAsCounted(final I_M_InventoryLine inventoryLine) { inventoryLine.setIsCounted(true); save(inventoryLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\impl\InventoryBL.java
1
请完成以下Java代码
public void setExportUser_ID (final int ExportUser_ID) { if (ExportUser_ID < 1) set_Value (COLUMNNAME_ExportUser_ID, null); else set_Value (COLUMNNAME_ExportUser_ID, ExportUser_ID); } @Override public int getExportUser_ID() { return get_ValueAsInt(COLUMNNAME_ExportUser_ID); } @Override public void setExternalSystem_ExportAudit_ID (final int ExternalSystem_ExportAudit_ID) { if (ExternalSystem_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, ExternalSystem_ExportAudit_ID); } @Override public int getExternalSystem_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ExportAudit_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID)
{ if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_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, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_ExportAudit.java
1
请完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getSourceCaseDefinitionId() { return sourceCaseDefinitionId; } public void setSourceCaseDefinitionId(String sourceCaseDefinitionId) { this.sourceCaseDefinitionId = sourceCaseDefinitionId; } public String getTargetCaseDefinitionId() { return targetCaseDefinitionId; } public void setTargetCaseDefinitionId(String targetCaseDefinitionId) { this.targetCaseDefinitionId = targetCaseDefinitionId; }
public String getMigrationMessage() { return migrationMessage; } public void setMigrationMessage(String migrationMessage) { this.migrationMessage = migrationMessage; } public String getMigrationStacktrace() { return migrationStacktrace; } public void setMigrationStacktrace(String migrationStacktrace) { this.migrationStacktrace = migrationStacktrace; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationPartResult.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<Foo> findListOfFoo() { return fooRepository.values(); } // API - read @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) throws HttpClientErrorException { Foo foo = fooRepository.get(id); if (foo == null) { throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } else { return foo; } } // API - write @RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { fooRepository.put(id, foo); return foo; } @RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { fooRepository.put(id, foo); return foo; } @RequestMapping(method = RequestMethod.POST, value = "/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResponseEntity<Foo> postFoo(@RequestBody final Foo foo) { fooRepository.put(foo.getId(), foo); final URI location = ServletUriComponentsBuilder .fromCurrentServletMapping() .path("/foos/{id}") .build() .expand(foo.getId()) .toUri(); final HttpHeaders headers = new HttpHeaders(); headers.setLocation(location); final ResponseEntity<Foo> entity = new ResponseEntity<Foo>(foo, headers, HttpStatus.CREATED); return entity; }
@RequestMapping(method = RequestMethod.HEAD, value = "/foos") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo headFoo() { return new Foo(1, randomAlphabetic(4)); } @RequestMapping(method = RequestMethod.POST, value = "/foos/new") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo createFoo(@RequestBody final Foo foo) { fooRepository.put(foo.getId(), foo); return foo; } @RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public long deleteFoo(@PathVariable final long id) { fooRepository.remove(id); return id; } @RequestMapping(method = RequestMethod.POST, value = "/foos/form", produces = MediaType.TEXT_PLAIN_VALUE) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public String submitFoo(@RequestParam("id") String id) { return id; } }
repos\tutorials-master\spring-web-modules\spring-resttemplate\src\main\java\com\baeldung\resttemplate\configuration\FooController.java
2
请完成以下Java代码
private String createInfoFieldName(@NonNull final DataEntryField dataEntryField) { return dataEntryWebuiTools.computeFieldName(dataEntryField.getId()) + "_Info"; } private static DetailId createDetailIdFor(@NonNull final DataEntryTab dataEntryTab) { return DetailId.fromPrefixAndId(I_DataEntry_Tab.Table_Name, dataEntryTab.getId().getRepoId()); } private static DetailId createDetailIdFor(@NonNull final DataEntrySubTab subTab) { return DetailId.fromPrefixAndId(I_DataEntry_SubTab.Table_Name, subTab.getId().getRepoId()); } private static DocumentFieldWidgetType ofFieldType(@NonNull final FieldType fieldType) { switch (fieldType) { case DATE: return DocumentFieldWidgetType.LocalDate; case LIST: return DocumentFieldWidgetType.List; case NUMBER: return DocumentFieldWidgetType.Number; case TEXT: return DocumentFieldWidgetType.Text;
case LONG_TEXT: return DocumentFieldWidgetType.LongText; case YESNO: return DocumentFieldWidgetType.YesNo; case CREATED_UPDATED_INFO: return DocumentFieldWidgetType.Text; case SUB_TAB_ID: return DocumentFieldWidgetType.Integer; case PARENT_LINK_ID: return DocumentFieldWidgetType.Integer; default: throw new AdempiereException("Unexpected DataEntryField.Type=" + fieldType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryTabLoader.java
1
请完成以下Java代码
public void setI_ErrorMsg (java.lang.String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import-Fehlermeldung. @return Meldungen, die durch den Importprozess generiert wurden */ @Override public java.lang.String getI_ErrorMsg () { return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg); } /** * I_IsImported AD_Reference_ID=540745 * Reference name: I_IsImported */ public static final int I_ISIMPORTED_AD_Reference_ID=540745; /** NotImported = N */ public static final String I_ISIMPORTED_NotImported = "N"; /** Imported = Y */ public static final String I_ISIMPORTED_Imported = "Y"; /** ImportFailed = E */ public static final String I_ISIMPORTED_ImportFailed = "E"; /** Set Importiert. @param I_IsImported Ist dieser Import verarbeitet worden? */ @Override public void setI_IsImported (java.lang.String I_IsImported) { set_Value (COLUMNNAME_I_IsImported, I_IsImported); } /** Get Importiert. @return Ist dieser Import verarbeitet worden? */ @Override public java.lang.String getI_IsImported () { return (java.lang.String)get_Value(COLUMNNAME_I_IsImported); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Datensatz-ID.
@param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Window Internal Name. @param WindowInternalName Window Internal Name */ @Override public void setWindowInternalName (java.lang.String WindowInternalName) { set_Value (COLUMNNAME_WindowInternalName, WindowInternalName); } /** Get Window Internal Name. @return Window Internal Name */ @Override public java.lang.String getWindowInternalName () { return (java.lang.String)get_Value(COLUMNNAME_WindowInternalName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_I_DataEntry_Record.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_EXP_Processor_Type[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Export Processor Type. @param EXP_Processor_Type_ID Export Processor Type */ public void setEXP_Processor_Type_ID (int EXP_Processor_Type_ID) { if (EXP_Processor_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, Integer.valueOf(EXP_Processor_Type_ID)); } /** Get Export Processor Type. @return Export Processor Type */ public int getEXP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Java Class. @param JavaClass Java Class */ public void setJavaClass (String JavaClass) {
set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */ public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); } /** 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); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor_Type.java
1
请在Spring Boot框架中完成以下Java代码
private SecurityWebFilterChain springSecurityFilterChain() { ServerHttpSecurity http = this.context.getBean(ServerHttpSecurity.class); return springSecurityFilterChain(http); } /** * The default {@link ServerHttpSecurity} configuration. * @param http * @return */ private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults()); http.formLogin(withDefaults()); } SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard {
static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请完成以下Java代码
public class CryptoUtils { public static SecretKey generateKey() throws GeneralSecurityException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(256); return keyGenerator.generateKey(); } public static SecretKey getKeyForText(String secretText) throws GeneralSecurityException { byte[] keyBytes = secretText.getBytes(StandardCharsets.UTF_8); return new SecretKeySpec(keyBytes, "AES"); } /* * Allows us to generate a deterministic key, for the purposes of producing * reliable and consistent demo code & tests! For a random key, consider using * the generateKey method above. */ public static SecretKey getFixedKey() throws GeneralSecurityException { String secretText = "BaeldungIsASuperCoolSite"; return getKeyForText(secretText); } public static IvParameterSpec getIV() { SecureRandom secureRandom = new SecureRandom(); byte[] iv = new byte[128 / 8]; byte[] nonce = new byte[96 / 8]; secureRandom.nextBytes(nonce); System.arraycopy(nonce, 0, iv, 0, nonce.length); return new IvParameterSpec(nonce); } public static IvParameterSpec getIVSecureRandom(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException { SecureRandom random = SecureRandom.getInstanceStrong(); byte[] iv = new byte[Cipher.getInstance(algorithm).getBlockSize()]; random.nextBytes(iv);
return new IvParameterSpec(iv); } public static IvParameterSpec getIVInternal(Cipher cipher) throws InvalidParameterSpecException { AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); return new IvParameterSpec(iv); } public static byte[] getRandomIVWithSize(int size) { byte[] nonce = new byte[size]; new SecureRandom().nextBytes(nonce); return nonce; } public static byte[] encryptWithPadding(SecretKey key, byte[] bytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherTextBytes = cipher.doFinal(bytes); return cipherTextBytes; } public static byte[] decryptWithPadding(SecretKey key, byte[] cipherTextBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(cipherTextBytes); } }
repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\utils\CryptoUtils.java
1
请完成以下Java代码
private String determineDisplayName(Version version) { StringBuilder sb = new StringBuilder(); sb.append(version.getMajor()).append(".").append(version.getMinor()).append(".").append(version.getPatch()); if (version.getQualifier() != null) { sb.append(determineSuffix(version.getQualifier())); } return sb.toString(); } private String determineSuffix(Qualifier qualifier) { String id = qualifier.getId(); if (id.equals("RELEASE")) { return ""; } StringBuilder sb = new StringBuilder(" ("); if (id.contains("SNAPSHOT")) { sb.append("SNAPSHOT"); } else { sb.append(id); if (qualifier.getVersion() != null) { sb.append(qualifier.getVersion()); } } sb.append(")"); return sb.toString(); }
private static final class VersionMetadataElementComparator implements Comparator<DefaultMetadataElement> { private static final VersionParser versionParser = VersionParser.DEFAULT; @Override public int compare(DefaultMetadataElement o1, DefaultMetadataElement o2) { Version o1Version = versionParser.parse(o1.getId()); Version o2Version = versionParser.parse(o2.getId()); return o1Version.compareTo(o2Version); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringBootMetadataReader.java
1
请完成以下Java代码
public synchronized <T> T convert(@NonNull final CaseConverter<T> converter) { if (initialHUQuery == null) { if (initialHUIds == null) { throw new IllegalStateException("initialHUIds shall not be null for " + this); } else if (initialHUIds.isAll()) { if (mustHUIds.isEmpty() && shallNotHUIds.isEmpty()) { return converter.acceptAll(); } else { return converter.acceptAllBut(ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } else { final ImmutableSet<HuId> fixedHUIds = Stream.concat( initialHUIds.stream(), mustHUIds.stream()) .distinct() .filter(huId -> !shallNotHUIds.contains(huId)) // not excluded .collect(ImmutableSet.toImmutableSet());
if (fixedHUIds.isEmpty()) { return converter.acceptNone(); } else { return converter.acceptOnly(HuIdsFilterList.of(fixedHUIds), ImmutableSet.copyOf(mustHUIds)); } } } else { return converter.huQuery(initialHUQuery.copy(), ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterData.java
1
请完成以下Java代码
public Optional<MachineInfo> getMachine(String ip, int port) { return machines.stream() .filter(e -> e.getIp().equals(ip) && e.getPort().equals(port)) .findFirst(); } private boolean heartbeatJudge(final int threshold) { if (machines.size() == 0) { return false; } if (threshold > 0) { long healthyCount = machines.stream() .filter(MachineInfo::isHealthy) .count(); if (healthyCount == 0) { // No healthy machines. return machines.stream() .max(Comparator.comparingLong(MachineInfo::getLastHeartbeat)) .map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold) .orElse(false); } } return true; } /** * Check whether current application has no healthy machines and should not be displayed. *
* @return true if the application should be displayed in the sidebar, otherwise false */ public boolean isShown() { return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis()); } /** * Check whether current application has no healthy machines and should be removed. * * @return true if the application is dead and should be removed, otherwise false */ public boolean isDead() { return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis()); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppInfo.java
1
请完成以下Java代码
public String getExplanation() { return explanation; } /** * Sets the value of the explanation property. * * @param value * allowed object is * {@link String } * */ public void setExplanation(String value) { this.explanation = value; } /** * Gets the value of the reimbursement property. * * @return * possible object is * {@link ReimbursementType } *
*/ public ReimbursementType getReimbursement() { return reimbursement; } /** * Sets the value of the reimbursement property. * * @param value * allowed object is * {@link ReimbursementType } * */ public void setReimbursement(ReimbursementType value) { this.reimbursement = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\AcceptedType.java
1
请完成以下Java代码
public String getPublicKey() { return RsaKeyHelper.encodePublicKey(this.publicKey, "application"); } @Override public String encrypt(String text) { return new String(Base64.getEncoder().encode(encrypt(text.getBytes(this.charset))), this.defaultCharset); } @Override public String decrypt(String encryptedText) { if (this.privateKey == null) { throw new IllegalStateException("Private key must be provided for decryption"); } return new String(decrypt(Base64.getDecoder().decode(encryptedText.getBytes(this.defaultCharset))), this.charset); } @Override public byte[] encrypt(byte[] byteArray) { return encrypt(byteArray, this.publicKey, this.algorithm); } @Override public byte[] decrypt(byte[] encryptedByteArray) { return decrypt(encryptedByteArray, this.privateKey, this.algorithm); } private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg) { ByteArrayOutputStream output = new ByteArrayOutputStream(text.length); try { final Cipher cipher = Cipher.getInstance(alg.getJceName()); int limit = Math.min(text.length, alg.getMaxLength()); int pos = 0; while (pos < text.length) { cipher.init(Cipher.ENCRYPT_MODE, key); cipher.update(text, pos, limit); pos += limit; limit = Math.min(text.length - pos, alg.getMaxLength()); byte[] buffer = cipher.doFinal(); output.write(buffer, 0, buffer.length); } return output.toByteArray(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Cannot encrypt", ex);
} } private static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) { ByteArrayOutputStream output = new ByteArrayOutputStream(text.length); try { final Cipher cipher = Cipher.getInstance(alg.getJceName()); int maxLength = getByteLength(key); int pos = 0; while (pos < text.length) { int limit = Math.min(text.length - pos, maxLength); cipher.init(Cipher.DECRYPT_MODE, key); cipher.update(text, pos, limit); pos += limit; byte[] buffer = cipher.doFinal(); output.write(buffer, 0, buffer.length); } return output.toByteArray(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Cannot decrypt", ex); } } // copied from sun.security.rsa.RSACore.getByteLength(java.math.BigInteger) public static int getByteLength(@Nullable RSAKey key) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } int n = key.getModulus().bitLength(); return (n + 7) >> 3; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaRawEncryptor.java
1
请在Spring Boot框架中完成以下Java代码
private SecurityContextRepository getSecurityContextRepository(H http) { SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class); if (securityContextRepository == null) { securityContextRepository = new HttpSessionSecurityContextRepository(); } return securityContextRepository; } private RequestMatcher getLogoutRequestMatcher(H http) { if (this.logoutRequestMatcher != null) { return this.logoutRequestMatcher; } this.logoutRequestMatcher = createLogoutRequestMatcher(http); return this.logoutRequestMatcher; }
@SuppressWarnings("unchecked") private RequestMatcher createLogoutRequestMatcher(H http) { RequestMatcher post = createLogoutRequestMatcher("POST"); if (http.getConfigurer(CsrfConfigurer.class) != null) { return post; } RequestMatcher get = createLogoutRequestMatcher("GET"); RequestMatcher put = createLogoutRequestMatcher("PUT"); RequestMatcher delete = createLogoutRequestMatcher("DELETE"); return new OrRequestMatcher(get, post, put, delete); } private RequestMatcher createLogoutRequestMatcher(String httpMethod) { return getRequestMatcherBuilder().matcher(HttpMethod.valueOf(httpMethod), this.logoutUrl); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\LogoutConfigurer.java
2
请完成以下Java代码
private OAuth2AuthorizationRequest deserialize(JsonParser parser, ObjectMapper mapper, JsonNode root) throws JsonParseException { AuthorizationGrantType authorizationGrantType = convertAuthorizationGrantType( JsonNodeUtils.findObjectNode(root, "authorizationGrantType")); Builder builder = getBuilder(parser, authorizationGrantType); builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri")); builder.clientId(JsonNodeUtils.findStringValue(root, "clientId")); builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri")); builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, mapper)); builder.state(JsonNodeUtils.findStringValue(root, "state")); builder.additionalParameters( JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, mapper)); builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri")); builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, mapper)); return builder.build(); } private Builder getBuilder(JsonParser parser, AuthorizationGrantType authorizationGrantType) throws JsonParseException {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) { return OAuth2AuthorizationRequest.authorizationCode(); } throw new JsonParseException(parser, "Invalid authorizationGrantType"); } private static AuthorizationGrantType convertAuthorizationGrantType(JsonNode jsonNode) { String value = JsonNodeUtils.findStringValue(jsonNode, "value"); if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) { return AuthorizationGrantType.AUTHORIZATION_CODE; } return null; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\jackson2\OAuth2AuthorizationRequestDeserializer.java
1
请完成以下Java代码
public class PhoneNumber { private int countryCode; private int cityCode; private int number; public PhoneNumber(int countryCode, int cityCode, int number) { this.countryCode = countryCode; this.cityCode = cityCode; this.number = number; } public int getCountryCode() { return countryCode; } public int getCityCode() { return cityCode; } public int getNumber() { return number; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhoneNumber that = (PhoneNumber) o; return countryCode == that.countryCode && cityCode == that.cityCode && number == that.number; } @Override public int hashCode() { return Objects.hash(countryCode, cityCode, number); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\PhoneNumber.java
1
请完成以下Java代码
private void setDunningGrace(final Iterator<I_C_Dunning_Candidate> it, final Timestamp dunningGrace) { while (it.hasNext()) { final I_C_Dunning_Candidate candidate = it.next(); setDunningGrace(candidate, dunningGrace); } } private void setDunningGrace(final I_C_Dunning_Candidate candidate, final Timestamp dunningGrace) { candidate.setDunningGrace(dunningGrace); // We want to make sure that model validators are triggered EVEN if the old DunningGrace value equals with new DunningGrace value markColumnChanged(candidate, I_C_Dunning_Candidate.COLUMNNAME_DunningGrace); save(candidate); } private Iterator<I_C_Dunning_Candidate> retrieveSelectionIterator() { final StringBuilder sqlWhere = new StringBuilder(); final List<Object> params = new ArrayList<>(); if (!Check.isEmpty(getProcessInfo().getWhereClause(), true)) { sqlWhere.append(getProcessInfo().getWhereClause()) .append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'"); // 03663 : Must make sure to take only unprocessed candidates.
} else { // We have no where clause. Assume all unprocessed candidates. sqlWhere.append(I_C_Dunning_Candidate.COLUMNNAME_IsActive + " = 'Y'") .append(" AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + " = 'N'"); } return new Query(getCtx(), I_C_Dunning_Candidate.Table_Name, sqlWhere.toString(), get_TrxName()) .setParameters(params) .setClient_ID() .setOnlyActiveRecords(true) .setRequiredAccess(Access.WRITE) .iterate(I_C_Dunning_Candidate.class, false); // guaranteed=false } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_SetDunningGrace.java
1
请在Spring Boot框架中完成以下Java代码
public boolean saveTenant(Tenant tenant) { if (Func.isEmpty(tenant.getId())) { List<Tenant> tenants = baseMapper.selectList(Wrappers.<Tenant>query().lambda().eq(Tenant::getIsDeleted, BladeConstant.DB_NOT_DELETED)); List<String> codes = tenants.stream().map(Tenant::getTenantId).collect(Collectors.toList()); String tenantId = getTenantId(codes); tenant.setTenantId(tenantId); // 新建租户对应的默认角色 Role role = new Role(); role.setTenantId(tenantId); role.setParentId(0L); role.setRoleName("管理员"); role.setRoleAlias("admin"); role.setSort(2); role.setIsDeleted(0); roleMapper.insert(role); // 新建租户对应的默认部门 Dept dept = new Dept(); dept.setTenantId(tenantId); dept.setParentId(0L); dept.setDeptName(tenant.getTenantName()); dept.setFullName(tenant.getTenantName()); dept.setSort(2); dept.setIsDeleted(0); deptMapper.insert(dept); // 新建租户对应的默认岗位 Post post = new Post(); post.setTenantId(tenantId); post.setCategory(1); post.setPostCode("ceo"); post.setPostName("首席执行官"); post.setSort(1); postService.save(post); // 新建租户对应的默认管理用户 User user = new User(); user.setTenantId(tenantId); user.setName("admin"); user.setRealName("admin"); user.setAccount("admin"); user.setPassword(DigestUtil.encrypt("admin"));
user.setRoleId(String.valueOf(role.getId())); user.setDeptId(String.valueOf(dept.getId())); user.setPostId(String.valueOf(post.getId())); user.setBirthday(new Date()); user.setSex(1); user.setIsDeleted(BladeConstant.DB_NOT_DELETED); boolean temp = super.saveOrUpdate(tenant); R<Boolean> result = userClient.saveUser(user); if (!result.isSuccess()) { throw new ServiceException(result.getMsg()); } return temp; } return super.saveOrUpdate(tenant); } private String getTenantId(List<String> codes) { String code = tenantId.generate(); if (codes.contains(code)) { return getTenantId(codes); } return code; } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\TenantServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Integer getQuickHowManyVisits() { try { TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager(); tm.begin(); Integer howManyVisits = transactionalCache.get(KEY); howManyVisits++; System.out.println("Ill try to set HowManyVisits to " + howManyVisits); StopWatch watch = new StopWatch(); watch.start(); transactionalCache.put(KEY, howManyVisits); watch.stop(); System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds"); tm.commit(); return howManyVisits; } catch (Exception e) { e.printStackTrace(); return 0;
} } public void startBackgroundBatch() { try { TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager(); tm.begin(); transactionalCache.put(KEY, 1000); System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction"); Thread.sleep(1000L); tm.rollback(); System.out.println("The slow batch suffered a rollback"); } catch (Exception e) { e.printStackTrace(); } } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\infinispan\service\TransactionalService.java
2
请完成以下Java代码
public abstract class StandardLayers implements Layers { /** * The dependencies layer. */ public static final Layer DEPENDENCIES = new Layer("dependencies"); /** * The spring boot loader layer. */ public static final Layer SPRING_BOOT_LOADER = new Layer("spring-boot-loader"); /** * The snapshot dependencies layer. */ public static final Layer SNAPSHOT_DEPENDENCIES = new Layer("snapshot-dependencies"); /** * The application layer. */ public static final Layer APPLICATION = new Layer("application"); private static final List<Layer> LAYERS; static {
List<Layer> layers = new ArrayList<>(); layers.add(DEPENDENCIES); layers.add(SPRING_BOOT_LOADER); layers.add(SNAPSHOT_DEPENDENCIES); layers.add(APPLICATION); LAYERS = Collections.unmodifiableList(layers); } @Override public Iterator<Layer> iterator() { return LAYERS.iterator(); } @Override public Stream<Layer> stream() { return LAYERS.stream(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\StandardLayers.java
1
请完成以下Java代码
public String toJsonString() {return groupId.getAsString() + SEPARATOR + value;} @NonNull public <T extends RepoIdAware> T getAsId(@NonNull final Class<T> type) {return RepoIdAwares.ofObject(value, type);} @NonNull public LocalDate getAsLocalDate() {return LocalDate.parse(value);} // NOTE: Quantity class is not accessible from this project :( @NonNull public ImmutablePair<BigDecimal, Integer> getAsQuantity() { try { final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value); if (parts.size() != 2) { throw new AdempiereException("Cannot get Quantity from " + this); } return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1))); } catch (AdempiereException ex) {
throw ex; } catch (final Exception ex) { throw new AdempiereException("Cannot get Quantity from " + this, ex); } } @NonNull public String getAsString() {return value;} @NonNull public <T> T deserializeTo(@NonNull final Class<T> targetClass) { return JSONObjectMapper.forClass(targetClass).readValue(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java
1
请完成以下Java代码
public JAXBElement<RetourenavisAnfragenResponse> createRetourenavisAnfragenResponse(RetourenavisAnfragenResponse value) { return new JAXBElement<RetourenavisAnfragenResponse>(_RetourenavisAnfragenResponse_QNAME, RetourenavisAnfragenResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RetourenavisAnkuendigen }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link RetourenavisAnkuendigen }{@code >} */ @XmlElementDecl(namespace = "urn:msv3:v2", name = "retourenavisAnkuendigen") public JAXBElement<RetourenavisAnkuendigen> createRetourenavisAnkuendigen(RetourenavisAnkuendigen value) { return new JAXBElement<RetourenavisAnkuendigen>(_RetourenavisAnkuendigen_QNAME, RetourenavisAnkuendigen.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RetourenavisAnkuendigenResponse }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link RetourenavisAnkuendigenResponse }{@code >} */ @XmlElementDecl(namespace = "urn:msv3:v2", name = "retourenavisAnkuendigenResponse") public JAXBElement<RetourenavisAnkuendigenResponse> createRetourenavisAnkuendigenResponse(RetourenavisAnkuendigenResponse value) { return new JAXBElement<RetourenavisAnkuendigenResponse>(_RetourenavisAnkuendigenResponse_QNAME, RetourenavisAnkuendigenResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DokumentAbfragen }{@code >} * * @param value * Java instance representing xml element's value. * @return
* the new instance of {@link JAXBElement }{@code <}{@link DokumentAbfragen }{@code >} */ @XmlElementDecl(namespace = "urn:msv3:v2", name = "dokumentAbfragen") public JAXBElement<DokumentAbfragen> createDokumentAbfragen(DokumentAbfragen value) { return new JAXBElement<DokumentAbfragen>(_DokumentAbfragen_QNAME, DokumentAbfragen.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DokumentAbfragenResponse }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link DokumentAbfragenResponse }{@code >} */ @XmlElementDecl(namespace = "urn:msv3:v2", name = "dokumentAbfragenResponse") public JAXBElement<DokumentAbfragenResponse> createDokumentAbfragenResponse(DokumentAbfragenResponse value) { return new JAXBElement<DokumentAbfragenResponse>(_DokumentAbfragenResponse_QNAME, DokumentAbfragenResponse.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\ObjectFactory.java
1
请完成以下Java代码
private void pickHU(@NonNull final HURow row) { final HuId huId = row.getHuId(); final PickRequest pickRequest = PickRequest.builder() .shipmentScheduleId(shipmentScheduleId) .pickFrom(PickFrom.ofHuId(huId)) .pickingSlotId(pickingSlotId) .build(); final ProcessPickingRequest.ProcessPickingRequestBuilder pickingRequestBuilder = ProcessPickingRequest.builder() .huIds(ImmutableSet.of(huId)) .shipmentScheduleId(shipmentScheduleId) .isTakeWholeHU(isTakeWholeHU); final IView view = getView(); if (view instanceof PPOrderLinesView) { final PPOrderLinesView ppOrderView = PPOrderLinesView.cast(view); pickingRequestBuilder.ppOrderId(ppOrderView.getPpOrderId());
} WEBUI_PP_Order_ProcessHelper.pickAndProcessSingleHU(pickRequest, pickingRequestBuilder.build()); } @Override protected void postProcess(final boolean success) { if (!success) { return; } invalidateView(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick.java
1
请完成以下Java代码
protected Object getAllocationRequestReferencedModel() { return getPP_Order(); } @Override protected IAllocationSource createAllocationSource() { final I_PP_Order ppOrder = getPP_Order(); return huPPOrderBL.createAllocationSourceForPPOrder(ppOrder); } @Override protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager() { final I_PP_Order ppOrder = getPP_Order(); return huPPOrderBL.createReceiptLUTUConfigurationManager(ppOrder); } @Override protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer() { final I_PP_Order order = getPP_Order(); final PPOrderId orderId = PPOrderId.ofRepoId(order.getPP_Order_ID()); final OrgId orgId = OrgId.ofRepoId(order.getAD_Org_ID()); return ReceiptCandidateRequestProducer.builder() .orderId(orderId) .orgId(orgId) .date(getMovementDate())
.locatorId(getLocatorId()) .pickingCandidateId(getPickingCandidateId()) .build(); } @Override protected void addAssignedHUs(final Collection<I_M_HU> hus) { final I_PP_Order ppOrder = getPP_Order(); huPPOrderBL.addAssignedHandlingUnits(ppOrder, hus); } @Override public IPPOrderReceiptHUProducer withPPOrderLocatorId() { return locatorId(LocatorId.ofRepoId(ppOrder.getM_Warehouse_ID(), ppOrder.getM_Locator_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateFinishedGoodsHUProducer.java
1
请在Spring Boot框架中完成以下Java代码
public void log(TransportProtos.DeviceStateServiceMsgProto msg) { totalCounter.increment(); deviceStateCounter.increment(); } public void log(TransportProtos.DeviceConnectProto msg) { totalCounter.increment(); deviceConnectsCounter.increment(); } public void log(TransportProtos.DeviceActivityProto msg) { totalCounter.increment(); deviceActivitiesCounter.increment(); } public void log(TransportProtos.DeviceDisconnectProto msg) { totalCounter.increment(); deviceDisconnectsCounter.increment(); } public void log(TransportProtos.DeviceInactivityProto msg) { totalCounter.increment(); deviceInactivitiesCounter.increment(); } public void log(TransportProtos.DeviceInactivityTimeoutUpdateProto msg) { totalCounter.increment(); deviceInactivityTimeoutUpdatesCounter.increment(); } public void log(TransportProtos.SubscriptionMgrMsgProto msg) { totalCounter.increment(); subscriptionMsgCounter.increment(); } public void log(TransportProtos.ToCoreNotificationMsg msg) { totalCounter.increment(); if (msg.hasToLocalSubscriptionServiceMsg()) { toCoreNfSubscriptionServiceCounter.increment(); } else if (msg.hasFromDeviceRpcResponse()) { toCoreNfDeviceRpcResponseCounter.increment(); } else if (msg.hasComponentLifecycle()) {
toCoreNfComponentLifecycleCounter.increment(); } else if (msg.getQueueUpdateMsgsCount() > 0) { toCoreNfQueueUpdateCounter.increment(); } else if (msg.getQueueDeleteMsgsCount() > 0) { toCoreNfQueueDeleteCounter.increment(); } else if (msg.hasVcResponseMsg()) { toCoreNfVersionControlResponseCounter.increment(); } else if (msg.hasToSubscriptionMgrMsg()) { toCoreNfSubscriptionManagerCounter.increment(); } else if (msg.hasNotificationRuleProcessorMsg()) { toCoreNfNotificationRuleProcessorCounter.increment(); } else { toCoreNfOtherCounter.increment(); } } public void printStats() { int total = totalCounter.get(); if (total > 0) { StringBuilder stats = new StringBuilder(); counters.forEach(counter -> stats.append(counter.getName()).append(" = [").append(counter.get()).append("] ")); log.info("Core Stats: {}", stats); } } public void reset() { counters.forEach(StatsCounter::clear); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbCoreConsumerStats.java
2
请完成以下Java代码
public static File zip(@NonNull final List<File> files) throws IOException { final File zipFile = File.createTempFile("ZIP", ".zip"); zipFile.deleteOnExit(); try (final FileOutputStream fileOutputStream = new FileOutputStream(zipFile); final ZipOutputStream zip = new ZipOutputStream(fileOutputStream)) { zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(Deflater.BEST_COMPRESSION); for (final File file : files) { addToZipFile(file, zip); } } return zipFile; } private static void addToZipFile(@NonNull final File file, @NonNull final ZipOutputStream zos) throws IOException { try (final FileInputStream fis = new FileInputStream(file)) { final ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); final byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length);
} zos.closeEntry(); } } /** * Java 8 implemention of Files.writeString */ public static void writeString(final Path path, final String content, final Charset charset, final OpenOption... options) throws IOException { final byte[] bytes = content.getBytes(charset); Files.write(path, bytes, options); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\FileUtil.java
1
请完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getAllowedOrigins() { if(enabled) { return allowedOrigins == null ? DEFAULT_ORIGINS : allowedOrigins; } return null; } public void setAllowedOrigins(String allowedOrigins) { this.allowedOrigins = allowedOrigins; } public boolean getAllowCredentials() { return allowCredentials; } public void setAllowCredentials(boolean allowCredentials) { this.allowCredentials = allowCredentials; } public String getAllowedHeaders() { return allowedHeaders; } public void setAllowedHeaders(String allowedHeaders) { this.allowedHeaders = allowedHeaders; }
public String getExposedHeaders() { return exposedHeaders; } public void setExposedHeaders(String exposedHeaders) { this.exposedHeaders = exposedHeaders; } public String getPreflightMaxAge() { return preflightMaxAge; } public void setPreflightMaxAge(String preflightMaxAge) { this.preflightMaxAge = preflightMaxAge; } @Override public String toString() { return "CamundaBpmRunCorsProperty [" + "enabled=" + enabled + ", allowCredentials=" + allowCredentials + ", allowedOrigins=" + allowedOrigins + ", allowedHeaders=" + allowedHeaders + ", exposedHeaders=" + exposedHeaders + ", preflightMaxAge=" + preflightMaxAge + ']'; } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunCorsProperty.java
1
请完成以下Java代码
public class DummyContentUtil { public static List<AppUser> generateDummyUsers() { List<AppUser> appUsers = new ArrayList<>(); BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); appUsers.add(new AppUser("Lionel Messi", "lionel@messi.com", passwordEncoder.encode("li1234"))); appUsers.add(new AppUser("Cristiano Ronaldo", "cristiano@ronaldo.com", passwordEncoder.encode("c1234"))); appUsers.add(new AppUser("Neymar Dos Santos", "neymar@neymar.com", passwordEncoder.encode("n1234"))); appUsers.add(new AppUser("Luiz Suarez", "luiz@suarez.com", passwordEncoder.encode("lu1234"))); appUsers.add(new AppUser("Andres Iniesta", "andres@iniesta.com", passwordEncoder.encode("a1234"))); appUsers.add(new AppUser("Ivan Rakitic", "ivan@rakitic.com", passwordEncoder.encode("i1234"))); appUsers.add(new AppUser("Ousman Dembele", "ousman@dembele.com", passwordEncoder.encode("o1234"))); appUsers.add(new AppUser("Sergio Busquet", "sergio@busquet.com", passwordEncoder.encode("s1234"))); appUsers.add(new AppUser("Gerard Pique", "gerard@pique.com", passwordEncoder.encode("g1234"))); appUsers.add(new AppUser("Ter Stergen", "ter@stergen.com", passwordEncoder.encode("t1234"))); return appUsers; } public static List<Tweet> generateDummyTweets(List<AppUser> users) { List<Tweet> tweets = new ArrayList<>(); Random random = new Random(); IntStream.range(0, 9) .sequential() .forEach(i -> { Tweet twt = new Tweet(String.format("Tweet %d", i), users.get(random.nextInt(users.size())) .getUsername()); twt.getLikes() .addAll(users.subList(0, random.nextInt(users.size())) .stream() .map(AppUser::getUsername)
.collect(Collectors.toSet())); tweets.add(twt); }); return tweets; } public static Collection<GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); GrantedAuthority grantedAuthority = new GrantedAuthority() { public String getAuthority() { return "ROLE_USER"; } }; grantedAuthorities.add(grantedAuthority); return grantedAuthorities; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\util\DummyContentUtil.java
1
请在Spring Boot框架中完成以下Java代码
static class SessionStompEndpointRegistry implements StompEndpointRegistry { private final WebMvcStompEndpointRegistry registry; private final HandshakeInterceptor interceptor; SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) { this.registry = registry; this.interceptor = interceptor; } @Override public StompWebSocketEndpointRegistration addEndpoint(String... paths) { StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths); endpoints.addInterceptors(this.interceptor); return endpoints; } @Override public void setOrder(int order) { this.registry.setOrder(order); } @Override
public void setUrlPathHelper(UrlPathHelper urlPathHelper) { this.registry.setUrlPathHelper(urlPathHelper); } @Override public WebMvcStompEndpointRegistry setErrorHandler(StompSubProtocolErrorHandler errorHandler) { return this.registry.setErrorHandler(errorHandler); } @Override public WebMvcStompEndpointRegistry setPreserveReceiveOrder(boolean preserveReceiveOrder) { return this.registry.setPreserveReceiveOrder(preserveReceiveOrder); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\config\annotation\AbstractSessionWebSocketMessageBrokerConfigurer.java
2
请完成以下Java代码
public int getM_Warehouse_ID() { if (m_M_Warehouse_ID <= 0) { final I_M_Locator loc = Services.get(IWarehouseDAO.class).getLocatorByRepoId(getM_Locator_ID()); m_M_Warehouse_ID = loc.getM_Warehouse_ID(); } return m_M_Warehouse_ID; } // getM_Warehouse_ID /** * String Representation * * @return info */
@Override public String toString() { final StringBuilder sb = new StringBuilder("MStorage[") .append("M_Locator_ID=").append(getM_Locator_ID()) .append(",M_Product_ID=").append(getM_Product_ID()) .append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID()) .append(": OnHand=").append(getQtyOnHand()) .append(",Reserved=").append(getQtyReserved()) .append(",Ordered=").append(getQtyOrdered()) .append("]"); return sb.toString(); } // toString } // MStorage
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MStorage.java
1
请完成以下Java代码
public AlarmId getId() { return super.getId(); } @Schema(description = "Timestamp of the alarm creation, in milliseconds", example = "1634058704567", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "status of the Alarm", example = "ACTIVE_UNACK", accessMode = Schema.AccessMode.READ_ONLY) public AlarmStatus getStatus() { return toStatus(cleared, acknowledged); }
public static AlarmStatus toStatus(boolean cleared, boolean acknowledged) { if (cleared) { return acknowledged ? AlarmStatus.CLEARED_ACK : AlarmStatus.CLEARED_UNACK; } else { return acknowledged ? AlarmStatus.ACTIVE_ACK : AlarmStatus.ACTIVE_UNACK; } } @JsonIgnore public DashboardId getDashboardId() { return Optional.ofNullable(getDetails()).map(details -> details.get("dashboardId")) .filter(JsonNode::isTextual).map(id -> new DashboardId(UUID.fromString(id.asText()))).orElse(null); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\Alarm.java
1