instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class RemoteAddrRoutePredicateFactory extends AbstractRoutePredicateFactory<RemoteAddrRoutePredicateFactory.Config> { private static final Log log = LogFactory.getLog(RemoteAddrRoutePredicateFactory.class); public RemoteAddrRoutePredicateFactory() { super(Config.class); } @Override public ShortcutType shortcutType() { return GATHER_LIST; } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList("sources"); } @NotNull private List<IpSubnetFilterRule> convert(List<String> values) { List<IpSubnetFilterRule> sources = new ArrayList<>(); for (String arg : values) { addSource(sources, arg); } return sources; } @Override public Predicate<ServerWebExchange> apply(Config config) { List<IpSubnetFilterRule> sources = convert(config.sources); return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { InetSocketAddress remoteAddress = config.remoteAddressResolver.resolve(exchange); if (remoteAddress != null && remoteAddress.getAddress() != null) { String hostAddress = remoteAddress.getAddress().getHostAddress(); String host = exchange.getRequest().getURI().getHost(); if (log.isDebugEnabled() && !hostAddress.equals(host)) { log.debug("Remote addresses didn't match " + hostAddress + " != " + host); } for (IpSubnetFilterRule source : sources) { if (source.matches(remoteAddress)) { return true; } } } return false; } @Override public Object getConfig() { return config; }
@Override public String toString() { return String.format("RemoteAddrs: %s", config.getSources()); } }; } private void addSource(List<IpSubnetFilterRule> sources, String source) { if (!source.contains("/")) { // no netmask, add default source = source + "/32"; } String[] ipAddressCidrPrefix = source.split("/", 2); String ipAddress = ipAddressCidrPrefix[0]; int cidrPrefix = Integer.parseInt(ipAddressCidrPrefix[1]); sources.add(new IpSubnetFilterRule(ipAddress, cidrPrefix, IpFilterRuleType.ACCEPT)); } public static class Config { @NotEmpty private List<String> sources = new ArrayList<>(); @NotNull private RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() { }; public List<String> getSources() { return sources; } public Config setSources(List<String> sources) { this.sources = sources; return this; } public Config setSources(String... sources) { this.sources = Arrays.asList(sources); return this; } public Config setRemoteAddressResolver(RemoteAddressResolver remoteAddressResolver) { this.remoteAddressResolver = remoteAddressResolver; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\RemoteAddrRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
private boolean isDescriptorEqual(JsonNode desc1, JsonNode desc2) { if (desc1 == null && desc2 == null) { return true; } if (desc1 == null || desc2 == null) { return false; } try { String hash1 = computeChecksum(desc1); String hash2 = computeChecksum(desc2); return Objects.equals(hash1, hash2); } catch (Exception e) { log.warn("Failed to compare descriptors using checksum, falling back to equals", e); return desc1.equals(desc2); } } private String computeChecksum(JsonNode node) { String canonicalString = JacksonUtil.toCanonicalString(node); if (canonicalString == null) { return null; } return Hashing.sha256().hashBytes(canonicalString.getBytes()).toString(); } private boolean acquireAdvisoryLock() { try { Boolean acquired = jdbcTemplate.queryForObject( "SELECT pg_try_advisory_lock(?)", Boolean.class, ADVISORY_LOCK_ID ); if (Boolean.TRUE.equals(acquired)) { log.trace("Acquired advisory lock"); return true; } return false; } catch (Exception e) { log.error("Failed to acquire advisory lock", e); return false; } }
private void releaseAdvisoryLock() { try { jdbcTemplate.queryForObject( "SELECT pg_advisory_unlock(?)", Boolean.class, ADVISORY_LOCK_ID ); log.debug("Released advisory lock"); } catch (Exception e) { log.error("Failed to release advisory lock", e); } } private VersionInfo parseVersion(String version) { try { String[] parts = version.split("\\."); int major = Integer.parseInt(parts[0]); int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; int maintenance = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; int patch = parts.length > 3 ? Integer.parseInt(parts[3]) : 0; return new VersionInfo(major, minor, maintenance, patch); } catch (Exception e) { log.error("Failed to parse version: {}", version, e); return null; } } private Stream<Path> listDir(Path dir) { try { return Files.list(dir); } catch (NoSuchFileException e) { return Stream.empty(); } catch (IOException e) { throw new UncheckedIOException(e); } } public record VersionInfo(int major, int minor, int maintenance, int patch) {} }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\system\SystemPatchApplier.java
2
请完成以下Java代码
public ViewId getIncludedViewId(final IViewRow row) { final PackingHUsViewKey key = extractPackingHUsViewKey(PickingSlotRow.cast(row)); return key.getPackingHUsViewId(); } private PackingHUsViewKey extractPackingHUsViewKey(final PickingSlotRow row) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(row.getPickingSlotRowId()); return PackingHUsViewKey.builder() .pickingSlotsClearingViewIdPart(getViewId().getViewIdPart()) .bpartnerId(rootRow.getBPartnerId()) .bpartnerLocationId(rootRow.getBPartnerLocationId()) .build(); } public Optional<HUEditorView> getPackingHUsViewIfExists(final ViewId packingHUsViewId) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); return packingHUsViewsCollection.getByKeyIfExists(key); } public Optional<HUEditorView> getPackingHUsViewIfExists(final PickingSlotRowId rowId) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(rowId); final PackingHUsViewKey key = extractPackingHUsViewKey(rootRow); return packingHUsViewsCollection.getByKeyIfExists(key); }
public HUEditorView computePackingHUsViewIfAbsent(@NonNull final ViewId packingHUsViewId, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsCollection.computeIfAbsent(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsViewFactory); } public void setPackingHUsView(@NonNull final HUEditorView packingHUsView) { final ViewId packingHUsViewId = packingHUsView.getViewId(); packingHUsViewsCollection.put(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsView); } void closePackingHUsView(final ViewId packingHUsViewId, final ViewCloseAction closeAction) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); packingHUsViewsCollection.removeIfExists(key) .ifPresent(packingHUsView -> packingHUsView.close(closeAction)); } public void handleEvent(final HUExtractedFromPickingSlotEvent event) { packingHUsViewsCollection.handleEvent(event); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PickingSlotsClearingView.java
1
请完成以下Java代码
public void setData(T data) { this.data = data; } public long getCurrentTime() { return currentTime; } public void setCurrentTime(long currentTime) { this.currentTime = currentTime; } public BaseResp(){} /** * * @param code 错误码 * @param message 信息 * @param data 数据 */ public BaseResp(int code, String message, T data) { this.code = code; this.message = message; this.data = data; this.currentTime = new Date().getTime(); } /**
* 不带数据的返回结果 * @param resultStatus */ public BaseResp(ResultStatus resultStatus) { this.code = resultStatus.getErrorCode(); this.message = resultStatus.getErrorMsg(); this.data = data; this.currentTime = new Date().getTime(); } /** * 带数据的返回结果 * @param resultStatus * @param data */ public BaseResp(ResultStatus resultStatus, T data) { this.code = resultStatus.getErrorCode(); this.message = resultStatus.getErrorMsg(); this.data = data; this.currentTime = new Date().getTime(); } }
repos\spring-boot-quick-master\quick-exception\src\main\java\com\quick\exception\utils\BaseResp.java
1
请完成以下Java代码
public class RuecknahmeangebotAnfordernResponse { @XmlElement(name = "return", namespace = "", required = true) protected RuecknahmeangebotAntwort _return; /** * Gets the value of the return property. * * @return * possible object is * {@link RuecknahmeangebotAntwort } * */ public RuecknahmeangebotAntwort getReturn() { return _return;
} /** * Sets the value of the return property. * * @param value * allowed object is * {@link RuecknahmeangebotAntwort } * */ public void setReturn(RuecknahmeangebotAntwort value) { this._return = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\RuecknahmeangebotAnfordernResponse.java
1
请完成以下Java代码
public void setLoginApiUrl (java.lang.String LoginApiUrl) { set_Value (COLUMNNAME_LoginApiUrl, LoginApiUrl); } /** Get URL Api Login. @return URL Api Login */ @Override public java.lang.String getLoginApiUrl () { return (java.lang.String)get_Value(COLUMNNAME_LoginApiUrl); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** * PaperFormat AD_Reference_ID=541073 * Reference name: DpdPaperFormat */ public static final int PAPERFORMAT_AD_Reference_ID=541073; /** A6 = A6 */ public static final String PAPERFORMAT_A6 = "A6"; /** A5 = A5 */ public static final String PAPERFORMAT_A5 = "A5";
/** A4 = A4 */ public static final String PAPERFORMAT_A4 = "A4"; /** Set Papierformat. @param PaperFormat Papierformat */ @Override public void setPaperFormat (java.lang.String PaperFormat) { set_Value (COLUMNNAME_PaperFormat, PaperFormat); } /** Get Papierformat. @return Papierformat */ @Override public java.lang.String getPaperFormat () { return (java.lang.String)get_Value(COLUMNNAME_PaperFormat); } /** Set URL Api Shipment Service. @param ShipmentServiceApiUrl URL Api Shipment Service */ @Override public void setShipmentServiceApiUrl (java.lang.String ShipmentServiceApiUrl) { set_Value (COLUMNNAME_ShipmentServiceApiUrl, ShipmentServiceApiUrl); } /** Get URL Api Shipment Service. @return URL Api Shipment Service */ @Override public java.lang.String getShipmentServiceApiUrl () { return (java.lang.String)get_Value(COLUMNNAME_ShipmentServiceApiUrl); } /** Set Shipper Product. @param ShipperProduct Shipper Product */ @Override public void setShipperProduct (java.lang.String ShipperProduct) { set_Value (COLUMNNAME_ShipperProduct, ShipperProduct); } /** Get Shipper Product. @return Shipper Product */ @Override public java.lang.String getShipperProduct () { return (java.lang.String)get_Value(COLUMNNAME_ShipperProduct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_Shipper_Config.java
1
请完成以下Spring Boot application配置
spring: ai: openai: api-key: ${OPENAI_API_KEY} embedding: options: model: text-embedding-3-small dimensions: 512 data: redis: url: ${REDIS_URL} com: baeldung: semantic: cache: similarit
y-threshold: 0.8 content-field: question embedding-field: embedding metadata-field: answer
repos\tutorials-master\spring-ai-modules\spring-ai-semantic-caching\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class WebClientConfig { @Bean ReactiveClientRegistrationRepository clientRegistrations( @Value("${spring.security.oauth2.client.provider.bael.token-uri}") String token_uri, @Value("${spring.security.oauth2.client.registration.bael.client-id}") String client_id, @Value("${spring.security.oauth2.client.registration.bael.client-secret}") String client_secret, @Value("${spring.security.oauth2.client.registration.bael.authorization-grant-type}") String authorizationGrantType ) { ClientRegistration registration = ClientRegistration .withRegistrationId("keycloak") .tokenUri(token_uri) .clientId(client_id) .clientSecret(client_secret) .authorizationGrantType(new AuthorizationGrantType(authorizationGrantType)) .build(); return new InMemoryReactiveClientRegistrationRepository(registration); } @Bean public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository) { InMemoryReactiveOAuth2AuthorizedClientService clientService = new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build();
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( clientRegistrationRepository, clientService); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } @Bean WebClient webClient(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager auth2AuthorizedClientManager) { ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServerOAuth2AuthorizedClientExchangeFilterFunction(auth2AuthorizedClientManager); oauth2Client.setDefaultClientRegistrationId("bael"); return WebClient.builder() .filter(oauth2Client) .build(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-oauth\src\main\java\com\baeldung\webclient\clientcredentials\configuration\WebClientConfig.java
2
请在Spring Boot框架中完成以下Java代码
public Adempiere adempiere() { // when this is done, Adempiere.getBean(...) is ready to use return Env.getSingleAdempiereInstance(applicationContext); } @Override public void afterPropertiesSet() { if (clearQuerySelectionsRateInSeconds > 0) { final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool( 1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix("cleanup-" + I_T_Query_Selection.Table_Name) .build()); // note: "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute." scheduledExecutor.scheduleAtFixedRate( QuerySelectionToDeleteHelper::deleteScheduledSelectionsNoFail, // command, don't fail because on failure the task won't be re-scheduled so it's game over clearQuerySelectionsRateInSeconds, // initialDelay
clearQuerySelectionsRateInSeconds, // period TimeUnit.SECONDS // timeUnit ); logger.info("Clearing query selection tables each {} seconds", clearQuerySelectionsRateInSeconds); } } private static void setDefaultProperties() { if (Check.isBlank(System.getProperty(SYSTEM_PROPERTY_APP_NAME))) { System.setProperty(SYSTEM_PROPERTY_APP_NAME, ServerBoot.class.getSimpleName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\ServerBoot.java
2
请在Spring Boot框架中完成以下Java代码
public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } public Duration getConnectTimeout() { return this.connectTimeout; } public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Transport getTransport() { return this.transport; } public void setTransport(Transport transport) { this.transport = transport; } public Compression getCompression() { return this.compression; } public void setCompression(Compression compression) { this.compression = compression; } public Map<String, String> getHeaders() { return this.headers; } public void setHeaders(Map<String, String> headers) {
this.headers = headers; } public enum Compression { /** * Gzip compression. */ GZIP, /** * No compression. */ NONE } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\otlp\OtlpTracingProperties.java
2
请完成以下Java代码
public int getAD_Process_ID() { return adProcessId; } public String getCaption(final String adLanguage) { final ITranslatableString originalProcessCaption = getOriginalProcessCaption(); String caption = getPreconditionsResolution().computeCaption(originalProcessCaption, adLanguage); if (Services.get(IDeveloperModeBL.class).isEnabled()) { final I_AD_Process adProcess = adProcessSupplier.get(); caption += "/" + adProcess.getValue(); } return caption; } private ITranslatableString getOriginalProcessCaption() { final I_AD_Process adProcess = adProcessSupplier.get(); return InterfaceWrapperHelper.getModelTranslationMap(adProcess) .getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName()); } public String getDescription(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); String description = adProcessTrl.getDescription(); if (Services.get(IDeveloperModeBL.class).isEnabled()) { if (description == null) { description = ""; } else { description += "\n - "; } description += "Classname:" + adProcess.getClassname() + ", ID=" + adProcess.getAD_Process_ID(); } return description; } public String getHelp(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage);
return adProcessTrl.getHelp(); } public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get(); final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS); } return Images.getImageIcon2(iconName); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get(); } public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请完成以下Java代码
public abstract class AbstractRecursiveScriptScanner extends AbstractScriptScanner { public AbstractRecursiveScriptScanner(final IScriptScanner parentScanner) { super(parentScanner); } /** * * @return next script scanner or null */ protected abstract IScriptScanner retrieveNextChildScriptScanner(); private boolean closed = false; private IScriptScanner currentChildScanner = null; @Override public boolean hasNext() { while (!closed) { if (currentChildScanner == null) { currentChildScanner = retrieveNextChildScriptScanner(); } if (currentChildScanner == null) {
closed = true; return false; } if (currentChildScanner.hasNext()) { return true; } else { currentChildScanner = null; } } return false; } @Override public IScript next() { if (!hasNext()) { throw new NoSuchElementException(); } return currentChildScanner.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractRecursiveScriptScanner.java
1
请完成以下Java代码
public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { return ImmutableList.of(); } @Override public Stream<PickingSlotRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public ViewId getIncludedViewId(final IViewRow row) { final PackingHUsViewKey key = extractPackingHUsViewKey(PickingSlotRow.cast(row)); return key.getPackingHUsViewId(); } private PackingHUsViewKey extractPackingHUsViewKey(final PickingSlotRow row) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(row.getPickingSlotRowId()); return PackingHUsViewKey.builder() .pickingSlotsClearingViewIdPart(getViewId().getViewIdPart()) .bpartnerId(rootRow.getBPartnerId()) .bpartnerLocationId(rootRow.getBPartnerLocationId()) .build(); } public Optional<HUEditorView> getPackingHUsViewIfExists(final ViewId packingHUsViewId) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); return packingHUsViewsCollection.getByKeyIfExists(key); }
public Optional<HUEditorView> getPackingHUsViewIfExists(final PickingSlotRowId rowId) { final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(rowId); final PackingHUsViewKey key = extractPackingHUsViewKey(rootRow); return packingHUsViewsCollection.getByKeyIfExists(key); } public HUEditorView computePackingHUsViewIfAbsent(@NonNull final ViewId packingHUsViewId, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsCollection.computeIfAbsent(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsViewFactory); } public void setPackingHUsView(@NonNull final HUEditorView packingHUsView) { final ViewId packingHUsViewId = packingHUsView.getViewId(); packingHUsViewsCollection.put(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsView); } void closePackingHUsView(final ViewId packingHUsViewId, final ViewCloseAction closeAction) { final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId); packingHUsViewsCollection.removeIfExists(key) .ifPresent(packingHUsView -> packingHUsView.close(closeAction)); } public void handleEvent(final HUExtractedFromPickingSlotEvent event) { packingHUsViewsCollection.handleEvent(event); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PickingSlotsClearingView.java
1
请完成以下Java代码
public TopicPartition getTopicPartition() { return this.topicPartition; } /** * How long the partition was idle. * @return the time in milliseconds. */ public long getIdleTime() { return this.idleTime; } /** * The id of the listener (if {@code @KafkaListener}) or the container bean name. * @return the id. */ public String getListenerId() { return this.listenerId; }
/** * Retrieve the consumer. Only populated if the listener is consumer-aware. * Allows the listener to resume a paused consumer. * @return the consumer. */ public Consumer<?, ?> getConsumer() { return this.consumer; } @Override public String toString() { return "ListenerContainerPartitionNoLongerIdleEvent [idleTime=" + ((float) this.idleTime / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic # + ", container=" + getSource() + ", topicPartition=" + this.topicPartition + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ListenerContainerPartitionNoLongerIdleEvent.java
1
请完成以下Java代码
private int retrieveDataId(@NonNull final MainDataRecordIdentifier identifier) { final int result = identifier .createQueryBuilder() .create() .firstIdOnly(); Check.errorIf(result <= 0, "Found no I_MD_Cockpit record for identifier={}", identifier); return result; } public int handleUpdateDetailRequest(@NonNull final UpdateDDOrderDetailRequest updateRequest) { final ICompositeQueryUpdater<I_MD_Cockpit_DDOrder_Detail> updater = queryBL .createCompositeQueryUpdater(I_MD_Cockpit_DDOrder_Detail.class) .addSetColumnValue( I_MD_Cockpit_DDOrder_Detail.COLUMNNAME_QtyPending, stripTrailingDecimalZeros(updateRequest.getQtyPending())); return updateRequest.getDdOrderDetailIdentifier() .createQuery() .update(updater); }
public int handleRemoveDetailRequest(@NonNull final RemoveDDOrderDetailRequest removeDDOrderDetailRequest) { return removeDDOrderDetailRequest .getDdOrderDetailIdentifier() .createQuery() .delete(); } @NonNull public Optional<I_MD_Cockpit_DDOrder_Detail> retrieveDDOrderDetail(@NonNull final DDOrderDetailIdentifier identifier) { return identifier.createQuery() .firstOnlyOptional(I_MD_Cockpit_DDOrder_Detail.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\ddorderdetail\DDOrderDetailRequestHandler.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain configure(final HttpSecurity http) { http.csrf(csrfConfigurer -> csrfConfigurer.disable()) .sessionManagement( sessionConfigurer -> sessionConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(authManager -> { authManager.requestMatchers(WHITELISTED_API_ENDPOINTS).permitAll().anyRequest().authenticated(); }); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @ConditionalOnMissingBean public CompromisedPasswordChecker compromisedPasswordChecker() {
return new HaveIBeenPwnedRestApiPasswordChecker(); } @Bean @ConditionalOnMissingBean public CompromisedPasswordChecker customCompromisedPasswordChecker() { RestClient customRestClient = RestClient.builder().baseUrl(CUSTOM_COMPROMISED_PASSWORD_CHECK_URL) .defaultHeader("X-API-KEY", "api-key").build(); HaveIBeenPwnedRestApiPasswordChecker compromisedPasswordChecker = new HaveIBeenPwnedRestApiPasswordChecker(); compromisedPasswordChecker.setRestClient(customRestClient); return compromisedPasswordChecker; } }
repos\tutorials-master\spring-security-modules\spring-security-compromised-password\src\main\java\com\baeldung\security\configuration\SecurityConfiguration.java
2
请完成以下Java代码
private boolean isContextAttribute(final int columnIndex) { if (columnIndex < 0) { return false; } final PO po = InterfaceWrapperHelper.getStrictPO(sessionPO); final String columnName = po.get_ColumnName(columnIndex); if (columnName == null) { return false; } if (CTX_IgnoredColumnNames.contains(columnName))
{ return false; } final POInfo poInfo = po.getPOInfo(); final int displayType = poInfo.getColumnDisplayType(columnIndex); if (displayType == DisplayType.String) { return poInfo.getFieldLength(columnIndex) <= 60; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\MFSession.java
1
请在Spring Boot框架中完成以下Java代码
public class FileDownloadController { private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class); @Autowired private FileStorageService fileStorageService; @GetMapping("/downloadFile/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) { // Load file as Resource Resource resource = fileStorageService.loadFileAsResource(fileName); // Try to determine file's content type String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) {
logger.info("Could not determine file type."); } // Fallback to the default content type if type could not be determined if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } }
repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-rest-api-example\src\main\java\net\alanbinu\springboot\fileuploaddownload\controller\FileDownloadController.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_Promotion[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Campaign getC_Campaign() throws RuntimeException { return (I_C_Campaign)MTable.get(getCtx(), I_C_Campaign.Table_Name) .getPO(getC_Campaign_ID(), get_TrxName()); } /** Set Campaign. @param C_Campaign_ID Marketing Campaign */ public void setC_Campaign_ID (int C_Campaign_ID) { if (C_Campaign_ID < 1) set_Value (COLUMNNAME_C_Campaign_ID, null); else set_Value (COLUMNNAME_C_Campaign_ID, Integer.valueOf(C_Campaign_ID)); } /** Get Campaign. @return Marketing Campaign */ public int getC_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Campaign_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 Promotion. @param M_Promotion_ID Promotion */ public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); 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 Relative Priority. @param PromotionPriority Which promotion should be apply to a product */ public void setPromotionPriority (int PromotionPriority) { set_Value (COLUMNNAME_PromotionPriority, Integer.valueOf(PromotionPriority)); } /** Get Relative Priority. @return Which promotion should be apply to a product */ public int getPromotionPriority () { Integer ii = (Integer)get_Value(COLUMNNAME_PromotionPriority); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Promotion.java
1
请完成以下Java代码
public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record) { return toOrderLine(record).map(OrderLineDocumentLocationAdapterFactory::locationAdapter); } @Override public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { return Optional.empty(); } @Override public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { return Optional.empty();
} @Override public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { return Optional.empty(); } private static Optional<I_C_OrderLine> toOrderLine(final Object record) { return InterfaceWrapperHelper.isInstanceOf(record, I_C_OrderLine.class) ? Optional.of(InterfaceWrapperHelper.create(record, I_C_OrderLine.class)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderLineDocumentLocationAdapterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void setMEASUREMENTUNIT(String value) { this.measurementunit = value; } /** * Gets the value of the tamou1 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 tamou1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTAMOU1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TAMOU1 } * * */ public List<TAMOU1> getTAMOU1() { if (tamou1 == null) { tamou1 = new ArrayList<TAMOU1>(); } return this.tamou1; } /** * Gets the value of the ttaxi1 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 ttaxi1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTTAXI1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TTAXI1 } * * */ public List<TTAXI1> getTTAXI1() { if (ttaxi1 == null) { ttaxi1 = new ArrayList<TTAXI1>(); } return this.ttaxi1; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\TRAILR.java
2
请完成以下Java代码
public static String getCurrentUsername() { return getCurrentUsername(getToken()); } /** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername(String token) { JWT jwt = JWTUtil.parseToken(token); return jwt.getPayload("sub").toString(); } /** * 获取Token
* @return / */ public static String getToken() { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder .getRequestAttributes())).getRequest(); String bearerToken = request.getHeader(header); if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) { // 去掉令牌前缀 return bearerToken.replace(tokenStartWith, ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SecurityUtils.java
1
请完成以下Java代码
void runServer() throws IOException, InterruptedException { Path socketPath = Path.of(System.getProperty("user.home")) .resolve("baeldung.socket"); Files.deleteIfExists(socketPath); UnixDomainSocketAddress socketAddress = getAddress(socketPath); ServerSocketChannel serverChannel = createServerSocketChannel(socketAddress); SocketChannel channel = serverChannel.accept(); while (true) { readSocketMessage(channel) .ifPresent(message -> System.out.printf("[Client message] %s%n", message)); Thread.sleep(100); } } UnixDomainSocketAddress getAddress(Path socketPath) { return UnixDomainSocketAddress.of(socketPath); } ServerSocketChannel createServerSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
serverChannel.bind(socketAddress); return serverChannel; } Optional<String> readSocketMessage(SocketChannel channel) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024); int bytesRead = channel.read(buffer); if (bytesRead < 0) return Optional.empty(); byte[] bytes = new byte[bytesRead]; buffer.flip(); buffer.get(bytes); String message = new String(bytes); return Optional.of(message); } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\socket\UnixDomainSocketServer.java
1
请完成以下Java代码
private void deleteInvoiceCandidate(@NonNull final I_C_Flatrate_DataEntry dataEntry) { final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_ID()); if (invoiceCandId != null) { final I_C_Invoice_Candidate invoiceCandidate = invoiceCandDAO.getById(invoiceCandId); if (invoiceCandidate != null) { dataEntry.setC_Invoice_Candidate_ID(0); InterfaceWrapperHelper.delete(invoiceCandidate); } } invoiceCandDAO.deleteAllReferencingInvoiceCandidates(dataEntry); } private void deleteInvoiceCandidateCorr(@NonNull final I_C_Flatrate_DataEntry dataEntry) { final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_Corr_ID()); if (invoiceCandId != null) { final I_C_Invoice_Candidate icCorr = invoiceCandDAO.getById(invoiceCandId); if (icCorr != null) { dataEntry.setC_Invoice_Candidate_Corr_ID(0); InterfaceWrapperHelper.delete(icCorr); } } } private void afterReactivate(final I_C_Flatrate_DataEntry dataEntry) { if (X_C_Flatrate_DataEntry.TYPE_Invoicing_PeriodBased.equals(dataEntry.getType()))
{ final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class); final List<I_C_Invoice_Clearing_Alloc> allocLines = flatrateDB.retrieveClearingAllocs(dataEntry); for (final I_C_Invoice_Clearing_Alloc alloc : allocLines) { final I_C_Invoice_Candidate candToClear = alloc.getC_Invoice_Cand_ToClear(); candToClear.setQtyInvoiced(BigDecimal.ZERO); InterfaceWrapperHelper.save(candToClear); alloc.setC_Invoice_Candidate_ID(0); InterfaceWrapperHelper.save(alloc); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_DataEntry.java
1
请完成以下Java代码
public String getTollid() { return tollid; } public void setTollid(String tollid) { this.tollid = tollid; } public String getBudgetid() { return budgetid; } public void setBudgetid(String budgetid) { this.budgetid = budgetid; } public String getCbudgetid() { return cbudgetid; } public void setCbudgetid(String cbudgetid) { this.cbudgetid = cbudgetid; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getAuditmsg() { return auditmsg; } public void setAuditmsg(String auditmsg) { this.auditmsg = auditmsg; } public String getTrialstatus() { return trialstatus; } public void setTrialstatus(String trialstatus) { this.trialstatus = trialstatus; } public String getFirauditer() { return firauditer; } public void setFirauditer(String firauditer) { this.firauditer = firauditer; } public String getFiraudittime() { return firaudittime; } public void setFiraudittime(String firaudittime) { this.firaudittime = firaudittime; } public String getFinauditer() { return finauditer; } public void setFinauditer(String finauditer) { this.finauditer = finauditer;
} public String getFinaudittime() { return finaudittime; } public void setFinaudittime(String finaudittime) { this.finaudittime = finaudittime; } public String getEdittime() { return edittime; } public void setEdittime(String edittime) { this.edittime = edittime; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtoll.java
1
请完成以下Java代码
public int hashCode() { return attachmentEntryId.hashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof AttachmentEntryItem) { final AttachmentEntryItem other = (AttachmentEntryItem)obj; return attachmentEntryId == other.attachmentEntryId; } else { return false; } } } /************************************************************************** * Graphic Image Panel */ class GImage extends JPanel { /** * */ private static final long serialVersionUID = 4991225210651641722L; /** * Graphic Image */ public GImage() { super(); } // GImage /** The Image */ private Image m_image = null; /** * Set Image * * @param image image */ public void setImage(final Image image) { m_image = image; if (m_image == null) {
return; } MediaTracker mt = new MediaTracker(this); mt.addImage(m_image, 0); try { mt.waitForID(0); } catch (Exception e) { } Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this)); this.setPreferredSize(dim); } // setImage /** * Paint * * @param g graphics */ @Override public void paint(final Graphics g) { Insets in = getInsets(); if (m_image != null) { g.drawImage(m_image, in.left, in.top, this); } } // paint /** * Update * * @param g graphics */ @Override public void update(final Graphics g) { paint(g); } // update } // GImage } // Attachment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\Attachment.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getEDICctop000VID() { return ediCctop000VID; } /** * Sets the value of the ediCctop000VID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop000VID(BigInteger value) { this.ediCctop000VID = value; } /** * Gets the value of the gln property. * * @return * possible object is * {@link String } *
*/ public String getGLN() { return gln; } /** * Sets the value of the gln property. * * @param value * allowed object is * {@link String } * */ public void setGLN(String value) { this.gln = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop000VType.java
2
请完成以下Java代码
public void setMSV3_Tour (java.lang.String MSV3_Tour) { set_Value (COLUMNNAME_MSV3_Tour, MSV3_Tour); } /** Get Tour. @return Tour */ @Override public java.lang.String getMSV3_Tour () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Tour); } /** Set MSV3_Tour. @param MSV3_Tour_ID MSV3_Tour */ @Override public void setMSV3_Tour_ID (int MSV3_Tour_ID) { if (MSV3_Tour_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Tour_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Tour_ID, Integer.valueOf(MSV3_Tour_ID)); } /** Get MSV3_Tour. @return MSV3_Tour */ @Override public int getMSV3_Tour_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Tour_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil getMSV3_VerfuegbarkeitAnteil() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class); } @Override public void setMSV3_VerfuegbarkeitAnteil(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil MSV3_VerfuegbarkeitAnteil)
{ set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class, MSV3_VerfuegbarkeitAnteil); } /** Set MSV3_VerfuegbarkeitAnteil. @param MSV3_VerfuegbarkeitAnteil_ID MSV3_VerfuegbarkeitAnteil */ @Override public void setMSV3_VerfuegbarkeitAnteil_ID (int MSV3_VerfuegbarkeitAnteil_ID) { if (MSV3_VerfuegbarkeitAnteil_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, Integer.valueOf(MSV3_VerfuegbarkeitAnteil_ID)); } /** Get MSV3_VerfuegbarkeitAnteil. @return MSV3_VerfuegbarkeitAnteil */ @Override public int getMSV3_VerfuegbarkeitAnteil_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Tour.java
1
请在Spring Boot框架中完成以下Java代码
public BufferedReader getReader() { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() { return bais.read(); } @Override
public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\BodyReaderHttpServletRequestWrapper.java
2
请在Spring Boot框架中完成以下Java代码
public String getContextKey(final I_AD_Preference preference) { final String attribute = preference.getAttribute(); Check.assume(!Check.isEmpty(attribute), "Attribute not empty for " + preference); final int adWindowId = preference.getAD_Window_ID(); if (adWindowId > 0) { return "P" + adWindowId + "|" + attribute; } else { return "P|" + attribute; } } private String coerceToString(final Object value) { if (value == null) { return null; } else if (value instanceof String) { return (String)value; } else if (value instanceof Boolean)
{ return DisplayType.toBooleanString((Boolean)value); } else { return value.toString(); } } @Override public void deleteUserPreferenceByUserId(final UserId userId) { queryBL.createQueryBuilder(I_AD_Preference.class) .addEqualsFilter(I_AD_Preference.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceDAO.java
2
请完成以下Java代码
public class Inventory { @Id private String id; private String item; private String status; private Size size; private List<InStock> inStock; public String getId() { return id; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Size getSize() { return size; } public void setSize(Size size) {
this.size = size; } public List<InStock> getInStock() { return inStock; } public void setInStock(List<InStock> inStock) { this.inStock = inStock; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Inventory inventory = (Inventory) o; return Objects.equals(id, inventory.id) && Objects.equals(item, inventory.item) && Objects.equals(status, inventory.status); } @Override public int hashCode() { return Objects.hash(id, item, status); } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\Inventory.java
1
请完成以下Java代码
public class BookImpl implements Book { private String isbn; private String author; private String title; private Double price; public BookImpl() { } public BookImpl(String isbn, String author, String title, Double price) { this.isbn = isbn; this.author = author; this.title = title; this.price = price; } @Override public String getIsbn() { return isbn; } @Override public void setIsbn(String isbn) { this.isbn = isbn; } @Override public String getAuthor() { return author; } @Override public void setAuthor(String author) { this.author = author; }
@Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = title; } @Override public Double getPrice() { return price; } @Override public void setPrice(Double price) { this.price = price; } }
repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\data\BookImpl.java
1
请完成以下Java代码
public final Iterator<T> getParentIterator() { return iterator; } @Override public final boolean hasNext() { clearCurrentIfNotValid(); if (current != null) { return true; } return iterator.hasNext(); } private final void clearCurrentIfNotValid() { if (current == null) { return; } final boolean valid = isValidPredicate.test(current); if (!valid) { current = null; }
} @Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } // NOTE: we assume "current" was also checked if it's still valid (in hasNext() method) if (current != null) { return current; } return iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\ReturnWhileValidIterator.java
1
请完成以下Java代码
public Object key() { return this.delegate.key(); } @Override public @Nullable Object getValue() { return this.delegate.getValue(); } @Override public void setValue(Object value) { setValueInternal(value); } @SuppressWarnings("unchecked") private <V> void setValueInternal(Object value) { ((ThreadLocalAccessor<V>) this.delegate).setValue((V) value); } @Override public void setValue() { this.delegate.setValue(); } @Override @Deprecated(since = "1.3.0", forRemoval = true) public void reset() { this.delegate.reset(); } @Override public void restore(Object previousValue) { restoreInternal(previousValue); } @SuppressWarnings("unchecked") public <V> void restoreInternal(Object previousValue) { ((ThreadLocalAccessor<V>) this.delegate).restore((V) previousValue); } @Override public void restore() { this.delegate.restore(); } private static final class DelegateAccessor implements ThreadLocalAccessor<Object> { @Override public Object key() { return SecurityContext.class.getName(); } @Override public Object getValue() { return SecurityContextHolder.getContext(); } @Override public void setValue(Object value) { SecurityContextHolder.setContext((SecurityContext) value); } @Override public void setValue() { SecurityContextHolder.clearContext(); } @Override public void restore(Object previousValue) { SecurityContextHolder.setContext((SecurityContext) previousValue); }
@Override public void restore() { SecurityContextHolder.clearContext(); } @Override @Deprecated(since = "1.3.0", forRemoval = true) public void reset() { SecurityContextHolder.clearContext(); } } private static final class NoOpAccessor implements ThreadLocalAccessor<Object> { @Override public Object key() { return getClass().getName(); } @Override public @Nullable Object getValue() { return null; } @Override public void setValue(Object value) { } @Override public void setValue() { } @Override public void restore(Object previousValue) { } @Override public void restore() { } @Override @Deprecated(since = "1.3.0", forRemoval = true) public void reset() { } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityContextThreadLocalAccessor.java
1
请在Spring Boot框架中完成以下Java代码
class SexType extends BasePaginationInfo implements Types { public SexType(String sexName, String emailName, Pageable pageable) { //String sexName, String emailName, super(sexName, emailName, pageable); } public Page<Persons> query() { return this.instance.findBySex( this.sex, this.pageable ); } public Integer getCount() { return this.query().getSize(); } public Integer getPageNumber() { return this.query().getNumber(); } public Long getTotal() { return this.query().getTotalElements(); } public Object getContent() { return this.query().getContent(); } }
public class PaginationFormatting { private PaginationMultiTypeValuesHelper multiValue = new PaginationMultiTypeValuesHelper(); private Map<String, PaginationMultiTypeValuesHelper> results = new HashMap<>(); public Map<String, PaginationMultiTypeValuesHelper> filterQuery(String sex, String email, Pageable pageable) { Types typeInstance; if (sex.length() == 0 && email.length() == 0) { typeInstance = new AllType(sex, email, pageable); } else if (sex.length() > 0 && email.length() > 0) { typeInstance = new SexEmailType(sex, email, pageable); } else { typeInstance = new SexType(sex, email, pageable); } this.multiValue.setCount(typeInstance.getCount()); this.multiValue.setPage(typeInstance.getPageNumber() + 1); this.multiValue.setResults(typeInstance.getContent()); this.multiValue.setTotal(typeInstance.getTotal()); this.results.put("data", this.multiValue); return results; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\pagination\PaginationFormatting.java
2
请完成以下Java代码
public void setDisplayableQRCode (final String DisplayableQRCode) { set_Value (COLUMNNAME_DisplayableQRCode, DisplayableQRCode); } @Override public String getDisplayableQRCode() { return get_ValueAsString(COLUMNNAME_DisplayableQRCode); } @Override public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID) { if (M_HU_QRCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID); } @Override public int getM_HU_QRCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID); }
@Override public void setRenderedQRCode (final String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); } @Override public String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } @Override public void setUniqueId (final String UniqueId) { set_ValueNoCheck (COLUMNNAME_UniqueId, UniqueId); } @Override public String getUniqueId() { return get_ValueAsString(COLUMNNAME_UniqueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { if (!m_button.isEnabled()) return; throw new AdempiereException("legacy feature removed"); } /** * Property Change Listener * @param evt event */ @Override public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue()); // metas: request focus (2009_0027_G131) if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS)) requestFocus(); // metas end } // propertyChange @Override public boolean isAutoCommit() { return true; } } // VAssignment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAssignment.java
1
请完成以下Java代码
public class ErrorResourceSerializer extends JsonSerializer<ErrorResource> { @Override public void serialize(ErrorResource value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { Map<String, List<String>> json = new HashMap<>(); gen.writeStartObject(); gen.writeObjectFieldStart("errors"); for (FieldErrorResource fieldErrorResource : value.getFieldErrors()) { if (!json.containsKey(fieldErrorResource.getField())) { json.put(fieldErrorResource.getField(), new ArrayList<String>()); } json.get(fieldErrorResource.getField()).add(fieldErrorResource.getMessage()); } for (Map.Entry<String, List<String>> pair : json.entrySet()) { gen.writeArrayFieldStart(pair.getKey());
pair.getValue() .forEach( content -> { try { gen.writeString(content); } catch (IOException e) { e.printStackTrace(); } }); gen.writeEndArray(); } gen.writeEndObject(); gen.writeEndObject(); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\exception\ErrorResourceSerializer.java
1
请完成以下Java代码
public void setMSV3_BestellungAuftrag_ID (int MSV3_BestellungAuftrag_ID) { if (MSV3_BestellungAuftrag_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, Integer.valueOf(MSV3_BestellungAuftrag_ID)); } /** Get MSV3_BestellungAuftrag. @return MSV3_BestellungAuftrag */ @Override public int getMSV3_BestellungAuftrag_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAuftrag_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GebindeId. @param MSV3_GebindeId GebindeId */ @Override public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId) { set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId); } /** Get GebindeId. @return GebindeId */ @Override public java.lang.String getMSV3_GebindeId () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId);
} /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAuftrag.java
1
请完成以下Java代码
public BigDecimal getXchgRate() { return xchgRate; } /** * Sets the value of the xchgRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setXchgRate(BigDecimal value) { this.xchgRate = value; } /** * Gets the value of the ctrctId property. * * @return * possible object is * {@link String } * */ public String getCtrctId() { return ctrctId; } /** * Sets the value of the ctrctId property. * * @param value * allowed object is * {@link String }
* */ public void setCtrctId(String value) { this.ctrctId = value; } /** * Gets the value of the qtnDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getQtnDt() { return qtnDt; } /** * Sets the value of the qtnDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setQtnDt(XMLGregorianCalendar value) { this.qtnDt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CurrencyExchange5.java
1
请完成以下Java代码
public Builder header(String name, String value) { this.headers.add(name, value); return this; } public Builder headers(HttpHeaders headers) { this.headers.addAll(headers); return this; } public Builder timestamp(Instant timestamp) { this.timestamp = timestamp; return this; } public Builder timestamp(Date timestamp) { this.timestamp = timestamp.toInstant(); return this;
} public Builder body(String data) { return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8))); } public Builder appendToBody(ByteBuffer byteBuffer) { this.body.add(byteBuffer); return this; } public CachedResponse build() { return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp)); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java
1
请完成以下Java代码
private static void predict(Map<User, HashMap<Item, Double>> data) { HashMap<Item, Double> uPred = new HashMap<Item, Double>(); HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>(); for (Item j : diff.keySet()) { uFreq.put(j, 0); uPred.put(j, 0.0); } for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) { for (Item j : e.getValue().keySet()) { for (Item k : diff.keySet()) { try { double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue(); double finalValue = predictedValue * freq.get(k).get(j).intValue(); uPred.put(k, uPred.get(k) + finalValue); uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue()); } catch (NullPointerException e1) { } } } HashMap<Item, Double> clean = new HashMap<Item, Double>(); for (Item j : uPred.keySet()) { if (uFreq.get(j) > 0) { clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue()); } } for (Item j : InputData.items) { if (e.getValue().containsKey(j)) { clean.put(j, e.getValue().get(j)); } else if (!clean.containsKey(j)) { clean.put(j, -1.0); }
} outputData.put(e.getKey(), clean); } printData(outputData); } private static void printData(Map<User, HashMap<Item, Double>> data) { for (User user : data.keySet()) { System.out.println(user.getUsername() + ":"); print(data.get(user)); } } private static void print(HashMap<Item, Double> hashMap) { NumberFormat formatter = new DecimalFormat("#0.000"); for (Item j : hashMap.keySet()) { System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue())); } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\slope_one\SlopeOne.java
1
请在Spring Boot框架中完成以下Java代码
public List<Job> getAllJobs(){ return jobRepository.findAll(); } @GET @Produces("application/json") @Path("/jobs") public ResponseEntity<Job> getJobById(@PathVariable(value = "id") Long jobId) throws ResourceNotFoundException{ Job job = jobRepository.findById(jobId) .orElseThrow(()-> new ResourceNotFoundException("Job not found ::" + jobId)); return ResponseEntity.ok().body(job); } @POST @Produces("appliction/json") @Consumes("application/json") @Path("/jobs") @PostMapping("/jobs") public Job createJob(Job job){ return jobRepository.save(job); } @PUT
@Consumes("application/json") @Path("/jobs/{id}") public ResponseEntity<Job> updateJob(@PathParam(value = "id") Long jobId, @Valid @RequestBody Job jobDetails) throws ResourceNotFoundException { Job job = jobRepository.findById(jobId) .orElseThrow(()->new ResourceNotFoundException("Job not found::" + jobId)); job.setEmailId(jobDetails.getEmailId()); job.setLastName(jobDetails.getLastName()); job.setFirstName(jobDetails.getFirstName()); final Job updateJob = jobRepository.save(job); return ResponseEntity.ok(updateJob); } @DELETE @Path("/jobs/{id}") public Map<String, Boolean> deleteJob (@PathParam(value = "id") Long jobId) throws ResourceNotFoundException{ Job job = jobRepository.findById(jobId) .orElseThrow(()-> new ResourceNotFoundException("User not found::" + jobId)); jobRepository.delete(job); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.FALSE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Jersey-JPA\src\main\java\spring\database\controller\JobResource.java
2
请完成以下Java代码
default Integer get_ValueOldAsInt(final String variableName, @Nullable final Integer defaultValue) { final String valueStr = get_ValueOldAsString(variableName); return Evaluatee.convertToInteger(variableName, valueStr, defaultValue); } @Nullable default Boolean get_ValueOldAsBoolean(final String variableName, @Nullable final Boolean defaultValue) { final String valueStr = get_ValueOldAsString(variableName); return DisplayType.toBoolean(valueStr, defaultValue); } @Nullable default BigDecimal get_ValueOldAsBigDecimal(final String variableName, @Nullable final BigDecimal defaultValue) { final String valueStr = get_ValueOldAsString(variableName); return Evaluatee.convertToBigDecimal(variableName, valueStr, defaultValue); }
@Nullable default java.util.Date get_ValueOldAsDate(final String variableName, @Nullable final java.util.Date defaultValue) { final String valueStr = get_ValueOldAsString(variableName); return Evaluatee.convertToDate(variableName, valueStr, defaultValue); } @Override default Optional<Object> get_ValueIfExists(@NonNull final String variableName, @NonNull final Class<?> targetType) { return has_Variable(variableName) ? Evaluatee.super.get_ValueIfExists(variableName, targetType) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatee2.java
1
请完成以下Java代码
private Role getRoleToLogin(LoginAuthenticateResponse response) { final ImmutableList<Role> roles = response.getAvailableRoles(); if (roles.isEmpty()) { throw new AdempiereException("User has no role assigned"); } else if (roles.size() == 1) { return roles.get(0); } else { final ArrayList<Role> nonSysAdminRoles = new ArrayList<>(); for (final Role role : roles) { if (role.isSystem()) { continue; } nonSysAdminRoles.add(role); }
if (nonSysAdminRoles.size() == 1) { return nonSysAdminRoles.get(0); } else { throw new AdempiereException("Multiple roles are not supported. Make sure user has only one role assigned"); } } } @NonNull private static Login getLoginService() { final LoginContext loginCtx = new LoginContext(Env.newTemporaryCtx()); loginCtx.setWebui(true); return new Login(loginCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\authentication\AuthenticationRestController.java
1
请完成以下Java代码
boolean isStandard(TbLogNodeConfiguration conf) { Objects.requireNonNull(conf, "node config is null"); final TbLogNodeConfiguration defaultConfig = new TbLogNodeConfiguration().defaultConfiguration(); if (conf.getScriptLang() == null || conf.getScriptLang().equals(ScriptLanguage.JS)) { return defaultConfig.getJsScript().equals(conf.getJsScript()); } else if (conf.getScriptLang().equals(ScriptLanguage.TBEL)) { return defaultConfig.getTbelScript().equals(conf.getTbelScript()); } else { log.warn("No rule to define isStandard script for script language [{}], assuming that is non-standard", conf.getScriptLang()); return false; } } void logStandard(TbContext ctx, TbMsg msg) { log.info(toLogMessage(msg)); ctx.tellSuccess(msg);
} String toLogMessage(TbMsg msg) { return "\n" + "Incoming message:\n" + msg.getData() + "\n" + "Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData()); } @Override public void destroy() { if (scriptEngine != null) { scriptEngine.destroy(); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbLogNode.java
1
请完成以下Java代码
static ArrayKey createValidationKey(final IValidationContext validationCtx, final MLookupInfo lookupInfo, final Object parentValidationKey) { final List<Object> keys = new ArrayList<>(); // final String rowIndexStr = validationCtx.get_ValueAsString(GridTab.CTX_CurrentRow); // keys.add(rowIndexStr); if (IValidationContext.NULL != validationCtx) { for (final String parameterName : lookupInfo.getValidationRule().getAllParameters()) { final String parameterValue = validationCtx.get_ValueAsString(parameterName); keys.add(parameterName); keys.add(parameterValue); } } keys.add(parentValidationKey); return new ArrayKey(keys.toArray()); } // metas: begin @Override public String getTableName() { return m_info.getTableName().getAsString(); } @Override public boolean isAutoComplete() { return m_info != null && m_info.isAutoComplete(); } public MLookupInfo getLookupInfo() {
return m_info; } @Override public Set<String> getParameters() { return m_info.getValidationRule().getAllParameters(); } @Override public IValidationContext getValidationContext() { return m_evalCtx; } public boolean isNumericKey() { return getColumnName().endsWith("_ID"); } @Override public NamePair suggestValidValue(final NamePair value) { return null; } } // MLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookup.java
1
请在Spring Boot框架中完成以下Java代码
public class AppEngineResource { @Autowired(required=false) protected AppRestApiInterceptor restApiInterceptor; @ApiOperation(value = "Get app engine info", tags = { "Engine" }, notes = "Returns a read-only view of the engine that is used in this REST-service.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the engine info is returned."), }) @GetMapping(value = "/app-management/engine", produces = "application/json") public EngineInfoResponse getEngineInfo() { if (restApiInterceptor != null) { restApiInterceptor.accessAppManagementInfo(); } EngineInfoResponse response = new EngineInfoResponse(); try { AppEngine appEngine = AppEngines.getDefaultAppEngine(); EngineInfo appEngineInfo = AppEngines.getAppEngineInfo(appEngine.getName());
if (appEngineInfo != null) { response.setName(appEngineInfo.getName()); response.setResourceUrl(appEngineInfo.getResourceUrl()); response.setException(appEngineInfo.getException()); } else { response.setName(appEngine.getName()); } } catch (Exception e) { throw new FlowableException("Error retrieving app engine info", e); } response.setVersion(AppEngine.class.getPackage().getImplementationVersion()); return response; } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\management\AppEngineResource.java
2
请完成以下Java代码
public IDeviceResponseGetConfigParams getRequiredConfigParams() { final List<IDeviceConfigParam> params = new ArrayList<IDeviceConfigParam>(); // params.add(new DeviceConfigParamPojo("DeviceClass", "DeviceClass", "")); // if we can query this device for its params, then we already know the device class. params.add(new DeviceConfigParam(PARAM_ENDPOINT_CLASS, "Endpoint.Class", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_IP, "Endpoint.IP", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_PORT, "Endpoint.Port", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_RETURN_LAST_LINE, PARAM_ENDPOINT_RETURN_LAST_LINE, "N")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, "500")); params.add(new DeviceConfigParam(PARAM_ROUND_TO_PRECISION, "RoundToPrecision", "-1")); return new IDeviceResponseGetConfigParams() { @Override public List<IDeviceConfigParam> getParams() {
return params; } }; } @Override public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler() { return new ConfigureDeviceHandler(this); } @Override public String toString() { return getClass().getSimpleName() + " with Endpoint " + endPoint.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\AbstractTcpScales.java
1
请完成以下Java代码
public String getEventHandlerType() { return EVENT_HANDLER_TYPE; } @Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) { if (eventSubscription.getExecutionId() != null) { super.handleEvent(eventSubscription, payload, commandContext); } else if (eventSubscription.getProcessDefinitionId() != null) { // Start event String processDefinitionId = eventSubscription.getProcessDefinitionId(); DeploymentManager deploymentCache = Context .getProcessEngineConfiguration() .getDeploymentManager(); ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null) { throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class); } ActivityImpl startActivity = processDefinition.findActivity(eventSubscription.getActivityId()); if (startActivity == null) {
throw new ActivitiException("Could no handle signal: no start activity found with id " + eventSubscription.getActivityId()); } ExecutionEntity processInstance = processDefinition.createProcessInstance(null, startActivity); if (processInstance == null) { throw new ActivitiException("Could not handle signal: no process instance started"); } if (payload != null) { if (payload instanceof Map) { Map<String, Object> variables = (Map<String, Object>) payload; processInstance.setVariables(variables); } } processInstance.start(); } else { throw new ActivitiException("Invalid signal handling: no execution nor process definition set"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\event\SignalEventHandler.java
1
请完成以下Java代码
private static class AllRowsSupplier implements RowsSupplier { private final int pageSize; private final IView view; private final JSONOptions jsonOpts; private final LoadingCache<PageIndex, ViewResult> cache = CacheBuilder.newBuilder() .maximumSize(2) // cache max 2 pages .build(new CacheLoader<PageIndex, ViewResult>() { @Override public ViewResult load(@NotNull final PageIndex pageIndex) { final ViewRowsOrderBy orderBys = ViewRowsOrderBy.empty(jsonOpts); // default return view.getPage(pageIndex.getFirstRow(), pageIndex.getPageLength(), orderBys); } }); private AllRowsSupplier( @NonNull final IView view, final int pageSize, @NonNull final JSONOptions jsonOpts) { this.view = view; this.pageSize = pageSize; this.jsonOpts = jsonOpts; } private ViewResult getPage(final PageIndex pageIndex) { try { return cache.get(pageIndex); } catch (final ExecutionException e) { throw AdempiereException.wrapIfNeeded(e); } } @Override @Nullable public IViewRow getRow(final int rowIndex) { final ViewResult page = getPage(PageIndex.getPageContainingRow(rowIndex, pageSize)); final int rowIndexInPage = rowIndex - page.getFirstRow(); if (rowIndexInPage < 0) { // shall not happen return null; } final List<IViewRow> rows = page.getPage(); if (rowIndexInPage >= rows.size()) { return null; } return rows.get(rowIndexInPage); } @Override public int getRowCount() { return (int)view.size(); } }
private static class ListRowsSupplier implements RowsSupplier { private final ImmutableList<IViewRow> rows; private ListRowsSupplier(@NonNull final IView view, @NonNull final DocumentIdsSelection rowIds) { Check.assume(!rowIds.isAll(), "rowIds is not ALL"); this.rows = view.streamByIds(rowIds).collect(ImmutableList.toImmutableList()); } @Override public IViewRow getRow(final int rowIndex) { Check.assume(rowIndex >= 0, "rowIndex >= 0"); final int rowsCount = rows.size(); Check.assume(rowIndex < rowsCount, "rowIndex < {}", rowsCount); return rows.get(rowIndex); } @Override public int getRowCount() { return rows.size(); } } @Override protected List<CellValue> getNextRow() { final ArrayList<CellValue> result = new ArrayList<>(); for (int i = 0; i < getColumnCount(); i++) { result.add(getValueAt(rowNumber, i)); } rowNumber++; return result; } @Override protected boolean hasNextRow() { return rowNumber < getRowCount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewExcelExporter.java
1
请完成以下Java代码
static ServerResponse.BodyBuilder badRequest() { return status(HttpStatus.BAD_REQUEST); } /** * Create a builder with a {@linkplain HttpStatus#NOT_FOUND 404 Not Found} status. * @return the created builder */ static ServerResponse.HeadersBuilder<?> notFound() { return status(HttpStatus.NOT_FOUND); } /** * Create a builder with a {@linkplain HttpStatus#UNPROCESSABLE_ENTITY 422 * Unprocessable Entity} status. * @return the created builder */ static ServerResponse.BodyBuilder unprocessableEntity() { return status(HttpStatus.UNPROCESSABLE_ENTITY); } /** * Create a (built) response with the given asynchronous response. Parameter * {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous,
* {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @return the asynchronous response * @since 5.3 */ static ServerResponse async(Object asyncResponse) { return GatewayAsyncServerResponse.create(asyncResponse, null); } /** * Create a (built) response with the given asynchronous response. Parameter * {@code asyncResponse} can be a {@link CompletableFuture * CompletableFuture&lt;ServerResponse&gt;} or {@link Publisher * Publisher&lt;ServerResponse&gt;} (or any asynchronous producer of a single * {@code ServerResponse} that can be adapted via the * {@link ReactiveAdapterRegistry}). * * <p> * This method can be used to set the response status code, headers, and body based on * an asynchronous result. If only the body is asynchronous, * {@link ServerResponse.BodyBuilder#body(Object)} can be used instead. * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or * {@code Publisher<ServerResponse>} * @param timeout maximum time period to wait for before timing out * @return the asynchronous response * @since 5.3.2 */ static ServerResponse async(Object asyncResponse, Duration timeout) { return GatewayAsyncServerResponse.create(asyncResponse, timeout); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponse.java
1
请在Spring Boot框架中完成以下Java代码
public class TaskController { @Autowired private CommentsService commentsService; private List<TaskDTO> tasks = Arrays.asList(new TaskDTO("task11", "description11", "1"), new TaskDTO("task12", "description12", "1"), new TaskDTO("task13", "description13", "1"), new TaskDTO("task21", "description21", "2"), new TaskDTO("task22", "description22", "2")); /** * Get all tasks * * @return */ @RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json") public List<TaskDTO> getTasks() { return tasks; } /** * Get tasks for specific taskid * * @param taskId * @return */ @RequestMapping(value = "{taskId}", method = RequestMethod.GET, headers = "Accept=application/json") public TaskDTO getTaskByTaskId(@PathVariable("taskId") String taskId) { TaskDTO taskToReturn = null; for (TaskDTO currentTask : tasks) { if (currentTask.getTaskId().equalsIgnoreCase(taskId)) { taskToReturn = currentTask; break; } }
if (taskToReturn != null) { taskToReturn.setComments(this.commentsService.getCommentsForTask(taskId)); } return taskToReturn; } /** * Get tasks for specific user that is passed in * * @param taskId * @return */ @RequestMapping(value = "/usertask/{userName}", method = RequestMethod.GET, headers = "Accept=application/json") public List<TaskDTO> getTasksByUserName(@PathVariable("userName") String userName) { List<TaskDTO> taskListToReturn = new ArrayList<TaskDTO>(); for (TaskDTO currentTask : tasks) { if (currentTask.getUserName().equalsIgnoreCase(userName)) { taskListToReturn.add(currentTask); } } return taskListToReturn; } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\apis\TaskController.java
2
请在Spring Boot框架中完成以下Java代码
private BeanMetadataElement getAuthorizationRequestRepository(Element element) { String authorizationRequestRepositoryRef = (element != null) ? element.getAttribute(ATT_AUTHORIZATION_REQUEST_REPOSITORY_REF) : null; if (StringUtils.hasLength(authorizationRequestRepositoryRef)) { return new RuntimeBeanReference(authorizationRequestRepositoryRef); } return BeanDefinitionBuilder .rootBeanDefinition( "org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository") .getBeanDefinition(); } private BeanMetadataElement getAuthorizationRedirectStrategy(Element element) { String authorizationRedirectStrategyRef = (element != null) ? element.getAttribute(ATT_AUTHORIZATION_REDIRECT_STRATEGY_REF) : null; if (StringUtils.hasText(authorizationRedirectStrategyRef)) { return new RuntimeBeanReference(authorizationRedirectStrategyRef); } return BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.web.DefaultRedirectStrategy") .getBeanDefinition(); } private BeanMetadataElement getAccessTokenResponseClient(Element element) { String accessTokenResponseClientRef = (element != null) ? element.getAttribute(ATT_ACCESS_TOKEN_RESPONSE_CLIENT_REF) : null; if (StringUtils.hasLength(accessTokenResponseClientRef)) { return new RuntimeBeanReference(accessTokenResponseClientRef);
} return BeanDefinitionBuilder.rootBeanDefinition( "org.springframework.security.oauth2.client.endpoint.RestClientAuthorizationCodeTokenResponseClient") .getBeanDefinition(); } BeanDefinition getDefaultAuthorizedClientRepository() { return this.defaultAuthorizedClientRepository; } BeanDefinition getAuthorizationRequestRedirectFilter() { return this.authorizationRequestRedirectFilter; } BeanDefinition getAuthorizationCodeGrantFilter() { return this.authorizationCodeGrantFilter; } BeanDefinition getAuthorizationCodeAuthenticationProvider() { return this.authorizationCodeAuthenticationProvider; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ClientBeanDefinitionParser.java
2
请完成以下Java代码
public class Order { private UUID id; private Type type; @JsonIgnoreType public static class Type { public long id; public String name; } public Order() { this.id = UUID.randomUUID(); } public Order(Type type) {
this(); this.type = type; } public UUID getId() { return id; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } }
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\inclusion\jsonignoretype\Order.java
1
请完成以下Java代码
public void setDescriptionURL (String DescriptionURL) { set_Value (COLUMNNAME_DescriptionURL, DescriptionURL); } /** Get Description URL. @return URL for the description */ public String getDescriptionURL () { return (String)get_Value(COLUMNNAME_DescriptionURL); } /** Set Knowledge Source. @param K_Source_ID Source of a Knowledge Entry */ public void setK_Source_ID (int K_Source_ID) { if (K_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID)); } /** Get Knowledge Source. @return Source of a Knowledge Entry */ public int getK_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_ID); 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Source.java
1
请完成以下Java代码
public boolean isCoProduct() { return getTrxType().isCoProduct(); } public boolean isByProduct() { return getTrxType() == PPOrderCostTrxType.ByProduct; } @NonNull public PPOrderCost addingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { if (amt.isZero() && qty.isZero()) { return this; } final boolean amtIsPositiveOrZero = amt.signum() >= 0; final boolean amtIsNotZero = amt.signum() != 0; final boolean qtyIsPositiveOrZero = qty.signum() >= 0; if (amtIsNotZero && amtIsPositiveOrZero != qtyIsPositiveOrZero ) { throw new AdempiereException("Amount and Quantity shall have the same sign: " + amt + ", " + qty); } final Quantity accumulatedQty = getAccumulatedQty(); final Quantity qtyConv = uomConverter.convertQuantityTo(qty, getProductId(), accumulatedQty.getUomId()); return toBuilder() .accumulatedAmount(getAccumulatedAmount().add(amt)) .accumulatedQty(accumulatedQty.add(qtyConv)) .build(); } public PPOrderCost subtractingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter);
} public PPOrderCost withPrice(@NonNull final CostPrice newPrice) { if (this.getPrice().equals(newPrice)) { return this; } return toBuilder().price(newPrice).build(); } /* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount) { this.postCalculationAmount = postCalculationAmount; } /* package */void setPostCalculationAmountAsAccumulatedAmt() { setPostCalculationAmount(getAccumulatedAmount()); } /* package */void setPostCalculationAmountAsZero() { setPostCalculationAmount(getPostCalculationAmount().toZero()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java
1
请完成以下Java代码
public class PmsProductAttributeValue implements Serializable { private Long id; private Long productId; private Long productAttributeId; @ApiModelProperty(value = "手动添加规格或参数的值,参数单值,规格有多个时以逗号隔开") private String value; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getProductAttributeId() { return productAttributeId; } public void setProductAttributeId(Long productAttributeId) {
this.productAttributeId = productAttributeId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", productAttributeId=").append(productAttributeId); sb.append(", value=").append(value); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeValue.java
1
请完成以下Spring Boot application配置
spring: application: name: user-service # 服务名 # Zipkin 配置项,对应 ZipkinProperties 类 zipkin: base-url: http://127.0.0.1:9411 # Zipkin 服务的地址 # Spring Cloud Sleuth 配置项 sleuth: # Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC web: enabled: true # 是否开启,默认为 true # 对应 RedisProperties 类 redis: host: 127.0.0.1 port: 6379 password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码! database: 0 # Redis 数据库号,默认为 0 。 timeout: 0 # Redis 连接超时时间,单位:毫秒。 # 对应 RedisProperties.Jedis 内部类 jedis:
pool: max-active: 8 # 连接池最大连接数,默认为 8 。使用负数表示没有限制。 max-idle: 8 # 默认连接数最小空闲的连接数,默认为 8 。使用负数表示没有限制。 min-idle: 0 # 默认连接池最小空闲的连接数,默认为 0 。允许设置 0 和 正数。 max-wait: -1 # 连接池最大阻塞等待时间,单位:毫秒。默认为 -1 ,表示不限制。
repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-db-redis\src\main\resources\application.yml
2
请完成以下Java代码
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 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** RecurringType AD_Reference_ID=282 */ public static final int RECURRINGTYPE_AD_Reference_ID=282; /** Invoice = I */ public static final String RECURRINGTYPE_Invoice = "I"; /** Order = O */ public static final String RECURRINGTYPE_Order = "O";
/** GL Journal = G */ public static final String RECURRINGTYPE_GLJournal = "G"; /** Project = J */ public static final String RECURRINGTYPE_Project = "J"; /** Set Recurring Type. @param RecurringType Type of Recurring Document */ public void setRecurringType (String RecurringType) { set_Value (COLUMNNAME_RecurringType, RecurringType); } /** Get Recurring Type. @return Type of Recurring Document */ public String getRecurringType () { return (String)get_Value(COLUMNNAME_RecurringType); } /** Set Maximum Runs. @param RunsMax Number of recurring runs */ public void setRunsMax (int RunsMax) { set_Value (COLUMNNAME_RunsMax, Integer.valueOf(RunsMax)); } /** Get Maximum Runs. @return Number of recurring runs */ public int getRunsMax () { Integer ii = (Integer)get_Value(COLUMNNAME_RunsMax); if (ii == null) return 0; return ii.intValue(); } /** Set Remaining Runs. @param RunsRemaining Number of recurring runs remaining */ public void setRunsRemaining (int RunsRemaining) { set_ValueNoCheck (COLUMNNAME_RunsRemaining, Integer.valueOf(RunsRemaining)); } /** Get Remaining Runs. @return Number of recurring runs remaining */ public int getRunsRemaining () { Integer ii = (Integer)get_Value(COLUMNNAME_RunsRemaining); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring.java
1
请完成以下Java代码
public static EMailAttachment ofNullable(@NonNull final String filename, @Nullable final byte[] content) { return content != null && content.length != 0 ? of(filename, content) : null; } public static EMailAttachment of(@NonNull final URI uri) { return new EMailAttachment(null, null, uri); } public static EMailAttachment of(@NonNull final Resource resource) { try { return of(resource.getURI()); } catch (IOException e) { //noinspection DataFlowIssue throw AdempiereException.wrapIfNeeded(e); } } @JsonProperty("filename") String filename; @JsonProperty("content") byte[] content; @JsonProperty("uri") URI uri; @JsonCreator private EMailAttachment( @JsonProperty("filename") final String filename, @JsonProperty("content") final byte[] content, @JsonProperty("uri") final URI uri) { this.filename = filename; this.content = content; this.uri = uri; }
@Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("filename", filename) .add("uri", uri) .add("content.size", content != null ? content.length : null) .toString(); } @JsonIgnore public DataSource createDataSource() { if (uri != null) { try { return new URLDataSource(uri.toURL()); } catch (final MalformedURLException ex) { throw new AdempiereException("@Invalid@ @URL@: " + uri, ex); } } else { return ByteArrayBackedDataSource.of(filename, content); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAttachment.java
1
请完成以下Java代码
public class City { private Short cityId; private String city; private Short countryId; private Date lastUpdate; public Short getCityId() { return cityId; } public void setCityId(Short cityId) { this.cityId = cityId; } public String getCity() { return city; } public void setCity(String city) { this.city = city == null ? null : city.trim();
} public Short getCountryId() { return countryId; } public void setCountryId(Short countryId) { this.countryId = countryId; } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } }
repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\entity\primary\City.java
1
请完成以下Java代码
static class MariaDbJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements JdbcConnectionDetails { private static final JdbcUrlBuilder jdbcUrlBuilder = new JdbcUrlBuilder("mariadb", 3306); private final MariaDbEnvironment environment; private final String jdbcUrl; MariaDbJdbcDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new MariaDbEnvironment(service.env()); this.jdbcUrl = jdbcUrlBuilder.build(service, this.environment.getDatabase()); } @Override public String getUsername() {
return this.environment.getUsername(); } @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\MariaDbJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Note. @param Note Optional additional user defined information */ public void setNote (String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Note. @return Optional additional user defined information */ public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
1
请完成以下Java代码
public void setPricingSystemSurchargeAmt (java.math.BigDecimal PricingSystemSurchargeAmt) { set_Value (COLUMNNAME_PricingSystemSurchargeAmt, PricingSystemSurchargeAmt); } /** Get Preisaufschlag. @return Aufschlag auf den Preis, der aus dem Preissystem resultieren würde */ @Override public java.math.BigDecimal getPricingSystemSurchargeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricingSystemSurchargeAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set QualityIssuePercentage. @param QualityIssuePercentage QualityIssuePercentage */ @Override public void setQualityIssuePercentage (java.math.BigDecimal QualityIssuePercentage) { set_Value (COLUMNNAME_QualityIssuePercentage, QualityIssuePercentage); } /** Get QualityIssuePercentage. @return QualityIssuePercentage */ @Override public java.math.BigDecimal getQualityIssuePercentage () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityIssuePercentage); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */
@Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak.java
1
请在Spring Boot框架中完成以下Java代码
public class MessageHandlerContainer implements InitializingBean { private Logger logger = LoggerFactory.getLogger(getClass()); /** * 消息类型与 MessageHandler 的映射 */ private final Map<String, MessageHandler> handlers = new HashMap<>(); @Autowired private ApplicationContext applicationContext; @Override public void afterPropertiesSet() throws Exception { // 通过 ApplicationContext 获得所有 MessageHandler Bean applicationContext.getBeansOfType(MessageHandler.class).values() // 获得所有 MessageHandler Bean .forEach(messageHandler -> handlers.put(messageHandler.getType(), messageHandler)); // 添加到 handlers 中 logger.info("[afterPropertiesSet][消息处理器数量:{}]", handlers.size()); } /** * 获得类型对应的 MessageHandler * * @param type 类型 * @return MessageHandler */ MessageHandler getMessageHandler(String type) { MessageHandler handler = handlers.get(type); if (handler == null) { throw new IllegalArgumentException(String.format("类型(%s) 找不到匹配的 MessageHandler 处理器", type)); } return handler; } /** * 获得 MessageHandler 处理的消息类 * * @param handler 处理器 * @return 消息类 */ static Class<? extends Message> getMessageClass(MessageHandler handler) { // 获得 Bean 对应的 Class 类名。因为有可能被 AOP 代理过。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(handler); // 获得接口的 Type 数组 Type[] interfaces = targetClass.getGenericInterfaces(); Class<?> superclass = targetClass.getSuperclass(); while ((Objects.isNull(interfaces) || 0 == interfaces.length) && Objects.nonNull(superclass)) { // 此处,是以父类的接口为准 interfaces = superclass.getGenericInterfaces(); superclass = targetClass.getSuperclass(); } if (Objects.nonNull(interfaces)) { // 遍历 interfaces 数组 for (Type type : interfaces) { // 要求 type 是泛型参数 if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; // 要求是 MessageHandler 接口 if (Objects.equals(parameterizedType.getRawType(), MessageHandler.class)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); // 取首个元素 if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) { return (Class<Message>) actualTypeArguments[0]; } else { throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler)); } } } } } throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler)); } }
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-common\src\main\java\cn\iocoder\springboot\lab67\nettycommondemo\dispatcher\MessageHandlerContainer.java
2
请完成以下Java代码
public Optional<PPRoutingId> getDefaultRoutingIdByType(@NonNull final PPRoutingType type) { return queryBL .createQueryBuilderOutOfTrx(I_AD_Workflow.class) .addEqualsFilter(I_AD_Workflow.COLUMNNAME_WorkflowType, type) .addEqualsFilter(I_AD_Workflow.COLUMNNAME_IsDefault, true) .create() .firstIdOnlyOptional(PPRoutingId::ofRepoIdOrNull); } @Override public void setFirstNodeToWorkflow(@NonNull final PPRoutingActivityId ppRoutingActivityId) { final I_AD_Workflow workflow = load(ppRoutingActivityId.getRoutingId(), I_AD_Workflow.class); workflow.setAD_WF_Node_ID(ppRoutingActivityId.getRepoId());
save(workflow); } @Override public SeqNo getActivityProductNextSeqNo(@NonNull final PPRoutingActivityId activityId) { final int lastSeqNoInt = queryBL .createQueryBuilder(I_PP_WF_Node_Product.class) //.addOnlyActiveRecordsFilter() // let's include non active ones too .addEqualsFilter(I_PP_WF_Node_Product.COLUMNNAME_AD_WF_Node_ID, activityId) .create() .maxInt(I_PP_WF_Node_Product.COLUMNNAME_SeqNo); return SeqNo.ofInt(Math.max(lastSeqNoInt, 0)).next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPRoutingRepository.java
1
请完成以下Java代码
public ExecutionResult getExecutionResult() { return executionResult; } @Override public void run(String trxName) { final CompositeMigrationStepExecutor executor = new CompositeMigrationStepExecutor(migrationCtx, step); if (action == Action.Apply) { try { executionResult = executor.apply(trxName); } catch (MigrationExecutorException e) { if (e.isFatal()) { throw e; } executionResult = ExecutionResult.Skipped; logger.info(e.getLocalizedMessage(), e); } } else if (action == Action.Rollback) { executionResult = executor.rollback(trxName); } else { throw new IllegalStateException("Unknown action: " + action); } } @Override public boolean doCatch(Throwable e) throws Throwable { exception = e; throw e; } @Override public void doFinally() { if (ExecutionResult.Ignored == executionResult) { // do nothing return; } setExecutionStatus(); InterfaceWrapperHelper.save(step); } /** * After step execution, sets ErrorMsg, StatusCode, Apply */ private void setExecutionStatus() { // Success if (exception == null) { Check.assumeNotNull(executionResult, "executionResult not null"); step.setErrorMsg(null); if (executionResult == ExecutionResult.Executed) { if (action == Action.Apply)
{ step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Applied); } else if (action == Action.Rollback) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied); } else { throw new AdempiereException("Unknown action: " + action); } } else if (executionResult == ExecutionResult.Skipped) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied); } else { throw new AdempiereException("Unknown execution result: " + executionResult); } } // Error / Warning else { logger.error("Action " + action + " of " + step + " failed.", exception); step.setErrorMsg(exception.getLocalizedMessage()); if (action == Action.Apply) { step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Failed); step.setApply(X_AD_MigrationStep.APPLY_Apply); } } if (X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode())) { step.setApply(X_AD_MigrationStep.APPLY_Rollback); } else if (X_AD_MigrationStep.STATUSCODE_Unapplied.equals(step.getStatusCode())) { step.setApply(X_AD_MigrationStep.APPLY_Apply); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationStepExecutorRunnable.java
1
请完成以下Java代码
public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified;
} public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getStrategy() { return strategy; } public void setStrategy(int strategy) { this.strategy = strategy; } @Override public Rule toRule(){ AuthorityRule rule=new AuthorityRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\AuthorityRuleCorrectEntity.java
1
请完成以下Java代码
public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @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 setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * ProjInvoiceRule AD_Reference_ID=383 * Reference name: C_Project InvoiceRule */ public static final int PROJINVOICERULE_AD_Reference_ID=383; /** None = - */ public static final String PROJINVOICERULE_None = "-"; /** Committed Amount = C */ public static final String PROJINVOICERULE_CommittedAmount = "C"; /** Time&Material max Comitted = c */ public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c"; /** Time&Material = T */
public static final String PROJINVOICERULE_TimeMaterial = "T"; /** Product Quantity = P */ public static final String PROJINVOICERULE_ProductQuantity = "P"; @Override public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule) { set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule); } @Override public java.lang.String getProjInvoiceRule() { return get_ValueAsString(COLUMNNAME_ProjInvoiceRule); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @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_C_ProjectTask.java
1
请完成以下Java代码
public void setC_ReferenceNo_ID (int C_ReferenceNo_ID) { if (C_ReferenceNo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID)); } /** Get Reference No. @return Reference No */ @Override public int getC_ReferenceNo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.document.refid.model.I_C_ReferenceNo_Type getC_ReferenceNo_Type() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class); } @Override public void setC_ReferenceNo_Type(de.metas.document.refid.model.I_C_ReferenceNo_Type C_ReferenceNo_Type) { set_ValueFromPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class, C_ReferenceNo_Type); } /** Set Reference No Type. @param C_ReferenceNo_Type_ID Reference No Type */ @Override public void setC_ReferenceNo_Type_ID (int C_ReferenceNo_Type_ID) { if (C_ReferenceNo_Type_ID < 1) set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, null); else set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, Integer.valueOf(C_ReferenceNo_Type_ID)); } /** Get Reference No Type. @return Reference No Type */ @Override public int getC_ReferenceNo_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Manuell. @param IsManual Dies ist ein manueller Vorgang */ @Override public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return Dies ist ein manueller Vorgang */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenznummer. @param ReferenceNo Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () { return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo.java
1
请完成以下Java代码
public class JapanesePersonRecognition { /** * 执行识别 * * @param segResult 粗分结果 * @param wordNetOptimum 粗分结果对应的词图 * @param wordNetAll 全词图 */ public static void recognition(List<Vertex> segResult, WordNet wordNetOptimum, WordNet wordNetAll) { StringBuilder sbName = new StringBuilder(); int appendTimes = 0; char[] charArray = wordNetAll.charArray; DoubleArrayTrie<Character>.LongestSearcher searcher = JapanesePersonDictionary.getSearcher(charArray); int activeLine = 1; int preOffset = 0; while (searcher.next()) { Character label = searcher.value; int offset = searcher.begin; String key = new String(charArray, offset, searcher.length); if (preOffset != offset) { if (appendTimes > 1 && sbName.length() > 2) // 日本人名最短为3字 { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll); } sbName.setLength(0); appendTimes = 0; } if (appendTimes == 0) { if (label == JapanesePersonDictionary.X) { sbName.append(key); ++appendTimes; activeLine = offset + 1; } } else { if (label == JapanesePersonDictionary.M) { sbName.append(key); ++appendTimes; } else { if (appendTimes > 1 && sbName.length() > 2) { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll);
} sbName.setLength(0); appendTimes = 0; } } preOffset = offset + key.length(); } if (sbName.length() > 0) { if (appendTimes > 1) { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll); } } } /** * 是否是bad case * @param name * @return */ public static boolean isBadCase(String name) { Character label = JapanesePersonDictionary.get(name); if (label == null) return false; return label.equals(JapanesePersonDictionary.A); } /** * 插入日本人名 * @param name * @param activeLine * @param wordNetOptimum * @param wordNetAll */ private static void insertName(String name, int activeLine, WordNet wordNetOptimum, WordNet wordNetAll) { if (isBadCase(name)) return; wordNetOptimum.insert(activeLine, new Vertex(Predefine.TAG_PEOPLE, name, new CoreDictionary.Attribute(Nature.nrj), WORD_ID), wordNetAll); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\recognition\nr\JapanesePersonRecognition.java
1
请完成以下Java代码
public PayPalOrder create(@NonNull final PaymentReservationId reservationId) { final I_PayPal_Order record = newInstance(I_PayPal_Order.class); record.setC_Payment_Reservation_ID(reservationId.getRepoId()); record.setStatus("-"); record.setPayPal_OrderJSON("{}"); record.setExternalId("-"); // need to set it because it's needed in PayPalOrder saveRecord(record); return toPayPalOrder(record); } public PayPalOrder save( @NonNull final PayPalOrderId id, @NonNull final com.paypal.orders.Order apiOrder) { final I_PayPal_Order existingRecord = getRecordById(id); return updateFromAPIOrderAndSave(existingRecord, apiOrder); } private PayPalOrder updateFromAPIOrderAndSave( @NonNull final I_PayPal_Order record, @NonNull final com.paypal.orders.Order apiOrder) { PayPalOrder order = toPayPalOrder(record); order = updateFromAPIOrder(order, apiOrder); updateRecord(record, order); saveRecord(record); order = order.withId(PayPalOrderId.ofRepoId(record.getPayPal_Order_ID())); return order; } private static PayPalOrderAuthorizationId extractAuthorizationIdOrNull(@NonNull final com.paypal.orders.Order apiOrder) { final List<PurchaseUnit> purchaseUnits = apiOrder.purchaseUnits(); if (purchaseUnits == null || purchaseUnits.isEmpty()) { return null; } final PaymentCollection payments = purchaseUnits.get(0).payments(); if (payments == null) { return null; } final List<Authorization> authorizations = payments.authorizations(); if (authorizations == null || authorizations.isEmpty()) { return null; } return PayPalOrderAuthorizationId.ofString(authorizations.get(0).id()); } private static String extractApproveUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder) { return extractUrlOrNull(apiOrder, "approve"); }
private static String extractUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder, @NonNull final String rel) { for (final LinkDescription link : apiOrder.links()) { if (rel.contentEquals(link.rel())) { return link.href(); } } return null; } private static String toJson(final com.paypal.orders.Order apiOrder) { if (apiOrder == null) { return ""; } try { // IMPORTANT: we shall use paypal's JSON serializer, else we won't get any result return new com.braintreepayments.http.serializer.Json().serialize(apiOrder); } catch (final Exception ex) { logger.warn("Failed converting {} to JSON. Returning toString()", apiOrder, ex); return apiOrder.toString(); } } public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id) { final I_PayPal_Order existingRecord = getRecordById(id); final PayPalOrder order = toPayPalOrder(existingRecord) .toBuilder() .status(PayPalOrderStatus.REMOTE_DELETED) .build(); updateRecord(existingRecord, order); saveRecord(existingRecord); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class GRSSignumDispatcherRouteBuilder extends RouteBuilder { public static final String GRS_DEADLETTER_ROUTE_ID = "direct:GRS-deadLetter"; public static final String GRS_DISPATCHER_ROUTE_ID = "GRSDispatcher"; public static final String GRS_MESSAGE_SENDER = "GRSMessageSender"; public static final String GRS_ENDPOINT_ID = "GRSEndpointId"; @Override public void configure() throws Exception { CamelRouteUtil.setupProperties(getContext()); final String maximumRedeliveries = CamelRouteUtil.resolveProperty(getContext(), GRSSignumConstants.EXPORT_BPARTNER_RETRY_COUNT, "0"); final String redeliveryDelay = CamelRouteUtil.resolveProperty(getContext(), GRSSignumConstants.EXPORT_BPARTNER_RETRY_DELAY, "0"); errorHandler(deadLetterChannel(GRS_DEADLETTER_ROUTE_ID) .logHandled(true) .maximumRedeliveries(Integer.parseInt(maximumRedeliveries)) .redeliveryDelay(Integer.parseInt(redeliveryDelay))); from(GRS_DEADLETTER_ROUTE_ID) .routeId(GRS_DEADLETTER_ROUTE_ID) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(GRS_DISPATCHER_ROUTE_ID)) .routeId(GRS_DISPATCHER_ROUTE_ID) .streamCache("true") .process(this::extractAndAttachGRSSignumHttpRequest) .to(direct(GRS_MESSAGE_SENDER)); from(direct(GRS_MESSAGE_SENDER)) .routeId(GRS_MESSAGE_SENDER) //dev-note: we need the whole route to be replayed in case of redelivery .errorHandler(noErrorHandler()) .log("invoked") //uncomment this to get an "escaped" JSON string with e.g. "\{ blabla \}"
//.marshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), String.class)) //dev-note: the actual path is computed in this.extractAndAttachGRSSignumHttpRequest() .to("https://placeholder").id(GRS_ENDPOINT_ID); } private void extractAndAttachGRSSignumHttpRequest(@NonNull final Exchange exchange) { final Object dispatchMessageRequestCandidate = exchange.getIn().getBody(); if (!(dispatchMessageRequestCandidate instanceof DispatchRequest)) { throw new RuntimeCamelException("The route " + GRS_DISPATCHER_ROUTE_ID + " requires the body to be instanceof DispatchMessageRequest." + " However, it is " + (dispatchMessageRequestCandidate == null ? "null" : dispatchMessageRequestCandidate.getClass().getName())); } final DispatchRequest dispatchMessageRequest = (DispatchRequest)dispatchMessageRequestCandidate; exchange.getIn().removeHeaders("CamelHttp*"); exchange.getIn().removeHeader(AUTHORIZATION); // remove the token from metasfresh's API exchange.getIn().setHeader(HTTP_URI, dispatchMessageRequest.getUrl()); exchange.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST); if (Check.isNotBlank(dispatchMessageRequest.getAuthToken())) { exchange.getIn().setHeader(AUTHORIZATION, dispatchMessageRequest.getAuthToken()); } exchange.getIn().setBody(dispatchMessageRequest.getRequest()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\client\GRSSignumDispatcherRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public class HttpsConfiguration { @Bean public ServletWebServerFactory servletContainer(){ // Enable SSL Traffic TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){ @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; // Add HTTP to HTTPS redirect tomcat.addAdditionalTomcatConnectors(httpToHttpRedirectConnector()); return tomcat;
} /* * We need redirect from HTTP to HTTPS. Without SSL, this application used port 8082. With SSL it will use port 8443. * SO, any request for 8082 needs to be redirected to HTTPS on 8443. * */ @Value("${server.port.http}") private int serverPortHttp; @Value("${server.port}") private int serverPortHttps; private Connector httpToHttpRedirectConnector(){ Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); connector.setScheme("http"); connector.setPort(serverPortHttp); connector.setSecure(false); connector.setRedirectPort(serverPortHttps); return connector; } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\HttpsConfiguration.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; }
public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\spring\data\persistence\like\model\Movie.java
1
请完成以下Java代码
public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value; } /** * Gets the value of the agt property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification4 } * */
public BranchAndFinancialInstitutionIdentification4 getAgt() { return agt; } /** * Sets the value of the agt property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public void setAgt(BranchAndFinancialInstitutionIdentification4 value) { this.agt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryAgent2.java
1
请完成以下Java代码
public List<IInvoicingItem> getRawAdditionalFeeProducts() { final List<IInvoicingItem> invoicingItems = type2AdditionalFeeProducts.get(QualityInspectionLineType.Raw); if(invoicingItems == null) { return ImmutableList.of(); } return invoicingItems; } @Override public BigDecimal getQualityAdjustmentForMonthOrNull(final int month) { return month2qualityAdjustment.get(month); } @Override public final BigDecimal getQualityAdjustmentForDateOrNull(final Date date) { if(date.after(getValidToDate())) { return maximumQualityAdjustment; } final int month = TimeUtil.asCalendar(date).get(Calendar.MONTH); return getQualityAdjustmentForMonthOrNull(month); } /** * @return zero if the given percentage is below 10, <code>0.06</code> otherwise */ @Override public BigDecimal getScrapProcessingFeeForPercentage(final BigDecimal percentage) { if (percentage.compareTo(getScrapPercentageTreshold()) < 0) { return BigDecimal.ZERO; } else { return scrapFee; } } @Override public BigDecimal getScrapPercentageTreshold() { return scrapPercentageTreshold; } @Override public boolean isFeeForProducedMaterial(final I_M_Product m_Product) { return productWithProcessingFee.getM_Product_ID() == m_Product.getM_Product_ID() && !feeProductPercentage2fee.isEmpty(); } @Override public BigDecimal getFeeForProducedMaterial(final I_M_Product m_Product, final BigDecimal percentage) { final List<BigDecimal> percentages = new ArrayList<>(feeProductPercentage2fee.keySet()); // iterating from first to 2nd-last for (int i = 0; i < percentages.size() - 1; i++) { final BigDecimal currentPercentage = percentages.get(i); final BigDecimal nextPercentage = percentages.get(i + 1); if (currentPercentage.compareTo(percentage) <= 0 && nextPercentage.compareTo(percentage) > 0) {
// found it: 'percentage' is in the interval that starts with 'currentPercentage' return feeProductPercentage2fee.get(currentPercentage); } } final BigDecimal lastInterval = percentages.get(percentages.size() - 1); return feeProductPercentage2fee.get(lastInterval); } @Override public int getOverallNumberOfInvoicings() { return numberOfInspections; } @Override public BigDecimal getWithholdingPercent() { return Env.ONEHUNDRED.divide(BigDecimal.valueOf(numberOfInspections), 2, RoundingMode.HALF_UP); } @Override public Currency getCurrency() { return currency; } @Override public I_M_Product getRegularPPOrderProduct() { return regularPPOrderProduct; } @Override public String toString() { return ObjectUtils.toString(this); } @Override public Timestamp getValidToDate() { return validToDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\RecordBackedQualityBasedConfig.java
1
请完成以下Spring Boot application配置
server: port: 8088 spring: quartz: job-store-type: memory #所有任务相关内容存储在内存中 scheduler-name: AnchorScheduler properties: org.quartz.scheduler.instanceId: 1122334 #集群中会用到,单节点无用,不填、填AUTO都可以 org.quartz.scheduler.rmi.export: false org.quartz.scheduler.rmi.proxy: false org.quartz.scheduler.wrapJobExecutionInUserTransaction: false org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool org.quartz.threadPool.threadCount: 9 #线程数 org.quartz.threadPool.threadPriority: 5
#线程优先级 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true org.quartz.jobStore.misfireThreshold: 60000 #作业最大延迟时间,毫秒 org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore #内存作业时负责跟踪调度所有工作数据
repos\springboot-demo-master\quartz\src\main\resources\application-simple.yaml
2
请在Spring Boot框架中完成以下Java代码
class TableDDL { @NonNull String tableName; @NonNull ImmutableList<ColumnDDL> columns; public String getSQLCreate() { final StringBuilder sqlColumns = new StringBuilder(); final StringBuilder sqlConstraints = new StringBuilder(); boolean hasPK = false; boolean hasParents = false; for (final ColumnDDL column : columns) { final String colSQL = column.getSQLDDL(); if (colSQL == null || Check.isBlank(colSQL)) { continue; // virtual column } if (sqlColumns.length() > 0) { sqlColumns.append(", "); } sqlColumns.append(column.getSQLDDL()); if (column.isPrimaryKey()) { hasPK = true; } if (column.isParentLink()) { hasParents = true; } final String constraint = column.getSQLConstraint(); if (!Check.isBlank(constraint))
{ sqlConstraints.append(", ").append(constraint); } } final StringBuilder sql = new StringBuilder(MigrationScriptFileLoggerHolder.DDL_PREFIX + "CREATE TABLE ") .append("public.") // schema .append(getTableName()) .append(" (") .append(sqlColumns); // Multi Column PK if (!hasPK && hasParents) { final String cols = columns.stream() .filter(ColumnDDL::isParentLink) .map(ColumnDDL::getColumnName) .collect(Collectors.joining(", ")); sql.append(", CONSTRAINT ").append(getTableName()).append("_Key PRIMARY KEY (").append(cols).append(")"); } sql.append(sqlConstraints).append(")"); return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ddl\TableDDL.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessProfile[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_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 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 Exclude. @param IsExclude Exclude access to the data - if not selected Include access to the data */ public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); }
/** Get Exclude. @return Exclude access to the data - if not selected Include access to the data */ public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); 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 */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java
1
请完成以下Java代码
public Optional<I_AD_User> getContactById(final BPartnerContactId contactId) { return getOrLoadContacts() .stream() .filter(contact -> contact.getAD_User_ID() == contactId.getRepoId()) .findFirst(); } private ArrayList<I_AD_User> getOrLoadContacts() { if (contacts == null) { if (record.getC_BPartner_ID() > 0) { contacts = new ArrayList<>(bpartnersRepo.retrieveContacts(record)); } else { contacts = new ArrayList<>();
} } return contacts; } public BPartnerContactId addAndSaveContact(final I_AD_User contact) { bpartnersRepo.save(contact); final BPartnerContactId contactId = BPartnerContactId.ofRepoId(contact.getC_BPartner_ID(), contact.getAD_User_ID()); if (!getContactById(contactId).isPresent()) { getOrLoadContacts().add(contact); } return contactId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnersCache.java
1
请完成以下Java代码
public static Builder with(OAuth2AuthorizationConsentAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2AuthorizationConsentAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2AuthorizationConsentAuthenticationContext, Builder> { private Builder(OAuth2AuthorizationConsentAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link OAuth2AuthorizationConsent.Builder authorization consent * builder}. * @param authorizationConsent the {@link OAuth2AuthorizationConsent.Builder} * @return the {@link Builder} for further configuration */ public Builder authorizationConsent(OAuth2AuthorizationConsent.Builder authorizationConsent) { return put(OAuth2AuthorizationConsent.Builder.class, authorizationConsent); } /** * Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration */ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); } /** * Sets the {@link OAuth2Authorization authorization}. * @param authorization the {@link OAuth2Authorization} * @return the {@link Builder} for further configuration */ public Builder authorization(OAuth2Authorization authorization) { return put(OAuth2Authorization.class, authorization); } /**
* Sets the {@link OAuth2AuthorizationRequest authorization request}. * @param authorizationRequest the {@link OAuth2AuthorizationRequest} * @return the {@link Builder} for further configuration */ public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) { return put(OAuth2AuthorizationRequest.class, authorizationRequest); } /** * Builds a new {@link OAuth2AuthorizationConsentAuthenticationContext}. * @return the {@link OAuth2AuthorizationConsentAuthenticationContext} */ @Override public OAuth2AuthorizationConsentAuthenticationContext build() { Assert.notNull(get(OAuth2AuthorizationConsent.Builder.class), "authorizationConsentBuilder cannot be null"); Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); OAuth2Authorization authorization = get(OAuth2Authorization.class); Assert.notNull(authorization, "authorization cannot be null"); if (authorization.getAuthorizationGrantType().equals(AuthorizationGrantType.AUTHORIZATION_CODE)) { Assert.notNull(get(OAuth2AuthorizationRequest.class), "authorizationRequest cannot be null"); } return new OAuth2AuthorizationConsentAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationConsentAuthenticationContext.java
1
请完成以下Java代码
public void setHR_Concept_Acct (int HR_Concept_Acct) { set_Value (COLUMNNAME_HR_Concept_Acct, Integer.valueOf(HR_Concept_Acct)); } /** Get Payroll Concept Account. @return Payroll Concept Account */ public int getHR_Concept_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Acct); if (ii == null) return 0; return ii.intValue(); } /** Set Payroll Concept Category. @param HR_Concept_Category_ID Payroll Concept Category */ public void setHR_Concept_Category_ID (int HR_Concept_Category_ID) { if (HR_Concept_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, Integer.valueOf(HR_Concept_Category_ID)); } /** Get Payroll Concept Category. @return Payroll Concept Category */ public int getHR_Concept_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); 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 */ 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 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\eevolution\model\X_HR_Concept_Category.java
1
请完成以下Java代码
IncludedDetailInfo setStale() { stale = true; return this; } public boolean isStale() { return stale; } public LogicExpressionResult getAllowNew() { return allowNew; } IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew) { this.allowNew = allowNew; return this; } public LogicExpressionResult getAllowDelete() { return allowDelete; } IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete) { this.allowDelete = allowDelete; return this; }
private void collectFrom(final IncludedDetailInfo from) { if (from.stale) { stale = from.stale; } if (from.allowNew != null) { allowNew = from.allowNew; } if (from.allowDelete != null) { allowDelete = from.allowDelete; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Optional<String> getName() { return Optional.ofNullable(name); } public void setName(String name) { this.name = name; } public Optional<String> getGenre() { return Optional.ofNullable(genre); } public void setGenre(String genre) { this.genre = genre; }
public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOptional\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
protected final IWeightable getWeightableOrNull(@Nullable final IAttributeSet attributeSet) { if (attributeSet == null) { return null; } else if (attributeSet instanceof IAttributeStorage) { final IAttributeStorage attributeStorage = (IAttributeStorage)attributeSet; return Weightables.wrap(attributeStorage); } else { return null; } } /** * See {@link #onValueChanged(IAttributeValueContext, IAttributeSet, I_M_Attribute, Object, Object)}. */ protected abstract boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew); /** * Calculate WeightGross = WeightNet + WeightTare + WeightTareAdjust * * @param attributeSet */ protected final void recalculateWeightGross(final IAttributeSet attributeSet) { // final IAttributeStorage attributeStorage = (IAttributeStorage)attributeSet; final IWeightable weightable = getWeightableOrNull(attributeSet); // NOTE: we calculate WeightGross, no matter if our HU is allowed to be weighted by user // final boolean weightUOMFriendly = weightable.isWeightable(); final BigDecimal weightTareTotal = weightable.getWeightTareTotal(); final BigDecimal weightNet = weightable.getWeightNet(); final BigDecimal weightGross = weightNet.add(weightTareTotal); weightable.setWeightGross(weightGross); } protected final void recalculateWeightNet(final IAttributeSet attributeSet) {
final IWeightable weightable = getWeightableOrNull(attributeSet); Weightables.updateWeightNet(weightable); } protected boolean isLUorTUorTopLevelVHU(IAttributeSet attributeSet) { if (!isVirtualHU(attributeSet)) { return true; } final I_M_HU hu = huAttributesBL.getM_HU_OrNull(attributeSet); final boolean virtualTopLevelHU = handlingUnitsBL.isTopLevel(hu); return virtualTopLevelHU; } @Override public final String generateStringValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { throw new UnsupportedOperationException("Not supported"); } @Override public final Date generateDateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute) { throw new UnsupportedOperationException("Not supported"); } @Override public final AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName) { throw new UnsupportedOperationException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\AbstractWeightAttributeValueCallout.java
1
请完成以下Java代码
public String invoice(final ICalloutField calloutField) { // FIXME: refactor it and use de.metas.banking.payment.impl.PaySelectionUpdater. In meantime pls keep in sync. if (isCalloutActive()) { return NO_ERROR; } // get invoice final I_C_PaySelectionLine psl = calloutField.getModel(I_C_PaySelectionLine.class); final int C_Invoice_ID = psl.getC_Invoice_ID(); if (C_Invoice_ID <= 0) { return NO_ERROR; } final I_C_PaySelection paySelection = psl.getC_PaySelection(); final int C_BP_BankAccount_ID = paySelection.getC_BP_BankAccount_ID(); Timestamp PayDate = paySelection.getPayDate(); if (PayDate == null) { PayDate = new Timestamp(System.currentTimeMillis()); } BigDecimal OpenAmt = BigDecimal.ZERO; BigDecimal DiscountAmt = BigDecimal.ZERO; boolean IsSOTrx = false; final String sql = "SELECT currencyConvert(invoiceOpen(i.C_Invoice_ID, 0), i.C_Currency_ID," + "ba.C_Currency_ID, i.DateInvoiced, i.C_ConversionType_ID, i.AD_Client_ID, i.AD_Org_ID)," + " paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?), i.IsSOTrx " + "FROM C_Invoice_v i, C_BP_BankAccount ba " + "WHERE i.C_Invoice_ID=? AND ba.C_BP_BankAccount_ID=?"; // #1..2 ResultSet rs = null; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); pstmt.setTimestamp(1, PayDate); pstmt.setInt(2, C_Invoice_ID); pstmt.setInt(3, C_BP_BankAccount_ID); rs = pstmt.executeQuery(); if (rs.next()) {
OpenAmt = rs.getBigDecimal(1); DiscountAmt = rs.getBigDecimal(2); IsSOTrx = DisplayType.toBoolean(rs.getString(3)); } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } psl.setOpenAmt(OpenAmt); psl.setPayAmt(OpenAmt.subtract(DiscountAmt)); psl.setDiscountAmt(DiscountAmt); psl.setDifferenceAmt(BigDecimal.ZERO); psl.setIsSOTrx(IsSOTrx); return NO_ERROR; } // invoice } // CalloutPaySelection
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutPaySelection.java
1
请完成以下Java代码
public ResponseEntity<PageResult<DictDetailDto>> queryDictDetail(DictDetailQueryCriteria criteria, @PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable){ return new ResponseEntity<>(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK); } @ApiOperation("查询多个字典详情") @GetMapping(value = "/map") public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){ String[] names = dictName.split("[,,]"); Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16); for (String name : names) { dictMap.put(name, dictDetailService.getDictByName(name)); } return new ResponseEntity<>(dictMap, HttpStatus.OK); } @Log("新增字典详情") @ApiOperation("新增字典详情") @PostMapping @PreAuthorize("@el.check('dict:add')") public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } dictDetailService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); }
@Log("修改字典详情") @ApiOperation("修改字典详情") @PutMapping @PreAuthorize("@el.check('dict:edit')") public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){ dictDetailService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除字典详情") @ApiOperation("删除字典详情") @DeleteMapping(value = "/{id}") @PreAuthorize("@el.check('dict:del')") public ResponseEntity<Object> deleteDictDetail(@PathVariable Long id){ dictDetailService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictDetailController.java
1
请完成以下Java代码
protected Color getCellForegroundColor(final int modelRowIndex, final int modelColumnIndex) { return null; } public List<ModelType> getSelectedRows(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel) { final int rowMinView = selectionModel.getMinSelectionIndex(); final int rowMaxView = selectionModel.getMaxSelectionIndex(); if (rowMinView < 0 || rowMaxView < 0) { return ImmutableList.of(); } final ImmutableList.Builder<ModelType> selection = ImmutableList.builder(); for (int rowView = rowMinView; rowView <= rowMaxView; rowView++) { if (selectionModel.isSelectedIndex(rowView)) { final int rowModel = convertRowIndexToModel.apply(rowView); selection.add(getRow(rowModel)); }
} return selection.build(); } public ModelType getSelectedRow(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel) { final int rowIndexView = selectionModel.getMinSelectionIndex(); if (rowIndexView < 0) { return null; } final int rowIndexModel = convertRowIndexToModel.apply(rowIndexView); return getRow(rowIndexModel); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\AnnotatedTableModel.java
1
请完成以下Java代码
private TranslatableParameterizedString getSelectById() { final StringBuilder sqlQueryFinal_BaseLang = new StringBuilder(getSelectSqlPart_BaseLang()); final StringBuilder sqlQueryFinal_Trl = new StringBuilder(getSelectSqlPart_Trl()); sqlQueryFinal_BaseLang.append(" WHERE (").append(keyColumn).append("=?").append(")"); sqlQueryFinal_Trl.append(" WHERE (").append(keyColumn).append("=?").append(")"); if (sqlWhereClauseStatic != null) { sqlQueryFinal_BaseLang.append(" AND (").append(sqlWhereClauseStatic).append(")"); sqlQueryFinal_Trl.append(" AND (").append(sqlWhereClauseStatic).append(")"); } return TranslatableParameterizedString.of( CTXNAME_AD_Language, sqlQueryFinal_BaseLang.toString(), sqlQueryFinal_Trl.toString()); } public TranslatableParameterizedString getSelectSqlPart() { return TranslatableParameterizedString.of(CTXNAME_AD_Language, getSelectSqlPart_BaseLang(), getSelectSqlPart_Trl()); } @NonNull public String getSelectSqlPart_BaseLang() { return "SELECT " + (isNumericKey ? keyColumn.getAsString() : "NULL") // 1 - Key + "," + (!isNumericKey ? keyColumn.getAsString() : "NULL") // 2 - Value + "," + displayColumnSQL_BaseLang // 3 - Display + "," + activeColumnSQL // 4 - IsActive + "," + (descriptionColumnSQL_BaseLang != null ? descriptionColumnSQL_BaseLang : "NULL") // 5 - Description + "," + (hasEntityTypeColumn ? tableName + ".EntityType" : "NULL") // 6 - EntityType + " FROM " + sqlFromPart.getSqlFrom_BaseLang(); } @NonNull public String getSelectSqlPart_Trl() { return "SELECT " + (isNumericKey ? keyColumn.getAsString() : "NULL") // 1 - Key + "," + (!isNumericKey ? keyColumn.getAsString() : "NULL") // 2 - Value
+ "," + displayColumnSQL_Trl // 3 - Display + "," + activeColumnSQL // 4 - IsActive + "," + (descriptionColumnSQL_Trl != null ? descriptionColumnSQL_Trl : "NULL") // 5 - Description + "," + (hasEntityTypeColumn ? tableName + ".EntityType" : "NULL") // 6 - EntityType + " FROM " + sqlFromPart.getSqlFrom_Trl(); } public TranslatableParameterizedString getDisplayColumnSql() { return TranslatableParameterizedString.of(CTXNAME_AD_Language, displayColumnSQL_BaseLang, displayColumnSQL_Trl); } public TranslatableParameterizedString getDescriptionColumnSql() { if (!Check.isBlank(descriptionColumnSQL_BaseLang)) { return TranslatableParameterizedString.of(CTXNAME_AD_Language, descriptionColumnSQL_BaseLang, descriptionColumnSQL_Trl); } else { return TranslatableParameterizedString.EMPTY; } } public int getEntityTypeQueryColumnIndex() {return isHasEntityTypeColumn() ? COLUMNINDEX_EntityType : -1;} } } // MLookupInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookupInfo.java
1
请在Spring Boot框架中完成以下Java代码
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests( auth -> { auth .anyRequest().authenticated(); }); http.sessionManagement( session -> session.sessionCreationPolicy( SessionCreationPolicy.STATELESS) ); //http.formLogin(); http.httpBasic(withDefaults()); http.csrf(csrf -> csrf.disable()); //http.csrf(AbstractHttpConfigurer::disable); http.headers(headers -> headers.frameOptions(frameOptionsConfig-> frameOptionsConfig.disable())); // http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)); return http.build(); } // @Bean // public UserDetailsService userDetailService() { // // var user = User.withUsername("in28minutes") // .password("{noop}dummy") // .roles("USER") // .build(); // // // var admin = User.withUsername("admin") // .password("{noop}dummy") // .roles("ADMIN") // .build(); // // return new InMemoryUserDetailsManager(user, admin); // }
@Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION) .build(); } @Bean public UserDetailsService userDetailService(DataSource dataSource) { var user = User.withUsername("in28minutes") //.password("{noop}dummy") .password("dummy") .passwordEncoder(str -> passwordEncoder().encode(str)) .roles("USER") .build(); var admin = User.withUsername("admin") //.password("{noop}dummy") .password("dummy") .passwordEncoder(str -> passwordEncoder().encode(str)) .roles("ADMIN", "USER") .build(); var jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource); jdbcUserDetailsManager.createUser(user); jdbcUserDetailsManager.createUser(admin); return jdbcUserDetailsManager; } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\basic\BasicAuthSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(Exception.class) public final ResponseEntity<ExceptionResponse> handleAllExceptions(Exception exception, WebRequest request) { var exceptionResponse = new ExceptionResponse(LocalDateTime.now(), exception.getMessage(), request.getDescription(false)); return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(StudentNotFoundException.class) public final ResponseEntity<ExceptionResponse> handleUserNotFoundException(StudentNotFoundException exception, WebRequest request) { var exceptionResponse = new ExceptionResponse(LocalDateTime.now(), exception.getMessage(),
request.getDescription(false)); return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND); } protected ResponseEntity<ExceptionResponse> handleMethodArgumentNotValid(MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request) { var exceptionResponse = new ExceptionResponse(LocalDateTime.now(), "Validation Failed", exception.getBindingResult().toString()); return new ResponseEntity<>(exceptionResponse, HttpStatus.BAD_REQUEST); } }
repos\spring-boot-examples-master\spring-boot-2-rest-service-validation\src\main\java\com\in28minutes\springboot\rest\example\exception\CustomizedResponseEntityExceptionHandler.java
2
请完成以下Java代码
public static String getLocalIp() { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { NetworkInterface anInterface = interfaces.nextElement(); // 在所有的接口下再遍历IP for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) { InetAddress inetAddr = inetAddresses.nextElement(); // 排除loopback类型地址 if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr.getHostAddress(); } else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址 candidateAddress = inetAddr; } }
} } if (candidateAddress != null) { return candidateAddress.getHostAddress(); } // 如果没有发现 non-loopback地址.只能用最次选的方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { return ""; } return jdkSuppliedAddress.getHostAddress(); } catch (Exception e) { return ""; } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\StringUtils.java
1
请完成以下Java代码
public static String decryptWithPrivateKey(byte[] encryptedData, String privateKey) throws Exception { // 解码私钥字符串 byte[] keyBytes = Base64.decodeBase64(privateKey); // 生成PKCS8EncodedKeySpec PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); // 实例化KeyFactory并指定为RSA KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 生成PrivateKey对象 PrivateKey rsaPrivateKey = keyFactory.generatePrivate(keySpec); // 实例化Cipher并指定为RSA/ECB/PKCS1Padding Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 使用私钥初始化Cipher为解密模式 cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey); // 执行解密操作 byte[] decryptedBytes = cipher.doFinal(encryptedData); // 将解密后的字节数组转换为字符串(使用UTF-8编码) return new String(decryptedBytes, StandardCharsets.UTF_8); } /** * 使用私钥对数据进行加密 * * @param data 明文数据(字符串形式) * @param privateKey 私钥字符串(Base64编码) * @return 加密后的密文(字节数组) * @throws Exception 加密过程中发生的异常 */ public static byte[] encryptWithPrivateKey(String data, String privateKey) throws Exception { // 解码私钥字符串 byte[] keyBytes = Base64.decodeBase64(privateKey); // 生成PKCS8EncodedKeySpec PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); // 实例化KeyFactory并指定为RSA KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 生成PrivateKey对象
PrivateKey rsaPrivateKey = keyFactory.generatePrivate(keySpec); // 实例化Cipher并指定为RSA/ECB/PKCS1Padding Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 使用私钥初始化Cipher为加密模式 cipher.init(Cipher.ENCRYPT_MODE, rsaPrivateKey); // 执行加密操作 return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); } /** * 使用公钥对数据进行解密 * * @param encryptedData 加密后的数据(字节数组形式) * @param publicKey 公钥字符串(Base64编码) * @return 解密后的明文数据(字符串) * @throws Exception 解密过程中发生的异常 */ public static String decryptWithPublicKey(byte[] encryptedData, String publicKey) throws Exception { // 解码公钥字符串 byte[] keyBytes = Base64.decodeBase64(publicKey); // 生成X509EncodedKeySpec X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); // 实例化KeyFactory并指定为RSA KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 生成PublicKey对象 PublicKey rsaPublicKey = keyFactory.generatePublic(keySpec); // 实例化Cipher并指定为RSA/ECB/PKCS1Padding Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 使用公钥初始化Cipher为解密模式 cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey); // 执行解密操作 byte[] decryptedBytes = cipher.doFinal(encryptedData); // 将解密后的字节数组转换为字符串(使用UTF-8编码) return new String(decryptedBytes, StandardCharsets.UTF_8); } }
repos\springboot-demo-master\InterfaceSecurity\src\main\java\com\et\interfacesecurity\util\RSAUtil.java
1
请完成以下Java代码
public class ResourceUtil implements Resource { protected String resourceName; protected int resourceType; public ResourceUtil(String resourceName, int resourceType) { this.resourceName = resourceName; this.resourceType = resourceType; } public String resourceName() { return resourceName; } public int resourceType() { return resourceType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode());
result = prime * result + resourceType; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ResourceUtil other = (ResourceUtil) obj; if (resourceName == null) { if (other.resourceName != null) return false; } else if (!resourceName.equals(other.resourceName)) return false; if (resourceType != other.resourceType) return false; return true; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\util\ResourceUtil.java
1
请完成以下Java代码
private static final class JwkThumbprintValidator implements OAuth2TokenValidator<Jwt> { private final OAuth2AccessTokenClaims accessToken; private JwkThumbprintValidator(OAuth2AccessTokenClaims accessToken) { Assert.notNull(accessToken, "accessToken cannot be null"); this.accessToken = accessToken; } @Override public OAuth2TokenValidatorResult validate(Jwt jwt) { Assert.notNull(jwt, "DPoP proof jwt cannot be null"); String jwkThumbprintClaim = null; Map<String, Object> confirmationMethodClaim = this.accessToken.getClaimAsMap("cnf"); if (!CollectionUtils.isEmpty(confirmationMethodClaim) && confirmationMethodClaim.containsKey("jkt")) { jwkThumbprintClaim = (String) confirmationMethodClaim.get("jkt"); } if (jwkThumbprintClaim == null) { OAuth2Error error = createOAuth2Error("jkt claim is required."); return OAuth2TokenValidatorResult.failure(error); } JWK jwk = null; @SuppressWarnings("unchecked") Map<String, Object> jwkJson = (Map<String, Object>) jwt.getHeaders().get("jwk"); try { jwk = JWK.parse(jwkJson); } catch (Exception ignored) { } if (jwk == null) { OAuth2Error error = createOAuth2Error("jwk header is missing or invalid."); return OAuth2TokenValidatorResult.failure(error); } String jwkThumbprint; try { jwkThumbprint = jwk.computeThumbprint().toString(); } catch (Exception ex) { OAuth2Error error = createOAuth2Error("Failed to compute SHA-256 Thumbprint for jwk."); return OAuth2TokenValidatorResult.failure(error); } if (!jwkThumbprintClaim.equals(jwkThumbprint)) { OAuth2Error error = createOAuth2Error("jkt claim is invalid."); return OAuth2TokenValidatorResult.failure(error); } return OAuth2TokenValidatorResult.success(); } private static OAuth2Error createOAuth2Error(String reason) {
return new OAuth2Error(OAuth2ErrorCodes.INVALID_DPOP_PROOF, reason, null); } } private static final class OAuth2AccessTokenClaims implements OAuth2Token, ClaimAccessor { private final OAuth2Token accessToken; private final Map<String, Object> claims; private OAuth2AccessTokenClaims(OAuth2Token accessToken, Map<String, Object> claims) { this.accessToken = accessToken; this.claims = claims; } @Override public String getTokenValue() { return this.accessToken.getTokenValue(); } @Override public Instant getIssuedAt() { return this.accessToken.getIssuedAt(); } @Override public Instant getExpiresAt() { return this.accessToken.getExpiresAt(); } @Override public Map<String, Object> getClaims() { return this.claims; } } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\DPoPAuthenticationProvider.java
1
请完成以下Java代码
public Caption copy() { return new Caption(this); } public void putTranslation(@NonNull final String adLanguage, @Nullable final String captionTrl) { Check.assumeNotEmpty(adLanguage, "adLanguage is not empty"); final String captionTrlNorm = captionTrl != null ? captionTrl.trim() : ""; if (!captionTrlNorm.isEmpty()) { translations.put(adLanguage, captionTrlNorm); } else { translations.remove(adLanguage); } computedTrl = null; } public ITranslatableString toTranslatableString() { ITranslatableString computedTrl = this.computedTrl; if (computedTrl == null) { computedTrl = this.computedTrl = computeTranslatableString(); } return computedTrl; }
private ITranslatableString computeTranslatableString() { if (translations.isEmpty()) { return TranslatableStrings.empty(); } else if (translations.size() == 1) { final Map.Entry<String, String> firstEntry = translations.entrySet().iterator().next(); final String adLanguage = firstEntry.getKey(); final String value = firstEntry.getValue(); return TranslatableStrings.singleLanguage(adLanguage, value); } else { String defaultValue = translations.get(baseAD_Language); if (defaultValue == null) { defaultValue = translations.values().iterator().next(); } return TranslatableStrings.ofMap(translations, defaultValue); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTabVO.java
1
请在Spring Boot框架中完成以下Java代码
public class Expense { @JmixGeneratedValue @Column(name = "ID", nullable = false) @Id private UUID id; @InstanceName @Column(name = "NAME", nullable = false) @NotNull private String name; @Column(name = "CATEGORY", nullable = false) @NotNull private String category; @Column(name = "VERSION", nullable = false) @Version private Integer version; public ExpenseCategory getCategory() { return category == null ? null : ExpenseCategory.fromId(category); } public void setCategory(ExpenseCategory category) { this.category = category == null ? null : category.getId(); }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\Expense.java
2
请在Spring Boot框架中完成以下Java代码
private AuthenticationConfiguration getAuthenticationConfiguration() { return this.context.getBean(AuthenticationConfiguration.class); } private boolean prePostEnabled() { return enableMethodSecurity().getBoolean("prePostEnabled"); } private boolean securedEnabled() { return enableMethodSecurity().getBoolean("securedEnabled"); } private boolean jsr250Enabled() { return enableMethodSecurity().getBoolean("jsr250Enabled"); } private boolean isAspectJ() { return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ;
} private AnnotationAttributes enableMethodSecurity() { if (this.enableMethodSecurity == null) { // if it is null look at this instance (i.e. a subclass was used) EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity.class); Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required"); Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation); this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs); } return this.enableMethodSecurity; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
2