instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
static Cipher newCipher(String algorithm) { try { return Cipher.getInstance(algorithm); } catch (NoSuchAlgorithmException ex) { throw new IllegalArgumentException("Not a valid encryption algorithm", ex); } catch (NoSuchPaddingException ex) { throw new IllegalStateException("Should not happen", ex); } } /** * Initializes the Cipher for use. */ static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) { try { return cipher.getParameters().getParameterSpec(parameterSpecClass); } catch (InvalidParameterSpecException ex) { throw new IllegalArgumentException("Unable to access parameter", ex); } } /** * Initializes the Cipher for use. */ static void initCipher(Cipher cipher, int mode, SecretKey secretKey) { initCipher(cipher, mode, secretKey, null); } /** * Initializes the Cipher for use. */ static void initCipher(Cipher cipher, int mode, SecretKey secretKey, byte[] salt, int iterationCount) { initCipher(cipher, mode, secretKey, new PBEParameterSpec(salt, iterationCount)); } /** * Initializes the Cipher for use. */ static void initCipher(Cipher cipher, int mode, SecretKey secretKey, @Nullable AlgorithmParameterSpec parameterSpec) { try { if (parameterSpec != null) { cipher.init(mode, secretKey, parameterSpec);
} else { cipher.init(mode, secretKey); } } catch (InvalidKeyException ex) { throw new IllegalArgumentException("Unable to initialize due to invalid secret key", ex); } catch (InvalidAlgorithmParameterException ex) { throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", ex); } } /** * Invokes the Cipher to perform encryption or decryption (depending on the * initialized mode). */ static byte[] doFinal(Cipher cipher, byte[] input) { try { return cipher.doFinal(input); } catch (IllegalBlockSizeException ex) { throw new IllegalStateException("Unable to invoke Cipher due to illegal block size", ex); } catch (BadPaddingException ex) { throw new IllegalStateException("Unable to invoke Cipher due to bad padding", ex); } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\CipherUtils.java
1
请完成以下Java代码
public Integer getControlBehavior() { return controlBehavior; } public void setControlBehavior(Integer controlBehavior) { this.controlBehavior = controlBehavior; } public Integer getBurst() { return burst; } public void setBurst(Integer burst) { this.burst = burst; } public Integer getMaxQueueingTimeoutMs() { return maxQueueingTimeoutMs; } public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) { this.maxQueueingTimeoutMs = maxQueueingTimeoutMs; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GatewayFlowRuleEntity that = (GatewayFlowRuleEntity) o; return Objects.equals(id, that.id) && Objects.equals(app, that.app) && Objects.equals(ip, that.ip) && Objects.equals(port, that.port) && Objects.equals(gmtCreate, that.gmtCreate) && Objects.equals(gmtModified, that.gmtModified) && Objects.equals(resource, that.resource) && Objects.equals(resourceMode, that.resourceMode) && Objects.equals(grade, that.grade) && Objects.equals(count, that.count) && Objects.equals(interval, that.interval) && Objects.equals(intervalUnit, that.intervalUnit) && Objects.equals(controlBehavior, that.controlBehavior) && Objects.equals(burst, that.burst) && Objects.equals(maxQueueingTimeoutMs, that.maxQueueingTimeoutMs) &&
Objects.equals(paramItem, that.paramItem); } @Override public int hashCode() { return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, resource, resourceMode, grade, count, interval, intervalUnit, controlBehavior, burst, maxQueueingTimeoutMs, paramItem); } @Override public String toString() { return "GatewayFlowRuleEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", resource='" + resource + '\'' + ", resourceMode=" + resourceMode + ", grade=" + grade + ", count=" + count + ", interval=" + interval + ", intervalUnit=" + intervalUnit + ", controlBehavior=" + controlBehavior + ", burst=" + burst + ", maxQueueingTimeoutMs=" + maxQueueingTimeoutMs + ", paramItem=" + paramItem + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\GatewayFlowRuleEntity.java
1
请完成以下Java代码
public class DefaultSchedulerComponent implements SchedulerComponent { private ScheduledExecutorService schedulerExecutor; @PostConstruct public void init() { schedulerExecutor = ThingsBoardExecutors.newSingleThreadScheduledExecutor("queue-scheduler"); } @PreDestroy public void destroy() { if (schedulerExecutor != null) { schedulerExecutor.shutdownNow(); } } public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return schedulerExecutor.schedule(command, delay, unit); } public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return schedulerExecutor.schedule(callable, delay, unit); } public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return schedulerExecutor.scheduleAtFixedRate(command, initialDelay, period, unit); } public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return schedulerExecutor.scheduleWithFixedDelay(command, initialDelay, delay, unit); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\scheduler\DefaultSchedulerComponent.java
1
请完成以下Java代码
public static SQLDatabaseDriverFactory get() { return instance; } private final Map<String, ISQLDatabaseDriver> dbType2driver = new HashMap<String, ISQLDatabaseDriver>(); private SQLDatabaseDriverFactory() { super(); // Register defaults dbType2driver.put(PgSQLDatabaseDriver.DBTYPE, new PgSQLDatabaseDriver()); } public ISQLDatabaseDriver getSQLDatabaseDriver(final String dbType)
{ if (dbType == null || dbType.trim().isEmpty()) { throw new IllegalArgumentException("dbType shall not be empty"); } final ISQLDatabaseDriver driver = dbType2driver.get(dbType); if (driver == null) { throw new IllegalStateException("No database driver was found for database type: " + dbType); } return driver; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\SQLDatabaseDriverFactory.java
1
请完成以下Java代码
public boolean isDeferredConstraints () { Object oo = get_Value(COLUMNNAME_IsDeferredConstraints); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Release No. @param ReleaseNo Internal Release Number */ @Override public void setReleaseNo (java.lang.String ReleaseNo) { set_Value (COLUMNNAME_ReleaseNo, ReleaseNo); } /** Get Release No. @return Internal Release Number */ @Override public java.lang.String getReleaseNo () { return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Sequence.
@param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_Value (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
1
请完成以下Java代码
public Map<String, Object> getSettings() { return this.settings; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AbstractSettings that = (AbstractSettings) obj; return this.settings.equals(that.settings); } @Override public int hashCode() { return Objects.hash(this.settings); } @Override public String toString() { return "AbstractSettings {" + "settings=" + this.settings + '}'; } /** * A builder for subclasses of {@link AbstractSettings}. * * @param <T> the type of object * @param <B> the type of the builder */ protected abstract static class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> { private final Map<String, Object> settings = new HashMap<>(); protected AbstractBuilder() { } /** * Sets a configuration setting. * @param name the name of the setting * @param value the value of the setting * @return the {@link AbstractBuilder} for further configuration */ public B setting(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); getSettings().put(name, value); return getThis();
} /** * A {@code Consumer} of the configuration settings {@code Map} allowing the * ability to add, replace, or remove. * @param settingsConsumer a {@link Consumer} of the configuration settings * {@code Map} * @return the {@link AbstractBuilder} for further configuration */ public B settings(Consumer<Map<String, Object>> settingsConsumer) { settingsConsumer.accept(getSettings()); return getThis(); } public abstract T build(); protected final Map<String, Object> getSettings() { return this.settings; } @SuppressWarnings("unchecked") protected final B getThis() { return (B) this; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AbstractSettings.java
1
请完成以下Java代码
public AnnotatedTableFactory setSelectionMode(final int selectionMode) { this.selectionMode = selectionMode; return this; } public AnnotatedTableFactory addListSelectionListener(final ListSelectionListener listener) { Check.assumeNotNull(listener, "listener not null"); selectionListeners.add(listener); return this; } public AnnotatedTableFactory setCreateStandardSelectActions(final boolean createStandardSelectActions) { this.createStandardSelectActions = createStandardSelectActions; return this; } /** * Adds an popup action. *
* NOTE to developer: you can easily implement table popup actions by extending {@link AnnotatedTableAction}. * * @param action * @return this */ public AnnotatedTableFactory addPopupAction(final Action action) { Check.assumeNotNull(action, "action not null"); if (!popupActions.contains(action)) { popupActions.add(action); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableFactory.java
1
请完成以下Java代码
protected List<PurchaseDemand> getDemands(@NonNull final CreateViewRequest request) { final Set<PurchaseCandidateId> purchaseCandidateIds = PurchaseCandidateId.ofRepoIds(request.getFilterOnlyIds()); Check.assumeNotEmpty(purchaseCandidateIds, "purchaseCandidateIds is not empty"); final List<PurchaseCandidate> purchaseCandidates = purchaseCandidatesRepo.getAllByIds(purchaseCandidateIds); Check.assumeNotEmpty(purchaseCandidates, "purchaseCandidates is not empty"); return PurchaseCandidateAggregator.aggregate(purchaseCandidates) .stream() .map(aggregate -> toPurchaseDemand(aggregate)) .collect(ImmutableList.toImmutableList()); } private static PurchaseDemand toPurchaseDemand(@NonNull final PurchaseCandidateAggregate aggregate) { return PurchaseDemand.builder() .existingPurchaseCandidateIds(aggregate.getPurchaseCandidateIds()) // .orgId(aggregate.getOrgId()) .warehouseId(aggregate.getWarehouseId()) // .productId(aggregate.getProductId()) .attributeSetInstanceId(aggregate.getAttributeSetInstanceId()) // .qtyToDeliver(aggregate.getQtyToDeliver())
// .salesPreparationDate(aggregate.getDatePromised()) // .build(); } @Override protected void onViewClosedByUser(@NonNull final PurchaseView purchaseView) { final List<PurchaseRow> rows = purchaseView.getRows(); PurchaseRowsSaver.builder() .purchaseCandidatesRepo(purchaseCandidatesRepo) .build() .save(rows); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseCandidates2PurchaseViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
class FileWatchingFailureHandler implements FailureHandler { private final FileSystemWatcherFactory fileSystemWatcherFactory; FileWatchingFailureHandler(FileSystemWatcherFactory fileSystemWatcherFactory) { this.fileSystemWatcherFactory = fileSystemWatcherFactory; } @Override public Outcome handle(Throwable failure) { CountDownLatch latch = new CountDownLatch(1); FileSystemWatcher watcher = this.fileSystemWatcherFactory.getFileSystemWatcher(); watcher.addSourceDirectories(new ClassPathDirectories(Restarter.getInstance().getInitialUrls())); watcher.addListener(new Listener(latch)); watcher.start(); try { latch.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return Outcome.RETRY; }
private static class Listener implements FileChangeListener { private final CountDownLatch latch; Listener(CountDownLatch latch) { this.latch = latch; } @Override public void onChange(Set<ChangedFiles> changeSet) { this.latch.countDown(); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\FileWatchingFailureHandler.java
2
请完成以下Java代码
public boolean isTaxIdMatch() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIdMatch); } @Override public void setIsTaxRateMatch (final boolean IsTaxRateMatch) { set_Value (COLUMNNAME_IsTaxRateMatch, IsTaxRateMatch); } @Override public boolean isTaxRateMatch() { return get_ValueAsBoolean(COLUMNNAME_IsTaxRateMatch); } @Override public void setRun_Tax_ID (final int Run_Tax_ID) { if (Run_Tax_ID < 1) set_Value (COLUMNNAME_Run_Tax_ID, null); else set_Value (COLUMNNAME_Run_Tax_ID, Run_Tax_ID); } @Override
public int getRun_Tax_ID() { return get_ValueAsInt(COLUMNNAME_Run_Tax_ID); } @Override public void setRun_Tax_Lookup_Log (final @Nullable java.lang.String Run_Tax_Lookup_Log) { set_Value (COLUMNNAME_Run_Tax_Lookup_Log, Run_Tax_Lookup_Log); } @Override public java.lang.String getRun_Tax_Lookup_Log() { return get_ValueAsString(COLUMNNAME_Run_Tax_Lookup_Log); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_RunLine.java
1
请完成以下Java代码
public OptimizeRestService getOptimizeRestService() { return super.getOptimizeRestService(null); } @Path(VersionRestService.PATH) public VersionRestService getVersionRestService() { return super.getVersionRestService(null); } @Path(SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService() { return super.getSchemaLogRestService(null); } @Path(EventSubscriptionRestService.PATH)
public EventSubscriptionRestService getEventSubscriptionRestService() { return super.getEventSubscriptionRestService(null); } @Path(TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService() { return super.getTelemetryRestService(null); } @Override protected URI getRelativeEngineUri(String engineName) { // the default engine return URI.create("/"); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public int updateProperty(String oldKeyValuePair, String newKeyValuePair) throws IOException { File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName)); List<String> fileContent = getFileLines(propertiesFile); int updatedIndex = -1; for (int i = 0; i < fileContent.size(); i++) { if (fileContent.get(i) .replaceAll("\\s+", "") .equals(oldKeyValuePair)) { fileContent.set(i, newKeyValuePair); updatedIndex = i; break; } } Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8); // depending on the system, sometimes the first line will be a comment with a timestamp of the file read
// the next line will make this method compatible with all systems if (fileContent.get(0).startsWith("#")) { updatedIndex--; } return updatedIndex; } private List<String> getFileLines() throws IOException { File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName)); return getFileLines(propertiesFile); } private List<String> getFileLines(File propertiesFile) throws IOException { return new ArrayList<>(Files.readAllLines(propertiesFile.toPath(), StandardCharsets.UTF_8)); } }
repos\tutorials-master\core-java-modules\core-java-properties\src\main\java\com\baeldung\core\java\properties\FileAPIPropertyMutator.java
1
请完成以下Java代码
private JSONDocumentChangedWebSocketEvent getCreateEvent(@NonNull final WindowId windowId, @NonNull final DocumentId documentId) { final EventKey key = new EventKey(windowId, documentId); final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events; if (events == null) { throw new AdempiereException("already closed: " + this); } return events.computeIfAbsent(key, this::createEvent); } private JSONDocumentChangedWebSocketEvent createEvent(final EventKey key) { return JSONDocumentChangedWebSocketEvent.rootDocument(key.getWindowId(), key.getDocumentId()); } public void staleRootDocument(final WindowId windowId, final DocumentId documentId) { staleRootDocument(windowId, documentId, false); } public void staleRootDocument(final WindowId windowId, final DocumentId documentId, final boolean markActiveTabStaled) { final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId); event.markRootDocumentAsStaled(); if (markActiveTabStaled) { event.markActiveTabStaled(); } } public void staleTabs(final WindowId windowId, final DocumentId documentId, final Set<DetailId> tabIds) { final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId); event.staleTabs(tabIds); } public void staleIncludedDocuments(final WindowId windowId, final DocumentId documentId, final DetailId tabId, final DocumentIdsSelection rowIds) { final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId); event.staleIncludedRows(tabId, rowIds); } public void mergeFrom(final WindowId windowId, final DocumentId documentId, final JSONIncludedTabInfo tabInfo) { final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId); event.addIncludedTabInfo(tabInfo); } public void mergeFrom(final JSONDocumentChangedWebSocketEventCollector from)
{ final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> fromEvents = from._events; if (fromEvents == null || fromEvents.isEmpty()) { return; } fromEvents.forEach(this::mergeFrom); } private void mergeFrom(final EventKey key, final JSONDocumentChangedWebSocketEvent from) { final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events; if (events == null) { throw new AdempiereException("already closed: " + this); } events.compute(key, (k, existingEvent) -> { if (existingEvent == null) { return from.copy(); } else { existingEvent.mergeFrom(from); return existingEvent; } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEventCollector.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_ReportView_ID())); } /** Set Function Column. @param FunctionColumn Overwrite Column with Function */ public void setFunctionColumn (String FunctionColumn) { set_Value (COLUMNNAME_FunctionColumn, FunctionColumn); } /** Get Function Column. @return Overwrite Column with Function */ public String getFunctionColumn () { return (String)get_Value(COLUMNNAME_FunctionColumn); } /** Set SQL Group Function. @param IsGroupFunction This function will generate a Group By Clause */ public void setIsGroupFunction (boolean IsGroupFunction) { set_Value (COLUMNNAME_IsGroupFunction, Boolean.valueOf(IsGroupFunction)); }
/** Get SQL Group Function. @return This function will generate a Group By Clause */ public boolean isGroupFunction () { Object oo = get_Value(COLUMNNAME_IsGroupFunction); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView_Col.java
1
请在Spring Boot框架中完成以下Java代码
public class XmlProcessing { /** expecting default = false */ @NonNull Boolean printAtIntermediate; /** expecting default = false */ @NonNull Boolean printCustomerCopy; @NonNull XmlTransport transport; @Singular List<XmlValidation> validations; @Singular List<XmlInstruction> instructions; @Nullable XmlDemand demand;
public XmlProcessing withMod(@Nullable final ProcessingMod processingMod) { if (processingMod == null) { return this; } final XmlProcessingBuilder builder = toBuilder(); return builder .transport(transport.withMod(processingMod.getTransportMod())) .build(); } @Value @Builder public static class ProcessingMod { @Nullable TransportMod transportMod; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\XmlProcessing.java
2
请在Spring Boot框架中完成以下Java代码
public ViewResolver htmlViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); resolver.setContentType("text/html"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.html")); return resolver; } private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); engine.setTemplateEngineMessageSource(messageSource()); return engine; } private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean
public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-5\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
private boolean isInvoiceRejected(@NonNull final ImportedInvoiceResponse responseWithTags) { return Status.REJECTED.equals(responseWithTags.getStatus()); } private ImportInvoiceResponseRequest createRequest(@NonNull final Path fileToImport) { try { final byte[] fileContent = Files.readAllBytes(fileToImport); final String fileName = fileToImport.getFileName().toString(); return ImportInvoiceResponseRequest .builder() .data(fileContent) .fileName(fileName) .mimeType(MimeType.getMimeType(fileName)) .build(); } catch (final IOException e)
{ throw AdempiereException.wrapIfNeeded(e); } } private void moveFile(@NonNull final Path fileToMove, @NonNull final Path outputDirectory) { try { Files.move(fileToMove, outputDirectory.resolve(fileToMove.getFileName())); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\process\C_Invoice_ImportInvoiceResponse.java
1
请完成以下Java代码
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) { if (isCalloutActive() || value == null) return ""; // get value int S_ResourceAssignment_ID = ((Integer)value).intValue(); if (S_ResourceAssignment_ID == 0) return ""; int M_Product_ID = 0; String Name = null; String Description = null; BigDecimal Qty = null; String sql = "SELECT p.M_Product_ID, ra.Name, ra.Description, ra.Qty " + "FROM S_ResourceAssignment ra" + " INNER JOIN M_Product p ON (p.S_Resource_ID=ra.S_Resource_ID) " + "WHERE ra.S_ResourceAssignment_ID=?"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, S_ResourceAssignment_ID); rs = pstmt.executeQuery(); if (rs.next()) { M_Product_ID = rs.getInt (1); Name = rs.getString(2); Description = rs.getString(3); Qty = rs.getBigDecimal(4); } } catch (SQLException e) { log.error("product", e); }
finally { DB.close(rs, pstmt); rs = null; pstmt = null; } log.debug("S_ResourceAssignment_ID=" + S_ResourceAssignment_ID + " - M_Product_ID=" + M_Product_ID); if (M_Product_ID != 0) { mTab.setValue ("M_Product_ID", new Integer (M_Product_ID)); if (Description != null) Name += " (" + Description + ")"; if (!".".equals(Name)) mTab.setValue("Description", Name); // String variable = "Qty"; // TimeExpenseLine if (mTab.getTableName().startsWith("C_Order")) variable = "QtyOrdered"; else if (mTab.getTableName().startsWith("C_Invoice")) variable = "QtyInvoiced"; if (Qty != null) mTab.setValue(variable, Qty); mTab.setValue("QtyEntered", Qty); //red1 BR2836655-Resource Assignment always return Qty 1 } return ""; } // product } // CalloutAssignment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutAssignment.java
1
请完成以下Java代码
public final int size() { return permissions.size(); } @Override public final Collection<PermissionType> getPermissionsList() { return permissions.values(); } protected final ImmutableMap<Resource, PermissionType> getPermissionsMap() { return permissions; } /** * Gets the "NO permission". * * It is an instance of PermissionType with all accesses revoked and with a generic {@link Resource}. * * <br/> * <b>NOTE to implementor: it is highly recommended that extended classes to not return <code>null</code> here.</b> * * @return no permission instance */ protected PermissionType noPermission() { return null; } @Override public final Optional<PermissionType> getPermissionIfExists(final Resource resource) { return Optional.fromNullable(permissions.get(resource)); } @Override public final PermissionType getPermissionOrDefault(final Resource resource) { // // Get the permission for given resource final Optional<PermissionType> permission = getPermissionIfExists(resource); if (permission.isPresent()) { return permission.get(); } // // Fallback: get the permission defined for the resource of "no permission", if any
final PermissionType nonePermission = noPermission(); if (nonePermission == null) { return null; } final Resource defaultResource = nonePermission.getResource(); return getPermissionIfExists(defaultResource) // Fallback: return the "no permission" .or(nonePermission); } @Override public final boolean hasPermission(final Permission permission) { return permissions.values().contains(permission); } @Override public final boolean hasAccess(final Resource resource, final Access access) { return getPermissionOrDefault(resource).hasAccess(access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\AbstractPermissions.java
1
请完成以下Java代码
public String getLastCalledFunctionNameFQ() { if (calledBy.isEmpty()) { return null; } else { return calledBy.get(calledBy.size() - 1).getFunctionNameFQ(); } } public String getInitiatorWindow() { final String windowName = !calledBy.isEmpty() ? calledBy.get(0).getWindowNameAndId() : ""; return windowName != null ? windowName : "NONE"; } public boolean isInitiator() {return calledBy.isEmpty();} public PerformanceMonitoringService.Type getEffectiveType(final PerformanceMonitoringService.Metadata metadata) { return !calledBy.isEmpty() ? calledBy.get(0).getType() : metadata.getType(); }
public int getDepth() {return calledBy.size();} public IAutoCloseable addCalledByIfNotNull(@Nullable final PerformanceMonitoringService.Metadata metadata) { if (metadata == null) { return () -> {}; } final int sizeBeforeAdd = calledBy.size(); calledBy.add(metadata); return () -> { while (calledBy.size() > sizeBeforeAdd) { calledBy.remove(calledBy.size() - 1); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringData.java
1
请完成以下Java代码
public class DmnDecisionTableEvaluationEventImpl implements DmnDecisionTableEvaluationEvent { protected DmnDecision decision; protected List<DmnEvaluatedInput> inputs = new ArrayList<DmnEvaluatedInput>(); protected List<DmnEvaluatedDecisionRule> matchingRules = new ArrayList<DmnEvaluatedDecisionRule>(); protected String collectResultName; protected TypedValue collectResultValue; protected long executedDecisionElements; public DmnDecision getDecisionTable() { return getDecision(); } public DmnDecision getDecision() { return decision; } public void setDecisionTable(DmnDecision decision) { this.decision = decision; } public List<DmnEvaluatedInput> getInputs() { return inputs; } public void setInputs(List<DmnEvaluatedInput> inputs) { this.inputs = inputs; } public List<DmnEvaluatedDecisionRule> getMatchingRules() { return matchingRules; } public void setMatchingRules(List<DmnEvaluatedDecisionRule> matchingRules) { this.matchingRules = matchingRules; } public String getCollectResultName() { return collectResultName; } public void setCollectResultName(String collectResultName) { this.collectResultName = collectResultName; } public TypedValue getCollectResultValue() { return collectResultValue; } public void setCollectResultValue(TypedValue collectResultValue) {
this.collectResultValue = collectResultValue; } public long getExecutedDecisionElements() { return executedDecisionElements; } public void setExecutedDecisionElements(long executedDecisionElements) { this.executedDecisionElements = executedDecisionElements; } @Override public String toString() { return "DmnDecisionTableEvaluationEventImpl{" + " key="+ decision.getKey() + ", name="+ decision.getName() + ", decisionLogic=" + decision.getDecisionLogic() + ", inputs=" + inputs + ", matchingRules=" + matchingRules + ", collectResultName='" + collectResultName + '\'' + ", collectResultValue=" + collectResultValue + ", executedDecisionElements=" + executedDecisionElements + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnDecisionTableEvaluationEventImpl.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task); checkClaimTask(task, commandContext); if (userId != null) { if (task.getAssignee() != null) { if (!task.getAssignee().equals(userId)) { // When the task is already claimed by another user, throw exception. Otherwise, ignore // this, post-conditions of method already met. throw new TaskAlreadyClaimedException(task.getId(), task.getAssignee()); } } else { task.setAssignee(userId); }
} else { // Task should be assigned to no one task.setAssignee(null); } task.triggerUpdateEvent(); task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_CLAIM); return null; } protected void checkClaimTask(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskWork(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ClaimTaskCmd.java
1
请完成以下Java代码
public void forget() { values.clear(); } } private static class MemoizingLastCallFunction<T, R, K> implements MemoizingFunction<T, R> { private final Function<T, R> delegate; private final Function<T, K> keyFunction; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private transient volatile K lastKey; private transient R lastValue; private MemoizingLastCallFunction(final Function<T, R> delegate, final Function<T, K> keyFunction) { Check.assumeNotNull(delegate, "Parameter function is not null"); Check.assumeNotNull(keyFunction, "Parameter keyFunction is not null"); this.delegate = delegate; this.keyFunction = keyFunction; } @Override public String toString() { return MoreObjects.toStringHelper("memoizing-last-call") .addValue(delegate) .toString(); } @Override public R apply(final T input) { final K key = keyFunction.apply(input); lock.readLock().lock(); boolean readLockAcquired = true; boolean writeLockAcquired = false; try { if (Objects.equals(lastKey, key)) { return lastValue; } // Upgrade to write lock lock.readLock().unlock(); // must release read lock before acquiring write lock readLockAcquired = false; lock.writeLock().lock(); writeLockAcquired = true; try { lastValue = delegate.apply(input); lastKey = key; return lastValue; } finally { // Downgrade to read lock lock.readLock().lock(); // acquire read lock before releasing write lock readLockAcquired = true; lock.writeLock().unlock(); // unlock write, still hold read writeLockAcquired = false; } } finally { if (writeLockAcquired) { lock.writeLock().unlock(); } if (readLockAcquired) {
lock.readLock().unlock(); } } } @Override public R peek(final T input) { final ReadLock readLock = lock.readLock(); readLock.lock(); try { return lastValue; } finally { readLock.unlock(); } } @Override public void forget() { final WriteLock writeLock = lock.writeLock(); writeLock.lock(); try { lastKey = null; lastValue = null; } finally { writeLock.unlock(); } } } private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T> { private SimpleMemoizingFunction(final Function<T, R> delegate) { super(delegate, input -> input); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java
1
请在Spring Boot框架中完成以下Java代码
public void setAuthnRequestCustomizer(Consumer<AuthnRequestContext> contextConsumer) { Assert.notNull(contextConsumer, "contextConsumer cannot be null"); this.delegate.setParametersConsumer( (parameters) -> contextConsumer.accept(new AuthnRequestContext(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthnRequest()))); } /** * Set the {@link RequestMatcher} to use for setting the * {@link BaseOpenSamlAuthenticationRequestResolver#setRequestMatcher(RequestMatcher)} * (RequestMatcher)} * @param requestMatcher the {@link RequestMatcher} to identify authentication * requests. * @since 5.8 */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.delegate.setRequestMatcher(requestMatcher); } /** * Use this {@link Clock} for generating the issued {@link Instant} * @param clock the {@link Clock} to use */ public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.delegate.setClock(clock); } /** * Use this {@link Converter} to compute the RelayState * @param relayStateResolver the {@link Converter} to use * @since 5.8 */ public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.delegate.setRelayStateResolver(relayStateResolver); } public static final class AuthnRequestContext { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final AuthnRequest authnRequest;
public AuthnRequestContext(HttpServletRequest request, RelyingPartyRegistration registration, AuthnRequest authnRequest) { this.request = request; this.registration = registration; this.authnRequest = authnRequest; } public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public AuthnRequest getAuthnRequest() { return this.authnRequest; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolver.java
2
请在Spring Boot框架中完成以下Java代码
public I_C_InvoiceLine createInvoiceLine(org.compiere.model.I_C_Invoice invoice) { throw new UnsupportedOperationException(); } @Override public List<I_C_LandedCost> retrieveLandedCosts(I_C_InvoiceLine invoiceLine, String whereClause, String trxName) { throw new UnsupportedOperationException(); } @Override public I_C_LandedCost createLandedCost(String trxName) { throw new UnsupportedOperationException(); } @Override public I_C_InvoiceLine createInvoiceLine(String trxName) { throw new UnsupportedOperationException(); } private List<I_C_AllocationLine> retrieveAllocationLines(final org.compiere.model.I_C_Invoice invoice) { Adempiere.assertUnitTestMode(); return db.getRecords(I_C_AllocationLine.class, pojo -> { if (pojo == null) { return false; } if (pojo.getC_Invoice_ID() != invoice.getC_Invoice_ID()) { return false; } return true; }); } private BigDecimal retrieveAllocatedAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor) { Adempiere.assertUnitTestMode(); final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); BigDecimal sum = BigDecimal.ZERO; for (final I_C_AllocationLine line : retrieveAllocationLines(invoice)) { final I_C_AllocationHdr ah = line.getC_AllocationHdr(); final BigDecimal lineAmt = amountAccessor.getValue(line); if ((null != ah) && (ah.getC_Currency_ID() != invoice.getC_Currency_ID())) { final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert( lineAmt, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID ah.getDateTrx().toInstant(), // ConvDate CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()), ClientId.ofRepoId(line.getAD_Client_ID()), OrgId.ofRepoId(line.getAD_Org_ID())); sum = sum.add(lineAmtConv); } else { sum = sum.add(lineAmt); } } return sum; } public BigDecimal retrieveWriteOffAmt(final org.compiere.model.I_C_Invoice invoice) { Adempiere.assertUnitTestMode(); return retrieveAllocatedAmt(invoice, o -> { final I_C_AllocationLine line = (I_C_AllocationLine)o; return line.getWriteOffAmt(); }); } @Override public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\PlainInvoiceDAO.java
2
请完成以下Java代码
public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } public UserQuery orderByUserFirstName() { return orderBy(UserQueryProperty.FIRST_NAME); } public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } //getters ////////////////////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getFirstName() { return firstName; } public String getFirstNameLike() { return firstNameLike; } public String getLastName() {
return lastName; } public String getLastNameLike() { return lastNameLike; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
class M_CostRevaluation { private static final AdMessageKey MSG_DeleteLinesFirstError = AdMessageKey.of("M_CostRevaluation.DeleteLinesFirstError"); private final CostRevaluationService costRevaluationService; M_CostRevaluation(@NonNull final CostRevaluationService costRevaluationService) { this.costRevaluationService = costRevaluationService; } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }) void beforeChange(@NonNull final I_M_CostRevaluation record, @NonNull final ModelChangeType type) { if (type.isChange() && InterfaceWrapperHelper.isValueChanged(record, I_M_CostRevaluation.COLUMNNAME_C_AcctSchema_ID,
I_M_CostRevaluation.COLUMNNAME_M_CostElement_ID, I_M_CostRevaluation.COLUMNNAME_EvaluationStartDate) && costRevaluationService.hasActiveLines(CostRevaluationId.ofRepoId(record.getM_CostRevaluation_ID())) ) { throw new AdempiereException(MSG_DeleteLinesFirstError); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) void beforeDelete(final I_M_CostRevaluation record) { final CostRevaluationId costRevaluationId = CostRevaluationId.ofRepoId(record.getM_CostRevaluation_ID()); costRevaluationService.deleteLinesAndDetailsByRevaluationId(costRevaluationId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\interceptor\M_CostRevaluation.java
2
请完成以下Java代码
public String getInfo() { return "WordFilter"; } /** this method actually performs the filtering. */ public String process(String to_process) { if ( to_process == null || to_process.length() == 0 ) return ""; String tmp = ""; // the true at the end is the key to making it work StringTokenizer st = new StringTokenizer(to_process, " ", true); StringBuffer newValue = new StringBuffer(to_process.length() + 50); while ( st.hasMoreTokens() ) { tmp = st.nextToken(); if (hasAttribute(tmp)) newValue.append((String)get(tmp)); else newValue.append(tmp); } return newValue.toString(); } /** Put a filter somewhere we can get to it. */ public Filter addAttribute(String attribute,Object entity) { put(attribute,entity); return(this); } /** Get rid of a current filter.
*/ public Filter removeAttribute(String attribute) { try { remove(attribute); } catch(NullPointerException exc) { // don't really care if this throws a null pointer exception } return(this); } /** Does the filter filter this? */ public boolean hasAttribute(String attribute) { return(containsKey(attribute)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\WordFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonOrderCustomer extends JsonCustomerBasicInfo { @Nullable @JsonProperty("customerId") @JsonInclude(JsonInclude.Include.NON_EMPTY) String customerId; @Builder JsonOrderCustomer( @JsonProperty("customerId") final String customerId, @JsonProperty("firstName") final String firstName, @JsonProperty("lastName") final String lastName, @JsonProperty("company") final String company, @JsonProperty("customerNumber") final String customerNumber, @JsonProperty("email") final String email,
@JsonProperty("createdAt") final ZonedDateTime createdAt, @JsonProperty("updatedAt") final ZonedDateTime updatedAt, @JsonProperty("vatIds") final List<String> vatIds) { super(firstName, lastName, company, customerNumber, email, createdAt, updatedAt, vatIds); this.customerId = customerId; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") static class JsonOrderCustomerBuilder { } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\order\JsonOrderCustomer.java
2
请完成以下Java代码
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); return (Mono<T>) this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId) .mapNotNull((clientRegistration) -> { OAuth2AuthorizedClientId id = new OAuth2AuthorizedClientId(clientRegistrationId, principalName); OAuth2AuthorizedClient cachedAuthorizedClient = this.authorizedClients.get(id); if (cachedAuthorizedClient == null) { return null; } return new OAuth2AuthorizedClient(clientRegistration, cachedAuthorizedClient.getPrincipalName(), cachedAuthorizedClient.getAccessToken(), cachedAuthorizedClient.getRefreshToken()); }); } @Override public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(principal, "principal cannot be null"); return Mono.fromRunnable(() -> { OAuth2AuthorizedClientId identifier = new OAuth2AuthorizedClientId( authorizedClient.getClientRegistration().getRegistrationId(), principal.getName()); this.authorizedClients.put(identifier, authorizedClient); });
} @Override public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); // @formatter:off return this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId) .map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName)) .doOnNext(this.authorizedClients::remove) .then(Mono.empty()); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\InMemoryReactiveOAuth2AuthorizedClientService.java
1
请完成以下Java代码
public class BuildProperties extends InfoProperties { /** * Create an instance with the specified entries. * @param entries the information to expose */ public BuildProperties(Properties entries) { super(processEntries(entries)); } /** * Return the groupId of the project or {@code null}. * @return the group */ public @Nullable String getGroup() { return get("group"); } /** * Return the artifactId of the project or {@code null}. * @return the artifact */ public @Nullable String getArtifact() { return get("artifact"); } /** * Return the name of the project or {@code null}. * @return the name */ public @Nullable String getName() { return get("name"); } /** * Return the version of the project or {@code null}. * @return the version */ public @Nullable String getVersion() { return get("version"); } /** * Return the timestamp of the build or {@code null}. * <p> * If the original value could not be parsed properly, it is still available with the * {@code time} key.
* @return the build time * @see #get(String) */ public @Nullable Instant getTime() { return getInstant("time"); } private static Properties processEntries(Properties properties) { coerceDate(properties, "time"); return properties; } private static void coerceDate(Properties properties, String key) { String value = properties.getProperty(key); if (value != null) { try { String updatedValue = String .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); } catch (DateTimeException ex) { // Ignore and store the original value } } } static class BuildPropertiesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("META-INF/build-info.properties"); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\BuildProperties.java
1
请完成以下Java代码
public void sendAfterCommit(@NonNull final List<UserNotificationRequest> requests) { try { if (requests.isEmpty()) { return; } newNotificationSender().sendAfterCommit(requests); } catch (final Exception ex) { logger.warn("Failed sending notifications: {}", requests, ex); } } @Override public void send(@NonNull final UserNotificationRequest request) { try { newNotificationSender().sendNow(request); } catch (final Exception ex) { logger.warn("Failed sending notification: {}", request, ex); } }
@Override public void addCtxProvider(final IRecordTextProvider ctxProvider) { ctxProviders.addCtxProvider(ctxProvider); } @Override public void setDefaultCtxProvider(final IRecordTextProvider defaultCtxProvider) { ctxProviders.setDefaultCtxProvider(defaultCtxProvider); } @Override public @NonNull UserNotificationsConfig getUserNotificationsConfig(final UserId adUserId) { return Services.get(IUserNotificationsConfigRepository.class).getByUserId(adUserId); } @Override public RoleNotificationsConfig getRoleNotificationsConfig(final RoleId adRoleId) { return Services.get(IRoleNotificationsConfigRepository.class).getByRoleId(adRoleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationBL.java
1
请完成以下Java代码
public void dispose() { if (disposed) { return; } this.disposed = true; final JComponent textComponent = textComponentRef.get(); if (textComponent != null) { textComponent.removePropertyChangeListener(PROPERTY_PreferredSize, this); textComponent.removePropertyChangeListener(PROPERTY_Background, this); } textComponentRef.clear(); actionButtonRef.clear(); } private final boolean isDisposed() { return disposed; } private VEditorActionButton getActionButton() { return actionButtonRef.get(); } private JComponent getTextComponent() { return textComponentRef.get(); } public void updateActionButtonUI() { if (isDisposed()) { return; } final JComponent textComponent = getTextComponent(); final VEditorActionButton actionButton = getActionButton(); if (textComponent == null || actionButton == null) { dispose(); return; } updateActionButtonUI_PreferredSize(actionButton, textComponent);
updateActionButtonUI_Background(actionButton, textComponent); } private static void updateActionButtonUI_PreferredSize(final VEditorActionButton actionButton, final JComponent textComponent) { final Dimension textCompSize = textComponent.getPreferredSize(); final int textCompHeight = textCompSize.height; final Dimension buttonSize = new Dimension(textCompHeight, textCompHeight); actionButton.setPreferredSize(buttonSize); } private static void updateActionButtonUI_Background(final VEditorActionButton actionButton, final JComponent textComponent) { final Color textCompBackground = textComponent.getBackground(); actionButton.setBackground(textCompBackground); } @Override public void propertyChange(final PropertyChangeEvent evt) { if (isDisposed()) { return; } final JComponent textComponent = (JComponent)evt.getSource(); if (textComponent == null) { return; // shall not happen } final VEditorActionButton actionButton = getActionButton(); if (actionButton == null) { dispose(); return; } final String propertyName = evt.getPropertyName(); if (PROPERTY_PreferredSize.equals(propertyName)) { updateActionButtonUI_PreferredSize(actionButton, textComponent); } else if (PROPERTY_Background.equals(propertyName)) { updateActionButtonUI_Background(actionButton, textComponent); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorActionButton.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_EXP_Processor_Type[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Export Processor Type. @param EXP_Processor_Type_ID Export Processor Type */ public void setEXP_Processor_Type_ID (int EXP_Processor_Type_ID) { if (EXP_Processor_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, Integer.valueOf(EXP_Processor_Type_ID)); } /** Get Export Processor Type. @return Export Processor Type */ public int getEXP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Java Class. @param JavaClass Java Class */ public void setJavaClass (String JavaClass) { set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */
public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor_Type.java
1
请完成以下Spring Boot application配置
server: port: 8888 spring: application: name: gateway-application cloud: # Spring Cloud Gateway 配置项,对应 GatewayProperties 类 gateway: # 路由配置项,对应 RouteDefinition 数组 routes: - id: hystrix_test uri: http://127.0.0.1:18181 predicates: - Path=/** filters: - name: Hystrix
args: name: fallbackcmd # 对应的 Hystrix Command 名字 fallbackUri: forward:/fallback # 处理 Hystrix fallback 的情况,重定向到指定地址
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo07-hystrix\src\main\resources\application.yaml
2
请完成以下Java代码
public void setJobRetries(String jobId, int retries) { commandExecutor.execute(new SetJobRetriesCmd(jobId, retries)); } @Override public TablePageQuery createTablePageQuery() { return new TablePageQueryImpl(commandExecutor); } @Override public JobQuery createJobQuery() { return new JobQueryImpl(commandExecutor); } @Override public TimerJobQuery createTimerJobQuery() { return new TimerJobQueryImpl(commandExecutor); } @Override public String getJobExceptionStacktrace(String jobId) { return commandExecutor.execute(new GetJobExceptionStacktraceCmd(jobId)); } @Override public Map<String, String> getProperties() { return commandExecutor.execute(new GetPropertiesCmd()); } @Override public <T> T executeCommand(Command<T> command) { if (command == null) { throw new ActivitiIllegalArgumentException("The command is null"); } return commandExecutor.execute(command); }
@Override public <T> T executeCommand(CommandConfig config, Command<T> command) { if (config == null) { throw new ActivitiIllegalArgumentException("The config is null"); } if (command == null) { throw new ActivitiIllegalArgumentException("The command is null"); } return commandExecutor.execute(config, command); } @Override public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution)); } @Override public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) { return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize)); } @Override public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) { return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId)); } @Override public void deleteEventLogEntry(long logNr) { commandExecutor.execute(new DeleteEventLogEntry(logNr)); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java
1
请完成以下Java代码
public static String calculateTimeAgoWithPeriodAndDuration(LocalDateTime pastTime, ZoneId zone) { Period period = Period.between(pastTime.toLocalDate(), getCurrentTimeByTimeZone(zone).toLocalDate()); Duration duration = Duration.between(pastTime, getCurrentTimeByTimeZone(zone)); if (period.getYears() != 0) return "several years ago"; else if (period.getMonths() != 0) return "several months ago"; else if (period.getDays() != 0) return "several days ago"; else if (duration.toHours() != 0) return "several hours ago"; else if (duration.toMinutes() != 0) return "several minutes ago"; else if (duration.getSeconds() != 0) return "several seconds ago";
else return "moments ago"; } public static String calculateTimeAgoWithPrettyTime(Date pastTime) { PrettyTime prettyTime = new PrettyTime(); return prettyTime.format(pastTime); } public static String calculateTimeAgoWithTime4J(Date pastTime, ZoneId zone, Locale locale) { return net.time4j.PrettyTime.of(locale) .printRelative(pastTime.toInstant(), zone); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\timeago\version8\TimeAgoCalculator.java
1
请完成以下Java代码
public void write(I_AD_Migration migration) { try { write0(migration); } catch (Exception e) { throw new AdempiereException(e); } } private void write0(I_AD_Migration migration) throws ParserConfigurationException, TransformerException, IOException { if (migration == null || migration.getAD_Migration_ID() <= 0) { throw new AdempiereException("No migration to export. Migration is null or new."); } logger.debug("Creating xml document for migration: " + migration); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement(NODENAME_Migrations); document.appendChild(root); final IXMLHandlerFactory converterFactory = Services.get(IXMLHandlerFactory.class); final IXMLHandler<I_AD_Migration> converter = converterFactory.getHandler(I_AD_Migration.class); final Node migrationNode = converter.toXmlNode(document, migration); root.appendChild(migrationNode); // set up a transformer final TransformerFactory transFactory = TransformerFactory.newInstance(); transFactory.setAttribute("indent-number", 2); final Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); logger.debug("Writing xml to file."); Writer writer = null; try { writer = getWriter(); final StreamResult result = new StreamResult(writer);
final DOMSource source = new DOMSource(document); trans.transform(source, result); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } writer = null; } } } private Writer getWriter() throws IOException { if (fileName != null) { return new FileWriter(fileName); } else if (outputStream != null) { return new OutputStreamWriter(outputStream); } else { throw new AdempiereException("Cannot identify target stream"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\XMLWriter.java
1
请完成以下Java代码
public Stream<I_M_Product> streamProductsWithNoProductPlanningButWithSchemaSelector() { final IQuery<I_PP_Product_Planning> existentProductPlanning = queryBL.createQueryBuilder(I_PP_Product_Planning.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .create(); // TODO move it to ProductDAO return queryBL.createQueryBuilder(I_M_Product.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addNotInSubQueryFilter(I_M_Product.COLUMNNAME_M_Product_ID, I_PP_Product_Planning.COLUMNNAME_M_Product_ID, existentProductPlanning) .addNotNull(I_M_Product.COLUMN_M_ProductPlanningSchema_Selector) .create() .iterateAndStream(); } @Override public Optional<ProductPlanning> retrieveManufacturingOrTradingPlanning(@NonNull final ProductId productId, @NonNull final OrgId orgId) { final ICompositeQueryFilter<I_PP_Product_Planning> manufacturedOrTraded = queryBL.createCompositeQueryFilter(I_PP_Product_Planning.class) .setJoinOr()
.addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_IsManufactured, X_PP_Product_Planning.ISMANUFACTURED_Yes) .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_IsTraded, X_PP_Product_Planning.ISTRADED_Yes); final I_PP_Product_Planning record = queryBL.createQueryBuilder(I_PP_Product_Planning.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Product_Planning.COLUMNNAME_M_Product_ID, productId) .addInArrayOrAllFilter(I_PP_Product_Planning.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY) .filter(manufacturedOrTraded) .orderBy() .addColumn(I_PP_Product_Planning.COLUMNNAME_AD_Org_ID, Direction.Descending, Nulls.Last) // specific org first .addColumn(I_PP_Product_Planning.COLUMNNAME_IsManufactured, Direction.Descending, Nulls.Last) // 'Y' first, NULL last .addColumn(I_PP_Product_Planning.COLUMNNAME_IsTraded, Direction.Descending, Nulls.Last) // 'Y' first, NULL last .addColumn(I_PP_Product_Planning.COLUMNNAME_M_Warehouse_ID, Direction.Descending, Nulls.Last) .endOrderBy() .create() .first(); return record != null ? Optional.of(ProductPlanningDAO.fromRecord(record)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\planning\impl\ProductPlanningDAO.java
1
请完成以下Java代码
public boolean isDropTo() { return pickedHUs != null && pickedHUs.isDroppedTo(); } public void assertNotDroppedTo() { if (isDropTo()) { throw new AdempiereException("Already Dropped To"); } } public void markAsDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId) { assertInTransit(); final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); pickedHUs.setDroppedTo(dropToLocatorId, dropToMovementId); updateStatus(); } private void updateStatus() { this.status = computeStatus(); } private DDOrderMoveScheduleStatus computeStatus() { if (isDropTo())
{ return DDOrderMoveScheduleStatus.COMPLETED; } else if (isPickedFrom()) { return DDOrderMoveScheduleStatus.IN_PROGRESS; } else { return DDOrderMoveScheduleStatus.NOT_STARTED; } } @NonNull public ExplainedOptional<LocatorId> getInTransitLocatorId() { if (pickedHUs == null) { return ExplainedOptional.emptyBecause("Schedule is not picked yet"); } return pickedHUs.getInTransitLocatorId(); } @NonNull public ImmutableSet<HuId> getPickedHUIds() { final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this); return pickedHUs.getActualHUIdsPicked(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java
1
请完成以下Java代码
public void setC_Currency_ID_To (int C_Currency_ID_To) { set_Value (COLUMNNAME_C_Currency_ID_To, Integer.valueOf(C_Currency_ID_To)); } /** Get Zielwährung. @return Target currency */ @Override public int getC_Currency_ID_To () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID_To); if (ii == null) return 0; return ii.intValue(); } /** Set Divisor. @param DivideRate To convert Source number to Target number, the Source is divided */ @Override public void setDivideRate (java.math.BigDecimal DivideRate) { set_Value (COLUMNNAME_DivideRate, DivideRate); } /** Get Divisor. @return To convert Source number to Target number, the Source is divided */ @Override public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return Env.ZERO; return bd; } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return Env.ZERO; return bd; } /** Set Gültig ab. @param ValidFrom Valid from including this date (first day) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} /** Get Gültig ab. @return Valid from including this date (first day) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Valid to including this date (last day) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Valid to including this date (last day) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Conversion_Rate.java
1
请在Spring Boot框架中完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; }
public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResponse.java
2
请完成以下Java代码
public Shape modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) throws BadLocationException { return m_view.modelToView(p0, b0, p1, b1, a); } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x x coordinate of the view location to convert * @param y y coordinate of the view location to convert * @param a the allocated region to render into * @param bias bias * @return the location within the model that best represents the * given point in the view */ public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) { return m_view.viewToModel(x, y, a, bias); } /** * Returns the document model underlying the view. * * @return the model */ public Document getDocument() { return m_view.getDocument(); } /** * Returns the starting offset into the model for this view. * * @return the starting offset */ public int getStartOffset() { return m_view.getStartOffset(); } /** * Returns the ending offset into the model for this view. * * @return the ending offset */ public int getEndOffset() { return m_view.getEndOffset(); } /**
* Gets the element that this view is mapped to. * * @return the view */ public Element getElement() { return m_view.getElement(); } /** * Sets the view size. * * @param width the width * @param height the height */ public void setSize(float width, float height) { this.m_width = (int) width; m_view.setSize(width, height); } /** * Fetches the factory to be used for building the * various view fragments that make up the view that * represents the model. This is what determines * how the model will be represented. This is implemented * to fetch the factory provided by the associated * EditorKit. * * @return the factory */ public ViewFactory getViewFactory() { return m_factory; } } // HTMLRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLRenderer.java
1
请完成以下Java代码
public de.metas.dataentry.model.I_DataEntry_SubTab getDataEntry_SubTab() { return get_ValueAsPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class); } @Override public void setDataEntry_SubTab(final de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab) { set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab); } @Override public void setDataEntry_SubTab_ID (final int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_Value (COLUMNNAME_DataEntry_SubTab_ID, null); else set_Value (COLUMNNAME_DataEntry_SubTab_ID, DataEntry_SubTab_ID); } @Override public int getDataEntry_SubTab_ID() { return get_ValueAsInt(COLUMNNAME_DataEntry_SubTab_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsInitiallyClosed (final boolean IsInitiallyClosed) { set_Value (COLUMNNAME_IsInitiallyClosed, IsInitiallyClosed); } @Override
public boolean isInitiallyClosed() { return get_ValueAsBoolean(COLUMNNAME_IsInitiallyClosed); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSectionName (final java.lang.String SectionName) { set_Value (COLUMNNAME_SectionName, SectionName); } @Override public java.lang.String getSectionName() { return get_ValueAsString(COLUMNNAME_SectionName); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Section.java
1
请完成以下Java代码
public Map<String, AcquiredJobs> getAcquiredJobsByEngine() { return acquiredJobsByEngine; } /** * Jobs that were rejected from execution in the acquisition cycle * due to lacking execution resources. * With an execution thread pool, these jobs could not be submitted due to * saturation of the underlying job queue. */ public Map<String, List<List<String>>> getRejectedJobsByEngine() { return rejectedJobBatchesByEngine; } /** * Jobs that have been acquired in previous cycles and are supposed to * be re-submitted for execution */ public Map<String, List<List<String>>> getAdditionalJobsByEngine() {
return additionalJobBatchesByEngine; } public void setAcquisitionException(Exception e) { this.acquisitionException = e; } public Exception getAcquisitionException() { return acquisitionException; } public void setJobAdded(boolean isJobAdded) { this.isJobAdded = isJobAdded; } public boolean isJobAdded() { return isJobAdded; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobAcquisitionContext.java
1
请完成以下Java代码
public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public boolean isCompleteable() { return completeable; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getActivePlanItemDefinitionId() { return activePlanItemDefinitionId; } public Set<String> getActivePlanItemDefinitionIds() { return activePlanItemDefinitionIds; } public String getInvolvedUser() { return involvedUser; } public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink;
} public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public Set<String> getInvolvedGroups() { return involvedGroups; } public boolean isIncludeCaseVariables() { return includeCaseVariables; } public Collection<String> getVariableNamesToInclude() { return variableNamesToInclude; } public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(CaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); } public List<CaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceQueryImpl.java
1
请完成以下Java代码
public class TypeCastUtil { private TypeCastUtil() {} public static Pair<DataType, Object> castValue(String value) { if (isNumber(value)) { String formattedValue = value.replace(',', '.'); try { BigDecimal bd = new BigDecimal(formattedValue); if (bd.stripTrailingZeros().scale() > 0 || isSimpleDouble(formattedValue)) { if (bd.scale() <= 16) { return Pair.of(DataType.DOUBLE, bd.doubleValue()); } } else { return Pair.of(DataType.LONG, bd.longValueExact()); } } catch (RuntimeException ignored) {} } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) { return Pair.of(DataType.BOOLEAN, Boolean.parseBoolean(value)); } else if (looksLikeJson(value)) { try { return Pair.of(DataType.JSON, JsonParser.parseString(value)); } catch (Exception ignored) { } } return Pair.of(DataType.STRING, value); } public static Pair<DataType, Number> castToNumber(String value) { if (isNumber(value)) { String formattedValue = value.replace(',', '.'); BigDecimal bd = new BigDecimal(formattedValue); if (bd.stripTrailingZeros().scale() > 0 || isSimpleDouble(formattedValue)) { if (bd.scale() <= 16) { return Pair.of(DataType.DOUBLE, bd.doubleValue()); } else { return Pair.of(DataType.DOUBLE, bd); } } else { return Pair.of(DataType.LONG, bd.longValueExact()); } } else {
throw new IllegalArgumentException("'" + value + "' can't be parsed as number"); } } private static boolean isNumber(String value) { return NumberUtils.isNumber(value.replace(',', '.')); } private static boolean isSimpleDouble(String valueAsString) { return valueAsString.contains(".") && !valueAsString.contains("E") && !valueAsString.contains("e"); } private static boolean looksLikeJson(String value) { String trimmed = value.trim(); return (trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]")); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\util\TypeCastUtil.java
1
请在Spring Boot框架中完成以下Java代码
public String resolve(HttpServletRequest request) { String authorizationHeaderToken = resolveFromAuthorizationHeader(request); String parameterToken = isParameterTokenSupportedForRequest(request) ? resolveFromRequestParameters(request) : null; if (authorizationHeaderToken != null) { if (parameterToken != null) { throw new OAuth2AuthenticationException( BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request")); } return authorizationHeaderToken; } return parameterToken; } private String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (!StringUtils.startsWithIgnoreCase(authorization, "token")) { return null; } Matcher matcher = AUTHORIZATION_PATTERN.matcher(authorization); if (!matcher.matches()) { throw new OAuth2AuthenticationException(BearerTokenErrors.invalidToken("Bearer token is malformed")); }
return matcher.group("token"); } private boolean isParameterTokenSupportedForRequest(HttpServletRequest request) { return (("POST".equals(request.getMethod()) && MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())) || "GET".equals(request.getMethod())); } private String resolveFromRequestParameters(HttpServletRequest request) { String[] values = request.getParameterValues(ACCESS_TOKEN_PARAM); if (values == null || values.length == 0) { return null; } if (values.length == 1) { return values[0]; } throw new OAuth2AuthenticationException( BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request")); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthTokenResolver.java
2
请在Spring Boot框架中完成以下Java代码
public class DDOrderCandidateRequestedEvent implements MaterialEvent { public static final String TYPE = "DDOrderCandidateRequestedEvent"; @NonNull EventDescriptor eventDescriptor; @NonNull Instant dateOrdered; @NonNull DDOrderCandidateData ddOrderCandidateData; boolean createDDOrder; @Builder @Jacksonized private DDOrderCandidateRequestedEvent( @NonNull final EventDescriptor eventDescriptor, @NonNull final Instant dateOrdered, @NonNull final DDOrderCandidateData ddOrderCandidateData, final boolean createDDOrder) { ddOrderCandidateData.assertMaterialDispoGroupIdIsSet();
this.eventDescriptor = eventDescriptor; this.dateOrdered = dateOrdered; this.ddOrderCandidateData = ddOrderCandidateData; this.createDDOrder = createDDOrder; } @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_DD_Order_Candidate.Table_Name, ddOrderCandidateData.getExitingDDOrderCandidateId()); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\DDOrderCandidateRequestedEvent.java
2
请完成以下Java代码
public class StartMessagePayload implements Payload { private final String id; private String name; private String businessKey; private Map<String, Object> variables = new LinkedHashMap<>(); public StartMessagePayload() { this.id = UUID.randomUUID().toString(); } public StartMessagePayload(String name, String businessKey, Map<String, Object> variables) { this(); Objects.requireNonNull(name, "name must not be null"); this.name = name; this.businessKey = businessKey; this.variables = variables; } @Override public String getId() { return id; } public String getName() { return name; } public String getBusinessKey() { return businessKey; } public Map<String, Object> getVariables() { return variables; }
@Override public int hashCode() { return Objects.hash(id, name, businessKey, variables); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StartMessagePayload other = (StartMessagePayload) obj; return ( Objects.equals(businessKey, other.businessKey) && Objects.equals(id, other.id) && Objects.equals(name, other.name) && Objects.equals(variables, other.variables) ); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("StartMessagePayload [id="); builder.append(id); builder.append(", name="); builder.append(name); builder.append(", businessKey="); builder.append(businessKey); builder.append(", variables="); builder.append(variables); builder.append("]"); return builder.toString(); } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\StartMessagePayload.java
1
请完成以下Java代码
public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getModelEntityManager().findModelCountByQueryCriteria(this); } public List<Model> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; }
public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Long getId() { return id; } public String getIdAsString() { return String.valueOf(getId()); } public String getUuid() { return uuid; } public void setUuid(final String uuid) { this.uuid = uuid; } public int getVersion() { return version; } public void setDeleted(final boolean deleted) { this.deleted = deleted; } public boolean isDeleted() { return deleted; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Objects.hashCode(id); return result; } @Override public boolean equals(final Object obj) {
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractEntity other = (AbstractEntity)obj; return Objects.equals(id, other.id); } protected Date getDateCreated() { return dateCreated; } protected Date getDateUpdated() { return dateUpdated; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\AbstractEntity.java
2
请完成以下Java代码
private void notifyHUMoved(final I_M_HU hu) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); // // Invalidate all documents which are about this HU. if (documentsCollection != null) { try { documentsCollection.invalidateDocumentByRecordId(I_M_HU.Table_Name, huId.getRepoId()); } catch (final Exception ex) { logger.warn("Failed invalidating documents for M_HU_ID={}. Ignored", huId, ex); } } // // Remove this HU from the view // Don't invalidate. We will do it at the end of all processing. // // NOTE/Later edit: we decided to not remove it anymore // because in some views it might make sense to keep it there. // The right way would be to check if after moving it, the HU is still elgible for view's filters. // // if (huView != null) { huView.removeHUIds(ImmutableSet.of(huId)); }
} /** * @return target warehouse where the HUs will be moved to. */ @NonNull private LocatorId getTargetLocatorId() { if (_targetLocatorId == null) { _targetLocatorId = huMovementBL.getDirectMoveLocatorId(); } return _targetLocatorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\HUMoveToDirectWarehouseService.java
1
请完成以下Java代码
public static String getSqlInjectField(String... fields) { for (String s : fields) { getSqlInjectField(s); } return String.join(SymbolConstant.COMMA, fields); } /** * 获取排序字段 * 返回:字符串 * * 1.将驼峰命名转化成下划线 * 2.限制sql注入 * @param sortField 排序字段 * @return */ public static String getSqlInjectSortField(String sortField) { String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField)); return field; } /** * 获取多个排序字段 * 返回:数组 * * 1.将驼峰命名转化成下划线 * 2.限制sql注入 * @param sortFields 多个排序字段 * @return */ public static List getSqlInjectSortFields(String... sortFields) { List list = new ArrayList<String>(); for (String sortField : sortFields) { list.add(getSqlInjectSortField(sortField)); }
return list; } /** * 获取 orderBy type * 返回:字符串 * <p> * 1.检测是否为 asc 或 desc 其中的一个 * 2.限制sql注入 * * @param orderType * @return */ public static String getSqlInjectOrderType(String orderType) { if (orderType == null) { return null; } orderType = orderType.trim(); if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) { return CommonConstant.ORDER_TYPE_ASC; } else { return CommonConstant.ORDER_TYPE_DESC; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SqlInjectionUtil.java
1
请在Spring Boot框架中完成以下Java代码
protected final @Nullable RedisStaticMasterReplicaConfiguration getMasterReplicaConfiguration() { if (this.masterReplicaConfiguration != null) { return this.masterReplicaConfiguration; } if (this.connectionDetails.getMasterReplica() != null) { List<Node> nodes = this.connectionDetails.getMasterReplica().getNodes(); Assert.state(!nodes.isEmpty(), "At least one node is required for master-replica configuration"); RedisStaticMasterReplicaConfiguration config = new RedisStaticMasterReplicaConfiguration( nodes.get(0).host(), nodes.get(0).port()); nodes.stream().skip(1).forEach((node) -> config.addNode(node.host(), node.port())); config.setUsername(this.connectionDetails.getUsername()); String password = this.connectionDetails.getPassword(); if (password != null) { config.setPassword(RedisPassword.of(password)); } return config; } return null; } private List<RedisNode> getNodes(Cluster cluster) { return cluster.getNodes().stream().map(this::asRedisNode).toList(); } private RedisNode asRedisNode(Node node) { return new RedisNode(node.host(), node.port()); } protected final DataRedisProperties getProperties() { return this.properties; } protected @Nullable SslBundle getSslBundle() { return this.connectionDetails.getSslBundle(); } protected final boolean isSslEnabled() { return getProperties().getSsl().isEnabled(); } protected final boolean urlUsesSsl(String url) { return DataRedisUrl.of(url).useSsl(); }
protected boolean isPoolEnabled(Pool pool) { Boolean enabled = pool.getEnabled(); return (enabled != null) ? enabled : COMMONS_POOL2_AVAILABLE; } private List<RedisNode> createSentinels(Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>(); for (Node node : sentinel.getNodes()) { nodes.add(asRedisNode(node)); } return nodes; } protected final DataRedisConnectionDetails getConnectionDetails() { return this.connectionDetails; } private Mode determineMode() { if (getSentinelConfig() != null) { return Mode.SENTINEL; } if (getClusterConfiguration() != null) { return Mode.CLUSTER; } if (getMasterReplicaConfiguration() != null) { return Mode.MASTER_REPLICA; } return Mode.STANDALONE; } enum Mode { STANDALONE, CLUSTER, MASTER_REPLICA, SENTINEL } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionConfiguration.java
2
请完成以下Java代码
public static InetAddress getLocalInetAddress() throws SocketException { // enumerates all network interfaces Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces(); while (enu.hasMoreElements()) { NetworkInterface ni = enu.nextElement(); if (ni.isLoopback()) { continue; } Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses(); while (addressEnumeration.hasMoreElements()) { InetAddress address = addressEnumeration.nextElement(); // ignores all invalidated addresses if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) { continue; }
return address; } } throw new RuntimeException("No validated local address!"); } /** * Retrieve local address * * @return the string local address */ public static String getLocalAddress() { return localAddress.getHostAddress(); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NetUtils.java
1
请完成以下Java代码
public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override public int getShipper_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID); }
@Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public String getTargetBean() { return targetBean; } public void setTargetBean(String targetBean) { this.targetBean = targetBean; } public String getTargetMethod() { return targetMethod; } public void setTargetMethod(String targetMethod) { this.targetMethod = targetMethod; } public List<Object> getArguments() { return arguments; } public void setArguments(List<Object> arguments) { this.arguments = arguments; } public List<String> getParameterTypes() {
return parameterTypes; } public void setParameterTypes(List<String> parameterTypes) { this.parameterTypes = parameterTypes; } /** * 必须重写equals和hashCode方法,否则放到set集合里没法去重 * * @param o * @return */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CachedMethodInvocation that = (CachedMethodInvocation) o; return key.equals(that.key); } @Override public int hashCode() { return key.hashCode(); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CachedMethodInvocation.java
1
请完成以下Java代码
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableCreateEvt(variableInstance, sourceScope); } }); } } @Override public void onDelete(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_DELETE, variableInstance) && !variableInstance.isTransient()) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableDeleteEvt(variableInstance, sourceScope); } }); } }
@Override public void onUpdate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_UPDATE, variableInstance) && !variableInstance.isTransient()) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableUpdateEvt(variableInstance, sourceScope); } }); } } protected HistoryLevel getHistoryLevel() { return Context.getProcessEngineConfiguration().getHistoryLevel(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceHistoryListener.java
1
请完成以下Java代码
public int getAD_Workflow_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); }
/** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow_Access.java
1
请完成以下Java代码
public int getAD_Org_Mapping_ID() { return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() {
return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org_Mapping.java
1
请完成以下Java代码
public class Car { private final String make; private final String model; private final int year; private final String color; private final boolean automatic; private final int numDoors; private final String features; private Car(CarBuilder carBuilder) { this.make = carBuilder.make; this.model = carBuilder.model; this.year = carBuilder.year; this.color = carBuilder.color; this.automatic = carBuilder.automatic; this.numDoors = carBuilder.numDoors; this.features = carBuilder.features; } public String getMake() { return make; } public String getModel() { return model; } public int getYear() { return year; } public String getColor() { return color; } public boolean isAutomatic() { return automatic; } public int getNumDoors() { return numDoors; } public String getFeatures() { return features; } public static class CarBuilder {
private final String make; private final String model; private final int year; private String color = "unknown"; private boolean automatic = false; private int numDoors = 4; private String features = ""; public CarBuilder(String make, String model, int year) { this.make = make; this.model = model; this.year = year; } public CarBuilder color(String color) { this.color = color; return this; } public CarBuilder automatic(boolean automatic) { this.automatic = automatic; return this; } public CarBuilder numDoors(int numDoors) { this.numDoors = numDoors; return this; } public CarBuilder features(String features) { this.features = features; return this; } public Car build() { return new Car(this); } } @Override public String toString() { return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]"; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\Car.java
1
请完成以下Java代码
public String getOperationType() { return operationType; } public String getAssignerId() { return assignerId; } public String getTenantId() { return tenantId; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) { HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto(); fromHistoricIdentityLink(dto, historicIdentityLink);
return dto; } public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto, HistoricIdentityLinkLog historicIdentityLink) { dto.id = historicIdentityLink.getId(); dto.assignerId = historicIdentityLink.getAssignerId(); dto.groupId = historicIdentityLink.getGroupId(); dto.operationType = historicIdentityLink.getOperationType(); dto.taskId = historicIdentityLink.getTaskId(); dto.time = historicIdentityLink.getTime(); dto.type = historicIdentityLink.getType(); dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId(); dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey(); dto.userId = historicIdentityLink.getUserId(); dto.tenantId = historicIdentityLink.getTenantId(); dto.removalTime = historicIdentityLink.getRemovalTime(); dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogDto.java
1
请在Spring Boot框架中完成以下Java代码
public final class CrossOriginOpenerPolicyConfig { private CrossOriginOpenerPolicyHeaderWriter writer; public CrossOriginOpenerPolicyConfig() { } /** * Sets the policy to be used in the {@code Cross-Origin-Opener-Policy} header * @param openerPolicy a {@code Cross-Origin-Opener-Policy} * @return the {@link CrossOriginOpenerPolicyConfig} for additional configuration * @throws IllegalArgumentException if openerPolicy is null */ public CrossOriginOpenerPolicyConfig policy( CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy openerPolicy) { this.writer.setPolicy(openerPolicy); return this; } } public final class CrossOriginEmbedderPolicyConfig { private CrossOriginEmbedderPolicyHeaderWriter writer; public CrossOriginEmbedderPolicyConfig() { } /** * Sets the policy to be used in the {@code Cross-Origin-Embedder-Policy} header * @param embedderPolicy a {@code Cross-Origin-Embedder-Policy} * @return the {@link CrossOriginEmbedderPolicyConfig} for additional * configuration * @throws IllegalArgumentException if embedderPolicy is null */ public CrossOriginEmbedderPolicyConfig policy( CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy embedderPolicy) { this.writer.setPolicy(embedderPolicy); return this; }
} public final class CrossOriginResourcePolicyConfig { private CrossOriginResourcePolicyHeaderWriter writer; public CrossOriginResourcePolicyConfig() { } /** * Sets the policy to be used in the {@code Cross-Origin-Resource-Policy} header * @param resourcePolicy a {@code Cross-Origin-Resource-Policy} * @return the {@link CrossOriginResourcePolicyConfig} for additional * configuration * @throws IllegalArgumentException if resourcePolicy is null */ public CrossOriginResourcePolicyConfig policy( CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy resourcePolicy) { this.writer.setPolicy(resourcePolicy); return this; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\HeadersConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
private static String getRelativePath(EntityType entityType, EntityId entityId) { String path = entityType.name().toLowerCase(); if (entityId != null) { path += "/" + entityId + ".json"; } return path; } private static PrepareMsg getCommitPrepareMsg(User user, VersionCreateRequest request) { return PrepareMsg.newBuilder().setCommitMsg(request.getVersionName()) .setBranchName(request.getBranch()).setAuthorName(getAuthorName(user)).setAuthorEmail(user.getEmail()).build(); } private static String getAuthorName(User user) { List<String> parts = new ArrayList<>(); if (StringUtils.isNotBlank(user.getFirstName())) { parts.add(user.getFirstName()); } if (StringUtils.isNotBlank(user.getLastName())) { parts.add(user.getLastName()); } if (parts.isEmpty()) { parts.add(user.getName()); } return String.join(" ", parts); } private ToVersionControlServiceMsg.Builder newRequestProto(PendingGitRequest<?> request, RepositorySettings settings) { var tenantId = request.getTenantId(); var requestId = request.getRequestId(); var builder = ToVersionControlServiceMsg.newBuilder() .setNodeId(serviceInfoProvider.getServiceId()) .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequestIdMSB(requestId.getMostSignificantBits()) .setRequestIdLSB(requestId.getLeastSignificantBits()); RepositorySettings vcSettings = settings; if (vcSettings == null && request.requiresSettings()) { vcSettings = entitiesVersionControlService.getVersionControlSettings(tenantId); } if (vcSettings != null) { builder.setVcSettings(ProtoUtils.toProto(vcSettings)); } else if (request.requiresSettings()) { throw new RuntimeException("No entity version control settings provisioned!"); } return builder; } private CommitRequestMsg.Builder buildCommitRequest(CommitGitRequest commit) { return CommitRequestMsg.newBuilder().setTxId(commit.getTxId().toString()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitVersionControlQueueService.java
2
请完成以下Java代码
public final class MethodInvocationAdapter implements MethodInvocation { private final ProceedingJoinPoint jp; private final Method method; private final Object target; MethodInvocationAdapter(JoinPoint jp) { this.jp = (ProceedingJoinPoint) jp; if (jp.getTarget() != null) { this.target = jp.getTarget(); } else { // SEC-1295: target may be null if an ITD is in use this.target = jp.getSignature().getDeclaringType(); } String targetMethodName = jp.getStaticPart().getSignature().getName(); Class<?>[] types = ((CodeSignature) jp.getStaticPart().getSignature()).getParameterTypes(); Class<?> declaringType = jp.getStaticPart().getSignature().getDeclaringType(); this.method = findMethod(targetMethodName, declaringType, types); Assert.notNull(this.method, () -> "Could not obtain target method from JoinPoint: '" + jp + "'"); } private Method findMethod(String name, Class<?> declaringType, Class<?>[] params) { Method method = null; try { method = declaringType.getMethod(name, params); } catch (NoSuchMethodException ignored) { } if (method == null) { try { method = declaringType.getDeclaredMethod(name, params); } catch (NoSuchMethodException ignored) { } } return method; }
@Override public Method getMethod() { return this.method; } @Override public Object[] getArguments() { return this.jp.getArgs(); } @Override public AccessibleObject getStaticPart() { return this.method; } @Override public Object getThis() { return this.target; } @Override public Object proceed() throws Throwable { return this.jp.proceed(); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\aspectj\MethodInvocationAdapter.java
1
请完成以下Java代码
public DefaultHttpGraphQlClientBuilder header(String name, String... values) { this.webClientBuilder.defaultHeader(name, values); return this; } @Override public DefaultHttpGraphQlClientBuilder headers(Consumer<HttpHeaders> headersConsumer) { this.webClientBuilder.defaultHeaders(headersConsumer); return this; } @Override public DefaultHttpGraphQlClientBuilder codecConfigurer(Consumer<CodecConfigurer> codecConfigurerConsumer) { this.webClientBuilder.codecs(codecConfigurerConsumer::accept); return this; } @Override public DefaultHttpGraphQlClientBuilder webClient(Consumer<WebClient.Builder> configurer) { configurer.accept(this.webClientBuilder); return this; } @Override public HttpGraphQlClient build() { // Pass the codecs to the parent for response decoding this.webClientBuilder.codecs((configurer) -> setJsonCodecs( CodecDelegate.findJsonEncoder(configurer), CodecDelegate.findJsonDecoder(configurer))); WebClient webClient = this.webClientBuilder.build(); GraphQlClient graphQlClient = super.buildGraphQlClient(new HttpGraphQlTransport(webClient)); return new DefaultHttpGraphQlClient(graphQlClient, webClient, getBuilderInitializer());
} /** * Default {@link HttpGraphQlClient} implementation. */ private static class DefaultHttpGraphQlClient extends AbstractDelegatingGraphQlClient implements HttpGraphQlClient { private final WebClient webClient; private final Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer; DefaultHttpGraphQlClient( GraphQlClient delegate, WebClient webClient, Consumer<AbstractGraphQlClientBuilder<?>> builderInitializer) { super(delegate); Assert.notNull(webClient, "WebClient is required"); Assert.notNull(builderInitializer, "`builderInitializer` is required"); this.webClient = webClient; this.builderInitializer = builderInitializer; } @Override public DefaultHttpGraphQlClientBuilder mutate() { DefaultHttpGraphQlClientBuilder builder = new DefaultHttpGraphQlClientBuilder(this.webClient); this.builderInitializer.accept(builder); return builder; } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultHttpGraphQlClientBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { @Autowired private FilterInvocationSecurityMetadataSource securityMetadataSource; @Autowired public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) { super.setAccessDecisionManager(myAccessDecisionManager); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain); HttpServletResponse response = (HttpServletResponse)servletResponse; HttpServletRequest request = (HttpServletRequest)servletRequest; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", ":x-requested-with,content-type"); filterChain.doFilter(servletRequest,servletResponse); if (!request.getRequestURI().equals("/oauth/token")) { invoke(fi); } } public void invoke(FilterInvocation fi) throws IOException, ServletException {
InterceptorStatusToken token = super.beforeInvocation(fi); try { //执行下一个拦截器 fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } }
repos\SpringBootLearning-master (1)\springboot-security-oauth2\src\main\java\com\gf\config\MyFilterSecurityInterceptor.java
2
请在Spring Boot框架中完成以下Java代码
public void saveAdHocBookDraft(String title) { Book book = BookDraft.$.produce(bookDraft -> { bookDraft.setCreatedAt(Instant.now()); bookDraft.setTitle(title); bookDraft.setAuthor(AuthorDraft.$.produce(authorDraft -> { authorDraft.setId(1L); })); bookDraft.setId(1L); }); sqlClient.save(book); } public List<BookView> findAllByTitleLike(String title) { List<BookView> values = sqlClient.createQuery(BookTable.$) .where(BookTable.$.title() .like(title)) .select(BookTable.$.fetch(BookView.class)) .execute(); return values; }
public List<BookView> findAllByTitleLikeProjection(String title) { List<Book> books = sqlClient.createQuery(BookTable.$) .where(BookTable.$.title() .like(title)) .select(BookTable.$.fetch(Fetchers.BOOK_FETCHER.title() .createdAt() .author())) .execute(); return books.stream() .map(BookView::new) .collect(Collectors.toList()); } }
repos\tutorials-master\persistence-modules\jimmer\src\main\java\com\baeldung\jimmer\introduction\repository\BookRepository.java
2
请完成以下Java代码
public static String stripCmmnFileSuffix(String cmmnFileResource) { for (String suffix : CMMN_RESOURCE_SUFFIXES) { if (cmmnFileResource.endsWith(suffix)) { return cmmnFileResource.substring(0, cmmnFileResource.length() - suffix.length()); } } return cmmnFileResource; } public static String getCaseDiagramResourceName(String cmmnFileResource, String caseKey, String diagramSuffix) { String cmmnFileResourceBase = stripCmmnFileSuffix(cmmnFileResource); return cmmnFileResourceBase + caseKey + "." + diagramSuffix; } /** * Finds the name of a resource for the diagram for a case definition. Assumes that the case definition's key and (CMMN) resource name are already set. * * <p> * It will first look for an image resource which matches the case specifically, before resorting to an image resource which matches the CMMN 1.1 xml file resource. * * <p> * Example: if the deployment contains a CMMN 1.1 xml resource called 'abc.cmmn.xml' containing only one case with key 'myCase', then this method will look for an image resources * called 'abc.myCase.png' (or .jpg, or .gif, etc.) or 'abc.png' if the previous one wasn't found. * * <p> * Example 2: if the deployment contains a CMMN 1.1 xml resource called 'abc.cmmn.xml' containing three cases (with keys a, b and c), then this method will first look for an image resource * called 'abc.a.png' before looking for 'abc.png' (likewise for b and c). Note that if abc.a.png, abc.b.png and abc.c.png don't exist, all cases will have the same image: abc.png. * * @return name of an existing resource, or null if no matching image resource is found in the resources. */ public static String getCaseDiagramResourceNameFromDeployment( CaseDefinitionEntity caseDefinition, Map<String, EngineResource> resources) {
if (StringUtils.isEmpty(caseDefinition.getResourceName())) { throw new IllegalStateException("Provided case definition must have its resource name set."); } String cmmnResourceBase = stripCmmnFileSuffix(caseDefinition.getResourceName()); String key = caseDefinition.getKey(); for (String diagramSuffix : DIAGRAM_SUFFIXES) { String possibleName = cmmnResourceBase + key + "." + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } possibleName = cmmnResourceBase + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\ResourceNameUtil.java
1
请完成以下Java代码
public void addMouseListener(MouseListener l) { m_text.addMouseListener(l); m_button.addMouseListener(l); m_combo.getEditor().getEditorComponent().addMouseListener(l); // popup } private boolean isRowLoading() { if (m_mField == null) { return false; } final String rowLoadingStr = Env.getContext(Env.getCtx(), m_mField.getWindowNo(), m_mField.getVO().TabNo, GridTab.CTX_RowLoading); return "Y".equals(rowLoadingStr); } /* package */IValidationContext getValidationContext() { final GridField gridField = m_mField; // In case there is no GridField set (e.g. VLookup was created from a custom swing form) if (gridField == null) { return IValidationContext.DISABLED; } final IValidationContext evalCtx = Services.get(IValidationRuleFactory.class).createValidationContext(gridField); // In case grid field validation context could not be created, disable validation // NOTE: in most of the cases when we reach this point is when we are in a custom form which used GridFields to create the lookups // but those custom fields does not have a GridTab // e.g. de.metas.paymentallocation.form.PaymentAllocationForm if (evalCtx == null) { return IValidationContext.DISABLED; } return evalCtx; }
@Override public void addFocusListener(final FocusListener l) { getEditorComponent().addFocusListener(l); } @Override public void removeFocusListener(FocusListener l) { getEditorComponent().removeFocusListener(l); } public void setInfoWindowEnabled(final boolean enabled) { this.infoWindowEnabled = enabled; if (m_button != null) { m_button.setVisible(enabled); } } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } } // VLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookup.java
1
请完成以下Java代码
public void setParentElement(final org.compiere.model.I_M_Ingredients ParentElement) { set_ValueFromPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class, ParentElement); } @Override public void setParentElement_ID (final int ParentElement_ID) { if (ParentElement_ID < 1) set_Value (COLUMNNAME_ParentElement_ID, null); else set_Value (COLUMNNAME_ParentElement_ID, ParentElement_ID); } @Override public int getParentElement_ID() { return get_ValueAsInt(COLUMNNAME_ParentElement_ID); } @Override public void setPrecision (final int Precision) { set_Value (COLUMNNAME_Precision, Precision); } @Override public int getPrecision() { return get_ValueAsInt(COLUMNNAME_Precision); } @Override public void setQty (final @Nullable java.lang.String Qty) { set_Value (COLUMNNAME_Qty, Qty); }
@Override public java.lang.String getQty() { return get_ValueAsString(COLUMNNAME_Qty); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java
1
请完成以下Java代码
public String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVATCode (final @Nullable String VATCode) { set_Value (COLUMNNAME_VATCode, VATCode); } @Override public String getVATCode() { return get_ValueAsString(COLUMNNAME_VATCode); } @Override public org.compiere.model.I_C_CostClassification_Category getC_CostClassification_Category() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class); } @Override public void setC_CostClassification_Category(final org.compiere.model.I_C_CostClassification_Category C_CostClassification_Category) { set_ValueFromPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class, C_CostClassification_Category); } @Override public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID) { if (C_CostClassification_Category_ID < 1) set_Value (COLUMNNAME_C_CostClassification_Category_ID, null); else set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID); } @Override public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID); }
@Override public org.compiere.model.I_C_CostClassification getC_CostClassification() { return get_ValueAsPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class); } @Override public void setC_CostClassification(final org.compiere.model.I_C_CostClassification C_CostClassification) { set_ValueFromPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class, C_CostClassification); } @Override public void setC_CostClassification_ID (final int C_CostClassification_ID) { if (C_CostClassification_ID < 1) set_Value (COLUMNNAME_C_CostClassification_ID, null); else set_Value (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID); } @Override public int getC_CostClassification_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Fact_Acct_Transactions_View.java
1
请完成以下Java代码
public class TransformsType { @XmlElement(name = "Transform", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected List<TransformType> transform; /** * Gets the value of the transform property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the transform property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTransform().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link TransformType } * * */ public List<TransformType> getTransform() { if (transform == null) { transform = new ArrayList<TransformType>(); } return this.transform; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransformsType.java
1
请完成以下Java代码
public NotificationRuleInfo findInfoById(TenantId tenantId, NotificationRuleId id) { NotificationRuleInfoEntity infoEntity = notificationRuleRepository.findInfoById(id.getId()); return infoEntity != null ? infoEntity.toData() : null; } @Override public void removeByTenantId(TenantId tenantId) { notificationRuleRepository.deleteByTenantId(tenantId.getId()); } @Override public NotificationRule findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public NotificationRule findByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndName(tenantId, name)); } @Override public PageData<NotificationRule> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(notificationRuleRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override public NotificationRuleId getExternalIdByInternal(NotificationRuleId internalId) { return DaoUtil.toEntityId(notificationRuleRepository.getExternalIdByInternal(internalId.getId()), NotificationRuleId::new); } @Override
public PageData<NotificationRule> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override protected Class<NotificationRuleEntity> getEntityClass() { return NotificationRuleEntity.class; } @Override protected JpaRepository<NotificationRuleEntity, UUID> getRepository() { return notificationRuleRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_RULE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRuleDao.java
1
请完成以下Java代码
class JettyEmbeddedWebAppContext extends WebAppContext { JettyEmbeddedWebAppContext() { setHiddenClassMatcher(new ClassMatcher("org.springframework.boot.loader.")); } @Override protected ServletHandler newServletHandler() { return new JettyEmbeddedServletHandler(); } void deferredInitialize() throws Exception { JettyEmbeddedServletHandler handler = (JettyEmbeddedServletHandler) getServletHandler(); getContext().call(handler::deferredInitialize, null); } @Override
public String getCanonicalNameForTmpDir() { return super.getCanonicalNameForTmpDir(); } private static final class JettyEmbeddedServletHandler extends ServletHandler { @Override public void initialize() throws Exception { } void deferredInitialize() throws Exception { super.initialize(); } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\JettyEmbeddedWebAppContext.java
1
请完成以下Java代码
public GenericIdentification32 getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link GenericIdentification32 } * */ public void setId(GenericIdentification32 value) { this.id = value; } /** * Gets the value of the sysNm property. * * @return * possible object is * {@link String } * */ public String getSysNm() { return sysNm; } /** * Sets the value of the sysNm property. * * @param value * allowed object is * {@link String } * */ public void setSysNm(String value) { this.sysNm = value; } /** * Gets the value of the grpId property. * * @return * possible object is * {@link String } * */ public String getGrpId() { return grpId; } /** * Sets the value of the grpId property. * * @param value * allowed object is * {@link String } * */ public void setGrpId(String value) { this.grpId = value; } /** * Gets the value of the cpblties property. * * @return * possible object is * {@link PointOfInteractionCapabilities1 } *
*/ public PointOfInteractionCapabilities1 getCpblties() { return cpblties; } /** * Sets the value of the cpblties property. * * @param value * allowed object is * {@link PointOfInteractionCapabilities1 } * */ public void setCpblties(PointOfInteractionCapabilities1 value) { this.cpblties = value; } /** * Gets the value of the cmpnt property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the cmpnt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCmpnt().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PointOfInteractionComponent1 } * * */ public List<PointOfInteractionComponent1> getCmpnt() { if (cmpnt == null) { cmpnt = new ArrayList<PointOfInteractionComponent1>(); } return this.cmpnt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteraction1.java
1
请完成以下Java代码
public void setSEPA_CreditorIdentifier (java.lang.String SEPA_CreditorIdentifier) { set_Value (COLUMNNAME_SEPA_CreditorIdentifier, SEPA_CreditorIdentifier); } /** Get Gläubiger-Identifikationsnummer. @return Gläubiger-Identifikationsnummer */ @Override public java.lang.String getSEPA_CreditorIdentifier () { return (java.lang.String)get_Value(COLUMNNAME_SEPA_CreditorIdentifier); } /** Set Gläubigername. @param SEPA_CreditorName Gläubigername */ @Override public void setSEPA_CreditorName (java.lang.String SEPA_CreditorName) { set_Value (COLUMNNAME_SEPA_CreditorName, SEPA_CreditorName); } /** Get Gläubigername. @return Gläubigername */ @Override public java.lang.String getSEPA_CreditorName () { return (java.lang.String)get_Value(COLUMNNAME_SEPA_CreditorName); } /** Set SEPA Export. @param SEPA_Export_ID SEPA Export */ @Override public void setSEPA_Export_ID (int SEPA_Export_ID) { if (SEPA_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, Integer.valueOf(SEPA_Export_ID)); } /** Get SEPA Export. @return SEPA Export */ @Override public int getSEPA_Export_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SEPA_Export_ID); if (ii == null) return 0; return ii.intValue(); } /** * SEPA_Protocol AD_Reference_ID=541110 * Reference name: SEPA_Protocol */ public static final int SEPA_PROTOCOL_AD_Reference_ID=541110; /** Credit Transfer (pain.001.001.03.ch.02) = pain.001.001.03.ch.02 */ public static final String SEPA_PROTOCOL_CreditTransferPain00100103Ch02 = "pain.001.001.03.ch.02"; /** Direct Debit (pain.008.003.02) = pain.008.003.02 */ public static final String SEPA_PROTOCOL_DirectDebitPain00800302 = "pain.008.003.02"; /** Set SEPA Protocol. @param SEPA_Protocol SEPA Protocol */ @Override
public void setSEPA_Protocol (java.lang.String SEPA_Protocol) { set_Value (COLUMNNAME_SEPA_Protocol, SEPA_Protocol); } /** Get SEPA Protocol. @return SEPA Protocol */ @Override public java.lang.String getSEPA_Protocol () { return (java.lang.String)get_Value(COLUMNNAME_SEPA_Protocol); } /** Set Swift code. @param SwiftCode Swift Code or BIC */ @Override public void setSwiftCode (java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } /** Get Swift code. @return Swift Code or BIC */ @Override public java.lang.String getSwiftCode () { return (java.lang.String)get_Value(COLUMNNAME_SwiftCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export.java
1
请完成以下Java代码
public boolean remove(ClassName className) { return this.singleAnnotations.remove(className) != null || this.repeatableAnnotations.remove(className) != null; } /** * Remove a single with the specified classname. * @param className the class name of an annotation * @return whether the annotation has been removed */ public boolean removeSingle(ClassName className) { return this.singleAnnotations.remove(className) != null; } /** * Remove all repeatable annotations with the specified classname. * @param className the class name of an annotation * @return whether any annotation has been removed
*/ public boolean removeAllRepeatable(ClassName className) { return this.repeatableAnnotations.remove(className) != null; } public AnnotationContainer deepCopy() { Map<ClassName, Builder> singleAnnotations = new LinkedHashMap<>(); this.singleAnnotations.forEach((className, builder) -> singleAnnotations.put(className, new Builder(builder))); MultiValueMap<ClassName, Builder> repeatableAnnotations = new LinkedMultiValueMap<>(); this.repeatableAnnotations.forEach((className, builders) -> builders .forEach((builder) -> repeatableAnnotations.add(className, new Builder(builder)))); return new AnnotationContainer(singleAnnotations, repeatableAnnotations); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\AnnotationContainer.java
1
请在Spring Boot框架中完成以下Java代码
private static @Nullable ExposableWebEndpoint getHealthEndpoint(WebEndpointsSupplier webEndpointsSupplier) { Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints(); return webEndpoints.stream() .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) .findFirst() .orElse(null); } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(ResourceConfig.class) @EnableConfigurationProperties(JerseyProperties.class) static class JerseyInfrastructureConfiguration { @Bean @ConditionalOnMissingBean JerseyApplicationPath jerseyApplicationPath(JerseyProperties properties, ResourceConfig config) { return new DefaultJerseyApplicationPath(properties.getApplicationPath(), config); } @Bean ResourceConfig resourceConfig(ObjectProvider<ResourceConfigCustomizer> resourceConfigCustomizers) { ResourceConfig resourceConfig = new ResourceConfig(); resourceConfigCustomizers.orderedStream().forEach((customizer) -> customizer.customize(resourceConfig)); return resourceConfig; } @Bean ServletRegistrationBean<ServletContainer> jerseyServletRegistration(JerseyApplicationPath jerseyApplicationPath, ResourceConfig resourceConfig) { return new ServletRegistrationBean<>(new ServletContainer(resourceConfig), jerseyApplicationPath.getUrlMapping()); } } static class JerseyAdditionalHealthEndpointPathsResourcesRegistrar implements ResourceConfigCustomizer { private final @Nullable ExposableWebEndpoint endpoint; private final HealthEndpointGroups groups; JerseyAdditionalHealthEndpointPathsResourcesRegistrar(@Nullable ExposableWebEndpoint endpoint, HealthEndpointGroups groups) { this.endpoint = endpoint; this.groups = groups; } @Override
public void customize(ResourceConfig config) { register(config); } private void register(ResourceConfig config) { EndpointMapping mapping = new EndpointMapping(""); JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.SERVER, this.groups); Collection<Resource> endpointResources = resourceFactory .createEndpointResources(mapping, (this.endpoint != null) ? Collections.singletonList(this.endpoint) : Collections.emptyList()) .stream() .filter(Objects::nonNull) .toList(); register(endpointResources, config); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\endpoint\web\HealthEndpointJerseyExtensionAutoConfiguration.java
2
请完成以下Java代码
public T deserialize(Object rawEvent) { return inboundEventDeserializer.deserialize(rawEvent); } public String detectEventDefinitionKey(FlowableEventInfo<T> event) { return inboundEventKeyDetector.detectEventDefinitionKey(event); } public Collection<EventPayloadInstance> extractPayload(EventModel eventDefinition, FlowableEventInfo<T> event) { return inboundEventPayloadExtractor.extractPayload(eventDefinition, event); } public Collection<EventRegistryEvent> transform(EventInstance eventInstance) { return inboundEventTransformer.transform(eventInstance); } public InboundEventDeserializer<T> getInboundEventDeserializer() { return inboundEventDeserializer; } public void setInboundEventDeserializer(InboundEventDeserializer<T> inboundEventDeserializer) { this.inboundEventDeserializer = inboundEventDeserializer; } public InboundEventKeyDetector<T> getInboundEventKeyDetector() { return inboundEventKeyDetector; } public void setInboundEventKeyDetector(InboundEventKeyDetector<T> inboundEventKeyDetector) { this.inboundEventKeyDetector = inboundEventKeyDetector; } public InboundEventTenantDetector<T> getInboundEventTenantDetector() { return inboundEventTenantDetector; }
public void setInboundEventTenantDetector(InboundEventTenantDetector<T> inboundEventTenantDetector) { this.inboundEventTenantDetector = inboundEventTenantDetector; } public InboundEventPayloadExtractor<T> getInboundEventPayloadExtractor() { return inboundEventPayloadExtractor; } public void setInboundEventPayloadExtractor(InboundEventPayloadExtractor<T> inboundEventPayloadExtractor) { this.inboundEventPayloadExtractor = inboundEventPayloadExtractor; } public InboundEventTransformer getInboundEventTransformer() { return inboundEventTransformer; } public void setInboundEventTransformer(InboundEventTransformer inboundEventTransformer) { this.inboundEventTransformer = inboundEventTransformer; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\pipeline\DefaultInboundEventProcessingPipeline.java
1
请完成以下Java代码
public String getF_END() { return F_END; } public void setF_END(String f_END) { F_END = f_END; } public String getF_QRCANTONID() { return F_QRCANTONID; } public void setF_QRCANTONID(String f_QRCANTONID) { F_QRCANTONID = f_QRCANTONID; } public String getF_DECLARE() {
return F_DECLARE; } public void setF_DECLARE(String f_DECLARE) { F_DECLARE = f_DECLARE; } public String getF_DECLAREISEND() { return F_DECLAREISEND; } public void setF_DECLAREISEND(String f_DECLAREISEND) { F_DECLAREISEND = f_DECLAREISEND; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscCanton.java
1
请完成以下Java代码
public IMaterialTrackingDocuments retrieveMaterialTrackingDocuments(final I_M_Material_Tracking materialTracking) { return new MaterialTrackingDocuments(materialTracking); } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsFor(@NonNull final I_PP_Order model) { final IMaterialTrackingDocuments materialTrackingDocuments = retrieveMaterialTrackingDocumentsOrNullFor(model); if (materialTrackingDocuments == null) { throw new AdempiereException("@NotFound@ @M_Material_Tracking_ID@" + "\n model: " + model); } return materialTrackingDocuments; }
@Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsOrNullFor(@NonNull final I_PP_Order model) { // Retrieve Material Tracking via material_tracklin final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(model); if (materialTracking == null) { return null; } return retrieveMaterialTrackingDocuments(materialTracking); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityBasedInvoicingDAO.java
1
请完成以下Java代码
public final class ExcludeAttributesKeyMatcher implements AttributesKeyMatcher { public static AttributesKeyMatcher of(final Collection<AttributesKeyMatcher> matchersToExclude) { return !matchersToExclude.isEmpty() ? new ExcludeAttributesKeyMatcher(matchersToExclude) : AcceptAllAttributesKeyMatcher.instance; } private final ImmutableSet<AttributesKeyMatcher> matchersToExclude; private ExcludeAttributesKeyMatcher(@NonNull final Collection<AttributesKeyMatcher> matchersToExclude) { this.matchersToExclude = ImmutableSet.copyOf(matchersToExclude); } @Override public boolean matches(@NonNull final AttributesKey attributesKey) { for (final AttributesKeyMatcher matcher : matchersToExclude) { if (matcher.matches(attributesKey)) { return false; } }
return true; } @Override public AttributesKey toAttributeKeys(final AttributesKey context) { return AttributesKey.OTHER; } @Override public Optional<AttributesKey> toAttributeKeys() { return Optional.of(AttributesKey.OTHER); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\ExcludeAttributesKeyMatcher.java
1
请完成以下Java代码
public class HMMSegmenter extends HMMTrainer implements Segmenter { CWSTagSet tagSet; public HMMSegmenter(HiddenMarkovModel model) { super(model); tagSet = new CWSTagSet(); } public HMMSegmenter() { tagSet = new CWSTagSet(); } @Override public List<String> segment(String text) { List<String> wordList = new LinkedList<String>(); segment(text, CharTable.convert(text), wordList); return wordList; } @Override public void segment(String text, String normalized, List<String> output) { int[] obsArray = new int[text.length()]; for (int i = 0; i < obsArray.length; i++) { obsArray[i] = vocabulary.idOf(normalized.substring(i, i + 1)); } int[] tagArray = new int[text.length()]; model.predict(obsArray, tagArray); StringBuilder result = new StringBuilder(); result.append(text.charAt(0)); for (int i = 1; i < tagArray.length; i++) { if (tagArray[i] == tagSet.B || tagArray[i] == tagSet.S) { output.add(result.toString()); result.setLength(0); } result.append(text.charAt(i)); } if (result.length() != 0) { output.add(result.toString()); } } @Override protected List<String[]> convertToSequence(Sentence sentence) { List<String[]> charList = new LinkedList<String[]>(); for (Word w : sentence.toSimpleWordList()) { String word = CharTable.convert(w.value); if (word.length() == 1) { charList.add(new String[]{word, "S"});
} else { charList.add(new String[]{word.substring(0, 1), "B"}); for (int i = 1; i < word.length() - 1; ++i) { charList.add(new String[]{word.substring(i, i + 1), "M"}); } charList.add(new String[]{word.substring(word.length() - 1), "E"}); } } return charList; } @Override protected TagSet getTagSet() { return tagSet; } /** * 获取兼容旧的Segment接口 * * @return */ public Segment toSegment() { return new Segment() { @Override protected List<Term> segSentence(char[] sentence) { List<String> wordList = segment(new String(sentence)); List<Term> termList = new LinkedList<Term>(); for (String word : wordList) { termList.add(new Term(word, null)); } return termList; } }.enableCustomDictionary(false); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMSegmenter.java
1
请完成以下Java代码
public void setIsManualCalibration (boolean IsManualCalibration) { set_Value (COLUMNNAME_IsManualCalibration, Boolean.valueOf(IsManualCalibration)); } @Override public boolean isManualCalibration() { return get_ValueAsBoolean(COLUMNNAME_IsManualCalibration); } @Override public void setMeasurementX (java.math.BigDecimal MeasurementX) { set_Value (COLUMNNAME_MeasurementX, MeasurementX); } @Override public java.math.BigDecimal getMeasurementX() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementX);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMeasurementY (java.math.BigDecimal MeasurementY) { set_Value (COLUMNNAME_MeasurementY, MeasurementY); } @Override public java.math.BigDecimal getMeasurementY() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementY); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_Calibration.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Board. @param WEBUI_Board_ID Board */ @Override public void setWEBUI_Board_ID (int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_Value (COLUMNNAME_WEBUI_Board_ID, null); else set_Value (COLUMNNAME_WEBUI_Board_ID, Integer.valueOf(WEBUI_Board_ID)); } /** Get Board. @return Board */ @Override public int getWEBUI_Board_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_WEBUI_Board_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Browse name. @param WEBUI_NameBrowse Browse name */ @Override public void setWEBUI_NameBrowse (java.lang.String WEBUI_NameBrowse) { set_Value (COLUMNNAME_WEBUI_NameBrowse, WEBUI_NameBrowse); } /** Get Browse name. @return Browse name */ @Override public java.lang.String getWEBUI_NameBrowse () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameBrowse); } /** Set New record name. @param WEBUI_NameNew New record name */ @Override public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew) { set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew);
} /** Get New record name. @return New record name */ @Override public java.lang.String getWEBUI_NameNew () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew); } /** Set New record name (breadcrumb). @param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */ @Override public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb) { set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb); } /** Get New record name (breadcrumb). @return New record name (breadcrumb) */ @Override public java.lang.String getWEBUI_NameNewBreadcrumb () { return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Menu.java
1
请完成以下Java代码
public Class<? extends ObservationConvention<? extends Context>> getDefaultConvention() { return DefaultRabbitStreamListenerObservationConvention.class; } @Override public String getPrefix() { return "spring.rabbit.stream.listener"; } @Override public KeyName[] getLowCardinalityKeyNames() { return ListenerLowCardinalityTags.values(); } }; /** * Low cardinality tags. */ public enum ListenerLowCardinalityTags implements KeyName { /** * Listener id. */ LISTENER_ID { @Override public String asString() { return "spring.rabbit.stream.listener.id"; } } } /** * Default {@link RabbitStreamListenerObservationConvention} for Rabbit listener key values. */ public static class DefaultRabbitStreamListenerObservationConvention implements RabbitStreamListenerObservationConvention { /**
* A singleton instance of the convention. */ public static final DefaultRabbitStreamListenerObservationConvention INSTANCE = new DefaultRabbitStreamListenerObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(RabbitStreamMessageReceiverContext context) { return KeyValues.of(RabbitStreamListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(), context.getListenerId()); } @Override public String getContextualName(RabbitStreamMessageReceiverContext context) { return context.getSource() + " receive"; } } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\micrometer\RabbitStreamListenerObservation.java
1
请完成以下Java代码
private WindowId getTargetWindowId(final KPIZoomIntoDetailsInfo detailsInfo) { final WindowId targetWindowId = detailsInfo.getTargetWindowId(); if (targetWindowId != null) { return targetWindowId; } return RecordWindowFinder.findAdWindowId(detailsInfo.getTableName()) .map(WindowId::of) .orElseThrow(() -> new AdempiereException("No window available to show the details")); } @PatchMapping("/kpis/{itemId}") public JSONDashboardItem changeKPIItem(@PathVariable("itemId") final int itemId, @RequestBody final List<JSONPatchEvent<DashboardItemPatchPath>> events) { return changeDashboardItem(DashboardWidgetType.KPI, UserDashboardItemId.ofRepoId(itemId), events); } @PatchMapping("/targetIndicators/{itemId}") public JSONDashboardItem changeTargetIndicatorItem(@PathVariable("itemId") final int itemId, @RequestBody final List<JSONPatchEvent<DashboardItemPatchPath>> events) { return changeDashboardItem(DashboardWidgetType.TargetIndicator, UserDashboardItemId.ofRepoId(itemId), events); } private JSONDashboardItem changeDashboardItem( final DashboardWidgetType widgetType, final UserDashboardItemId itemId,
final List<JSONPatchEvent<DashboardItemPatchPath>> events) { userSession.assertLoggedIn(); // // Change the dashboard item final UserDashboardItemChangeRequest request = UserDashboardItemChangeRequest.of(widgetType, itemId, userSession.getAD_Language(), events); final UserDashboardItemChangeResult changeResult = dashboardRepo.changeUserDashboardItem(getUserDashboard().get(), request); // // Notify on websocket final UserDashboard dashboard = getUserDashboard().get(); websocketSender.sendDashboardItemChangedEvent(dashboard, changeResult); // Return the changed item { final UserDashboardItem item = dashboard.getItemById(widgetType, itemId); final UserDashboardItemDataResponse data = dashboardDataService.getData(dashboard.getId()) .getItemData(UserDashboardItemDataRequest.builder() .itemId(item.getId()) .widgetType(widgetType) .context(KPIDataContext.ofUserSession(userSession)) .build()); return JSONDashboardItem.of(item, data, newKPIJsonOptions()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\DashboardRestController.java
1
请完成以下Java代码
private static class DistributionNetworksMap { private final ImmutableMap<DistributionNetworkId, DistributionNetwork> byId; private final ImmutableList<DistributionNetwork> emptiesDistributionNetworks; private final ImmutableMap<DistributionNetworkLineId, ImmutablePair<DistributionNetwork, DistributionNetworkLine>> byLineId; private DistributionNetworksMap(final List<DistributionNetwork> list) { this.byId = Maps.uniqueIndex(list, DistributionNetwork::getId); this.byLineId = list.stream() .flatMap(network -> network.getLines().stream().map(line -> ImmutablePair.of(network, line))) .collect(ImmutableMap.toImmutableMap( pair -> pair.getRight().getId(), pair -> pair)); this.emptiesDistributionNetworks = list.stream() .filter(DistributionNetwork::isEmptiesDistributionNetwork) .collect(ImmutableList.toImmutableList()); } public static Collector<DistributionNetwork, ?, DistributionNetworksMap> collect() { return GuavaCollectors.collectUsingListAccumulator(DistributionNetworksMap::new); } public DistributionNetwork getById(@NonNull DistributionNetworkId id) { final DistributionNetwork distributionNetwork = byId.get(id); if (distributionNetwork == null) { throw new AdempiereException("No distribution network found with id " + id); } return distributionNetwork; } public DistributionNetwork getEmptiesDistributionNetwork() { if (emptiesDistributionNetworks.isEmpty())
{ throw new AdempiereException("No empties distribution network found"); } else if (emptiesDistributionNetworks.size() > 1) { throw new AdempiereException("Multiple empties distribution networks found"); } else { return emptiesDistributionNetworks.get(0); } } public DistributionNetworkLine getLineById(@NonNull final DistributionNetworkLineId lineId) { final ImmutablePair<DistributionNetwork, DistributionNetworkLine> pair = byLineId.get(lineId); if (pair == null) { throw new AdempiereException("No line found with id " + lineId); } return pair.getRight(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ddorder\DistributionNetworkRepository.java
1
请完成以下Java代码
public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_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 Landscape. @param IsLandscape Landscape orientation */ public void setIsLandscape (boolean IsLandscape) { set_Value (COLUMNNAME_IsLandscape, Boolean.valueOf(IsLandscape)); } /** Get Landscape. @return Landscape orientation */ public boolean isLandscape () { Object oo = get_Value(COLUMNNAME_IsLandscape); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Label Height. @param LabelHeight Height of the label */ public void setLabelHeight (int LabelHeight) { set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight)); } /** Get Label Height. @return Height of the label */ public int getLabelHeight () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight); if (ii == null) return 0; return ii.intValue(); } /** Set Label Width.
@param LabelWidth Width of the Label */ public void setLabelWidth (int LabelWidth) { set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth)); } /** Get Label Width. @return Width of the Label */ public int getLabelWidth () { Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Printer Name. @param PrinterName Name of the Printer */ public void setPrinterName (String PrinterName) { set_Value (COLUMNNAME_PrinterName, PrinterName); } /** Get Printer Name. @return Name of the Printer */ public String getPrinterName () { return (String)get_Value(COLUMNNAME_PrinterName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
1
请完成以下Java代码
public String getCreateUserId() { return createUserId; } public Date getStartTime() { return startTime; } public void setStartTime(final Date startTime) { this.startTime = startTime; } public Date getExecutionStartTime() { return executionStartTime; } public void setExecutionStartTime(final Date executionStartTime) { this.executionStartTime = executionStartTime; } public static BatchDto fromBatch(Batch batch) { BatchDto dto = new BatchDto();
dto.id = batch.getId(); dto.type = batch.getType(); dto.totalJobs = batch.getTotalJobs(); dto.jobsCreated = batch.getJobsCreated(); dto.batchJobsPerSeed = batch.getBatchJobsPerSeed(); dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob(); dto.seedJobDefinitionId = batch.getSeedJobDefinitionId(); dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId(); dto.batchJobDefinitionId = batch.getBatchJobDefinitionId(); dto.suspended = batch.isSuspended(); dto.tenantId = batch.getTenantId(); dto.createUserId = batch.getCreateUserId(); dto.startTime = batch.getStartTime(); dto.executionStartTime = batch.getExecutionStartTime(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchDto.java
1
请完成以下Java代码
public class RoleDto extends BaseDTO implements Serializable { @ApiModelProperty(value = "ID") private Long id; @ApiModelProperty(value = "菜单") private Set<MenuDto> menus; @ApiModelProperty(value = "部门") private Set<DeptDto> depts; @ApiModelProperty(value = "名称") private String name; @ApiModelProperty(value = "数据权限") private String dataScope; @ApiModelProperty(value = "级别") private Integer level; @ApiModelProperty(value = "描述") private String description;
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RoleDto roleDto = (RoleDto) o; return Objects.equals(id, roleDto.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\dto\RoleDto.java
1
请完成以下Java代码
public void setPP_MRP_Supply_ID (int PP_MRP_Supply_ID) { if (PP_MRP_Supply_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, Integer.valueOf(PP_MRP_Supply_ID)); } /** Get MRP Supply. @return MRP Supply */ @Override public int getPP_MRP_Supply_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Supply_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugewiesene Menge.
@param QtyAllocated Zugewiesene Menge */ @Override public void setQtyAllocated (java.math.BigDecimal QtyAllocated) { set_Value (COLUMNNAME_QtyAllocated, QtyAllocated); } /** Get Zugewiesene Menge. @return Zugewiesene Menge */ @Override public java.math.BigDecimal getQtyAllocated () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyAllocated); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alloc.java
1
请完成以下Java代码
public int getC_BPartner_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Alberta_ID); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setIsArchived (final boolean IsArchived) { set_Value (COLUMNNAME_IsArchived, IsArchived); } @Override public boolean isArchived() { return get_ValueAsBoolean(COLUMNNAME_IsArchived); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) {
set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setTitleShort (final @Nullable java.lang.String TitleShort) { set_Value (COLUMNNAME_TitleShort, TitleShort); } @Override public java.lang.String getTitleShort() { return get_ValueAsString(COLUMNNAME_TitleShort); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_Alberta.java
1
请完成以下Java代码
public class NotificationTargetEntity extends BaseSqlEntity<NotificationTarget> { @Column(name = ModelConstants.TENANT_ID_PROPERTY, nullable = false) private UUID tenantId; @Column(name = ModelConstants.NAME_PROPERTY, nullable = false) private String name; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.NOTIFICATION_TARGET_CONFIGURATION_PROPERTY, nullable = false) private JsonNode configuration; @Column(name = ModelConstants.EXTERNAL_ID_PROPERTY) private UUID externalId; public NotificationTargetEntity() {} public NotificationTargetEntity(NotificationTarget notificationTarget) { setId(notificationTarget.getUuidId()); setCreatedTime(notificationTarget.getCreatedTime()); setTenantId(getTenantUuid(notificationTarget.getTenantId()));
setName(notificationTarget.getName()); setConfiguration(toJson(notificationTarget.getConfiguration())); setExternalId(getUuid(notificationTarget.getExternalId())); } @Override public NotificationTarget toData() { NotificationTarget notificationTarget = new NotificationTarget(); notificationTarget.setId(new NotificationTargetId(id)); notificationTarget.setCreatedTime(createdTime); notificationTarget.setTenantId(getTenantId(tenantId)); notificationTarget.setName(name); notificationTarget.setConfiguration(fromJson(configuration, NotificationTargetConfig.class)); notificationTarget.setExternalId(getEntityId(externalId, NotificationTargetId::new)); return notificationTarget; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\NotificationTargetEntity.java
1
请完成以下Java代码
public StripVersion getStripVersion() { return stripVersion; } public RewriteLocationResponseHeaderConfig setStripVersion(String stripVersion) { this.stripVersion = StripVersion.valueOf(stripVersion); return this; } public RewriteLocationResponseHeaderConfig setStripVersion(StripVersion stripVersion) { this.stripVersion = stripVersion; return this; } public String getLocationHeaderName() { return locationHeaderName; } public RewriteLocationResponseHeaderConfig setLocationHeaderName(String locationHeaderName) { this.locationHeaderName = locationHeaderName; return this; } public @Nullable String getHostValue() { return hostValue; } public RewriteLocationResponseHeaderConfig setHostValue(String hostValue) { this.hostValue = hostValue; return this; }
public String getProtocolsRegex() { return protocolsRegex; } public RewriteLocationResponseHeaderConfig setProtocolsRegex(String protocolsRegex) { this.protocolsRegex = protocolsRegex; this.hostPortPattern = compileHostPortPattern(protocolsRegex); this.hostPortVersionPattern = compileHostPortVersionPattern(protocolsRegex); return this; } public Pattern getHostPortPattern() { return hostPortPattern; } public Pattern getHostPortVersionPattern() { return hostPortVersionPattern; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RewriteLocationResponseHeaderFilterFunctions.java
1
请完成以下Java代码
int getAD_Table_ID() { return AD_Table_ID; } int getRecord_ID() { return Record_ID; } /** * @param showHelp * @see X_AD_Process#SHOWHELP_AD_Reference_ID */ public ProcessDialogBuilder setShowHelp(final String showHelp) { this.showHelp = showHelp; return this; } String getShowHelp(final Supplier<String> defaultValueSupplier) { return showHelp != null ? showHelp : defaultValueSupplier.get(); } ProcessDialogBuilder skipResultsPanel() { skipResultsPanel = true; return this; } boolean isSkipResultsPanel() { return skipResultsPanel; } public ProcessDialogBuilder setAllowProcessReRun(final Boolean allowProcessReRun) { this.allowProcessReRun = allowProcessReRun; return this; } boolean isAllowProcessReRun(final Supplier<Boolean> defaultValueSupplier) { return allowProcessReRun != null ? allowProcessReRun : defaultValueSupplier.get(); } public ProcessDialogBuilder setFromGridTab(GridTab gridTab) { final int windowNo = gridTab.getWindowNo(); final int tabNo = gridTab.getTabNo(); setWindowAndTabNo(windowNo, tabNo);
setAdWindowId(gridTab.getAdWindowId()); setIsSOTrx(Env.isSOTrx(gridTab.getCtx(), windowNo)); setTableAndRecord(gridTab.getAD_Table_ID(), gridTab.getRecord_ID()); setWhereClause(gridTab.getTableModel().getSelectWhereClauseFinal()); skipResultsPanel(); return this; } public ProcessDialogBuilder setProcessExecutionListener(final IProcessExecutionListener processExecutionListener) { this.processExecutionListener = processExecutionListener; return this; } IProcessExecutionListener getProcessExecutionListener() { return processExecutionListener; } public ProcessDialogBuilder setPrintPreview(final boolean printPreview) { this._printPreview = printPreview; return this; } boolean isPrintPreview() { if (_printPreview != null) { return _printPreview; } return Ini.isPropertyBool(Ini.P_PRINTPREVIEW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessDialogBuilder.java
1
请完成以下Java代码
private static final String getColumnSQL(I_AD_Column column) { String columnSQL = column.getColumnName(); if (!Check.isEmpty(column.getColumnSQL())) columnSQL = column.getColumnSQL(); return columnSQL; } public static String getTableName(Class<?> cl) { try { return (String)cl.getField("Table_Name").get(null); } catch (Exception e) { throw new AdempiereException(e); } } public static ColumnInfo[] createColumnInfo(GridTab gridTab) { final List<ColumnInfo> list = new ArrayList<ColumnInfo>(); for (GridField gridField : gridTab.getFields()) { final boolean isID = gridField.getDisplayType() == DisplayType.ID; if (!gridField.isDisplayed() && !isID) continue; ColumnInfo ci = createColumnInfo(gridField); if (ci != null) { if (isID) list.add(0, ci); else
list.add(ci); } } return list.toArray(new ColumnInfo[list.size()]); } public static ColumnInfo createColumnInfo(GridField gridField) { final String tableName = gridField.getGridTab().getTableName(); final String header = gridField.getHeader(); final int displayType = gridField.getDisplayType(); final ReferenceId referenceId = gridField.getAD_Reference_Value_ID(); final String columnName = gridField.getColumnName(); final String columnSQL = gridField.getColumnSQL(false); return createColumnInfo(header, tableName, columnName, columnSQL, displayType, ReferenceId.toRepoId(referenceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\MiniTableUtil.java
1
请完成以下Java代码
public class UserEntity implements Serializable{ private String id; private String userName; private String userType; private String password; private String email; private int age; private Date regTime; private String state; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) {
this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\entity\UserEntity.java
1