instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) { this.showSummaryOutput = showSummaryOutput; } public @Nullable UiService getUiService() { return this.uiService; } public void setUiService(@Nullable UiService uiService) { this.uiService = uiService; } public @Nullable Boolean getAnalyticsEnabled() { return this.analyticsEnabled; } public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) { this.analyticsEnabled = analyticsEnabled; } public @Nullable String getLicenseKey() { return this.licenseKey; } public void setLicenseKey(@Nullable String licenseKey) { this.licenseKey = licenseKey; } /** * Enumeration of types of summary to show. Values are the same as those on * {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum * is not used directly. */ public enum ShowSummary { /** * Do not show a summary. */ OFF, /** * Show a summary. */ SUMMARY, /** * Show a verbose summary. */ VERBOSE } /** * Enumeration of destinations to which the summary should be output. Values are the * same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards * compatibility, the Liquibase enum is not used directly. */ public enum ShowSummaryOutput { /** * Log the summary. */ LOG,
/** * Output the summary to the console. */ CONSOLE, /** * Log the summary and output it to the console. */ ALL } /** * Enumeration of types of UIService. Values are the same as those on * {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is * not used directly. */ public enum UiService { /** * Console-based UIService. */ CONSOLE, /** * Logging-based UIService. */ LOGGER } }
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java
2
请完成以下Java代码
public static ActivityInstanceEntityManager getActivityInstanceEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getActivityInstanceEntityManager(); } public static HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() { return getHistoricActivityInstanceEntityManager(getCommandContext()); } public static HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getHistoricActivityInstanceEntityManager(); } public static HistoryManager getHistoryManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getHistoryManager(); } public static HistoricDetailEntityManager getHistoricDetailEntityManager() { return getHistoricDetailEntityManager(getCommandContext()); } public static HistoricDetailEntityManager getHistoricDetailEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getHistoricDetailEntityManager(); } public static AttachmentEntityManager getAttachmentEntityManager() { return getAttachmentEntityManager(getCommandContext()); } public static AttachmentEntityManager getAttachmentEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getAttachmentEntityManager(); } public static EventLogEntryEntityManager getEventLogEntryEntityManager() { return getEventLogEntryEntityManager(getCommandContext()); } public static EventLogEntryEntityManager getEventLogEntryEntityManager(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getEventLogEntryEntityManager(); } public static FlowableEventDispatcher getEventDispatcher() { return getEventDispatcher(getCommandContext()); } public static FlowableEventDispatcher getEventDispatcher(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventDispatcher(); } public static FailedJobCommandFactory getFailedJobCommandFactory() { return getFailedJobCommandFactory(getCommandContext()); } public static FailedJobCommandFactory getFailedJobCommandFactory(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getFailedJobCommandFactory(); } public static ProcessInstanceHelper getProcessInstanceHelper() { return getProcessInstanceHelper(getCommandContext()); } public static ProcessInstanceHelper getProcessInstanceHelper(CommandContext commandContext) { return getProcessEngineConfiguration(commandContext).getProcessInstanceHelper(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CommandContextUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class AutoConfigurations extends Configurations implements Ordered { private static final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); private static final int ORDER = AutoConfigurationImportSelector.ORDER; static final AutoConfigurationReplacements replacements = AutoConfigurationReplacements .load(AutoConfiguration.class, null); private final UnaryOperator<String> replacementMapper; protected AutoConfigurations(Collection<Class<?>> classes) { this(replacements::replace, classes); } AutoConfigurations(UnaryOperator<String> replacementMapper, Collection<Class<?>> classes) { super(sorter(replacementMapper), classes, Class::getName); this.replacementMapper = replacementMapper; } private static UnaryOperator<Collection<Class<?>>> sorter(UnaryOperator<String> replacementMapper) { AutoConfigurationSorter sorter = new AutoConfigurationSorter(metadataReaderFactory, null, replacementMapper); return (classes) -> { List<String> names = classes.stream().map(Class::getName).map(replacementMapper::apply).toList(); List<String> sorted = sorter.getInPriorityOrder(names); return sorted.stream() .map((className) -> ClassUtils.resolveClassName(className, null)) .collect(Collectors.toCollection(ArrayList::new)); }; }
@Override public int getOrder() { return ORDER; } @Override protected AutoConfigurations merge(Set<Class<?>> mergedClasses) { return new AutoConfigurations(this.replacementMapper, mergedClasses); } public static AutoConfigurations of(Class<?>... classes) { return new AutoConfigurations(Arrays.asList(classes)); } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurations.java
2
请完成以下Java代码
public static <T extends ReactiveJwtDecoder> T fromIssuerLocation(String issuer) { Assert.hasText(issuer, "issuer cannot be empty"); Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils .getConfigurationForIssuerLocation(issuer); return (T) withProviderConfiguration(configuration, issuer); } /** * Build {@link ReactiveJwtDecoder} from <a href= * "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID * Provider Configuration Response</a> and * <a href="https://tools.ietf.org/html/rfc8414#section-3.2">Authorization Server * Metadata Response</a>. * @param configuration the configuration values * @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a> * @return {@link ReactiveJwtDecoder} */ private static ReactiveJwtDecoder withProviderConfiguration(Map<String, Object> configuration, String issuer) { JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer); OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer); String jwkSetUri = configuration.get("jwks_uri").toString(); NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri) .jwtProcessorCustomizer(ReactiveJwtDecoderProviderConfigurationUtils::addJWSAlgorithms) .build(); jwtDecoder.setJwtValidator(jwtValidator); return jwtDecoder; } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\ReactiveJwtDecoders.java
1
请完成以下Java代码
private @Nullable ThreadPoolTaskScheduler createTaskScheduler(String cleanupCron) { if (cleanupCron == null) { return null; } ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setThreadNamePrefix("spring-one-time-tokens-"); taskScheduler.initialize(); taskScheduler.schedule(this::cleanupExpiredTokens, new CronTrigger(cleanupCron)); return taskScheduler; } public void cleanupExpiredTokens() { List<SqlParameterValue> parameters = List .of(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(Instant.now()))); PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray()); int deletedCount = this.jdbcOperations.update(DELETE_ONE_TIME_TOKENS_BY_EXPIRY_TIME_QUERY, pss); if (this.logger.isDebugEnabled()) { this.logger.debug("Cleaned up " + deletedCount + " expired tokens"); } } @Override public void afterPropertiesSet() throws Exception { if (this.taskScheduler != null) { this.taskScheduler.afterPropertiesSet(); } } @Override public void destroy() throws Exception { if (this.taskScheduler != null) { this.taskScheduler.shutdown(); } } /** * Sets the {@link Clock} used when generating one-time token and checking token * expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * The default {@code Function} that maps {@link OneTimeToken} to a {@code List} of * {@link SqlParameterValue}. * * @author Max Batischev * @since 6.4 */ private static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) { List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue())); parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername())); parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt()))); return parameters; } } /** * The default {@link RowMapper} that maps the current row in * {@code java.sql.ResultSet} to {@link OneTimeToken}. * * @author Max Batischev * @since 6.4 */ private static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> { @Override public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException { String tokenValue = rs.getString("token_value"); String userName = rs.getString("username"); Instant expiresAt = rs.getTimestamp("expires_at").toInstant(); return new DefaultOneTimeToken(tokenValue, userName, expiresAt); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\JdbcOneTimeTokenService.java
1
请完成以下Java代码
public class InsertJsonData { private static final String URL = "jdbc:postgresql://localhost:5432/database_name"; private static final String USER = "username"; private static final String PASSWORD = "password"; public Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } public void insertUser(String name, JSONObject info) throws SQLException { String sql = "INSERT INTO users (name, info) VALUES (?, ?::jsonb)"; Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name); pstmt.setString(2, info.toString()); pstmt.executeUpdate(); System.out.println("Data inserted successfully."); } public static void main(String[] args) throws SQLException { JSONObject jsonInfo = new JSONObject(); jsonInfo.put("email", "john.doe@example.com"); jsonInfo.put("age", 30); jsonInfo.put("active", true); InsertJsonData insertJsonData = new InsertJsonData(); insertJsonData.insertUser("John Doe", jsonInfo); } }
repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\preparedstatement\InsertJsonData.java
1
请完成以下Java代码
public String helloSleuthNewSpan() throws InterruptedException { logger.info("New Span"); sleuthService.doSomeWorkNewSpan(); return "success"; } @GetMapping("/new-thread") public String helloSleuthNewThread() { logger.info("New Thread"); Runnable runnable = () -> { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("I'm inside the new thread - with a new span");
}; executor.execute(runnable); logger.info("I'm done - with the original span"); return "success"; } @GetMapping("/async") public String helloSleuthAsync() throws InterruptedException { logger.info("Before Async Method Call"); sleuthService.asyncMethod(); logger.info("After Async Method Call"); return "success"; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-sleuth\src\main\java\com\baeldung\spring\session\SleuthController.java
1
请完成以下Java代码
public void setIsOrdered (boolean IsOrdered) { set_Value (COLUMNNAME_IsOrdered, Boolean.valueOf(IsOrdered)); } /** Get Auftrag erteilt. @return Auftrag erteilt */ @Override public boolean isOrdered () { Object oo = get_Value(COLUMNNAME_IsOrdered); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { throw new IllegalArgumentException ("Phone is virtual column"); } /** Get Telefon. @return Beschreibt eine Telefon Nummer */ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Anrufdatum. @param PhonecallDate Anrufdatum */ @Override public void setPhonecallDate (java.sql.Timestamp PhonecallDate) { set_Value (COLUMNNAME_PhonecallDate, PhonecallDate); } /** Get Anrufdatum. @return Anrufdatum */ @Override public java.sql.Timestamp getPhonecallDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallDate); } /** Set Erreichbar bis. @param PhonecallTimeMax Erreichbar bis */ @Override public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax) { set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax); } /** Get Erreichbar bis. @return Erreichbar bis */ @Override public java.sql.Timestamp getPhonecallTimeMax () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax); } /** Set Erreichbar von. @param PhonecallTimeMin Erreichbar von */ @Override public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin) {
set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin); } /** Get Erreichbar von. @return Erreichbar von */ @Override public java.sql.Timestamp getPhonecallTimeMin () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin); } /** Set Kundenbetreuer. @param SalesRep_ID Kundenbetreuer */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Kundenbetreuer. @return Kundenbetreuer */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schedule.java
1
请完成以下Java代码
public void addImpression() { setActualImpression(getActualImpression()+1); if (getCurrentImpression()>=getMaxImpression()) setIsActive(false); save(); } /** * Get Next of this Category, this Procedure will return the next Ad in a category and expire it if needed * @param ctx Context * @param CM_Ad_Cat_ID Category * @param trxName Transaction * @return MAd */ public static MAd getNext(Properties ctx, int CM_Ad_Cat_ID, String trxName) { MAd thisAd = null; int [] thisAds = MAd.getAllIDs("CM_Ad","ActualImpression+StartImpression<MaxImpression AND CM_Ad_Cat_ID=" + CM_Ad_Cat_ID, trxName); if (thisAds!=null) { for (int i=0;i<thisAds.length;i++) { MAd tempAd = new MAd(ctx, thisAds[i], trxName); if (thisAd==null) thisAd = tempAd; if (tempAd.getCurrentImpression()<=thisAd.getCurrentImpression()) thisAd = tempAd;
} } if (thisAd!=null) thisAd.addImpression(); return thisAd; } /** * Add Click Record to Log */ public void addClick() { setActualClick(getActualClick()+1); if (getActualClick()>getMaxClick()) setIsActive(true); save(); } } // MAd
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAd.java
1
请完成以下Java代码
public void deleteAttachmentsByTaskCaseInstanceIds(List<String> caseInstanceIds) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("caseInstanceIds", caseInstanceIds); deleteAttachments(parameters); } protected void deleteAttachments(Map<String, Object> parameters) { getDbEntityManager().deletePreserveOrder(ByteArrayEntity.class, "deleteAttachmentByteArraysByIds", parameters); getDbEntityManager().deletePreserveOrder(AttachmentEntity.class, "deleteAttachmentByIds", parameters); } public Attachment findAttachmentByTaskIdAndAttachmentId(String taskId, String attachmentId) { checkHistoryEnabled(); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("taskId", taskId); parameters.put("id", attachmentId); return (AttachmentEntity) getDbEntityManager().selectOne("selectAttachmentByTaskIdAndAttachmentId", parameters); }
public DbOperation deleteAttachmentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(AttachmentEntity.class, "deleteAttachmentsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentManager.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "productid") private Long productId; @Column(name = "productname") private String productName; @Column(name = "stock") private Integer stock; @Column(name = "price") private BigDecimal price; public Product() { } public Product(Long productId, String productName, Integer stock, BigDecimal price) { this.productId = productId; this.productName = productName; this.stock = stock; this.price = price; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; }
public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\model\Product.java
2
请在Spring Boot框架中完成以下Java代码
public class TaskEventResource extends TaskBaseResource { @ApiOperation(value = "Get an event on a task", tags = { "Tasks" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the task and event were found and the event is returned."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have an event with the given ID.") }) @GetMapping(value = "/runtime/tasks/{taskId}/events/{eventId}", produces = "application/json") public EventResponse getEvent(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "eventId") @PathVariable("eventId") String eventId) { HistoricTaskInstance task = getHistoricTaskFromRequest(taskId); Event event = taskService.getEvent(eventId); if (event == null || !task.getId().equals(event.getTaskId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an event with id '" + eventId + "'.", Event.class); } return restResponseFactory.createEventResponse(event); } @ApiOperation(value = "Delete an event on a task", tags = { "Tasks" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the task was found and the events are returned."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have the requested event.")
}) @DeleteMapping(value = "/runtime/tasks/{taskId}/events/{eventId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteEvent(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "eventId") @PathVariable("eventId") String eventId) { // Check if task exists Task task = getTaskFromRequestWithoutAccessCheck(taskId); Event event = taskService.getEvent(eventId); if (event == null || event.getTaskId() == null || !event.getTaskId().equals(task.getId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an event with id '" + event + "'.", Event.class); } if (restApiInterceptor != null) { restApiInterceptor.deleteTaskEvent(task, event); } taskService.deleteComment(eventId); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskEventResource.java
2
请完成以下Java代码
public int getC_Phonecall_Schema_Version_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Phonecall_Schema_Version_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Erreichbar bis. @param PhonecallTimeMax Erreichbar bis */ @Override public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax) { set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax); } /** Get Erreichbar bis. @return Erreichbar bis */ @Override public java.sql.Timestamp getPhonecallTimeMax () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax); } /** Set Erreichbar von. @param PhonecallTimeMin Erreichbar von */ @Override public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin) { set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin); }
/** Get Erreichbar von. @return Erreichbar von */ @Override public java.sql.Timestamp getPhonecallTimeMin () { return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schema_Version_Line.java
1
请完成以下Java代码
public boolean isMainProduct() { return getTrxType() == PPOrderCostTrxType.MainProduct; } public boolean isCoProduct() { return getTrxType().isCoProduct(); } public boolean isByProduct() { return getTrxType() == PPOrderCostTrxType.ByProduct; } @NonNull public PPOrderCost addingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { if (amt.isZero() && qty.isZero()) { return this; } final boolean amtIsPositiveOrZero = amt.signum() >= 0; final boolean amtIsNotZero = amt.signum() != 0; final boolean qtyIsPositiveOrZero = qty.signum() >= 0; if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero ) { throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty); } final Quantity accumulatedQty = getAccumulatedQty(); final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId()); return toBuilder() .accumulatedAmount(getAccumulatedAmount().add(amt)) .accumulatedQty(accumulatedQty.add(qtyConv)) .build(); } public PPOrderCost subtractingAccumulatedAmountAndQty( @NonNull final CostAmount amt,
@NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter); } public PPOrderCost withPrice(@NonNull final CostPrice newPrice) { if (this.getPrice().equals(newPrice)) { return this; } return toBuilder().price(newPrice).build(); } /* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount) { this.postCalculationAmount = postCalculationAmount; } /* package */void setPostCalculationAmountAsAccumulatedAmt() { setPostCalculationAmount(getAccumulatedAmount()); } /* package */void setPostCalculationAmountAsZero() { setPostCalculationAmount(getPostCalculationAmount().toZero()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java
1
请在Spring Boot框架中完成以下Java代码
public void handleParentChanged(@NonNull final HandleParentChangedRequest request) { if (request.getCurrentParentId() != null) { final IssueHierarchy issueHierarchy = issueRepository.buildUpStreamIssueHierarchy(request.getCurrentParentId()); issueHierarchy .getUpStreamForId(request.getCurrentParentId()) .forEach(issue -> { issue.addAggregatedEffort(request.getCurrentAggregatedEffort()); issue.addInvoiceableChildEffort(request.getCurrentInvoicableEffort()); recomputeLatestActivityOnSubIssues(issue); issueRepository.save(issue); } ); } if (request.getOldParentId() != null) { final IssueHierarchy issueHierarchy = issueRepository.buildUpStreamIssueHierarchy(request.getOldParentId()); issueHierarchy.getUpStreamForId(request.getOldParentId()) .forEach(oldParent -> { if (request.getOldAggregatedEffort() != null) { oldParent.addAggregatedEffort(request.getOldAggregatedEffort().negate()); } if (request.getOldInvoicableEffort() != null) { oldParent.addInvoiceableChildEffort(request.getOldInvoicableEffort().negate()); } recomputeLatestActivityOnSubIssues(oldParent); issueRepository.save(oldParent); }); } } public void addIssueProgress(@NonNull final AddIssueProgressRequest request) { final IssueEntity issueEntity = issueRepository.getById(request.getIssueId()); issueEntity.addIssueEffort(request.getBookedEffort()); issueEntity.addAggregatedEffort(request.getBookedEffort()); recomputeLatestActivityOnIssue(issueEntity); issueRepository.save(issueEntity); if(issueEntity.getParentIssueId() != null) { issueRepository .buildUpStreamIssueHierarchy(issueEntity.getParentIssueId()) .getUpStreamForId(issueEntity.getParentIssueId())
.forEach(parentIssue -> { parentIssue.addAggregatedEffort(request.getBookedEffort()); recomputeLatestActivityOnSubIssues(parentIssue); issueRepository.save(parentIssue); }); } } private void recomputeLatestActivityOnSubIssues(@NonNull final IssueEntity issueEntity) { final ImmutableList<IssueEntity> subIssues = issueRepository.getDirectlyLinkedSubIssues(issueEntity.getIssueId()); final Instant mostRecentActivity = subIssues .stream() .map(IssueEntity::getLatestActivity) .filter(Objects::nonNull) .max(Instant::compareTo) .orElse(null); issueEntity.setLatestActivityOnSubIssues(mostRecentActivity); } private void recomputeLatestActivityOnIssue(@NonNull final IssueEntity issueEntity) { final ImmutableList<TimeBooking> timeBookings = timeBookingRepository.getAllByIssueId(issueEntity.getIssueId()); final Instant latestActivityDate = timeBookings.stream() .map(TimeBooking::getBookedDate) .max(Instant::compareTo) .orElse(null); issueEntity.setLatestActivityOnIssue(latestActivityDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\IssueService.java
2
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * Enable authentication with three in-memory users: UserA, UserB and UserC. * * Spring Security will provide a default login form where insert username * and password. */ @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth // Defines three users with their passwords and roles .inMemoryAuthentication() .withUser("UserA").password("UserA").roles("USER") .and() .withUser("UserB").password("UserB").roles("USER") .and() .withUser("UserC").password("UserC").roles("USER"); return; }
/** * Disable CSRF protection (to simplify this demo) and enable the default * login form. */ @Override protected void configure(HttpSecurity http) throws Exception { http // Disable CSRF protection .csrf().disable() // Set default configurations from Spring Security .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); return; } } // class WebSecurityConfig
repos\spring-boot-samples-master\spring-boot-web-socket-user-notifications\src\main\java\netgloo\configs\WebSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
static class StandaloneEngineConfiguration extends BaseEngineConfigurationWithConfigurers<SpringProcessEngineConfiguration> { @Bean public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) throws Exception { ProcessEngineFactoryBean processEngineFactoryBean = new ProcessEngineFactoryBean(); processEngineFactoryBean.setProcessEngineConfiguration(configuration); invokeConfigurers(configuration); return processEngineFactoryBean; } } @Bean @ConditionalOnMissingBean public RuntimeService runtimeServiceBean(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } @Bean @ConditionalOnMissingBean public RepositoryService repositoryServiceBean(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } @Bean @ConditionalOnMissingBean public TaskService taskServiceBean(ProcessEngine processEngine) { return processEngine.getTaskService(); } @Bean @ConditionalOnMissingBean public HistoryService historyServiceBean(ProcessEngine processEngine) { return processEngine.getHistoryService(); } @Bean
@ConditionalOnMissingBean public ManagementService managementServiceBean(ProcessEngine processEngine) { return processEngine.getManagementService(); } @Bean @ConditionalOnMissingBean public DynamicBpmnService dynamicBpmnServiceBean(ProcessEngine processEngine) { return processEngine.getDynamicBpmnService(); } @Bean @ConditionalOnMissingBean public ProcessMigrationService processInstanceMigrationService(ProcessEngine processEngine) { return processEngine.getProcessMigrationService(); } @Bean @ConditionalOnMissingBean public FormService formServiceBean(ProcessEngine processEngine) { return processEngine.getFormService(); } @Bean @ConditionalOnMissingBean public IdentityService identityServiceBean(ProcessEngine processEngine) { return processEngine.getIdentityService(); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ProcessEngineServicesAutoConfiguration.java
2
请完成以下Java代码
public class AdminUserDetails implements UserDetails { private UmsAdmin umsAdmin; public AdminUserDetails(UmsAdmin umsAdmin) { this.umsAdmin = umsAdmin; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { //返回当前用户的权限 return Arrays.asList(new SimpleGrantedAuthority("TEST")); } @Override public String getPassword() { return umsAdmin.getPassword(); } @Override public String getUsername() { return umsAdmin.getUsername();
} @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\bo\AdminUserDetails.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getHandshakeTimeout() { return handshakeTimeout; } public void setHandshakeTimeout(Duration handshakeTimeout) { this.handshakeTimeout = handshakeTimeout; } public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout; } public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength;
} public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class AlipayService { @Autowired private AlipayConfig alipayConfig; public String createOrder(String outTradeNo, String totalAmount, String subject) throws AlipayApiException { AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json", "UTF-8", alipayConfig.getAlipayPublicKey(), "RSA2"); AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\",\"total_amount\":\"" + totalAmount + "\",\"subject\":\"" + subject + "\"}"); request.setNotifyUrl(alipayConfig.getNotifyUrl()); request.setReturnUrl(alipayConfig.getReturnUrl()); try { AlipayTradePrecreateResponse response = alipayClient.execute(request); if (response.isSuccess()) { return response.getQrCode(); // 返回二维码链接 } else { return "创建支付失败: " + response.getMsg(); } } catch (AlipayApiException e) { e.printStackTrace(); return "异常: " + e.getMessage();
} } public String queryPayment(String outTradeNo) { AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json", "UTF-8", alipayConfig.getAlipayPublicKey(), "RSA2"); AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"}"); try { AlipayTradeQueryResponse response = alipayClient.execute(request); if (response.isSuccess()) { return response.getTradeStatus(); // 返回订单状态 } else { return "查询失败: " + response.getMsg(); } } catch (AlipayApiException e) { e.printStackTrace(); return "异常: " + e.getMessage(); } } }
repos\springboot-demo-master\Alipay-facetoface\src\main\java\com\et\service\AlipayService.java
2
请完成以下Java代码
public int getM_HU_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Attribute_ID); } @Override public void setM_HU_Attribute_Snapshot_ID (final int M_HU_Attribute_Snapshot_ID) { if (M_HU_Attribute_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Attribute_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Attribute_Snapshot_ID, M_HU_Attribute_Snapshot_ID); } @Override public int getM_HU_Attribute_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Attribute_Snapshot_ID); } @Override public de.metas.handlingunits.model.I_M_HU getM_HU() { return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID) { if (M_HU_PI_Attribute_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID); } @Override public int getM_HU_PI_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID); } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); }
@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); } @Override public void setValueInitial (final @Nullable java.lang.String ValueInitial) { set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial); } @Override public java.lang.String getValueInitial() { return get_ValueAsString(COLUMNNAME_ValueInitial); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial) { set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial); } @Override public BigDecimal getValueNumberInitial() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial); 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_Attribute_Snapshot.java
1
请完成以下Java代码
public void setQtyOutgoing (java.math.BigDecimal QtyOutgoing) { set_Value (COLUMNNAME_QtyOutgoing, QtyOutgoing); } /** Get QtyOutgoing. @return QtyOutgoing */ @Override public java.math.BigDecimal getQtyOutgoing () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOutgoing); if (bd == null) return Env.ZERO; return bd; } /** Set ResetDate. @param ResetDate ResetDate */ @Override public void setResetDate (java.sql.Timestamp ResetDate) { set_Value (COLUMNNAME_ResetDate, ResetDate); } /** Get ResetDate. @return ResetDate */ @Override
public java.sql.Timestamp getResetDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ResetDate); } /** Set ResetDateEffective. @param ResetDateEffective ResetDateEffective */ @Override public void setResetDateEffective (java.sql.Timestamp ResetDateEffective) { set_Value (COLUMNNAME_ResetDateEffective, ResetDateEffective); } /** Get ResetDateEffective. @return ResetDateEffective */ @Override public java.sql.Timestamp getResetDateEffective () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ResetDateEffective); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inout\model\X_M_Material_Balance_Detail.java
1
请完成以下Java代码
public class PvmAtomicOperationActivityInitStack implements PvmAtomicOperation { protected PvmAtomicOperation operationOnScopeInitialization; public PvmAtomicOperationActivityInitStack(PvmAtomicOperation operationOnScopeInitialization) { this.operationOnScopeInitialization = operationOnScopeInitialization; } public String getCanonicalName() { return "activity-stack-init"; } public void execute(PvmExecutionImpl execution) { ScopeInstantiationContext executionStartContext = execution.getScopeInstantiationContext(); InstantiationStack instantiationStack = executionStartContext.getInstantiationStack(); List<PvmActivity> activityStack = instantiationStack.getActivities(); PvmActivity currentActivity = activityStack.remove(0); PvmExecutionImpl propagatingExecution = execution; if (currentActivity.isScope()) { propagatingExecution = execution.createExecution(); execution.setActive(false);
propagatingExecution.setActivity(currentActivity); propagatingExecution.initialize(); } else { propagatingExecution.setActivity(currentActivity); } // notify listeners for the instantiated activity propagatingExecution.performOperation(operationOnScopeInitialization); } public boolean isAsync(PvmExecutionImpl instance) { return false; } public PvmExecutionImpl getStartContextExecution(PvmExecutionImpl execution) { return execution; } public boolean isAsyncCapable() { return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInitStack.java
1
请完成以下Java代码
public de.metas.handlingunits.model.I_M_HU getM_HU() { return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Source_HU_ID (final int M_Source_HU_ID) { if (M_Source_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Source_HU_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_Source_HU_ID, M_Source_HU_ID); } @Override public int getM_Source_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_Source_HU_ID); } @Override public void setPreDestroy_Snapshot_UUID (final @Nullable java.lang.String PreDestroy_Snapshot_UUID) { set_Value (COLUMNNAME_PreDestroy_Snapshot_UUID, PreDestroy_Snapshot_UUID); } @Override public java.lang.String getPreDestroy_Snapshot_UUID() { return get_ValueAsString(COLUMNNAME_PreDestroy_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Source_HU.java
1
请完成以下Java代码
public static void concatByFormatBy100(Blackhole blackhole) { concatByFormat(FORMAT_STR_100, DATA_100, blackhole); } @Benchmark public static void concatByFormatBy1000(Blackhole blackhole) { concatByFormat(FORMAT_STR_1000, DATA_1000, blackhole); } @Benchmark public static void concatByFormatBy10000(Blackhole blackhole) { concatByFormat(FORMAT_STR_10000, DATA_10000, blackhole); } public static void concatByFormat(String formatStr, String[] data, Blackhole blackhole) { String concatString = String.format(formatStr, data); blackhole.consume(concatString); } @Benchmark public static void concatByStreamBy100(Blackhole blackhole) { concatByStream(DATA_100, blackhole); } @Benchmark public static void concatByStreamBy1000(Blackhole blackhole) { concatByStream(DATA_1000, blackhole); } @Benchmark public static void concatByStreamBy10000(Blackhole blackhole) { concatByStream(DATA_10000, blackhole); } public static void concatByStream(String[] data, Blackhole blackhole) {
String concatString = ""; List<String> strList = List.of(data); concatString = strList.stream().collect(Collectors.joining("")); blackhole.consume(concatString); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(BatchConcatBenchmark.class.getSimpleName()).threads(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\performance\BatchConcatBenchmark.java
1
请完成以下Java代码
public int compare(Map.Entry<E, Integer> o1, Map.Entry<E, Integer> o2) { return -o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<E, Integer> entry : entries) { sb.append(entry.getKey()); sb.append(' '); sb.append(entry.getValue()); sb.append(' '); } return sb.toString(); } public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param) {
if (param == null) return null; String[] array = param.split(" "); return create(array); } @SuppressWarnings("unchecked") public static Map.Entry<String, Map.Entry<String, Integer>[]> create(String param[]) { if (param.length % 2 == 0) return null; int natureCount = (param.length - 1) / 2; Map.Entry<String, Integer>[] entries = (Map.Entry<String, Integer>[]) Array.newInstance(Map.Entry.class, natureCount); for (int i = 0; i < natureCount; ++i) { entries[i] = new AbstractMap.SimpleEntry<String, Integer>(param[1 + 2 * i], Integer.parseInt(param[2 + 2 * i])); } return new AbstractMap.SimpleEntry<String, Map.Entry<String, Integer>[]>(param[0], entries); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\EnumItem.java
1
请完成以下Java代码
private @NonNull <T> Iterable<T> asIterable(@NonNull Iterator<T> iterator) { return () -> iterator; } // TODO configure via an SPI private JsonToPdxConverter newJsonToPdxConverter() { return new JSONFormatterJsonToPdxConverter(); } // TODO configure via an SPI private ObjectMapper newObjectMapper() { return new ObjectMapper(); } /** * Returns a reference to the configured {@link JsonToPdxConverter} used to convert from a single object, * {@literal JSON} {@link String} to PDX (i.e. as a {@link PdxInstance}. * * @return a reference to the configured {@link JsonToPdxConverter}; never {@literal null}. * @see org.springframework.geode.data.json.converter.JsonToPdxConverter */ protected @NonNull JsonToPdxConverter getJsonToPdxConverter() { return this.converter; } /** * Returns a reference to the configured Jackson {@link ObjectMapper}. * * @return a reference to the configured Jackson {@link ObjectMapper}; never {@literal null}. * @see com.fasterxml.jackson.databind.ObjectMapper */ protected @NonNull ObjectMapper getObjectMapper() { return this.objectMapper; } /** * Converts the given {@link String JSON} containing multiple objects into an array of {@link PdxInstance} objects. * * @param json {@link String JSON} data to convert. * @return an array of {@link PdxInstance} objects from the given {@link String JSON}. * @throws IllegalStateException if the {@link String JSON} does not start with * either a JSON array or a JSON object. * @see org.apache.geode.pdx.PdxInstance */ @Nullable @Override public PdxInstance[] convert(String json) { try { JsonNode jsonNode = getObjectMapper().readTree(json); List<PdxInstance> pdxList = new ArrayList<>(); if (isArray(jsonNode)) { ArrayNode arrayNode = (ArrayNode) jsonNode; JsonToPdxConverter converter = getJsonToPdxConverter();
for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) { pdxList.add(converter.convert(object.toString())); } } else if (isObject(jsonNode)) { ObjectNode objectNode = (ObjectNode) jsonNode; pdxList.add(getJsonToPdxConverter().convert(objectNode.toString())); } else { String message = String.format("Unable to process JSON node of type [%s];" + " expected either an [%s] or an [%s]", jsonNode.getNodeType(), JsonNodeType.OBJECT, JsonNodeType.ARRAY); throw new IllegalStateException(message); } return pdxList.toArray(new PdxInstance[0]); } catch (JsonProcessingException cause) { throw new DataRetrievalFailureException("Failed to read JSON content", cause); } } private boolean isArray(@Nullable JsonNode node) { return node != null && (node.isArray() || JsonNodeType.ARRAY.equals(node.getNodeType())); } private boolean isObject(@Nullable JsonNode node) { return node != null && (node.isObject() || JsonNodeType.OBJECT.equals(node.getNodeType())); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToPdxConverter.java
1
请在Spring Boot框架中完成以下Java代码
private synchronized String getEmail(String emailUrl, String oauth2Token) { restTemplateBuilder = restTemplateBuilder.defaultHeader(AUTHORIZATION, "token " + oauth2Token); RestTemplate restTemplate = restTemplateBuilder.build(); GithubEmailsResponse githubEmailsResponse; try { githubEmailsResponse = restTemplate.getForEntity(emailUrl, GithubEmailsResponse.class).getBody(); if (githubEmailsResponse == null){ throw new RuntimeException("Empty Github response!"); } } catch (Exception e) { log.error("There was an error during connection to Github API", e); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } Optional<String> emailOpt = githubEmailsResponse.stream() .filter(GithubEmailResponse::isPrimary) .map(GithubEmailResponse::getEmail) .findAny(); if (emailOpt.isPresent()){ return emailOpt.get();
} else { log.error("Could not find primary email from {}.", githubEmailsResponse); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } } private static class GithubEmailsResponse extends ArrayList<GithubEmailResponse> {} @Data @ToString private static class GithubEmailResponse { private String email; private boolean verified; private boolean primary; private String visibility; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\GithubOAuth2ClientMapper.java
2
请在Spring Boot框架中完成以下Java代码
public void save(User user) { if (userMapper.findById(user.getId()) == null) { userMapper.insert(user); } else { userMapper.update(user); } } @Override public Optional<User> findById(String id) { return Optional.ofNullable(userMapper.findById(id)); } @Override public Optional<User> findByUsername(String username) { return Optional.ofNullable(userMapper.findByUsername(username)); } @Override public Optional<User> findByEmail(String email) {
return Optional.ofNullable(userMapper.findByEmail(email)); } @Override public void saveRelation(FollowRelation followRelation) { if (!findRelation(followRelation.getUserId(), followRelation.getTargetId()).isPresent()) { userMapper.saveRelation(followRelation); } } @Override public Optional<FollowRelation> findRelation(String userId, String targetId) { return Optional.ofNullable(userMapper.findRelation(userId, targetId)); } @Override public void removeRelation(FollowRelation followRelation) { userMapper.deleteRelation(followRelation); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\infrastructure\repository\MyBatisUserRepository.java
2
请完成以下Java代码
final class DPoPProofVerifier { private static final JwtDecoderFactory<DPoPProofContext> dPoPProofVerifierFactory = new DPoPProofJwtDecoderFactory(); private DPoPProofVerifier() { } static Jwt verifyIfAvailable(OAuth2AuthorizationGrantAuthenticationToken authorizationGrantAuthentication) { String dPoPProof = (String) authorizationGrantAuthentication.getAdditionalParameters().get("dpop_proof"); if (!StringUtils.hasText(dPoPProof)) { return null; } String method = (String) authorizationGrantAuthentication.getAdditionalParameters().get("dpop_method"); String targetUri = (String) authorizationGrantAuthentication.getAdditionalParameters().get("dpop_target_uri"); Jwt dPoPProofJwt;
try { // @formatter:off DPoPProofContext dPoPProofContext = DPoPProofContext.withDPoPProof(dPoPProof) .method(method) .targetUri(targetUri) .build(); // @formatter:on JwtDecoder dPoPProofVerifier = dPoPProofVerifierFactory.createDecoder(dPoPProofContext); dPoPProofJwt = dPoPProofVerifier.decode(dPoPProof); } catch (Exception ex) { throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF), ex); } return dPoPProofJwt; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\DPoPProofVerifier.java
1
请完成以下Java代码
public static List<Map<String, Object>> findListByHash(final String dbKey, String sql, HashMap<String, Object> data) { List<Map<String, Object>> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); list = namedParameterJdbcTemplate.queryForList(sql, data); return list; } /** * 此方法只能返回单列,不能返回实体类 * @param dbKey 数据源的key * @param sql sal * @param clazz 类 * @param param 参数 * @param <T> * @return */ public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz, Object... param) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); if (ArrayUtils.isEmpty(param)) { list = jdbcTemplate.queryForList(sql, clazz); } else { list = jdbcTemplate.queryForList(sql, clazz, param); } return list; } /** * 支持miniDao语法操作的查询 返回单列数据list * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 类型Long、String等 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); list = namedParameterJdbcTemplate.queryForList(sql, data, clazz); return list; } /** * 直接sql查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持 minidao 语法逻辑 * @param clazz 返回实体类列表的class * @param param sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntities(final String dbKey, String sql, Class<T> clazz, Object... param) { List<Map<String, Object>> queryList = findList(dbKey, sql, param); return ReflectHelper.transList2Entrys(queryList, clazz); } /** * 支持miniDao语法操作的查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 返回实体类列表的class * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntitiesByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<Map<String, Object>> queryList = findListByHash(dbKey, sql, data); return ReflectHelper.transList2Entrys(queryList, clazz); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DynamicDBUtil.java
1
请在Spring Boot框架中完成以下Java代码
public static class RouteCacheConfiguration implements HasRouteId { private @Nullable DataSize size; private @Nullable Duration timeToLive; private @Nullable String routeId; public @Nullable DataSize getSize() { return size; } public RouteCacheConfiguration setSize(@Nullable DataSize size) { this.size = size; return this; } public @Nullable Duration getTimeToLive() { return timeToLive; }
public RouteCacheConfiguration setTimeToLive(@Nullable Duration timeToLive) { this.timeToLive = timeToLive; return this; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override public @Nullable String getRouteId() { return this.routeId; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheGatewayFilterFactory.java
2
请完成以下Java代码
public static <S, T> void addCollectionToMapOfSets(Map<S, Set<T>> map, S key, Collection<T> values) { Set<T> set = map.get(key); if (set == null) { set = new HashSet<>(); map.put(key, set); } set.addAll(values); } /** * Chops a list into non-view sublists of length partitionSize. Note: the argument list * may be included in the result. */ public static <T> List<List<T>> partition(List<T> list, final int partitionSize) { List<List<T>> parts = new ArrayList<>(); final int listSize = list.size(); if (listSize <= partitionSize) { // no need for partitioning parts.add(list); } else { for (int i = 0; i < listSize; i += partitionSize) { parts.add(new ArrayList<>(list.subList(i, Math.min(listSize, i + partitionSize)))); } } return parts; }
public static <T> List<T> collectInList(Iterator<T> iterator) { List<T> result = new ArrayList<>(); while (iterator.hasNext()) { result.add(iterator.next()); } return result; } public static <T> T getLastElement(final Iterable<T> elements) { T lastElement = null; if (elements instanceof List) { return ((List<T>) elements).get(((List<T>) elements).size() - 1); } for (T element : elements) { lastElement = element; } return lastElement; } public static boolean isEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CollectionUtil.java
1
请完成以下Java代码
public CleanableHistoricCaseInstanceReport caseDefinitionKeyIn(String... caseDefinitionKeys) { ensureNotNull(NotValidException.class, "", "caseDefinitionKeyIn", (Object[]) caseDefinitionKeys); this.caseDefinitionKeyIn = caseDefinitionKeys; return this; } @Override public CleanableHistoricCaseInstanceReport tenantIdIn(String... tenantIds) { ensureNotNull(NotValidException.class, "", "tenantIdIn", (Object[]) tenantIds); this.tenantIdIn = tenantIds; isTenantIdSet = true; return this; } @Override public CleanableHistoricCaseInstanceReport withoutTenantId() { this.tenantIdIn = null; isTenantIdSet = true; return this; } @Override public CleanableHistoricCaseInstanceReport compact() { this.isCompact = true; return this; } @Override public CleanableHistoricCaseInstanceReport orderByFinished() { orderBy(CleanableHistoricInstanceReportProperty.FINISHED_AMOUNT); return this; } @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricCaseInstanceManager() .findCleanableHistoricCaseInstancesReportCountByCriteria(this); } @Override public List<CleanableHistoricCaseInstanceReportResult> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricCaseInstanceManager() .findCleanableHistoricCaseInstancesReportByCriteria(this, page); } public String[] getCaseDefinitionIdIn() { return caseDefinitionIdIn; } public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn; } public String[] getCaseDefinitionKeyIn() { return caseDefinitionKeyIn; } public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) { this.caseDefinitionKeyIn = caseDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isCompact() { return isCompact; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public UserInfoResponse setUserInfo(@ApiParam(name = "userId") @PathVariable("userId") String userId, @ApiParam(name = "key") @PathVariable("key") String key, @RequestBody UserInfoRequest userRequest) { User user = getUserFromRequest(userId); String validKey = getValidKeyFromRequest(user, key); if (userRequest.getValue() == null) { throw new FlowableIllegalArgumentException("The value cannot be null."); } if (userRequest.getKey() == null || validKey.equals(userRequest.getKey())) { identityService.setUserInfo(user.getId(), key, userRequest.getValue()); } else { throw new FlowableIllegalArgumentException("Key provided in request body does not match the key in the resource URL."); } return restResponseFactory.createUserInfoResponse(key, userRequest.getValue(), user.getId()); } @ApiOperation(value = "Delete a user’s info", tags = { "Users" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the user was found and the info for the given key has been deleted. Response body is left empty intentionally."), @ApiResponse(code = 404, message = "Indicates the requested user was not found or the user does not have info for the given key. Status description contains additional information about the error.") }) @DeleteMapping("/identity/users/{userId}/info/{key}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteUserInfo(@ApiParam(name = "userId") @PathVariable("userId") String userId, @ApiParam(name = "key") @PathVariable("key") String key) { User user = getUserFromRequest(userId);
if (restApiInterceptor != null) { restApiInterceptor.deleteUser(user); } String validKey = getValidKeyFromRequest(user, key); identityService.setUserInfo(user.getId(), validKey, null); } protected String getValidKeyFromRequest(User user, String key) { String existingValue = identityService.getUserInfo(user.getId(), key); if (existingValue == null) { throw new FlowableObjectNotFoundException("User info with key '" + key + "' does not exists for user '" + user.getId() + "'.", null); } return key; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserInfoResource.java
2
请完成以下Java代码
public @Nullable Object getCredentials() { return this.credentials; } @Override public Object getPrincipal() { return this.identifier; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link CasServiceTicketAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> {
private String principal; private @Nullable Object credentials; protected Builder(CasServiceTicketAuthenticationToken token) { super(token); this.principal = token.identifier; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.isInstanceOf(String.class, principal, "principal must be of type String"); this.principal = (String) principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { Assert.notNull(credentials, "credentials cannot be null"); this.credentials = credentials; return (B) this; } @Override public CasServiceTicketAuthenticationToken build() { return new CasServiceTicketAuthenticationToken(this); } } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\authentication\CasServiceTicketAuthenticationToken.java
1
请完成以下Java代码
public void setValue(Object value) { if (value == m_value) return; m_value = value; int S_ResourceAssignment_ID = 0; if (m_value != null && m_value instanceof Integer) S_ResourceAssignment_ID = ((Integer)m_value).intValue(); // Set Empty if (S_ResourceAssignment_ID == 0) { m_text.setText(""); return; } // Statement if (m_pstmt == null) m_pstmt = DB.prepareStatement("SELECT r.Name,ra.AssignDateFrom,ra.Qty,uom.UOMSymbol " + "FROM S_ResourceAssignment ra, S_Resource r, S_ResourceType rt, C_UOM uom " + "WHERE ra.S_ResourceAssignment_ID=?" + " AND ra.S_Resource_ID=r.S_Resource_ID" + " AND r.S_ResourceType_ID=rt.S_ResourceType_ID" + " and rt.C_UOM_ID=uom.C_UOM_ID", null); // try { m_pstmt.setInt(1, S_ResourceAssignment_ID); ResultSet rs = m_pstmt.executeQuery(); if (rs.next()) { StringBuffer sb = new StringBuffer(rs.getString(1)); sb.append(" ").append(m_dateFormat.format(rs.getTimestamp(2))) .append(" ").append(m_qtyFormat.format(rs.getBigDecimal(3))) .append(" ").append(rs.getString(4).trim()); m_text.setText(sb.toString()); } else m_text.setText("<" + S_ResourceAssignment_ID + ">"); rs.close(); } catch (Exception e) { log.error("", e); } } // setValue /** * Get Value * @return value */ @Override public Object getValue() { return m_value; } // getValue /** * Get Display Value * @return info */ @Override public String getDisplay() { return m_text.getText(); } // getDisplay /*************************************************************************/ /** * Set Field - NOP * @param mField MField
*/ @Override public void setField(GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * Action Listener Interface * @param listener listener */ @Override public void addActionListener(ActionListener listener) { // m_text.addActionListener(listener); } // addActionListener /** * Action Listener - start dialog * @param e Event */ @Override public void actionPerformed(ActionEvent e) { if (!m_button.isEnabled()) return; throw new AdempiereException("legacy feature removed"); } /** * Property Change Listener * @param evt event */ @Override public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); // metas: request focus (2009_0027_G131) if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS)) requestFocus(); // metas end } // propertyChange @Override public boolean isAutoCommit() { return true; } } // VAssignment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAssignment.java
1
请完成以下Java代码
public IStringExpression toStringExpression() { final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias) ? joinOnTableNameOrAlias + "." + joinOnColumnName : joinOnColumnName; if (sqlExpression == null) { return ConstantStringExpression.of(joinOnColumnNameFQ); } else { return sqlExpression.toStringExpression(joinOnColumnNameFQ); } } public IStringExpression toOrderByStringExpression() { final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias) ? joinOnTableNameOrAlias + "." + joinOnColumnName : joinOnColumnName; if (sqlExpression == null) { return ConstantStringExpression.of(joinOnColumnNameFQ); } else { return sqlExpression.toOrderByStringExpression(joinOnColumnNameFQ); } }
public SqlSelectDisplayValue withJoinOnTableNameOrAlias(@Nullable final String joinOnTableNameOrAlias) { return !Objects.equals(this.joinOnTableNameOrAlias, joinOnTableNameOrAlias) ? toBuilder().joinOnTableNameOrAlias(joinOnTableNameOrAlias).build() : this; } public String toSqlOrderByUsingColumnNameAlias() { final String columnNameAliasFQ = joinOnTableNameOrAlias != null ? joinOnTableNameOrAlias + "." + columnNameAlias : columnNameAlias; if (sqlExpression != null) { return columnNameAliasFQ + "[" + sqlExpression.getNameSqlArrayIndex() + "]"; } else { return columnNameAliasFQ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlSelectDisplayValue.java
1
请完成以下Java代码
public class UserTaskActivityBehavior extends TaskActivityBehavior implements MigrationObserverBehavior { protected TaskDecorator taskDecorator; @Deprecated public UserTaskActivityBehavior(ExpressionManager expressionManager, TaskDefinition taskDefinition) { this.taskDecorator = new TaskDecorator(taskDefinition, expressionManager); } public UserTaskActivityBehavior(TaskDecorator taskDecorator) { this.taskDecorator = taskDecorator; } @Override public void performExecution(ActivityExecution execution) throws Exception { TaskEntity task = new TaskEntity((ExecutionEntity) execution); task.insert(); // initialize task properties taskDecorator.decorate(task, execution); // fire lifecycle events after task is initialized task.transitionTo(TaskState.STATE_CREATED); } public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception { leave(execution); } // migration @Override public void migrateScope(ActivityExecution scopeExecution) { } @Override public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { ExecutionEntity execution = migratingInstance.resolveRepresentativeExecution(); for (TaskEntity task : execution.getTasks()) { migratingInstance.addMigratingDependentInstance(new MigratingUserTaskInstance(task, migratingInstance)); parseContext.consume(task); Collection<VariableInstanceEntity> variables = task.getVariablesInternal(); if (variables != null) { for (VariableInstanceEntity variable : variables) { // we don't need to represent task variables in the migrating instance structure because // they are migrated by the MigratingTaskInstance as well
parseContext.consume(variable); } } } } // getters public TaskDefinition getTaskDefinition() { return taskDecorator.getTaskDefinition(); } public ExpressionManager getExpressionManager() { return taskDecorator.getExpressionManager(); } public TaskDecorator getTaskDecorator() { return taskDecorator; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\UserTaskActivityBehavior.java
1
请完成以下Java代码
public LookupValuesPage getFieldTypeahead(@NonNull final String fieldName, final String query) { return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), query); } public LookupValuesList getFieldDropdown(@NonNull final String fieldName) { return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), 20).getValues(); } private LookupDataSource getLookupDataSource(@NonNull final String fieldName) { if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName)) { return paymentTermLookup; } else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName)) { return priceTypeLookup; } else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName)) { return pricingSystemLookup; } else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName)) { return currencyIdLookup; } else { throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field"); }
} public String getTemporaryPriceConditionsColor() { return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor); } private String retrieveTemporaryPriceConditionsColor() { final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId(); return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId)); } private static String toHexString(@Nullable final MFColor color) { if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java
1
请完成以下Java代码
public int getUseLifeYears () { Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears); if (ii == null) return 0; return ii.intValue(); } /** Set Use units. @param UseUnits Currently used units of the assets */ public void setUseUnits (int UseUnits) { set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits)); } /** Get Use units. @return Currently used units of the assets */ public int getUseUnits () { Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits); if (ii == null) return 0; return ii.intValue(); } /** 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); } /** Set Version No. @param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_Value (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Asset.java
1
请完成以下Java代码
private class CInputVerifier extends InputVerifier { @Override public boolean verify(JComponent input) { //NOTE: We return true no matter what since the InputVerifier is only introduced to fireVetoableChange in due time if (getText() == null && m_oldText == null) return true; else if (getText().equals(m_oldText)) return true; // try { String text = getText(); fireVetoableChange(m_columnName, null, text); m_oldText = text;
return true; } catch (PropertyVetoException pve) {} return true; } // verify } // CInputVerifier // metas @Override public boolean isAutoCommit() { return true; } } // VMemo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VMemo.java
1
请完成以下Java代码
final class ADMessageTranslatableString implements ITranslatableString { private final AdMessageKey adMessage; private final List<Object> msgParameters; ADMessageTranslatableString(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { this.adMessage = adMessage; if (msgParameters == null || msgParameters.length == 0) { this.msgParameters = ImmutableList.of(); } else { // NOTE: avoid using ImmutableList because there might be null parameters this.msgParameters = Collections.unmodifiableList(Arrays.asList(msgParameters)); } } @Override @Deprecated public String toString() { return adMessage.toAD_Message(); }
@Override public String translate(final String adLanguage) { return Msg.getMsg(adLanguage, adMessage.toAD_Message(), msgParameters.toArray()); } @Override public String getDefaultValue() { return adMessage.toAD_MessageWithMarkers(); } @Override public Set<String> getAD_Languages() { return Services.get(ILanguageBL.class).getAvailableLanguages().getAD_Languages(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\ADMessageTranslatableString.java
1
请完成以下Spring Boot application配置
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver #### beetlsql starter不能开启下面选项 # type: com.zaxxer.hikari.HikariDataSource # initialization-mode: always # continue-on-error: true # schema: # - "classpath:db/schema.sql" # data: # - "classpath:db/data.sql" # hikari: # minimum-idle: 5 # connection-test-query: SELECT 1 FROM DUAL # maximum-pool-size: 20 # auto-commit: true # idle-timeout: 30000 # pool-name: SpringBootDemoHikariCP # max-lifetime: 60000 # connection-timeout: 30000 loggi
ng: level: com.xkcoding: debug com.xkcoding.orm.beetlsql: trace beetl: enabled: false beetlsql: enabled: true sqlPath: /sql daoSuffix: Dao basePackage: com.xkcoding.orm.beetlsql.dao dbStyle: org.beetl.sql.core.db.MySqlStyle nameConversion: org.beetl.sql.core.UnderlinedNameConversion beet-beetlsql: dev: true
repos\spring-boot-demo-master\demo-orm-beetlsql\src\main\resources\application.yml
2
请完成以下Java代码
private static HUAttributeChange mergeChange( @Nullable final HUAttributeChange previousChange, @NonNull final HUAttributeChange currentChange) { return previousChange != null ? previousChange.mergeWithNextChange(currentChange) : currentChange; } public boolean isEmpty() { return attributes.isEmpty(); } public AttributesKey getOldAttributesKey() { return toAttributesKey(HUAttributeChange::getOldAttributeKeyPartOrNull); } public AttributesKey getNewAttributesKey() { return toAttributesKey(HUAttributeChange::getNewAttributeKeyPartOrNull); }
private AttributesKey toAttributesKey(final Function<HUAttributeChange, AttributesKeyPart> keyPartExtractor) { if (attributes.isEmpty()) { return AttributesKey.NONE; } final ImmutableList<AttributesKeyPart> parts = attributes.values() .stream() .map(keyPartExtractor) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); return AttributesKey.ofParts(parts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChanges.java
1
请完成以下Java代码
public BaseCallableElement getCallableElement() { return callableElement; } public void setCallableElement(BaseCallableElement callableElement) { this.callableElement = callableElement; } protected String getDefinitionKey(CmmnActivityExecution execution) { CmmnExecution caseExecution = (CmmnExecution) execution; return getCallableElement().getDefinitionKey(caseExecution); } protected Integer getVersion(CmmnActivityExecution execution) { CmmnExecution caseExecution = (CmmnExecution) execution; return getCallableElement().getVersion(caseExecution); } protected String getDeploymentId(CmmnActivityExecution execution) { return getCallableElement().getDeploymentId(); }
protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding(); } protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected boolean isVersionTagBinding() { return getCallableElement().isVersionTagBinding(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CallingTaskActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemNotificationHelper { private static final Logger log = LogManager.getLogger(ExternalSystemNotificationHelper.class); private static final String SYS_CONFIG_EXTERNAL_SYSTEM_NOTIFICATION_USER_GROUP = "de.metas.externalsystem.externalservice.authorization.notificationUserGroupId"; private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private final INotificationBL notificationBL = Services.get(INotificationBL.class); private final IMsgBL msgBL = Services.get(IMsgBL.class); public void sendNotification( @NonNull final AdMessageKey messageKey, @Nullable final List<Object> params) { final int externalSystemAPIUserGroup = sysConfigBL.getIntValue(SYS_CONFIG_EXTERNAL_SYSTEM_NOTIFICATION_USER_GROUP, -1); final UserGroupId userGroupId = UserGroupId.ofRepoIdOrNull(externalSystemAPIUserGroup); if (userGroupId == null) {
log.error("No AD_UserGroup is configured to be in charge of the ExternalSystem services authorization! Just dumping the notification here: {}", msgBL.getMsg(Env.getAD_Language(), messageKey, params)); return; } final Recipient recipient = Recipient.group(userGroupId); final UserNotificationRequest verificationFailureNotification = UserNotificationRequest.builder() .recipient(recipient) .contentADMessage(messageKey) .contentADMessageParams(params) .build(); notificationBL.send(verificationFailureNotification); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\authorization\ExternalSystemNotificationHelper.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_T_MRP_CRP[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_PInstance getAD_PInstance() throws RuntimeException { return (I_AD_PInstance)MTable.get(getCtx(), I_AD_PInstance.Table_Name) .getPO(getAD_PInstance_ID(), get_TrxName()); } /** Set Process Instance. @param AD_PInstance_ID Instance of the process */ public void setAD_PInstance_ID (int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID)); } /** Get Process Instance. @return Instance of the process */ public int getAD_PInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Sequence.
@param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Temporal MRP & CRP. @param T_MRP_CRP_ID Temporal MRP & CRP */ public void setT_MRP_CRP_ID (int T_MRP_CRP_ID) { if (T_MRP_CRP_ID < 1) set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null); else set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID)); } /** Get Temporal MRP & CRP. @return Temporal MRP & CRP */ public int getT_MRP_CRP_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_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\eevolution\model\X_T_MRP_CRP.java
1
请完成以下Java代码
protected void registerInterceptors(final IModelValidationEngine engine) { engine.addModelValidator(DLM_Partition_Config.INSTANCE); engine.addModelValidator(DLM_Partition_Config_Line.INSTANCE); final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); if (sysConfigBL.getBooleanValue(SYSCONFIG_DLM_PARTITIONER_INTERCEPTOR_ENABLED, false)) { // gh #969: only do partitioning if it's enabled engine.addModelValidator(PartitionerInterceptor.INSTANCE); } } @Override protected void registerCallouts(final IProgramaticCalloutProvider calloutsRegistry) { calloutsRegistry.registerAnnotatedCallout(DLM_Partition_Config_Reference.INSTANCE); } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{ DBException.registerExceptionWrapper(DLMReferenceExceptionWrapper.INSTANCE); // gh #1411: only register the connection customizer if it was enabled. final IDLMService dlmService = Services.get(IDLMService.class); if (dlmService.isConnectionCustomizerEnabled(AD_User_ID)) { Services.get(IConnectionCustomizerService.class).registerPermanentCustomizer(DLMPermanentIniCustomizer.INSTANCE); } Services.get(ICoordinatorService.class).registerInspector(LastUpdatedInspector.INSTANCE); // gh #968: register handler to try to get back archived records, if PO could not load them NoDataFoundHandlers.get().addHandler(UnArchiveRecordHandler.INSTANCE); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\Main.java
1
请完成以下Java代码
public List<JobEntity> findJobsByProcessDefinitionId(final String processDefinitionId) { Map<String, String> params = new HashMap<String, String>(1); params.put("processDefinitionId", processDefinitionId); return getDbSqlSession().selectList("selectJobByProcessDefinitionId", params); } @Override public List<JobEntity> findJobsByTypeAndProcessDefinitionId( final String jobHandlerType, final String processDefinitionId ) { Map<String, String> params = new HashMap<String, String>(2); params.put("handlerType", jobHandlerType); params.put("processDefinitionId", processDefinitionId); return getDbSqlSession().selectList("selectJobByTypeAndProcessDefinitionId", params); } @Override @SuppressWarnings("unchecked") public List<JobEntity> findJobsByProcessInstanceId(final String processInstanceId) { return getDbSqlSession().selectList("selectJobsByProcessInstanceId", processInstanceId); } @Override @SuppressWarnings("unchecked") public List<JobEntity> findExpiredJobs(Page page) { Date now = getClock().getCurrentTime(); return getDbSqlSession().selectList("selectExpiredJobs", now, page); } @Override @SuppressWarnings("unchecked") public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) { final String query = "selectJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery, page); } @Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectJobCountByQueryCriteria", jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().update("updateJobTenantIdForDeployment", params); } @Override public void resetExpiredJob(String jobId) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("id", jobId); getDbSqlSession().update("resetExpiredJob", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisJobDataManager.java
1
请完成以下Java代码
private boolean isExecutionGrantedOrLog(final RelatedProcessDescriptor relatedProcess, final IUserRolePermissions permissions) { if (relatedProcess.isExecutionGranted(permissions)) { return true; } if (logger.isDebugEnabled()) { logger.debug("Skip process {} because execution was not granted using {}", relatedProcess, permissions); } return false; } private boolean isEnabledOrLog(final SwingRelatedProcessDescriptor relatedProcess) { if (relatedProcess.isEnabled()) { return true; } if (!relatedProcess.isSilentRejection())
{ return true; } // // Log and filter it out if (logger.isDebugEnabled()) { final String disabledReason = relatedProcess.getDisabledReason(Env.getAD_Language(Env.getCtx())); logger.debug("Skip process {} because {} (silent={})", relatedProcess, disabledReason, relatedProcess.isSilentRejection()); } return false; } @VisibleForTesting /* package */ProcessPreconditionsResolution checkPreconditionApplicable(final RelatedProcessDescriptor relatedProcess, final IProcessPreconditionsContext preconditionsContext) { return ProcessPreconditionChecker.newInstance() .setProcess(relatedProcess) .setPreconditionsContext(preconditionsContext) .checkApplies(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\AProcessModel.java
1
请完成以下Java代码
public MNewsChannel getNewsChannel() { int[] thisNewsChannel = MNewsChannel.getAllIDs("CM_NewsChannel","CM_NewsChannel_ID=" + this.getCM_NewsChannel_ID(), get_TrxName()); if (thisNewsChannel!=null) { if (thisNewsChannel.length==1) return new MNewsChannel(getCtx(), thisNewsChannel[0], get_TrxName()); } return null; } // getNewsChannel /** * Get rss2 Item Code * @param xmlCode xml * @param thisChannel channel * @return rss item code */ public StringBuffer get_rss2ItemCode(StringBuffer xmlCode, MNewsChannel thisChannel) { if (this != null) // never null ?? { xmlCode.append ("<item>"); xmlCode.append ("<CM_NewsItem_ID>"+ this.get_ID() + "</CM_NewsItem_ID>"); xmlCode.append (" <title><![CDATA[" + this.getTitle () + "]]></title>"); xmlCode.append (" <description><![CDATA[" + this.getDescription () + "]]></description>"); xmlCode.append (" <content><![CDATA[" + this.getContentHTML () + "]]></content>"); xmlCode.append (" <link>" + thisChannel.getLink () + "?CM_NewsItem_ID=" + this.get_ID() + "</link>"); xmlCode.append (" <author><![CDATA[" + this.getAuthor () + "]]></author>"); xmlCode.append (" <pubDate>" + this.getPubDate () + "</pubDate>"); xmlCode.append ("</item>"); } return xmlCode; } /** * After Save. * Insert * - create / update index * @param newRecord insert * @param success save success
* @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (!newRecord) { MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID()); } reIndex(newRecord); return success; } // afterSave /** * reIndex * @param newRecord */ public void reIndex(boolean newRecord) { int CMWebProjectID = 0; if (getNewsChannel()!=null) CMWebProjectID = getNewsChannel().getCM_WebProject_ID(); String [] toBeIndexed = new String[4]; toBeIndexed[0] = this.getAuthor(); toBeIndexed[1] = this.getDescription(); toBeIndexed[2] = this.getTitle(); toBeIndexed[3] = this.getContentHTML(); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated()); } // reIndex }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNewsItem.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteAuthorsViaDeleteAllInBatch() { authorRepository.deleteAllInBatch(); } // good if the number of deletes can be converted into // a DELETE of type, delete from author where id=? or id=? or id=? ... // without exceeding the maximum accepted size (as a workaround, // split the number of deletes in multiple chunks to avoid this issue) // doesn't prevent lost updates @Transactional public void deleteAuthorsViaDeleteInBatch() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteInBatch(authors); } // good if you want an alternative to deleteInBatch() @Transactional public void deleteAuthorsViaDeleteInBulk() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteInBulk(authors); } // good if you need to delete in a classical batch approach @Transactional
public void deleteAuthorsViaDeleteAll() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteAll(authors); // for deleting all Authors use deleteAll() with no arguments } // good if you need to delete in a classical batch approach @Transactional public void deleteAuthorsViaDelete() { List<Author> authors = authorRepository.findByAgeLessThan(60); authors.forEach(authorRepository::delete); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteSingleEntity\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Spring Boot application配置
server.port=80 # \u6570\u636E\u6E90\u914D\u7F6E spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.url=jdbc:h2:mem:ssb_test spring.datasource.druid.driver-class-name=org.h2.Driver spring.datasource.druid.username=root spring.datasource.druid.password=root spring.datasource.schema=classpath:db/schema.sql spring.datasource.data=classpath:db/data.sql # \u8FDB\u884C\u8BE5\u914D\u7F6E\u540E\uFF0Ch2 web consloe\u5C31\u53EF\u4EE5\u5728\u8FDC\u7A0B\u8BBF\u95EE\u4E86\u3002\u5426\u5219\u53EA\u80FD\u5728\u672C\u673A\u8BBF\u95EE\u3002 spring.h2.console.settings.web-allow-others=true # \u8FDB\u884C\u8BE5\u914D\u7F6E\uFF0C\u4F60\u5C31\u53EF\u4EE5\u901A\u8FC7YOUR_URL/h2-console\u8BBF\u95EEh2 web consloe\u3002YOUR_URL\u662F\u4F60\u7A0B\u5E8F\u7684\u8BBF\u95EEURl\u3002 spring.h2.console.path=/h2-console # \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 # \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4 spring.datasource.druid.max-wait=60000 # \u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.druid.time-between-eviction-runs-millis=60000 # \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.druid.min-evictable-idle-time-millis=300000 #\u68C0\u6D4B\u8FDE\u63A5\u662F\u5426\u6709\u6548\u7684sql spring.datasource.druid.validation-query=SELECT 'x' spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false # PSCache Mysql\u4E0B\u5EFA\u8BAE\u5173\u95ED spring.datasource.druid.pool-prepared-statements=false spring.datasource.druid.max-pool-prepared-statement-per-connection-size=-1 # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u
9632\u706B\u5899 spring.datasource.druid.filters=stat,wall,log4j # \u5408\u5E76\u591A\u4E2ADruidDataSource\u7684\u76D1\u63A7\u6570\u636E spring.datasource.druid.use-global-data-source-stat=true spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #mybatis #entity\u626B\u63CF\u7684\u5305\u540D mybatis.type-aliases-package=com.xiaolyuh.domain.model #Mapper.xml\u6240\u5728\u7684\u4F4D\u7F6E mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xml #\u5F00\u542FMyBatis\u7684\u4E8C\u7EA7\u7F13\u5B58 mybatis.configuration.cache-enabled=true #pagehelper pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql #\u65E5\u5FD7\u914D\u7F6E logging.level.com.xiaolyuh=debug logging.level.org.springframework.web=debug logging.level.org.springframework.transaction=debug logging.level.org.mybatis=debug debug=false
repos\spring-boot-student-master\spring-boot-student-mybatis-druid\src\main\resources\application.properties
2
请完成以下Java代码
public Object getPersistentState() { // details are not updatable so we always provide the same object as the state return HistoricDetailEntityImpl.class; } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; }
public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getOrgCheckFilePath() { return orgCheckFilePath; } public void setOrgCheckFilePath(String orgCheckFilePath) { this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim(); } public String getReleaseCheckFilePath() { return releaseCheckFilePath; } public void setReleaseCheckFilePath(String releaseCheckFilePath) { this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim(); } public String getReleaseStatus() { return releaseStatus; } public void setReleaseStatus(String releaseStatus) { this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim(); } public BigDecimal getFee() { return fee; }
public void setFee(BigDecimal fee) { this.fee = fee; } public String getCheckFailMsg() { return checkFailMsg; } public void setCheckFailMsg(String checkFailMsg) { this.checkFailMsg = checkFailMsg; } public String getBankErrMsg() { return bankErrMsg; } public void setBankErrMsg(String bankErrMsg) { this.bankErrMsg = bankErrMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
2
请在Spring Boot框架中完成以下Java代码
public class PPOrderIssueScheduleId implements RepoIdAware { int repoId; private PPOrderIssueScheduleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_IssueSchedule_ID"); } @JsonCreator public static PPOrderIssueScheduleId ofRepoId(final int repoId) {return new PPOrderIssueScheduleId(repoId);} public static PPOrderIssueScheduleId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? new PPOrderIssueScheduleId(repoId) : null;} public static int toRepoId(final PPOrderIssueScheduleId id) {return id != null ? id.getRepoId() : -1;} public static PPOrderIssueScheduleId ofString(@NonNull final String idStr) { try
{ return ofRepoId(Integer.parseInt(idStr)); } catch (final Exception ex) { final AdempiereException metasfreshEx = new AdempiereException("Invalid id: `" + idStr + "`"); metasfreshEx.addSuppressed(ex); throw metasfreshEx; } } @Override @JsonValue public int getRepoId() {return repoId;} public static boolean equals(@Nullable final PPOrderIssueScheduleId id1, @Nullable final PPOrderIssueScheduleId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\issue_schedule\PPOrderIssueScheduleId.java
2
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFileName (final java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setTags (final @Nullable java.lang.String Tags) { set_Value (COLUMNNAME_Tags, Tags); } @Override public java.lang.String getTags() { return get_ValueAsString(COLUMNNAME_Tags); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Local File-URL = LU */ public static final String TYPE_LocalFile_URL = "LU"; @Override public void setType (final java.lang.String Type)
{ set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry.java
1
请完成以下Java代码
public Page<User> users(@PageableDefault(size = 5) Pageable pageable) { return userManagement.findAll(pageable); } /** * Registers a new {@link User} for the data provided by the given {@link UserForm}. Note, how an interface is used to * bind request parameters. * * @param userForm the request data bound to the {@link UserForm} instance. * @param binding the result of the binding operation. * @param model the Spring MVC {@link Model}. * @return */ @RequestMapping(method = RequestMethod.POST) public Object register(UserForm userForm, BindingResult binding, Model model) { userForm.validate(binding, userManagement); if (binding.hasErrors()) { return "users"; } userManagement.register(new Username(userForm.getUsername()), Password.raw(userForm.getPassword())); var redirectView = new RedirectView("redirect:/users"); redirectView.setPropagateQueryParams(true); return redirectView; } /** * Populates the {@link Model} with the {@link UserForm} automatically created by Spring Data web components. It will * create a {@link Map}-backed proxy for the interface. * * @param model will never be {@literal null}. * @param userForm will never be {@literal null}. * @return */ @RequestMapping(method = RequestMethod.GET) public String listUsers(Model model, UserForm userForm) { model.addAttribute("userForm", userForm); return "users"; } /** * An interface to represent the form to be used * * @author Oliver Gierke */
interface UserForm { String getUsername(); String getPassword(); String getRepeatedPassword(); /** * Validates the {@link UserForm}. * * @param errors * @param userManagement */ default void validate(BindingResult errors, UserManagement userManagement) { rejectIfEmptyOrWhitespace(errors, "username", "user.username.empty"); rejectIfEmptyOrWhitespace(errors, "password", "user.password.empty"); rejectIfEmptyOrWhitespace(errors, "repeatedPassword", "user.repeatedPassword.empty"); if (!getPassword().equals(getRepeatedPassword())) { errors.rejectValue("repeatedPassword", "user.password.no-match"); } try { userManagement.findByUsername(new Username(getUsername())).ifPresent( user -> errors.rejectValue("username", "user.username.exists")); } catch (IllegalArgumentException o_O) { errors.rejectValue("username", "user.username.invalidFormat"); } } } }
repos\spring-data-examples-main\web\example\src\main\java\example\users\web\UserController.java
1
请完成以下Java代码
public void setSetup_Place_No (final int Setup_Place_No) { set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public int getSetup_Place_No() { return get_ValueAsInt(COLUMNNAME_Setup_Place_No); } /** * ShipmentAllocation_BestBefore_Policy AD_Reference_ID=541043 * Reference name: ShipmentAllocation_BestBefore_Policy */ public static final int SHIPMENTALLOCATION_BESTBEFORE_POLICY_AD_Reference_ID=541043; /** Newest_First = N */ public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Newest_First = "N"; /** Expiring_First = E */ public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Expiring_First = "E"; @Override public void setShipmentAllocation_BestBefore_Policy (final @Nullable java.lang.String ShipmentAllocation_BestBefore_Policy) { set_ValueNoCheck (COLUMNNAME_ShipmentAllocation_BestBefore_Policy, ShipmentAllocation_BestBefore_Policy); } @Override public java.lang.String getShipmentAllocation_BestBefore_Policy() { return get_ValueAsString(COLUMNNAME_ShipmentAllocation_BestBefore_Policy); } @Override public void setShipperName (final @Nullable java.lang.String ShipperName) { set_ValueNoCheck (COLUMNNAME_ShipperName, ShipperName); } @Override
public java.lang.String getShipperName() { return get_ValueAsString(COLUMNNAME_ShipperName); } @Override public void setWarehouseName (final @Nullable java.lang.String WarehouseName) { set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName); } @Override public java.lang.String getWarehouseName() { return get_ValueAsString(COLUMNNAME_WarehouseName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Packageable_V.java
1
请完成以下Java代码
private Quantity getQtyToPurchase() { return getPurchaseCandidate().getQtyToPurchase(); } public boolean purchaseMatchesRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) == 0; } private boolean purchaseMatchesOrExceedsRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0; } public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId) { this.purchaseOrderAndLineId = purchaseOrderAndLineId; } public void markPurchasedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.markProcessed(); } } public void markReqCreatedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.setReqCreated(true); } } @Nullable public BigDecimal getPrice() { return purchaseCandidate.getPriceEnteredEff(); } @Nullable public UomId getPriceUomId() { return purchaseCandidate.getPriceUomId(); } @Nullable public Percent getDiscount()
{ return purchaseCandidate.getDiscountEff(); } @Nullable public String getExternalPurchaseOrderUrl() { return purchaseCandidate.getExternalPurchaseOrderUrl(); } @Nullable public ExternalId getExternalHeaderId() { return purchaseCandidate.getExternalHeaderId(); } @Nullable public ExternalSystemId getExternalSystemId() { return purchaseCandidate.getExternalSystemId(); } @Nullable public ExternalId getExternalLineId() { return purchaseCandidate.getExternalLineId(); } @Nullable public String getPOReference() { return purchaseCandidate.getPOReference(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
1
请完成以下Java代码
public void setM_CustomsTariff_ID (int M_CustomsTariff_ID) { if (M_CustomsTariff_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CustomsTariff_ID, Integer.valueOf(M_CustomsTariff_ID)); } /** Get Customs Tariff. @return Customs Tariff */ @Override public int getM_CustomsTariff_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CustomsTariff_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */
@Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CustomsTariff.java
1
请完成以下Java代码
default void onIgnore(final ICalloutRecord calloutRecord) { } /** * Note that this method is <b>not</b> fired if a record is cloned. To do something on a record clone, you can register an {@link Interceptor} or a {@code IOnRecordCopiedListener} */ default void onNew(final ICalloutRecord calloutRecord) { } default void onSave(final ICalloutRecord calloutRecord) { } default void onDelete(final ICalloutRecord calloutRecord) { }
default void onRefresh(final ICalloutRecord calloutRecord) { } default void onRefreshAll(final ICalloutRecord calloutRecord) { } /** * Called after {@link ICalloutRecord} was queried. */ default void onAfterQuery(final ICalloutRecord calloutRecord) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\ITabCallout.java
1
请完成以下Java代码
private void setReadTimeout(ClientHttpRequestFactory factory, Duration readTimeout) { Method method = tryFindMethod(factory, "setReadTimeout", Duration.class); if (method != null) { invoke(factory, method, readTimeout); return; } method = findMethod(factory, "setReadTimeout", int.class); int timeout = Math.toIntExact(readTimeout.toMillis()); invoke(factory, method, timeout); } private Method findMethod(ClientHttpRequestFactory requestFactory, String methodName, Class<?>... parameters) { Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters); Assert.state(method != null, () -> "Request factory %s does not have a suitable %s method" .formatted(requestFactory.getClass().getName(), methodName)); Assert.state(!method.isAnnotationPresent(Deprecated.class), () -> "Request factory %s has the %s method marked as deprecated" .formatted(requestFactory.getClass().getName(), methodName)); return method; }
private @Nullable Method tryFindMethod(ClientHttpRequestFactory requestFactory, String methodName, Class<?>... parameters) { Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters); if (method == null) { return null; } if (method.isAnnotationPresent(Deprecated.class)) { return null; } return method; } private void invoke(ClientHttpRequestFactory requestFactory, Method method, Object... parameters) { ReflectionUtils.invokeMethod(method, requestFactory, parameters); } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ReflectiveComponentsClientHttpRequestFactoryBuilder.java
1
请完成以下Java代码
public void putAll(Map<? extends Object, ? extends Object> t) { getDelegate().putAll(t); } @Override public void clear() { getDelegate().clear(); } @Override public Object clone() { return getDelegate().clone(); } @Override public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException
{ getDelegate().storeToXML(os, comment, encoding); } @Override public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
private List<I_PP_Order_BOMLine> getAllPPOrderBOMLines() { if (_ppOrderBOMLines == null) { _ppOrderBOMLines = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrder); } return _ppOrderBOMLines; } /** * Gets the main component BOM Line for a given Variant BOM Line. * * @param variantComponentBOMLine * @return main component BOM Line; never return null */ private I_PP_Order_BOMLine getMainComponentOrderBOMLine(final I_PP_Order_BOMLine variantComponentBOMLine) { Check.assumeNotNull(variantComponentBOMLine, "variantComponentBOMLine not null"); final String variantGroup = variantComponentBOMLine.getVariantGroup(); Check.assumeNotEmpty(variantGroup, "variantGroup not empty"); // // Iterate through order BOM Lines and find out which is our main component line which have the same VariantGroup I_PP_Order_BOMLine componentBOMLine = null; final List<I_PP_Order_BOMLine> ppOrderBOMLines = getAllPPOrderBOMLines(); for (final I_PP_Order_BOMLine ppOrderBOMLine : ppOrderBOMLines) { // lines which are not components are not interesting for us if (!PPOrderUtil.isComponent(ppOrderBOMLine)) { continue; }
// lines which does not have our variant group are not interesting for us if (!Objects.equals(variantGroup, ppOrderBOMLine.getVariantGroup())) { continue; } // We found our main component line. // Make sure is the only one that we found. Check.assumeNull(componentBOMLine, "Only one main component shall be found for variant group {}: {}, {}", variantGroup, componentBOMLine, ppOrderBOMLine); componentBOMLine = ppOrderBOMLine; } // Make sure we found a main component line Check.assumeNotNull(componentBOMLine, "No main component line found for variant group: {}", variantGroup); // Return the main component line return componentBOMLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\ProductionMaterialQueryExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpRequest { /** HTTP GET method */ public static final String METHOD_GET = "GET"; /** HTTP POST method */ public static final String METHOD_POST = "POST"; /** * 待请求的url */ private String url = null; /** * 默认的请求方式 */ private String method = METHOD_POST; private int timeout = 0; private int connectionTimeout = 0; /** * Post方式请求时组装好的参数值对 */ private NameValuePair[] parameters = null; /** * Get方式请求时对应的参数 */ private String queryString = null; /** * 默认的请求编码方式 */ private String charset = "GBK"; /** * 请求发起方的ip地址 */ private String clientIp; /** * 请求返回的方式 */ private HttpResultType resultType = HttpResultType.BYTES; public HttpRequest(HttpResultType resultType) { super(); this.resultType = resultType; } /** * @return Returns the clientIp. */ public String getClientIp() { return clientIp; } /** * @param clientIp The clientIp to set. */ public void setClientIp(String clientIp) { this.clientIp = clientIp; } public NameValuePair[] getParameters() { return parameters; } public void setParameters(NameValuePair[] parameters) { this.parameters = parameters; } public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public int getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the charset. */ public String getCharset() { return charset; } /** * @param charset The charset to set. */ public void setCharset(String charset) { this.charset = charset; } public HttpResultType getResultType() { return resultType; } public void setResultType(HttpResultType resultType) { this.resultType = resultType; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\httpClient\HttpRequest.java
2
请完成以下Java代码
public void setDateDoc (java.sql.Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Belegdatum. @return Datum des Belegs */ @Override public java.sql.Timestamp getDateDoc () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateDoc); } /** Set M_Material_Tracking_Report. @param M_Material_Tracking_Report_ID M_Material_Tracking_Report */ @Override public void setM_Material_Tracking_Report_ID (int M_Material_Tracking_Report_ID) { if (M_Material_Tracking_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, Integer.valueOf(M_Material_Tracking_Report_ID)); } /** Get M_Material_Tracking_Report. @return M_Material_Tracking_Report */ @Override public int getM_Material_Tracking_Report_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_ID); if (ii == null) return 0; return ii.intValue(); } /** 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report.java
1
请完成以下Java代码
public SimpleAsyncTaskSchedulerBuilder additionalCustomizers( Iterable<? extends SimpleAsyncTaskSchedulerCustomizer> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return new SimpleAsyncTaskSchedulerBuilder(this.threadNamePrefix, this.concurrencyLimit, this.virtualThreads, this.taskTerminationTimeout, this.taskDecorator, append(this.customizers, customizers)); } /** * Build a new {@link SimpleAsyncTaskScheduler} instance and configure it using this * builder. * @return a configured {@link SimpleAsyncTaskScheduler} instance. * @see #configure(SimpleAsyncTaskScheduler) */ public SimpleAsyncTaskScheduler build() { return configure(new SimpleAsyncTaskScheduler()); } /** * Configure the provided {@link SimpleAsyncTaskScheduler} instance using this * builder. * @param <T> the type of task scheduler * @param taskScheduler the {@link SimpleAsyncTaskScheduler} to configure * @return the task scheduler instance * @see #build() */ public <T extends SimpleAsyncTaskScheduler> T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get(); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix);
map.from(this.concurrencyLimit).to(taskScheduler::setConcurrencyLimit); map.from(this.virtualThreads).to(taskScheduler::setVirtualThreads); map.from(this.taskTerminationTimeout).as(Duration::toMillis).to(taskScheduler::setTaskTerminationTimeout); map.from(this.taskDecorator).to(taskScheduler::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\SimpleAsyncTaskSchedulerBuilder.java
1
请完成以下Java代码
public class MUserDefField extends X_AD_UserDef_Field { /** * */ private static final long serialVersionUID = -5464451156146805763L; public MUserDefField(Properties ctx, int AD_UserDef_Field_ID, String trxName) { super(ctx, AD_UserDef_Field_ID, trxName); } public MUserDefField(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } public void apply(final GridFieldVO vo) { final GridFieldLayoutConstraints layoutConstraints = vo.getLayoutConstraints(); final String name = getName(); if (!Check.isEmpty(name) && name.length() > 1) vo.setHeader(name); if (!Check.isEmpty(getDescription())) vo.setDescription(getDescription()); if (!Check.isEmpty(getHelp())) vo.setHelp(getHelp()); // vo.setIsDisplayed(this.isDisplayed());
if (this.getIsReadOnly() != null) { vo.setIsReadOnly(DisplayType.toBoolean(getIsReadOnly())); } if (this.getIsSameLine() != null) { layoutConstraints.setSameLine("Y".equals(this.getIsSameLine())); } if (this.getIsUpdateable() != null) { vo.setIsUpdateable(DisplayType.toBoolean(getIsUpdateable())); } if (this.getIsMandatory() != null) vo.setMandatory("Y".equals(this.getIsMandatory())); if (this.getDisplayLength() > 0) { layoutConstraints.setDisplayLength(this.getDisplayLength()); } if (!Check.isEmpty(this.getDisplayLogic(), true)) { vo.setDisplayLogic(this.getDisplayLogic()); } if (!Check.isEmpty(this.getDefaultValue(), true)) vo.DefaultValue = this.getDefaultValue(); if (this.getSortNo() > 0) vo.SortNo = this.getSortNo(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MUserDefField.java
1
请在Spring Boot框架中完成以下Java代码
private MilestoneId getMilestoneIdByExternalId(@NonNull final ExternalId externalId, @NonNull final OrgId orgId) { final Integer milestoneId = externalReferenceRepository.getReferencedRecordIdOrNullBy( ExternalReferenceQuery.builder() .orgId(orgId) .externalSystem(externalId.getExternalSystem()) .externalReference(externalId.getId()) .externalReferenceType(ExternalServiceReferenceType.MILESTONE_ID) .build()); return MilestoneId.ofRepoIdOrNull(milestoneId); } private void createMissingRefListForLabels(@NonNull final ImmutableList<IssueLabel> issueLabels) { issueLabels.stream() .filter(label -> adReferenceService.retrieveListItemOrNull(LABEL_AD_Reference_ID, label.getValue()) == null) .map(this::buildRefList) .forEach(adReferenceService::saveRefList); } private ADRefListItemCreateRequest buildRefList(@NonNull final IssueLabel issueLabel) { return ADRefListItemCreateRequest .builder() .name(TranslatableStrings.constant(issueLabel.getValue()))
.value(issueLabel.getValue()) .referenceId(ReferenceId.ofRepoId(LABEL_AD_Reference_ID)) .build(); } private void extractAndPropagateAdempiereException(final CompletableFuture completableFuture) { try { completableFuture.get(); } catch (final ExecutionException ex) { throw AdempiereException.wrapIfNeeded(ex.getCause()); } catch (final InterruptedException ex1) { throw AdempiereException.wrapIfNeeded(ex1); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\importer\IssueImporterService.java
2
请完成以下Java代码
public void setUid(String uid) { ((InetOrgPerson) this.instance).uid = uid; if (this.instance.getUsername() == null) { setUsername(uid); } } public void setInitials(String initials) { ((InetOrgPerson) this.instance).initials = initials; } public void setO(String organization) { ((InetOrgPerson) this.instance).o = organization; } public void setOu(String ou) { ((InetOrgPerson) this.instance).ou = ou; } public void setRoomNumber(String no) { ((InetOrgPerson) this.instance).roomNumber = no; } public void setTitle(String title) { ((InetOrgPerson) this.instance).title = title; } public void setCarLicense(String carLicense) { ((InetOrgPerson) this.instance).carLicense = carLicense; } public void setDepartmentNumber(String departmentNumber) { ((InetOrgPerson) this.instance).departmentNumber = departmentNumber; } public void setDisplayName(String displayName) { ((InetOrgPerson) this.instance).displayName = displayName; } public void setEmployeeNumber(String no) { ((InetOrgPerson) this.instance).employeeNumber = no; } public void setDestinationIndicator(String destination) { ((InetOrgPerson) this.instance).destinationIndicator = destination;
} public void setHomePhone(String homePhone) { ((InetOrgPerson) this.instance).homePhone = homePhone; } public void setStreet(String street) { ((InetOrgPerson) this.instance).street = street; } public void setPostalCode(String postalCode) { ((InetOrgPerson) this.instance).postalCode = postalCode; } public void setPostalAddress(String postalAddress) { ((InetOrgPerson) this.instance).postalAddress = postalAddress; } public void setMobile(String mobile) { ((InetOrgPerson) this.instance).mobile = mobile; } public void setHomePostalAddress(String homePostalAddress) { ((InetOrgPerson) this.instance).homePostalAddress = homePostalAddress; } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\InetOrgPerson.java
1
请完成以下Java代码
public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return BigDecimal.ZERO; } @Override protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { final IWeightable weightable = getWeightableOrNull(attributeSet); if (weightable == null) { return false; } final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue()); if (!weightable.isWeightGrossAttribute(attributeCode)) { return false; } if (!weightable.hasWeightGross()) { return false; } if (!weightable.hasWeightTare()) { return false; }
if (!(attributeValueContext instanceof IHUAttributePropagationContext)) { return false; } final IHUAttributePropagationContext huAttributePropagationContext = (IHUAttributePropagationContext)attributeValueContext; final AttributeCode attr_WeightNet = weightable.getWeightNetAttribute(); if (huAttributePropagationContext.isExternalInput() && huAttributePropagationContext.isValueUpdatedBefore(attr_WeightNet)) { // // Net weight was set externally. Do not modify it. return false; } return true; } @Override public boolean isDisplayedUI(@NonNull final IAttributeSet attributeSet, @NonNull final I_M_Attribute attribute) { return isLUorTUorTopLevelVHU(attributeSet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightGrossAttributeValueCallout.java
1
请完成以下Java代码
public ZoneId getTimeZone(@NonNull final OrgId orgId) { if (!orgId.isRegular()) { return SystemTime.zoneId(); } final ZoneId timeZone = getOrgInfoById(orgId).getTimeZone(); return timeZone != null ? timeZone : SystemTime.zoneId(); } @Override public boolean isEUOneStopShop(@NonNull final OrgId orgId) { final I_AD_Org org = getById(orgId); if (org == null) { throw new AdempiereException("No Organization found for ID: " + orgId); } return org.isEUOneStopShop(); } @Override public UserGroupId getSupplierApprovalExpirationNotifyUserGroupID(final OrgId orgId) { return getOrgInfoById(orgId).getSupplierApprovalExpirationNotifyUserGroupID(); }
@Override public UserGroupId getPartnerCreatedFromAnotherOrgNotifyUserGroupID(final OrgId orgId) { return getOrgInfoById(orgId).getPartnerCreatedFromAnotherOrgNotifyUserGroupID(); } @Override public String getOrgName(@NonNull final OrgId orgId) { return getById(orgId).getName(); } @Override public boolean isAutoInvoiceFlatrateTerm(@NonNull final OrgId orgId) { final OrgInfo orgInfo = getOrgInfoById(orgId); return orgInfo.isAutoInvoiceFlatrateTerms(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\impl\OrgDAO.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Object getPersistentState() { return AppResourceEntityImpl.class; } @Override
public boolean isGenerated() { return false; } @Override public void setGenerated(boolean generated) { this.generated = generated; } @Override public String toString() { return "CmmnResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppResourceEntityImpl.java
1
请完成以下Java代码
public int getAD_Document_Action_Access_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Document_Action_Access_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Ref_List getAD_Ref_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class); } @Override public void setAD_Ref_List(org.compiere.model.I_AD_Ref_List AD_Ref_List) { set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List); } /** Set Referenzliste. @param AD_Ref_List_ID Reference List based on Table */ @Override public void setAD_Ref_List_ID (int AD_Ref_List_ID) { if (AD_Ref_List_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, Integer.valueOf(AD_Ref_List_ID)); } /** Get Referenzliste. @return Reference List based on Table */ @Override public int getAD_Ref_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Ref_List_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class); } @Override public void setAD_Role(org.compiere.model.I_AD_Role AD_Role) { set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role); } /** Set Rolle. @param AD_Role_ID Responsibility Role */ @Override public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class); } @Override public void setC_DocType(org.compiere.model.I_C_DocType C_DocType) { set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType); } /** Set Belegart. @param C_DocType_ID Document type or rules */ @Override public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Document type or rules */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Document_Action_Access.java
1
请完成以下Java代码
private XmlRecordOther createRecordXmlRecordOther(@NonNull final RecordOtherType recordOtherType) { final XmlRecordOtherBuilder xRecordOther = XmlRecordOther.builder(); xRecordOther.recordService(createXmlRecordService(recordOtherType)); xRecordOther.tariffType(recordOtherType.getTariffType()); return xRecordOther.build(); } private XmlRecordService createXmlRecordService(@NonNull final RecordServiceType recordServiceType) { final XmlRecordServiceBuilder xRecordService = XmlRecordService.builder(); xRecordService.recordId(recordServiceType.getRecordId()); xRecordService.name(recordServiceType.getName()); xRecordService.dateBegin(recordServiceType.getDateBegin()); xRecordService.code(recordServiceType.getCode()); xRecordService.refCode(recordServiceType.getRefCode()); xRecordService.name(recordServiceType.getName()); xRecordService.session(recordServiceType.getSession()); xRecordService.quantity(recordServiceType.getQuantity()); xRecordService.dateBegin(recordServiceType.getDateBegin()); xRecordService.dateEnd(recordServiceType.getDateEnd()); xRecordService.providerId(recordServiceType.getProviderId()); xRecordService.responsibleId(recordServiceType.getResponsibleId()); xRecordService.unit(recordServiceType.getUnit()); xRecordService.unitFactor(recordServiceType.getUnitFactor()); xRecordService.externalFactor(recordServiceType.getExternalFactor()); xRecordService.amount(recordServiceType.getAmount()); xRecordService.vatRate(recordServiceType.getVatRate()); xRecordService.validate(recordServiceType.isValidate()); xRecordService.obligation(recordServiceType.isObligation()); xRecordService.sectionCode(recordServiceType.getSectionCode()); xRecordService.remark(recordServiceType.getRemark()); xRecordService.serviceAttributes(recordServiceType.getServiceAttributes()); return xRecordService.build(); } private ImmutableList<XmlDocument> createXmlDocuments(@Nullable final DocumentsType documents) { if (documents == null) { return ImmutableList.of(); } final ImmutableList.Builder<XmlDocument> xDocuments = ImmutableList.builder();
for (final DocumentType document : documents.getDocument()) { xDocuments.add(createXmlDocument(document)); } return xDocuments.build(); } private XmlDocument createXmlDocument(@NonNull final DocumentType documentType) { final XmlDocumentBuilder xDocument = XmlDocument.builder(); xDocument.filename(documentType.getFilename()); xDocument.mimeType(documentType.getMimeType()); xDocument.viewer(documentType.getViewer()); xDocument.base64(documentType.getBase64()); xDocument.url(documentType.getUrl()); return xDocument.build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\Invoice440ToCrossVersionModelTool.java
1
请完成以下Java代码
private static void streamOf() { Map<String, Employee> map3 = Stream.of(map1, map2) .flatMap(map -> map.entrySet().stream()) .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> new Employee(v1.getId(), v2.getName()) ) ); map3.entrySet().forEach(System.out::println); } private static void streamConcat() { Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (value1, value2) -> new Employee(value2.getId(), value1.getName()) )); result.entrySet().forEach(System.out::println); } private static void mergeFunction() { Map<String, Employee> map3 = new HashMap<>(map1); map2.forEach( (key, value) -> map3.merge(key, value, (v1, v2) -> new Employee(v1.getId(), v2.getName())) );
map3.entrySet().forEach(System.out::println); } private static void initialize() { Employee employee1 = new Employee(1L, "Henry"); map1.put(employee1.getName(), employee1); Employee employee2 = new Employee(22L, "Annie"); map1.put(employee2.getName(), employee2); Employee employee3 = new Employee(8L, "John"); map1.put(employee3.getName(), employee3); Employee employee4 = new Employee(2L, "George"); map2.put(employee4.getName(), employee4); Employee employee5 = new Employee(3L, "Henry"); map2.put(employee5.getName(), employee5); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-2\src\main\java\com\baeldung\map\mergemaps\MergeMaps.java
1
请在Spring Boot框架中完成以下Java代码
public class MultiFileItemWriteDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private ListItemReader<TestData> simpleReader; @Autowired private ItemStreamWriter<TestData> fileItemWriter; @Autowired private ItemStreamWriter<TestData> xmlFileItemWriter; @Bean public Job multiFileItemWriterJob() { return jobBuilderFactory.get("multiFileItemWriterJob6") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(simpleReader) .writer(multiFileItemWriter()) // .stream(fileItemWriter) // .stream(xmlFileItemWriter) .build(); } // 输出数据到多个文件 private CompositeItemWriter<TestData> multiFileItemWriter() { // 使用CompositeItemWriter代理 CompositeItemWriter<TestData> writer = new CompositeItemWriter<>(); // 设置具体写代理 writer.setDelegates(Arrays.asList(fileItemWriter, xmlFileItemWriter));
return writer; } // 将数据分类,然后分别输出到对应的文件(此时需要将writer注册到ioc容器,否则报 // WriterNotOpenException: Writer must be open before it can be written to) private ClassifierCompositeItemWriter<TestData> classifierMultiFileItemWriter() { ClassifierCompositeItemWriter<TestData> writer = new ClassifierCompositeItemWriter<>(); writer.setClassifier((Classifier<TestData, ItemWriter<? super TestData>>) testData -> { try { // id能被2整除则输出到普通文本,否则输出到xml文本 return testData.getId() % 2 == 0 ? fileItemWriter : xmlFileItemWriter; } catch (Exception e) { e.printStackTrace(); } return null; }); return writer; } }
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\MultiFileItemWriteDemo.java
2
请完成以下Java代码
public static Optional<LocationBasicInfo> ofNullable(@Nullable final JsonLocation location) { return location != null ? of(location) : Optional.empty(); } @NonNull public static Optional<LocationBasicInfo> of(@NonNull final JsonLocation location) { if (Check.isBlank(location.getCountryCode()) || Check.isBlank(location.getCity()) || Check.isBlank(location.getZipCode())) { return Optional.empty(); }
final List<String> streetAndHouseNoParts = Stream.of(location.getStreet(), location.getHouseNo()) .filter(Check::isNotBlank) .collect(Collectors.toList()); final String streetAndHouseNo = !streetAndHouseNoParts.isEmpty() ? Joiner.on(",").join(streetAndHouseNoParts) : null; return Optional.of(LocationBasicInfo.builder() .countryCode(CountryCode.ofAlpha2(location.getCountryCode())) .city(location.getCity()) .postalCode(location.getZipCode()) .streetAndNumber(streetAndHouseNo) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\LocationBasicInfo.java
1
请在Spring Boot框架中完成以下Java代码
void init(HttpSecurity httpSecurity) { AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils .getAuthorizationServerSettings(httpSecurity); String authorizationServerMetadataEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed() ? "/.well-known/oauth-authorization-server/**" : "/.well-known/oauth-authorization-server"; this.requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, authorizationServerMetadataEndpointUri); } @Override void configure(HttpSecurity httpSecurity) { OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter = new OAuth2AuthorizationServerMetadataEndpointFilter(); Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = getAuthorizationServerMetadataCustomizer(); if (authorizationServerMetadataCustomizer != null) { authorizationServerMetadataEndpointFilter .setAuthorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer); } httpSecurity.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); } private Consumer<OAuth2AuthorizationServerMetadata.Builder> getAuthorizationServerMetadataCustomizer() { Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = null; if (this.defaultAuthorizationServerMetadataCustomizer != null || this.authorizationServerMetadataCustomizer != null) {
if (this.defaultAuthorizationServerMetadataCustomizer != null) { authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer; } if (this.authorizationServerMetadataCustomizer != null) { authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null) ? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer) : this.authorizationServerMetadataCustomizer; } } return authorizationServerMetadataCustomizer; } @Override RequestMatcher getRequestMatcher() { return this.requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2AuthorizationServerMetadataEndpointConfigurer.java
2
请完成以下Java代码
public boolean isChannelTransacted() { return this.transactional; } /** * Flag to indicate that channels created by this component will be transactional. * * @param transactional the flag value to set */ public void setChannelTransacted(boolean transactional) { this.transactional = transactional; } /** * Set the ConnectionFactory to use for obtaining RabbitMQ {@link Connection Connections}. * * @param connectionFactory The connection factory. */ public void setConnectionFactory(ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } /** * @return The ConnectionFactory that this accessor uses for obtaining RabbitMQ {@link Connection Connections}. */ public ConnectionFactory getConnectionFactory() { return this.connectionFactory; } @Override public void afterPropertiesSet() { Assert.notNull(this.connectionFactory, "ConnectionFactory is required"); } /** * Create a RabbitMQ Connection via this template's ConnectionFactory and its host and port values. * @return the new RabbitMQ Connection * @see ConnectionFactory#createConnection */ protected Connection createConnection() { return this.connectionFactory.createConnection(); } /** * Fetch an appropriate Connection from the given RabbitResourceHolder. * * @param holder the RabbitResourceHolder * @return an appropriate Connection fetched from the holder, or <code>null</code> if none found */ protected @Nullable Connection getConnection(RabbitResourceHolder holder) { return holder.getConnection(); }
/** * Fetch an appropriate Channel from the given RabbitResourceHolder. * * @param holder the RabbitResourceHolder * @return an appropriate Channel fetched from the holder, or <code>null</code> if none found */ protected @Nullable Channel getChannel(RabbitResourceHolder holder) { return holder.getChannel(); } protected RabbitResourceHolder getTransactionalResourceHolder() { return ConnectionFactoryUtils.getTransactionalResourceHolder(this.connectionFactory, isChannelTransacted()); } protected RuntimeException convertRabbitAccessException(Exception ex) { return RabbitExceptionTranslator.convertRabbitAccessException(ex); } protected void obtainObservationRegistry(@Nullable ApplicationContext appContext) { if (appContext != null) { ObjectProvider<ObservationRegistry> registry = appContext.getBeanProvider(ObservationRegistry.class); this.observationRegistry = registry.getIfUnique(() -> this.observationRegistry); } } protected ObservationRegistry getObservationRegistry() { return this.observationRegistry; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitAccessor.java
1
请完成以下Java代码
public MaterialDescriptor withProductDescriptor(final ProductDescriptor productDescriptor) { final MaterialDescriptor result = MaterialDescriptor.builder() .productDescriptor(productDescriptor) .date(this.date) .warehouseId(this.warehouseId) .locatorId(this.locatorId) .customerId(this.customerId) .quantity(this.quantity) .build(); return result.asssertMaterialDescriptorComplete(); } public MaterialDescriptor withCustomerId(@Nullable final BPartnerId customerId) { final MaterialDescriptor result = MaterialDescriptor.builder() .warehouseId(this.warehouseId) .locatorId(this.locatorId) .date(this.date) .productDescriptor(this) .customerId(customerId)
.quantity(this.quantity) .build(); return result.asssertMaterialDescriptorComplete(); } public MaterialDescriptor withStorageAttributes( @NonNull final AttributesKey storageAttributesKey, final int attributeSetInstanceId) { final ProductDescriptor newProductDescriptor = ProductDescriptor .forProductAndAttributes( getProductId(), storageAttributesKey, attributeSetInstanceId); return withProductDescriptor(newProductDescriptor); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\MaterialDescriptor.java
1
请完成以下Java代码
public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Review) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Review{" + "id=" + id + ", content=" + content + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Review.java
1
请完成以下Java代码
public Set<Method> getDateDeprecatedMethods() { Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class); return deprecatedMethodsSet; } @SuppressWarnings("rawtypes") public Set<Constructor> getDateDeprecatedConstructors() { Reflections reflections = new Reflections(Date.class, new MethodAnnotationsScanner()); Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class); return constructorsSet; } public Set<Method> getMethodsWithDateParam() { Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class); return methodsSet; } public Set<Method> getMethodsWithVoidReturn() {
Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner()); Set<Method> methodsSet = reflections.getMethodsReturn(void.class); return methodsSet; } public Set<String> getPomXmlPaths() { Reflections reflections = new Reflections(new ResourcesScanner()); Set<String> resourcesSet = reflections.getResources(Pattern.compile(".*pom\\.xml")); return resourcesSet; } public Set<Class<? extends Scanner>> getReflectionsSubTypesUsingBuilder() { Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.reflections")) .setScanners(new SubTypesScanner())); Set<Class<? extends Scanner>> scannersSet = reflections.getSubTypesOf(Scanner.class); return scannersSet; } }
repos\tutorials-master\libraries-jdk8\src\main\java\reflections\ReflectionsApp.java
1
请在Spring Boot框架中完成以下Java代码
public class ApplicationProperties { /** Log the configuration to the log on startup */ private boolean showConfigOnStartup; /** URL (host/port) for second service */ private RemoteService client = new RemoteService(); private Set<String> propagatedHeaders; public boolean isShowConfigOnStartup() { return showConfigOnStartup; } public void setShowConfigOnStartup(boolean showConfigOnStartup) { this.showConfigOnStartup = showConfigOnStartup; } public RemoteService getClient() { return client; } public void setClient(RemoteService client) { this.client = client;
} public Set<String> getPropagatedHeaders() { return propagatedHeaders; } public void setPropagatedHeaders(Set<String> propagatedHeaders) { this.propagatedHeaders = propagatedHeaders; } @Override public String toString() { return "ApplicationProperties{" + "showConfigOnStartup=" + showConfigOnStartup + ", client=" + client + '}'; } }
repos\spring-boot3-demo-master\src\main\java\com\giraone\sb3\demo\config\ApplicationProperties.java
2
请完成以下Java代码
default ITranslatableString getColumnTrl(@NonNull final String columnName, @Nullable final String defaultValue) { final Map<String, String> columnTrls = new HashMap<>(); for (final IModelTranslation modelTrl : getAllTranslations().values()) { if (!modelTrl.isTranslated(columnName)) { continue; } final String adLanguage = modelTrl.getAD_Language(); final String columnTrl = modelTrl.getTranslation(columnName); columnTrls.put(adLanguage, Strings.nullToEmpty(columnTrl)); } return TranslatableStrings.ofMap(columnTrls, defaultValue); } /** * Translates columnName to given adLanguage. If the language or the column was not found, {@link Optional#empty()} will be returned. */
default Optional<String> translateColumn(final String columnName, final String adLanguage) { final IModelTranslation modelTrl = getTranslation(adLanguage); if (NullModelTranslation.isNull(modelTrl)) { return Optional.empty(); } final String columnTrl = modelTrl.getTranslation(columnName); if (columnTrl == null) { return Optional.empty(); } return Optional.of(columnTrl); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\IModelTranslationMap.java
1
请完成以下Java代码
public String getDisplay (final IValidationContext evalCtx, final Object key) { // linear search in m_data final int size = getSize(); for (int i = 0; i < size; i++) { final Object oo = getElementAt(i); if (oo != null && oo instanceof NamePair) { NamePair pp = (NamePair)oo; if (pp.getID().equals(key)) return pp.getName(); } } return "<" + key + ">"; } // getDisplay /** * The Lookup contains the key * @param key key * @return true if contains key */ @Override public boolean containsKey (final IValidationContext evalCtx, final Object key) { // linear search in p_data final int size = getSize(); for (int i = 0; i < size; i++) { final Object oo = getElementAt(i); if (oo != null && oo instanceof NamePair) { NamePair pp = (NamePair)oo; if (pp.getID().equals(key)) return true; } } return false; } // containsKey /** * Get Object of Key Value * @param key key * @return Object or null */ @Override public NamePair get (final IValidationContext evalCtx, Object key) { // linear search in m_data final int size = getSize(); for (int i = 0; i < size; i++) { Object oo = getElementAt(i); if (oo != null && oo instanceof NamePair) { NamePair pp = (NamePair)oo; if (pp.getID().equals(key)) return pp; } } return null; } // get /** * Return data as sorted Array * @param mandatory mandatory * @param onlyValidated only validated * @param onlyActive only active * @param temporary force load for temporary display * @return list of data */ @Override public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { final int size = getSize();
final List<Object> list = new ArrayList<Object>(size); for (int i = 0; i < size; i++) { final Object oo = getElementAt(i); list.add(oo); } // Sort Data if (m_keyColumn.endsWith("_ID")) { KeyNamePair p = KeyNamePair.EMPTY; if (!mandatory) list.add (p); Collections.sort (list, p); } else { ValueNamePair p = ValueNamePair.EMPTY; if (!mandatory) list.add (p); Collections.sort (list, p); } return list; } // getArray /** * Refresh Values (nop) * @return number of cache */ @Override public int refresh() { return getSize(); } // refresh @Override public String getTableName() { if (Check.isEmpty(m_keyColumn, true)) { return null; } return MQuery.getZoomTableName(m_keyColumn); } /** * Get underlying fully qualified Table.Column Name * @return column name */ @Override public String getColumnName() { return m_keyColumn; } // getColumnName @Override public String getColumnNameNotFQ() { return m_keyColumn; } } // XLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\XLookup.java
1
请在Spring Boot框架中完成以下Java代码
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { RawAccessJwtToken token = new RawAccessJwtToken(tokenExtractor.extract(request)); return getAuthenticationManager().authenticate(new JwtAuthenticationToken(token)); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authResult); SecurityContextHolder.setContext(context); chain.doFilter(request, response); } @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { if (!super.requiresAuthentication(request, response)) { return false; } String header = request.getHeader(AUTHORIZATION_HEADER); if (header == null) { header = request.getHeader(AUTHORIZATION_HEADER_V2); }
if (header == null) { // If there is NO auth header at all, let the JWT filter try to attempt Authentication and failure in the process. return true; } return header.startsWith(BEARER_HEADER_PREFIX); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); failureHandler.onAuthenticationFailure(request, response, failed); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\JwtTokenAuthenticationProcessingFilter.java
2
请完成以下Java代码
public boolean isSplitAcctTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSplitAcctTrx); } @Override public void setLine (final int Line) { set_Value (COLUMNNAME_Line, Line); } @Override public int getLine() { return get_ValueAsInt(COLUMNNAME_Line); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } /**
* Type AD_Reference_ID=540534 * Reference name: GL_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=540534; /** Normal = N */ public static final String TYPE_Normal = "N"; /** Tax = T */ public static final String TYPE_Tax = "T"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java
1
请在Spring Boot框架中完成以下Java代码
private void logFailure(Throwable e) { if (e instanceof CancellationException) { //Probably this is fine and happens due to re-balancing. log.trace("Partition fetch task error", e); } else { log.error("Partition fetch task error", e); } } private void logPartitions() { log.info("[{}] Managing following partitions:", getServiceName()); partitionedEntities.forEach((tpi, entities) -> { log.info("[{}][{}]: {} entities", getServiceName(), tpi.getFullTopicName(), entities.size()); }); }
protected void onRepartitionEvent() { } private Set<TopicPartitionInfo> getLatestPartitions() { log.debug("getLatestPartitionsFromQueue, queue size {}", subscribeQueue.size()); Set<TopicPartitionInfo> partitions = null; while (!subscribeQueue.isEmpty()) { partitions = subscribeQueue.poll(); log.debug("polled from the queue partitions {}", partitions); } log.debug("getLatestPartitionsFromQueue, partitions {}", partitions); return partitions; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\partition\AbstractPartitionBasedService.java
2
请完成以下Java代码
public void setHostname(String hostname) { this.hostname = hostname; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public long getHeartbeatVersion() { return heartbeatVersion; } public void setHeartbeatVersion(long heartbeatVersion) { this.heartbeatVersion = heartbeatVersion; } public String getVersion() { return version; } public MachineInfo setVersion(String version) { this.version = version; return this; } public boolean isHealthy() { long delta = System.currentTimeMillis() - lastHeartbeat; return delta < DashboardConfig.getUnhealthyMachineMillis(); } /** * whether dead should be removed * * @return */ public boolean isDead() { if (DashboardConfig.getAutoRemoveMachineMillis() > 0) { long delta = System.currentTimeMillis() - lastHeartbeat; return delta > DashboardConfig.getAutoRemoveMachineMillis(); } return false; } public long getLastHeartbeat() { return lastHeartbeat; } public void setLastHeartbeat(long lastHeartbeat) { this.lastHeartbeat = lastHeartbeat; } @Override public int compareTo(MachineInfo o) { if (this == o) { return 0; } if (!port.equals(o.getPort())) { return port.compareTo(o.getPort()); } if (!StringUtil.equals(app, o.getApp())) { return app.compareToIgnoreCase(o.getApp()); } return ip.compareToIgnoreCase(o.getIp()); }
@Override public String toString() { return new StringBuilder("MachineInfo {") .append("app='").append(app).append('\'') .append(",appType='").append(appType).append('\'') .append(", hostname='").append(hostname).append('\'') .append(", ip='").append(ip).append('\'') .append(", port=").append(port) .append(", heartbeatVersion=").append(heartbeatVersion) .append(", lastHeartbeat=").append(lastHeartbeat) .append(", version='").append(version).append('\'') .append(", healthy=").append(isHealthy()) .append('}').toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MachineInfo)) { return false; } MachineInfo that = (MachineInfo)o; return Objects.equals(app, that.app) && Objects.equals(ip, that.ip) && Objects.equals(port, that.port); } @Override public int hashCode() { return Objects.hash(app, ip, port); } /** * Information for log * * @return */ public String toLogString() { return app + "|" + ip + "|" + port + "|" + version; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\MachineInfo.java
1
请在Spring Boot框架中完成以下Java代码
public void setDepartment(String value) { this.department = value; } /** * Gets the value of the customerReferenceNumber property. * * @return * possible object is * {@link String } * */ public String getCustomerReferenceNumber() { return customerReferenceNumber; } /** * Sets the value of the customerReferenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setCustomerReferenceNumber(String value) { this.customerReferenceNumber = value; } /** * Fiscal number of the invoice recipient. * * @return * possible object is * {@link String }
* */ public String getFiscalNumber() { return fiscalNumber; } /** * Sets the value of the fiscalNumber property. * * @param value * allowed object is * {@link String } * */ public void setFiscalNumber(String value) { this.fiscalNumber = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\InvoiceRecipientExtensionType.java
2
请完成以下Java代码
public void onNext(ServerStreamingResponse value) {} @Override public void onError(Throwable t) { CallServerStreamingRpc(); } @Override public void onCompleted() { CallServerStreamingRpc(); } }); } private void CallBidStreamingRpc() { byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)]; ThreadLocalRandom.current().nextBytes(bytes); BidiStreamingRequest request = BidiStreamingRequest.newBuilder() .setMessage(new String(bytes)).build(); StreamObserver<BidiStreamingRequest> requestStreamObserver = stub.bidiStreamingRpc( new StreamObserver<>() { @Override public void onNext(BidiStreamingResponse value) {} @Override public void onError(Throwable t) { CallBidStreamingRpc();
} @Override public void onCompleted() { CallBidStreamingRpc(); } }); requestStreamObserver.onNext(request); requestStreamObserver.onCompleted(); } @Override public void run(String... args) { CallUnaryRpc(); CallServerStreamingRpc(); CallClientStreamingRpc(); CallBidStreamingRpc(); } }
repos\grpc-spring-master\examples\grpc-observability\frontend\src\main\java\net\devh\boot\grpc\examples\observability\frontend\FrontendApplication.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getReleaseYear() { return releaseYear; } public void setReleaseYear(int releaseYear) { this.releaseYear = releaseYear; }
public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Book(String name, int releaseYear, String isbn) { this.name = name; this.releaseYear = releaseYear; this.isbn = isbn; } }
repos\tutorials-master\core-java-modules\core-java-collections-conversions\src\main\java\com\baeldung\convertToMap\Book.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductCategoryId implements RepoIdAware { int repoId; @JsonCreator public static ProductCategoryId ofRepoId(final int repoId) { return new ProductCategoryId(repoId); } @Nullable public static ProductCategoryId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ProductCategoryId(repoId) : null; } public static Optional<ProductCategoryId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static int toRepoId(@Nullable final ProductCategoryId productCategoryId) {
return productCategoryId != null ? productCategoryId.getRepoId() : -1; } private ProductCategoryId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_Product_Category_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ProductCategoryId.java
2
请完成以下Java代码
public synchronized void close() { if (this.shutdown) { return; } this.shutdown = true; final List<ShutdownRecord> shutdownEntries = new ArrayList<>(); for (final Entry<String, ManagedChannel> entry : this.channels.entrySet()) { final ManagedChannel channel = entry.getValue(); channel.shutdown(); final long gracePeriod = this.properties.getChannel(entry.getKey()).getShutdownGracePeriod().toMillis(); shutdownEntries.add(new ShutdownRecord(entry.getKey(), channel, gracePeriod)); } try { final long start = System.currentTimeMillis(); shutdownEntries.sort(comparingLong(ShutdownRecord::getGracePeriod)); for (final ShutdownRecord entry : shutdownEntries) { if (!entry.channel.isTerminated()) { log.debug("Awaiting channel termination: {}", entry.name); final long waitedTime = System.currentTimeMillis() - start; final long waitTime = entry.gracePeriod - waitedTime; if (waitTime > 0) { entry.channel.awaitTermination(waitTime, MILLISECONDS); } entry.channel.shutdownNow(); } log.debug("Completed channel termination: {}", entry.name); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); log.debug("We got interrupted - Speeding up shutdown process"); } finally { for (final ManagedChannel channel : this.channels.values()) { if (!channel.isTerminated()) { log.debug("Channel not terminated yet - force shutdown now: {} ", channel); channel.shutdownNow(); } } }
final int channelCount = this.channels.size(); this.channels.clear(); this.channelStates.clear(); log.debug("GrpcChannelFactory closed (including {} channels)", channelCount); } private static class ShutdownRecord { private final String name; private final ManagedChannel channel; private final long gracePeriod; public ShutdownRecord(final String name, final ManagedChannel channel, final long gracePeriod) { this.name = name; this.channel = channel; // gracePeriod < 0 => Infinite this.gracePeriod = gracePeriod < 0 ? Long.MAX_VALUE : gracePeriod; } long getGracePeriod() { return this.gracePeriod; } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\channelfactory\AbstractChannelFactory.java
1
请完成以下Java代码
public LinearRing createLinearRingByWKT(String ringWKT) throws ParseException{ WKTReader reader = new WKTReader( geometryFactory ); return (LinearRing) reader.read(ringWKT); } /** * 几何对象转GeoJson对象 * @param geometry * @return * @throws Exception */ public static String geometryToGeoJson(Geometry geometry) throws Exception { if (geometry == null) { return null; } StringWriter writer = new StringWriter(); geometryJson.write(geometry, writer); String geojson = writer.toString();
writer.close(); return geojson; } /** * GeoJson转几何对象 * @param geojson * @return * @throws Exception */ public static Geometry geoJsonToGeometry(String geojson) throws Exception { return geometryJson.read(new StringReader(geojson)); } }
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\geotools\GeometryCreator.java
1
请完成以下Java代码
public String getMediaType() { return this.mediaType; } public boolean isNegated() { return this.negated; } } /** * A description of a {@link NameValueExpression} in a request mapping condition. */ public static class NameValueExpressionDescription { private final String name; private final @Nullable Object value; private final boolean negated; NameValueExpressionDescription(NameValueExpression<?> expression) { this.name = expression.getName();
this.value = expression.getValue(); this.negated = expression.isNegated(); } public String getName() { return this.name; } public @Nullable Object getValue() { return this.value; } public boolean isNegated() { return this.negated; } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\RequestMappingConditionsDescription.java
1
请完成以下Java代码
private I_PP_Order getPP_Order() { // not null return ppOrder; } /** * Delete existing {@link I_PP_Order_Report}s lines linked to current manufacturing order. */ public void deleteReportLines() { final I_PP_Order ppOrder = getPP_Order(); queryBL.createQueryBuilder(I_PP_Order_Report.class, getContext()) .addEqualsFilter(org.eevolution.model.I_PP_Order_Report.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID()) .create() // create query .delete(); // delete matching records _createdReportLines.clear(); _seqNoNext = 10; // reset seqNo } /** * Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} lines). * * @param qiLines */ public void save(final Collection<IQualityInspectionLine> qiLines) { if (qiLines == null || qiLines.isEmpty()) { return; } final List<IQualityInspectionLine> qiLinesToSave = new ArrayList<>(qiLines); // // Discard not accepted lines and then sort them if (reportLinesSorter != null) { reportLinesSorter.filterAndSort(qiLinesToSave); } // // Iterate lines and save one by one for (final IQualityInspectionLine qiLine : qiLinesToSave) { save(qiLine); } } /** * Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} line). * * @param qiLine */ private void save(final IQualityInspectionLine qiLine) { Check.assumeNotNull(qiLine, "qiLine not null"); final I_PP_Order ppOrder = getPP_Order(); final int seqNo = _seqNoNext; BigDecimal qty = qiLine.getQty(); if (qty != null && qiLine.isNegateQtyInReport()) {
qty = qty.negate(); } // // Create report line final I_PP_Order_Report reportLine = InterfaceWrapperHelper.newInstance(I_PP_Order_Report.class, getContext()); reportLine.setPP_Order(ppOrder); reportLine.setAD_Org_ID(ppOrder.getAD_Org_ID()); reportLine.setSeqNo(seqNo); reportLine.setIsActive(true); // reportLine.setQualityInspectionLineType(qiLine.getQualityInspectionLineType()); reportLine.setProductionMaterialType(qiLine.getProductionMaterialType()); reportLine.setM_Product(qiLine.getM_Product()); reportLine.setName(qiLine.getName()); reportLine.setQty(qty); reportLine.setC_UOM(qiLine.getC_UOM()); reportLine.setPercentage(qiLine.getPercentage()); reportLine.setQtyProjected(qiLine.getQtyProjected()); reportLine.setComponentType(qiLine.getComponentType()); reportLine.setVariantGroup(qiLine.getVariantGroup()); // // Save report line InterfaceWrapperHelper.save(reportLine); _createdReportLines.add(reportLine); _seqNoNext += 10; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderReportWriter.java
1