instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) { return asEnvironment(target) .filter(environment -> environment.containsProperty(name)) .isPresent(); } /** * @inheritDoc */ @Override public TypedValue read(EvaluationContext context, @Nullable Object target, String name) { String value = asEnvironment(target) .map(environment -> environment.getProperty(name)) .orElse(null); return new TypedValue(value); } /**
* @inheritDoc * @return {@literal false}. */ @Override public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) { return false; } /** * @inheritDoc */ @Override public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) { } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\expression\SmartEnvironmentAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public class SqlInitializationProperties { /** * Locations of the schema (DDL) scripts to apply to the database. */ private @Nullable List<String> schemaLocations; /** * Locations of the data (DML) scripts to apply to the database. */ private @Nullable List<String> dataLocations; /** * Platform to use in the default schema or data script locations, * schema-${platform}.sql and data-${platform}.sql. */ private String platform = "all"; /** * Username of the database to use when applying initialization scripts (if * different). */ private @Nullable String username; /** * Password of the database to use when applying initialization scripts (if * different). */ private @Nullable String password; /** * Whether initialization should continue when an error occurs. */ private boolean continueOnError; /** * Statement separator in the schema and data scripts. */ private String separator = ";"; /** * Encoding of the schema and data scripts. */ private @Nullable Charset encoding; /** * Mode to apply when determining whether initialization should be performed. */ private DatabaseInitializationMode mode = DatabaseInitializationMode.EMBEDDED; public @Nullable List<String> getSchemaLocations() { return this.schemaLocations; } public void setSchemaLocations(@Nullable List<String> schemaLocations) { this.schemaLocations = schemaLocations; } public @Nullable List<String> getDataLocations() { return this.dataLocations; } public void setDataLocations(@Nullable List<String> dataLocations) { this.dataLocations = dataLocations; } public String getPlatform() { return this.platform; } public void setPlatform(String platform) { this.platform = platform; }
public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public boolean isContinueOnError() { return this.continueOnError; } public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } public String getSeparator() { return this.separator; } public void setSeparator(String separator) { this.separator = separator; } public @Nullable Charset getEncoding() { return this.encoding; } public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } public DatabaseInitializationMode getMode() { return this.mode; } public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\autoconfigure\init\SqlInitializationProperties.java
2
请完成以下Java代码
public class PrimeGenerator { public static List<Integer> sieveOfEratosthenes(int n) { final boolean prime[] = new boolean[n + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) prime[i] = false; } } final List<Integer> primes = new LinkedList<>(); for (int i = 2; i <= n; i++) { if (prime[i]) primes.add(i); } return primes; } public static List<Integer> primeNumbersBruteForce(int max) { final List<Integer> primeNumbers = new LinkedList<Integer>(); for (int i = 2; i <= max; i++) { if (isPrimeBruteForce(i)) { primeNumbers.add(i); } }
return primeNumbers; } private static boolean isPrimeBruteForce(int x) { for (int i = 2; i < x; i++) { if (x % i == 0) { return false; } } return true; } public static List<Integer> primeNumbersTill(int max) { return IntStream.rangeClosed(2, max) .filter(x -> isPrime(x)) .boxed() .collect(Collectors.toList()); } private static boolean isPrime(int x) { return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) .allMatch(n -> x % n != 0); } }
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\prime\PrimeGenerator.java
1
请完成以下Java代码
public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); 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_AD_Alert.java
1
请在Spring Boot框架中完成以下Java代码
public static class Export { /** * Whether unsampled spans should be exported. */ private boolean includeUnsampled; /** * Maximum time an export will be allowed to run before being cancelled. */ private Duration timeout = Duration.ofSeconds(30); /** * Maximum batch size for each export. This must be less than or equal to * 'maxQueueSize'. */ private int maxBatchSize = 512; /** * Maximum number of spans that are kept in the queue before they will be dropped. */ private int maxQueueSize = 2048; /** * The delay interval between two consecutive exports. */ private Duration scheduleDelay = Duration.ofSeconds(5); public boolean isIncludeUnsampled() { return this.includeUnsampled; } public void setIncludeUnsampled(boolean includeUnsampled) { this.includeUnsampled = includeUnsampled; } public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; }
public int getMaxBatchSize() { return this.maxBatchSize; } public void setMaxBatchSize(int maxBatchSize) { this.maxBatchSize = maxBatchSize; } public int getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(int maxQueueSize) { this.maxQueueSize = maxQueueSize; } public Duration getScheduleDelay() { return this.scheduleDelay; } public void setScheduleDelay(Duration scheduleDelay) { this.scheduleDelay = scheduleDelay; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingProperties.java
2
请完成以下Java代码
public String getDescription() { if (localizedDescription != null && localizedDescription.length() > 0) { return localizedDescription; } else { return description; } } public void setDescription(String description) { this.description = description; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getType() {
return type; } public void setType(String type) { this.type = type; } public String getDataObjectDefinitionKey() { return dataObjectDefinitionKey; } public void setDataObjectDefinitionKey(String dataObjectDefinitionKey) { this.dataObjectDefinitionKey = dataObjectDefinitionKey; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DataObjectImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() {
return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getCallbackIds() { return callbackIds; } public void setCallbackIds(Set<String> callbackIds) { this.callbackIds = callbackIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceQueryRequest.java
2
请完成以下Java代码
public Builder setMandatory(final boolean mandatory) { this.mandatory = mandatory; return this; } public Builder setHideGridColumnIfEmpty(final boolean hideGridColumnIfEmpty) { this.hideGridColumnIfEmpty = hideGridColumnIfEmpty; return this; } public Builder setValueClass(final Class<?> valueClass) { this._valueClass = valueClass; return this; } private Class<?> getValueClass() { if (_valueClass != null) { return _valueClass; } return getWidgetType().getValueClass(); } public Builder setWidgetType(final DocumentFieldWidgetType widgetType) { this._widgetType = widgetType; return this; } private DocumentFieldWidgetType getWidgetType() { Check.assumeNotNull(_widgetType, "Parameter widgetType is not null"); return _widgetType; } public Builder setMinPrecision(@NonNull final OptionalInt minPrecision) { this.minPrecision = minPrecision; return this; } private OptionalInt getMinPrecision() { return minPrecision; } public Builder setSqlValueClass(final Class<?> sqlValueClass) { this._sqlValueClass = sqlValueClass; return this; } private Class<?> getSqlValueClass() {
if (_sqlValueClass != null) { return _sqlValueClass; } return getValueClass(); } public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor) { this._lookupDescriptor = lookupDescriptor; return this; } public OptionalBoolean getNumericKey() { return _numericKey; } public Builder setKeyColumn(final boolean keyColumn) { this.keyColumn = keyColumn; return this; } public Builder setEncrypted(final boolean encrypted) { this.encrypted = encrypted; return this; } /** * Sets ORDER BY priority and direction (ascending/descending) * * @param priority priority; if positive then direction will be ascending; if negative then direction will be descending */ public Builder setDefaultOrderBy(final int priority) { if (priority >= 0) { orderByPriority = priority; orderByAscending = true; } else { orderByPriority = -priority; orderByAscending = false; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java
1
请完成以下Java代码
private void syncCollectedExternalReferencesIfRequired(@NonNull final Collection<ExternalReferenceId> externalReferenceIds) { if (externalReferenceIds.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("ExternalReferenceId list to sync is empty! No action is performed!"); return; } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { Loggables.withLogger(logger, Level.DEBUG).addLog("No active config found for external system type: {}! No action is performed!", getExternalSystemType()); return; // nothing to do } for (final ExternalReferenceId externalReferenceId : externalReferenceIds) { final TableRecordReference externalReferenceToExportRecordRef = TableRecordReference.of(I_S_ExternalReference.Table_Name, externalReferenceId); exportToExternalSystemIfRequired(externalReferenceToExportRecordRef, () -> getAdditionalExternalSystemConfigIds(externalReferenceId)); } }
@NonNull protected abstract Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final ExternalReferenceId externalReferenceId); @Override protected void runPreExportHook(final TableRecordReference recordReferenceToExport) { } protected abstract Map<String, String> buildParameters(@NonNull final IExternalSystemChildConfig childConfig, @NonNull final ExternalReferenceId externalReferenceId); protected abstract boolean isSyncExternalReferenceEnabled(@NonNull final IExternalSystemChildConfig childConfig); protected abstract String getExternalCommand(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\externalreference\ExportExternalReferenceToExternalSystem.java
1
请在Spring Boot框架中完成以下Java代码
public class UserApi { private final UserServiceImpl userServiceImpl; public UserApi(UserServiceImpl userServiceImpl) { this.userServiceImpl = userServiceImpl; } @PostMapping public ResponseEntity<Response> createUser(@RequestBody User user) { if (StringUtils.isBlank(user.getId())) { user.setId(UUID.randomUUID().toString()); } userServiceImpl.saveUser(user); Response response = new Response(HttpStatus.CREATED.value(), "User created successfully", System.currentTimeMillis()); URI location = URI.create("/users/" + user.getId()); return ResponseEntity.created(location).body(response); } @GetMapping("/{userId}")
public User getUser(@PathVariable("userId") String userId) { return userServiceImpl.findById(userId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No user exists with the given Id")); } @GetMapping() public List<User> getAllUsers() { return userServiceImpl.findAll().orElse(new ArrayList<>()); } @DeleteMapping("/{userId}") public ResponseEntity<Response> deleteUser(@PathVariable("userId") String userId) { userServiceImpl.deleteUser(userId); return ResponseEntity.ok(new Response(200, "The user has been deleted successfully", System.currentTimeMillis())); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\httpfirewall\api\UserApi.java
2
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SubscriptionState that = (SubscriptionState) o; if (subscriptionId != that.subscriptionId) return false; if (wsSessionId != null ? !wsSessionId.equals(that.wsSessionId) : that.wsSessionId != null) return false; if (entityId != null ? !entityId.equals(that.entityId) : that.entityId != null) return false; return type == that.type; } @Override public int hashCode() { int result = wsSessionId != null ? wsSessionId.hashCode() : 0;
result = 31 * result + subscriptionId; result = 31 * result + (entityId != null ? entityId.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); return result; } @Override public String toString() { return "SubscriptionState{" + "type=" + type + ", entityId=" + entityId + ", subscriptionId=" + subscriptionId + ", wsSessionId='" + wsSessionId + '\'' + '}'; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\telemetry\sub\SubscriptionState.java
2
请完成以下Java代码
public void setSiteName (final @Nullable java.lang.String SiteName) { set_ValueNoCheck (COLUMNNAME_SiteName, SiteName); } @Override public java.lang.String getSiteName() { return get_ValueAsString(COLUMNNAME_SiteName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() {
return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_119_v.java
1
请完成以下Java代码
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { String identityLinkType = BpmnXMLUtil.getAttributeValue(ATTRIBUTE_NAME, xtr); // the attribute value may be unqualified if (identityLinkType == null) { identityLinkType = xtr.getAttributeValue(null, ATTRIBUTE_NAME); } if (identityLinkType == null) { return; } String resourceElement = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(resourceElement) && ELEMENT_RESOURCE_ASSIGNMENT.equals(resourceElement)) { String expression = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(expression) && ELEMENT_FORMAL_EXPRESSION.equals(expression)) { List<String> assignmentList = CommaSplitter.splitCommas(xtr.getElementText()); for (String assignmentValue : assignmentList) { if (assignmentValue == null) { continue; } assignmentValue = assignmentValue.trim(); if (assignmentValue.length() == 0) { continue; }
String userPrefix = "user("; String groupPrefix = "group("; if (assignmentValue.startsWith(userPrefix)) { assignmentValue = assignmentValue.substring(userPrefix.length(), assignmentValue.length() - 1).trim(); ((UserTask) parentElement).addCustomUserIdentityLink(assignmentValue, identityLinkType); } else if (assignmentValue.startsWith(groupPrefix)) { assignmentValue = assignmentValue.substring(groupPrefix.length(), assignmentValue.length() - 1).trim(); ((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType); } else { ((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType); } } } } } } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\UserTaskXMLConverter.java
1
请完成以下Java代码
public static DeliveryViaRule ofNullableCode(@Nullable final String code) { final DeliveryViaRule defaultWhenNull = null; return ofNullableCodeOr(code, defaultWhenNull); } @Nullable public static DeliveryViaRule ofNullableCodeOr(@Nullable final String code, @Nullable final DeliveryViaRule defaultWhenNull) { return code != null ? ofCode(code) : defaultWhenNull; } public static DeliveryViaRule ofCode(@NonNull final String code) { final DeliveryViaRule type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + DeliveryViaRule.class + " found for code: " + code);
} return type; } private static final ImmutableMap<String, DeliveryViaRule> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), DeliveryViaRule::getCode); public boolean isShipper() { return this == Shipper; } @Nullable public static String toCodeOrNull(final DeliveryViaRule type) { return type != null ? type.getCode() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\order\DeliveryViaRule.java
1
请完成以下Spring Boot application配置
management.endpoints.web.exposure.include=* management.metrics.enable.root=true management.metrics.enable.jvm=true management.endpoint.restart.enabled=true spring.
datasource.jmx-enabled=false management.endpoint.shutdown.enabled=true
repos\tutorials-master\spring-boot-modules\spring-boot-deployment\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public CustomNotifier customNotifier(InstanceRepository repository) { return new CustomNotifier(repository); } @Bean public CustomEndpoint customEndpoint() { return new CustomEndpoint(); } // tag::customization-http-headers-providers[] @Bean public HttpHeadersProvider customHttpHeadersProvider() { return (instance) -> { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("X-CUSTOM", "My Custom Value"); return httpHeaders; }; } // end::customization-http-headers-providers[] @Bean public HttpExchangeRepository httpTraceRepository() { return new InMemoryHttpExchangeRepository();
} @Bean public AuditEventRepository auditEventRepository() { return new InMemoryAuditEventRepository(); } @Bean public EmbeddedDatabase dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) .addScript("org/springframework/session/jdbc/schema-hsqldb.sql") .build(); } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminServletApplication.java
2
请完成以下Java代码
public TransportClient getObject() throws Exception { return client; } @Override public Class<TransportClient> getObjectType() { return TransportClient.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { buildClient(); } protected void buildClient() throws Exception { // 创建可追踪的 TracingPreBuiltTransportClient client = new TracingPreBuiltTransportClient(tracer, settings()); clusterNodes.stream() // .peek(it -> logger.info("Adding transport node : " + it.toString())) // .forEach(client::addTransportAddress); client.connectedNodes(); } private Settings settings() { if (properties != null) { Settings.Builder builder = Settings.builder(); properties.forEach((key, value) -> { builder.put(key.toString(), value.toString()); }); return builder.build(); } return Settings.builder() .put("cluster.name", clusterName) .put("client.transport.sniff", clientTransportSniff) .put("client.transport.ignore_cluster_name", clientIgnoreClusterName) .put("client.transport.ping_timeout", clientPingTimeout) .put("client.transport.nodes_sampler_interval", clientNodesSamplerInterval) .build(); } public void setClusterNodes(String clusterNodes) { this.clusterNodes = ClusterNodes.of(clusterNodes); } public void setClusterName(String clusterName) { this.clusterName = clusterName;
} public void setClientTransportSniff(Boolean clientTransportSniff) { this.clientTransportSniff = clientTransportSniff; } public String getClientNodesSamplerInterval() { return clientNodesSamplerInterval; } public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { this.clientNodesSamplerInterval = clientNodesSamplerInterval; } public String getClientPingTimeout() { return clientPingTimeout; } public void setClientPingTimeout(String clientPingTimeout) { this.clientPingTimeout = clientPingTimeout; } public Boolean getClientIgnoreClusterName() { return clientIgnoreClusterName; } public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { this.clientIgnoreClusterName = clientIgnoreClusterName; } public void setProperties(Properties properties) { this.properties = properties; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\spring\TracingTransportClientFactoryBean.java
1
请完成以下Java代码
public String getEmployeeUsingMapSqlParameterSource() { final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", 1); return namedParameterJdbcTemplate.queryForObject("SELECT FIRST_NAME FROM EMPLOYEE WHERE ID = :id", namedParameters, String.class); } public int getEmployeeUsingBeanPropertySqlParameterSource() { final Employee employee = new Employee(); employee.setFirstName("James"); final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName"; final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee); return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class); } public int[] batchUpdateUsingJDBCTemplate(final List<Employee> employees) { return jdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(final PreparedStatement ps, final int i) throws SQLException { ps.setInt(1, employees.get(i).getId()); ps.setString(2, employees.get(i).getFirstName()); ps.setString(3, employees.get(i).getLastName()); ps.setString(4, employees.get(i).getAddress());
} @Override public int getBatchSize() { return 3; } }); } public int[] batchUpdateUsingNamedParameterJDBCTemplate(final List<Employee> employees) { final SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray()); final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); return updateCounts; } public Employee getEmployeeUsingSimpleJdbcCall(int id) { SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); Map<String, Object> out = simpleJdbcCall.execute(in); Employee emp = new Employee(); emp.setFirstName((String) out.get("FIRST_NAME")); emp.setLastName((String) out.get("LAST_NAME")); return emp; } }
repos\tutorials-master\persistence-modules\spring-persistence-simple\src\main\java\com\baeldung\spring\jdbc\template\guide\EmployeeDAO.java
1
请完成以下Java代码
public class MaterialTrackingReportAgregationItem { /** * * @param ppOrder can be <code>null</code>. If <code>null</code>, then the item is counted as an <code>M_InOut</code> material receipt.<br> * If not <code>null</code> then it is counted as a <code>PP_Order</code> material issue. * @param inOutLine may not be <code>null</code> * @param materialTracking * @param qty the qty in the product's "internal" UOM */ public MaterialTrackingReportAgregationItem( final I_PP_Order ppOrder, final I_M_InOutLine inOutLine, final I_M_Material_Tracking materialTracking, final BigDecimal qty) { this.ppOrder = ppOrder; this.inOutLine = inOutLine; this.materialTracking = materialTracking; this.qty = qty; } /** * Will be set only if we deal with an issue item */ private final I_PP_Order ppOrder; /** * Will always be set. It is either taken from the material tracking ref ( receipt side) or the issued inout lines of the pp_Order (issued side) */ private final I_M_InOutLine inOutLine;
/** * Useful for tracking, troubleshooting */ private final I_M_Material_Tracking materialTracking; /** * The significant qty for the item. It can either be qtyIssued if the pp_Order is set, or qtyReceived if it isn't */ BigDecimal qty; public BigDecimal getQty() { return qty; } public I_PP_Order getPPOrder() { return ppOrder; } public I_M_Material_Tracking getMaterialTracking() { return materialTracking; } public I_M_InOutLine getInOutLine() { return inOutLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\MaterialTrackingReportAgregationItem.java
1
请完成以下Java代码
public Set<InvoiceId> generateInvoicesFromShipmentLines(@NonNull final List<I_M_InOutLine> shipmentLines) { if (shipmentLines.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("generateInvoicesFromShipmentLines - Given shipmentLines list is empty; -> nothing to do"); return ImmutableSet.of(); } final Set<InvoiceCandidateId> invoiceCandidateIds = retrieveInvoiceCandsByInOutLines(shipmentLines) .stream() .map(I_C_Invoice_Candidate::getC_Invoice_Candidate_ID) .map(InvoiceCandidateId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); return generateInvoicesFromInvoiceCandidateIds(invoiceCandidateIds); } public ImmutableSet<InvoiceId> generateInvoicesFromInvoiceCandidateIds(@NonNull final Set<InvoiceCandidateId> invoiceCandidateIds) { processInvoiceCandidates(ImmutableSet.copyOf(invoiceCandidateIds)); return invoiceCandidateIds.stream() .map(invoiceCandDAO::retrieveIlForIc) .flatMap(List::stream) .map(org.compiere.model.I_C_InvoiceLine::getC_Invoice_ID) .map(InvoiceId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } private void processInvoiceCandidates(@NonNull final Set<InvoiceCandidateId> invoiceCandidateIds) { generateInvoicesForAsyncBatch(invoiceCandidateIds); } @NonNull public List<I_C_Invoice_Candidate> retrieveInvoiceCandsByInOutLines(@NonNull final List<I_M_InOutLine> shipmentLines) { return shipmentLines.stream() .map(invoiceCandDAO::retrieveInvoiceCandidatesForInOutLine) .flatMap(List::stream) .collect(ImmutableList.toImmutableList()); } private void generateInvoicesForAsyncBatch(@NonNull final Set<InvoiceCandidateId> invoiceCandIds) {
final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch(C_Async_Batch_InternalName_InvoiceCandidate_Processing); final PInstanceId invoiceCandidatesSelectionId = DB.createT_Selection(invoiceCandIds, Trx.TRXNAME_None); final IInvoiceCandidateEnqueuer enqueuer = invoiceCandBL.enqueueForInvoicing() .setContext(getCtx()) .setAsyncBatchId(asyncBatchId) .setInvoicingParams(createDefaultIInvoicingParams()) .setFailIfNothingEnqueued(true); // this creates workpackages enqueuer.prepareSelection(invoiceCandidatesSelectionId); final Supplier<IEnqueueResult> enqueueInvoiceCandidates = () -> enqueuer .enqueueSelection(invoiceCandidatesSelectionId); asyncBatchService.executeBatch(enqueueInvoiceCandidates, asyncBatchId); } @NonNull private IInvoicingParams createDefaultIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setIgnoreInvoiceSchedule(false); invoicingParams.setDateInvoiced(LocalDate.now()); return invoicingParams; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoice\InvoiceService.java
1
请完成以下Java代码
public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getIntercompanyDueFrom_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getIntercompanyDueFrom_Acct(), get_TrxName()); } /** Set Intercompany Due From Acct. @param IntercompanyDueFrom_Acct Intercompany Due From / Receivables Account */ public void setIntercompanyDueFrom_Acct (int IntercompanyDueFrom_Acct) { set_Value (COLUMNNAME_IntercompanyDueFrom_Acct, Integer.valueOf(IntercompanyDueFrom_Acct)); } /** Get Intercompany Due From Acct. @return Intercompany Due From / Receivables Account */ public int getIntercompanyDueFrom_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueFrom_Acct); if (ii == null) return 0; return ii.intValue();
} public I_C_ValidCombination getIntercompanyDueTo_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getIntercompanyDueTo_Acct(), get_TrxName()); } /** Set Intercompany Due To Acct. @param IntercompanyDueTo_Acct Intercompany Due To / Payable Account */ public void setIntercompanyDueTo_Acct (int IntercompanyDueTo_Acct) { set_Value (COLUMNNAME_IntercompanyDueTo_Acct, Integer.valueOf(IntercompanyDueTo_Acct)); } /** Get Intercompany Due To Acct. @return Intercompany Due To / Payable Account */ public int getIntercompanyDueTo_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueTo_Acct); 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_InterOrg_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public FileWritableDataSource writableDataSource(ObjectMapper objectMapper) throws IOException { // File 配置。这里先写死,推荐后面写到 application.yaml 配置文件中。 String directory = System.getProperty("user.home") + File.separator + "sentinel" + File.separator + System.getProperty("project.name"); mkdirs(directory); String path = directory + File.separator + "flow-rule.json"; creteFile(path); // 创建 FileRefreshableDataSource 对象 FileRefreshableDataSource<List<FlowRule>> refreshableDataSource = new FileRefreshableDataSource<>(path, new Converter<String, List<FlowRule>>() { // 转换器,将读取的文本配置,转换成 FlowRule 数组 @Override public List<FlowRule> convert(String value) { try { return Arrays.asList(objectMapper.readValue(value, FlowRule[].class)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); // 注册到 FlowRuleManager 中 FlowRuleManager.register2Property(refreshableDataSource.getProperty()); // 创建 FileWritableDataSource 对象 FileWritableDataSource<List<FlowRule>> fileWritableDataSource = new FileWritableDataSource<>(path, new Converter<List<FlowRule>, String>() { @Override public String convert(List<FlowRule> source) { try { return objectMapper.writeValueAsString(source);
} catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); // 注册到 WritableDataSourceRegistry 中 WritableDataSourceRegistry.registerFlowDataSource(fileWritableDataSource); return fileWritableDataSource; } private void mkdirs(String path) { File file = new File(path); if (file.exists()) { return; } file.mkdirs(); } private void creteFile(String path) throws IOException { File file = new File(path); if (file.exists()) { return; } file.createNewFile(); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo-file\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\config\SentinelConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class FunctionalSpringBootApplication { private static final Actor BRAD_PITT = new Actor("Brad", "Pitt"); private static final Actor TOM_HANKS = new Actor("Tom", "Hanks"); private static final List<Actor> actors = new CopyOnWriteArrayList<>(Arrays.asList(BRAD_PITT, TOM_HANKS)); private RouterFunction<ServerResponse> routingFunction() { FormHandler formHandler = new FormHandler(); RouterFunction<ServerResponse> restfulRouter = route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) .doOnNext(actors::add) .then(ok().build())); return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))) .andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter) .filter((request, next) -> { System.out.println("Before handler invocation: " + request.path()); return next.handle(request);
}); } @Bean public ServletRegistrationBean servletRegistrationBean() throws Exception { HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler((WebHandler) toHttpHandler(routingFunction())) .filter(new IndexRewriteFilter()) .build(); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(new RootServlet(httpHandler), "/"); registrationBean.setLoadOnStartup(1); registrationBean.setAsyncSupported(true); return registrationBean; } public static void main(String[] args) { SpringApplication.run(FunctionalSpringBootApplication.class, args); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\functional\FunctionalSpringBootApplication.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isReadable() { return this.resource.isReadable(); } @Override public boolean isOpen() { return this.resource.isOpen(); } @Override public URL getURL() throws IOException { return this.resource.getURL(); } @Override public URI getURI() throws IOException { return this.resource.getURI(); } @Override public File getFile() throws IOException { return this.resource.getFile(); } @NonNull @Override public InputStream getInputStream() throws IOException { return this.resource.getInputStream(); } @Override public long contentLength() throws IOException { return this.resource.contentLength(); } @Override public long lastModified() throws IOException { return this.resource.lastModified(); } @Override
public net.shibboleth.shared.resource.Resource createRelativeResource(String relativePath) throws IOException { return new SpringResource(this.resource.createRelative(relativePath)); } @Override public String getFilename() { return this.resource.getFilename(); } @Override public String getDescription() { return this.resource.getDescription(); } } } private static final class CriteriaSetResolverWrapper extends MetadataResolverAdapter { CriteriaSetResolverWrapper(MetadataResolver metadataResolver) { super(metadataResolver); } @Override EntityDescriptor resolveSingle(EntityIdCriterion entityId) throws Exception { return super.metadataResolver.resolveSingle(new CriteriaSet(entityId)); } @Override Iterable<EntityDescriptor> resolve(EntityRoleCriterion role) throws Exception { return super.metadataResolver.resolve(new CriteriaSet(role)); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\registration\OpenSaml5AssertingPartyMetadataRepository.java
2
请完成以下Spring Boot application配置
server: port: 8081 spring: security: oauth2: client: registration: keycloak: client-id: my-client scope: openid,profile,email authorization-grant-type: authorization_code redirect-uri: "{baseUrl}/login/oauth
2/code/{registrationId}" provider: keycloak: issuer-uri: http://localhost:8787/realms/my-realm
repos\tutorials-master\spring-security-modules\spring-security-faking-oauth2-sso\src\main\resources\application.yaml
2
请完成以下Java代码
private I_C_Invoice retrieveInvoiceRecordByDocumentNoAndCreated(@NonNull final String documentNo, @NonNull final Instant created) { final I_C_Invoice invoiceRecord = retrieveInvoiceRecordByDocumentNoAndCreatedOrNull(documentNo, created); if (invoiceRecord != null) { return invoiceRecord; } throw new InvoiceResponseRepoException(MSG_INVOICE_NOT_FOUND_2P, documentNo, created.getEpochSecond()) .markAsUserValidationError(); } @Nullable private I_C_Invoice retrieveInvoiceRecordByDocumentNoAndCreatedOrNull(@NonNull final String documentNo, @NonNull final Instant created) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMN_DocumentNo, documentNo) .addEqualsFilter(I_C_Invoice.COLUMN_Created, created) .create() .setRequiredAccess(Access.WRITE) .firstOnly(I_C_Invoice.class); } private I_C_Invoice retrieveInvoiceRecordById(@NonNull final InvoiceId invoiceId) { final I_C_Invoice invoiceRecord; invoiceRecord = load(invoiceId, I_C_Invoice.class); if (invoiceRecord == null) { throw new InvoiceResponseRepoException(MSG_INVOICE_NOT_FOUND_BY_ID_1P, invoiceId.getRepoId()) .markAsUserValidationError(); } return invoiceRecord; } private void updateInvoiceRecord(@NonNull final ImportedInvoiceResponse response, @NonNull final I_C_Invoice invoiceRecord) { invoiceRecord.setIsInDispute(ImportedInvoiceResponse.Status.REJECTED.equals(response.getStatus())); saveRecord(invoiceRecord); } private void attachFileToInvoiceRecord( @NonNull final ImportedInvoiceResponse response, @NonNull final I_C_Invoice invoiceRecord) { final AttachmentTags attachmentTags = AttachmentTags.builder()
.tags(response.getAdditionalTags()) .build(); final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest .builderFromByteArray(response.getRequest().getFileName(), response.getRequest().getData()) .tags(attachmentTags) .build(); attachmentEntryService.createNewAttachment(invoiceRecord, attachmentEntryCreateRequest); } @SuppressWarnings("WeakerAccess") public static final class InvoiceResponseRepoException extends AdempiereException { private static final long serialVersionUID = -4024895067979792864L; public InvoiceResponseRepoException(@NonNull final ITranslatableString message) { super(message); } public InvoiceResponseRepoException(@NonNull final AdMessageKey adMessage, final Object... params) { super(adMessage, params); } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\InvoiceResponseRepo.java
1
请在Spring Boot框架中完成以下Java代码
public CalculatedFieldType getType() { return CalculatedFieldType.GEOFENCING; } @Override @JsonIgnore public Map<String, Argument> getArguments() { Map<String, Argument> args = new HashMap<>(entityCoordinates.toArguments()); zoneGroups.forEach((zgName, zgConfig) -> args.put(zgName, zgConfig.toArgument())); return args; } @Override public Set<EntityId> getReferencedEntities() { return zoneGroups == null ? Collections.emptySet() : zoneGroups.values().stream()
.map(ZoneGroupConfiguration::getRefEntityId) .filter(Objects::nonNull) .collect(toSet()); } @Override public Output getOutput() { return output; } @Override public void validate() { zoneGroups.forEach((key, value) -> value.validate(key)); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\geofencing\GeofencingCalculatedFieldConfiguration.java
2
请完成以下Java代码
public class PurchaseViewLayoutFactory { private final CCache<LayoutKey, ViewLayout> viewLayoutCache = CCache.newCache(PurchaseViewLayoutFactory.class + "#ViewLayout", 1, 0); private final ITranslatableString caption; @Builder private PurchaseViewLayoutFactory(final ITranslatableString caption) { this.caption = caption; } public ViewLayout getViewLayout(@NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType) { final LayoutKey key = LayoutKey.builder() .windowId(windowId) .viewDataType(viewDataType) .build(); return viewLayoutCache.getOrLoad(key, this::createViewLayout); } private ViewLayout createViewLayout(final LayoutKey key) { return ViewLayout.builder() .setWindowId(key.getWindowId()) .setCaption(caption) // .setHasAttributesSupport(false)
.setHasTreeSupport(true) .setTreeCollapsible(true) .setTreeExpandedDepth(ViewLayout.TreeExpandedDepth_AllCollapsed) // .addElementsFromViewRowClass(PurchaseRow.class, key.getViewDataType()) // .build(); } @lombok.Value @lombok.Builder private static class LayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewLayoutFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void refreshEx(I_AD_Table_MView mview, PO sourcePO, RefreshMode refreshMode, String trxName) { if (refreshMode == RefreshMode.Complete) { updateComplete(mview); } else if (refreshMode == RefreshMode.Partial) { updatePartial(mview, sourcePO, trxName); } else { throw new AdempiereException("RefreshMode " + refreshMode + " not supported"); } } /** * Try to update the materialized view. This method is not throwing an exception in case it fails but it logs it and * return false. This is useful because we don't want to condition the update of triggering PO to updating the * MView. That can be solved later * * @return true if updated, false if failed */ @Override public boolean refresh(final I_AD_Table_MView mview, final PO sourcePO, final RefreshMode refreshMode, final String trxName) { final boolean[] ok = new boolean[] { false }; Services.get(ITrxManager.class).run(trxName, new TrxRunnable2() { @Override public void run(String trxName) { refreshEx(mview, sourcePO, refreshMode, trxName); ok[0] = true; } @Override public boolean doCatch(Throwable e) { // log the error, return true to rollback the transaction but don't throw it forward log.error(e.getLocalizedMessage() + ", mview=" + mview + ", sourcePO=" + sourcePO + ", trxName=" + trxName, e); ok[0] = false; return true; } @Override public void doFinally() {
} }); return ok[0]; } @Override public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType) { final String sourceTableName = sourcePO.get_TableName(); final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName); if (sourceColumns == null || sourceColumns.isEmpty()) return false; if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE) { return true; } for (String sourceColumn : sourceColumns) { if (sourcePO.is_ValueChanged(sourceColumn)) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable Boolean getEnableComplexMapKeySerialization() { return this.enableComplexMapKeySerialization; } public void setEnableComplexMapKeySerialization(@Nullable Boolean enableComplexMapKeySerialization) { this.enableComplexMapKeySerialization = enableComplexMapKeySerialization; } public @Nullable Boolean getDisableInnerClassSerialization() { return this.disableInnerClassSerialization; } public void setDisableInnerClassSerialization(@Nullable Boolean disableInnerClassSerialization) { this.disableInnerClassSerialization = disableInnerClassSerialization; } public @Nullable LongSerializationPolicy getLongSerializationPolicy() { return this.longSerializationPolicy; } public void setLongSerializationPolicy(@Nullable LongSerializationPolicy longSerializationPolicy) { this.longSerializationPolicy = longSerializationPolicy; } public @Nullable FieldNamingPolicy getFieldNamingPolicy() { return this.fieldNamingPolicy; } public void setFieldNamingPolicy(@Nullable FieldNamingPolicy fieldNamingPolicy) { this.fieldNamingPolicy = fieldNamingPolicy; } public @Nullable Boolean getPrettyPrinting() { return this.prettyPrinting; } public void setPrettyPrinting(@Nullable Boolean prettyPrinting) { this.prettyPrinting = prettyPrinting; } public @Nullable Strictness getStrictness() { return this.strictness; } public void setStrictness(@Nullable Strictness strictness) { this.strictness = strictness; } public void setLenient(@Nullable Boolean lenient) { setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT); } public @Nullable Boolean getDisableHtmlEscaping() { return this.disableHtmlEscaping; }
public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) { this.disableHtmlEscaping = disableHtmlEscaping; } public @Nullable String getDateFormat() { return this.dateFormat; } public void setDateFormat(@Nullable String dateFormat) { this.dateFormat = dateFormat; } /** * Enumeration of levels of strictness. Values are the same as those on * {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize * backwards compatibility, the Gson enum is not used directly. */ public enum Strictness { /** * Lenient compliance. */ LENIENT, /** * Strict compliance with some small deviations for legacy reasons. */ LEGACY_STRICT, /** * Strict compliance. */ STRICT } }
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
2
请完成以下Java代码
public String getSrlNb() { return srlNb; } /** * Sets the value of the srlNb property. * * @param value * allowed object is * {@link String } * */ public void setSrlNb(String value) { this.srlNb = value; } /** * Gets the value of the apprvlNb 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 apprvlNb property. * * <p> * For example, to add a new item, do as follows: * <pre> * getApprvlNb().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getApprvlNb() { if (apprvlNb == null) { apprvlNb = new ArrayList<String>(); } return this.apprvlNb; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteractionComponent1.java
1
请完成以下Java代码
public long getTimeoutTime() { return timeoutTime; } public void setTimeoutTime(long timeoutTime) { this.timeoutTime = timeoutTime; } } /** * set cache * * @param key * @param val * @param cacheTime * @return */ public static boolean set(String key, Object val, long cacheTime){ // clean timeout cache, before set new cache (avoid cache too much) cleanTimeoutCache(); // set new cache if (key==null || key.trim().length()==0) { return false; } if (val == null) { remove(key); } if (cacheTime <= 0) { remove(key); } long timeoutTime = System.currentTimeMillis() + cacheTime; LocalCacheData localCacheData = new LocalCacheData(key, val, timeoutTime); cacheRepository.put(localCacheData.getKey(), localCacheData); return true; } /** * remove cache * * @param key * @return */ public static boolean remove(String key){ if (key==null || key.trim().length()==0) { return false; } cacheRepository.remove(key); return true;
} /** * get cache * * @param key * @return */ public static Object get(String key){ if (key==null || key.trim().length()==0) { return null; } LocalCacheData localCacheData = cacheRepository.get(key); if (localCacheData!=null && System.currentTimeMillis()<localCacheData.getTimeoutTime()) { return localCacheData.getVal(); } else { remove(key); return null; } } /** * clean timeout cache * * @return */ public static boolean cleanTimeoutCache(){ if (!cacheRepository.keySet().isEmpty()) { for (String key: cacheRepository.keySet()) { LocalCacheData localCacheData = cacheRepository.get(key); if (localCacheData!=null && System.currentTimeMillis()>=localCacheData.getTimeoutTime()) { cacheRepository.remove(key); } } } return true; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\LocalCacheUtil.java
1
请完成以下Java代码
I_C_Order getOrder() { return order; } private void setBPSalesRepIdToOrder(@NonNull final I_C_Order order, @NonNull final OLCand olCand) { switch (olCand.getAssignSalesRepRule()) { case Candidate: order.setC_BPartner_SalesRep_ID(BPartnerId.toRepoId(olCand.getSalesRepId())); break; case BPartner: order.setC_BPartner_SalesRep_ID(BPartnerId.toRepoId(olCand.getSalesRepInternalId())); break; case CandidateFirst: final int salesRepInt = Optional.ofNullable(olCand.getSalesRepId()) .map(BPartnerId::getRepoId) .orElseGet(() -> BPartnerId.toRepoId(olCand.getSalesRepInternalId())); order.setC_BPartner_SalesRep_ID(salesRepInt); break; default: throw new AdempiereException("Unsupported SalesRepFrom type") .appendParametersToMessage() .setParameter("salesRepFrom", olCand.getAssignSalesRepRule()); } }
private void setExternalBPartnerInfo(@NonNull final I_C_OrderLine orderLine, @NonNull final OLCand candidate) { orderLine.setExternalSeqNo(candidate.getLine()); final I_C_OLCand olCand = candidate.unbox(); orderLine.setBPartner_QtyItemCapacity(olCand.getQtyItemCapacity()); final UomId uomId = UomId.ofRepoIdOrNull(olCand.getC_UOM_ID()); if (uomId != null) { orderLine.setC_UOM_BPartner_ID(uomId.getRepoId()); orderLine.setQtyEnteredInBPartnerUOM(olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandOrderFactory.java
1
请完成以下Java代码
public class BubbleSort { void bubbleSort(Integer[] arr) { int n = arr.length; IntStream.range(0, n - 1) .flatMap(i -> IntStream.range(1, n - i)) .forEach(j -> { if (arr[j - 1] > arr[j]) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } }); } void optimizedBubbleSort(Integer[] arr) { int i = 0, n = arr.length;
boolean swapNeeded = true; while (i < n - 1 && swapNeeded) { swapNeeded = false; for (int j = 1; j < n - i; j++) { if (arr[j - 1] > arr[j]) { int temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; swapNeeded = true; } } if (!swapNeeded) break; i++; } } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\bubblesort\BubbleSort.java
1
请完成以下Java代码
public void setExtension(String newExtension) { m_extension = newExtension; } /** * Get Extension * @return extension */ public String getExtension() { return m_extension; } /** * Accept File * @param file file to be tested * @return true if OK */ public boolean accept(File file) { // Need to accept directories if (file.isDirectory()) return true; String ext = file.getName(); int pos = ext.lastIndexOf('.'); // No extension if (pos == -1) return false; ext = ext.substring(pos+1); if (m_extension.equalsIgnoreCase(ext)) return true; return false; } // accept /** * Verify file name with filer * @param file file * @param filter filter * @return file name */ public static String getFileName(File file, FileFilter filter) { return getFile(file, filter).getAbsolutePath();
} // getFileName /** * Verify file with filter * @param file file * @param filter filter * @return file */ public static File getFile(File file, FileFilter filter) { String fName = file.getAbsolutePath(); if (fName == null || fName.equals("")) fName = "Adempiere"; // ExtensionFileFilter eff = null; if (filter instanceof ExtensionFileFilter) eff = (ExtensionFileFilter)filter; else return file; // int pos = fName.lastIndexOf('.'); // No extension if (pos == -1) { fName += '.' + eff.getExtension(); return new File(fName); } String ext = fName.substring(pos+1); // correct extension if (ext.equalsIgnoreCase(eff.getExtension())) return file; fName += '.' + eff.getExtension(); return new File(fName); } // getFile } // ExtensionFileFilter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void initExecutor() { executor = ThingsBoardExecutors.newSingleThreadScheduledExecutor("re-rest-callback"); } @PreDestroy public void shutdownExecutor() { if (executor != null) { executor.shutdownNow(); } } @Override public void processRestApiCallToRuleEngine(TenantId tenantId, UUID requestId, TbMsg request, boolean useQueueFromTbMsg, Consumer<TbMsg> responseConsumer) { log.trace("[{}] Processing REST API call to rule engine: [{}] for entity: [{}]", tenantId, requestId, request.getOriginator()); requests.put(requestId, responseConsumer); sendRequestToRuleEngine(tenantId, request, useQueueFromTbMsg); scheduleTimeout(request, requestId, requests); } @Override public void onQueueMsg(TransportProtos.RestApiCallResponseMsgProto restApiCallResponseMsg, TbCallback callback) { UUID requestId = new UUID(restApiCallResponseMsg.getRequestIdMSB(), restApiCallResponseMsg.getRequestIdLSB()); Consumer<TbMsg> consumer = requests.remove(requestId); if (consumer != null) { consumer.accept(TbMsg.fromProto(null, restApiCallResponseMsg.getResponseProto(), restApiCallResponseMsg.getResponse(), TbMsgCallback.EMPTY)); } else { log.trace("[{}] Unknown or stale rest api call response received", requestId); }
callback.onSuccess(); } private void sendRequestToRuleEngine(TenantId tenantId, TbMsg msg, boolean useQueueFromTbMsg) { clusterService.pushMsgToRuleEngine(tenantId, msg.getOriginator(), msg, useQueueFromTbMsg, null); } private void scheduleTimeout(TbMsg request, UUID requestId, ConcurrentMap<UUID, Consumer<TbMsg>> requestsMap) { long expirationTime = Long.parseLong(request.getMetaData().getValue("expirationTime")); long timeout = Math.max(0, expirationTime - System.currentTimeMillis()); log.trace("[{}] processing the request: [{}]", this.hashCode(), requestId); executor.schedule(() -> { Consumer<TbMsg> consumer = requestsMap.remove(requestId); if (consumer != null) { log.trace("[{}] request timeout detected: [{}]", this.hashCode(), requestId); consumer.accept(null); } }, timeout, TimeUnit.MILLISECONDS); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ruleengine\DefaultRuleEngineCallService.java
2
请在Spring Boot框架中完成以下Java代码
public void requestAllUpdates() { convertAndSend(RabbitMQConfig.QUEUENAME_MSV3ServerRequests, MSV3ServerRequest.requestAll()); logger.info("Requested all data from MSV3 server peer"); } public void requestConfigUpdates() { convertAndSend(RabbitMQConfig.QUEUENAME_MSV3ServerRequests, MSV3ServerRequest.requestConfig()); logger.info("Requested config data from MSV3 server peer"); } public void publishUserChangedEvent(@NonNull final MSV3UserChangedBatchEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, event); } public void publishUserChangedEvent(@NonNull final MSV3UserChangedEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, MSV3UserChangedBatchEvent.builder() .event(event) .build()); } public void publishStockAvailabilityUpdatedEvent(@NonNull final MSV3StockAvailabilityUpdatedEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_StockAvailabilityUpdatedEvent, event);
} public void publishProductExcludes(@NonNull final MSV3ProductExcludesUpdateEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_ProductExcludeUpdatedEvents, event); } public void publishSyncOrderRequest(final MSV3OrderSyncRequest request) { convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderRequestEvents, request); } public void publishSyncOrderResponse(@NonNull final MSV3OrderSyncResponse response) { convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderResponseEvents, response); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\service\MSV3ServerPeerService.java
2
请完成以下Java代码
protected void initializeVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, BaseCallableElement callableElement) { ExpressionManager expressionManager = context.getExpressionManager(); String version = getVersion(element, activity, context); ParameterValueProvider versionProvider = createParameterValueProvider(version, expressionManager); callableElement.setVersionValueProvider(versionProvider); } protected void initializeTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, BaseCallableElement callableElement) { ParameterValueProvider tenantIdProvider = null; ExpressionManager expressionManager = context.getExpressionManager(); String tenantId = getTenantId(element, activity, context); if (tenantId != null && tenantId.length() > 0) { tenantIdProvider = createParameterValueProvider(tenantId, expressionManager); } callableElement.setTenantIdProvider(tenantIdProvider); } protected ParameterValueProvider createParameterValueProvider(String value, ExpressionManager expressionManager) { if (value == null) { return new NullValueProvider();
} else if (isCompositeExpression(value, expressionManager)) { Expression expression = expressionManager.createExpression(value); return new ElValueProvider(expression); } else { return new ConstantValueProvider(value); } } protected abstract BaseCallableElement createCallableElement(); protected abstract String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CallingTaskItemHandler.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getSettFee() { return settFee; } /** * 结算手续费 * * @param settFee */ public void setSettFee(BigDecimal settFee) { this.settFee = settFee; } /** * 结算打款金额 * * @return */ public BigDecimal getRemitAmount() { return remitAmount; } /** * 结算打款金额 * * @param remitAmount */ public void setRemitAmount(BigDecimal remitAmount) { this.remitAmount = remitAmount; } /** 结算状态(参考枚举:SettRecordStatusEnum) **/ public String getSettStatus() { return settStatus; } /** 结算状态(参考枚举:SettRecordStatusEnum) **/ public void setSettStatus(String settStatus) { this.settStatus = settStatus; } /** * 打款发送时间 * * @return */ public Date getRemitRequestTime() { return remitRequestTime; } /** * 打款发送时间 * * @param remitRequestTime */ public void setRemitRequestTime(Date remitRequestTime) { this.remitRequestTime = remitRequestTime; } /** * 打款确认时间 * * @return */ public Date getRemitConfirmTime() { return remitConfirmTime; } /** * 打款确认时间 * * @param remitConfirmTime */ public void setRemitConfirmTime(Date remitConfirmTime) { this.remitConfirmTime = remitConfirmTime; } /** * 打款备注 *
* @return */ public String getRemitRemark() { return remitRemark; } /** * 打款备注 * * @param remitRemark */ public void setRemitRemark(String remitRemark) { this.remitRemark = remitRemark == null ? null : remitRemark.trim(); } /** * 操作员登录名 * * @return */ public String getOperatorLoginname() { return operatorLoginname; } /** * 操作员登录名 * * @param operatorLoginname */ public void setOperatorLoginname(String operatorLoginname) { this.operatorLoginname = operatorLoginname == null ? null : operatorLoginname.trim(); } /** * 操作员姓名 * * @return */ public String getOperatorRealname() { return operatorRealname; } /** * 操作员姓名 * * @param operatorRealname */ public void setOperatorRealname(String operatorRealname) { this.operatorRealname = operatorRealname == null ? null : operatorRealname.trim(); } public String getSettStatusDesc() { return SettRecordStatusEnum.getEnum(this.getSettStatus()).getDesc(); } public String getCreateTimeDesc() { return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss"); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettRecord.java
2
请完成以下Java代码
private void processDocuments(final Iterator<GenericPO> documents, final String docAction) { while (documents.hasNext()) { final Object doc = documents.next(); trxManager.runInNewTrx(new TrxRunnable2() { @Override public void run(final String localTrxName) { InterfaceWrapperHelper.refresh(doc, localTrxName); docActionBL.processEx(doc, docAction, null); // expectedDocStatus=null because it is *not* always equal to the docAaction (Prepay-Order) addLog("Document " + doc + ": Processed"); countOK++; } @Override public boolean doCatch(final Throwable e)
{ final String msg = "Processing of document " + doc + ": Failed - ProccessMsg: " + documentBL.getDocument(doc).getProcessMsg() + "; ExceptionMsg: " + e.getMessage(); addLog(msg); log.warn(msg, e); countError++; return true; // rollback } @Override public void doFinally() { // nothing } }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\AbstractProcessDocumentsTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { return this.notSupportedFile(model, fileAttribute, "系统还不支持该格式文件的在线预览"); } /** * 通用的预览失败,导向到不支持的文件响应页面 * * @return 页面 */ public String notSupportedFile(Model model, FileAttribute fileAttribute, String errMsg) { return this.notSupportedFile(model, fileAttribute.getSuffix(), errMsg); } /** * 通用的预览失败,导向到不支持的文件响应页面 * * @return 页面 */ public String notSupportedFile(Model model, String errMsg) {
return this.notSupportedFile(model, "未知", errMsg); } /** * 通用的预览失败,导向到不支持的文件响应页面 * * @return 页面 */ public String notSupportedFile(Model model, String fileType, String errMsg) { model.addAttribute("fileType", KkFileUtils.htmlEscape(fileType)); model.addAttribute("msg", KkFileUtils.htmlEscape(errMsg)); return NOT_SUPPORTED_FILE_PAGE; } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\OtherFilePreviewImpl.java
2
请完成以下Java代码
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) { if (origin.length() == rotation.length()) { return checkPrefixAndSuffix(origin, rotation); } return false; } static boolean checkPrefixAndSuffix(String origin, String rotation) { if (origin.length() == rotation.length()) { for (int i = 0; i < origin.length(); i++) { if (origin.charAt(i) == rotation.charAt(0)) { if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) { if (checkOriginPrefixWithRotationSuffix(origin, rotation, i)) return true; }
} } } return false; } private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) { return origin.substring(i) .equals(rotation.substring(0, origin.length() - i)); } private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) { return origin.substring(0, i) .equals(rotation.substring(origin.length() - i)); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\stringrotation\StringRotation.java
1
请完成以下Java代码
public Boolean getGenerateUniqueProcessEngineName() { return generateUniqueProcessEngineName; } public void setGenerateUniqueProcessEngineName(Boolean generateUniqueProcessEngineName) { this.generateUniqueProcessEngineName = generateUniqueProcessEngineName; } public Boolean getGenerateUniqueProcessApplicationName() { return generateUniqueProcessApplicationName; } public void setGenerateUniqueProcessApplicationName(Boolean generateUniqueProcessApplicationName) { this.generateUniqueProcessApplicationName = generateUniqueProcessApplicationName; } @Override public String toString() { return joinOn(this.getClass()) .add("enabled=" + enabled) .add("processEngineName=" + processEngineName) .add("generateUniqueProcessEngineName=" + generateUniqueProcessEngineName) .add("generateUniqueProcessApplicationName=" + generateUniqueProcessApplicationName) .add("historyLevel=" + historyLevel)
.add("historyLevelDefault=" + historyLevelDefault) .add("autoDeploymentEnabled=" + autoDeploymentEnabled) .add("deploymentResourcePattern=" + Arrays.toString(deploymentResourcePattern)) .add("defaultSerializationFormat=" + defaultSerializationFormat) .add("licenseFile=" + licenseFile) .add("metrics=" + metrics) .add("database=" + database) .add("jobExecution=" + jobExecution) .add("webapp=" + webapp) .add("restApi=" + restApi) .add("authorization=" + authorization) .add("genericProperties=" + genericProperties) .add("adminUser=" + adminUser) .add("filter=" + filter) .add("idGenerator=" + idGenerator) .add("jobExecutorAcquireByPriority=" + jobExecutorAcquireByPriority) .add("defaultNumberOfRetries" + defaultNumberOfRetries) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CamundaBpmProperties.java
1
请完成以下Java代码
private synchronized void updateFromBusinessRulesRepository() { final BusinessRulesCollection rulesPrev = this.rules; this.rules = ruleService.getRules(); if (Objects.equals(this.rules, rulesPrev)) { return; } updateRegisteredInterceptors(); } private synchronized void updateRegisteredInterceptors() { final IModelValidationEngine engine = getEngine(); final BusinessRulesCollection rules = getRules(); final HashSet<String> registeredTableNamesNoLongerNeeded = new HashSet<>(registeredTableNames); for (final AdTableId triggerTableId : rules.getTriggerTableIds()) { final String triggerTableName = TableIdsCache.instance.getTableName(triggerTableId); registeredTableNamesNoLongerNeeded.remove(triggerTableName); if (registeredTableNames.contains(triggerTableName)) { // already registered continue; } engine.addModelChange(triggerTableName, this);
registeredTableNames.add(triggerTableName); logger.info("Registered trigger for {}", triggerTableName); } // // Remove no longer needed interceptors for (final String triggerTableName : registeredTableNamesNoLongerNeeded) { engine.removeModelChange(triggerTableName, this); registeredTableNames.remove(triggerTableName); logger.info("Unregistered trigger for {}", triggerTableName); } } @Override public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType modelChangeType) throws Exception { final TriggerTiming timing = TriggerTiming.ofModelChangeType(modelChangeType).orElse(null); if (timing == null) { return; } ruleService.fireTriggersForSourceModel(model, timing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\interceptor\BusinessRuleTriggerInterceptor.java
1
请完成以下Java代码
public class PermissionCheckBuilder { protected List<PermissionCheck> atomicChecks = new ArrayList<PermissionCheck>(); protected List<CompositePermissionCheck> compositeChecks = new ArrayList<CompositePermissionCheck>(); protected boolean disjunctive = true; protected PermissionCheckBuilder parent; public PermissionCheckBuilder() { } public PermissionCheckBuilder(PermissionCheckBuilder parent) { this.parent = parent; } public PermissionCheckBuilder disjunctive() { this.disjunctive = true; return this; } public PermissionCheckBuilder conjunctive() { this.disjunctive = false; return this; } public PermissionCheckBuilder atomicCheck(Resource resource, String queryParam, Permission permission) { if (!isPermissionDisabled(permission)) { PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceIdQueryParam(queryParam); permCheck.setPermission(permission); this.atomicChecks.add(permCheck); } return this; } public PermissionCheckBuilder atomicCheckForResourceId(Resource resource, String resourceId, Permission permission) { if (!isPermissionDisabled(permission)) { PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceId(resourceId); permCheck.setPermission(permission); this.atomicChecks.add(permCheck); } return this; } public PermissionCheckBuilder composite() { return new PermissionCheckBuilder(this); } public PermissionCheckBuilder done() { parent.compositeChecks.add(this.build());
return parent; } public CompositePermissionCheck build() { validate(); CompositePermissionCheck permissionCheck = new CompositePermissionCheck(disjunctive); permissionCheck.setAtomicChecks(atomicChecks); permissionCheck.setCompositeChecks(compositeChecks); return permissionCheck; } public List<PermissionCheck> getAtomicChecks() { return atomicChecks; } protected void validate() { if (!atomicChecks.isEmpty() && !compositeChecks.isEmpty()) { throw new ProcessEngineException("Mixed authorization checks of atomic and composite permissions are not supported"); } } public boolean isPermissionDisabled(Permission permission) { AuthorizationManager authorizationManager = Context.getCommandContext().getAuthorizationManager(); return authorizationManager.isPermissionDisabled(permission); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheckBuilder.java
1
请完成以下Java代码
private IQueryBuilder<I_C_POS_Order> toSqlQuery(final POSOrderQuery query) { final IQueryBuilder<I_C_POS_Order> sqlQueryBuilder = queryBL.createQueryBuilder(I_C_POS_Order.class) .addEqualsFilter(I_C_POS_Order.COLUMNNAME_C_POS_ID, query.getPosTerminalId()) .addEqualsFilter(I_C_POS_Order.COLUMNNAME_Cashier_ID, query.getCashierId()); if (query.isOpen()) { sqlQueryBuilder.addInArrayFilter(I_C_POS_Order.COLUMNNAME_Status, POSOrderStatus.OPEN_STATUSES); } final Set<POSOrderExternalId> onlyOrderExternalIds = query.getOnlyOrderExternalIds(); if (onlyOrderExternalIds != null && !onlyOrderExternalIds.isEmpty()) { sqlQueryBuilder.addInArrayFilter(I_C_POS_Order.COLUMNNAME_ExternalId, POSOrderExternalId.toStringSet(onlyOrderExternalIds)); } return sqlQueryBuilder; } public POSOrder getById(@NonNull final POSOrderId posOrderId) { return newLoaderAndSaver().getById(posOrderId); } public POSOrder updateByExternalId(final @NonNull POSOrderExternalId externalId, final @NonNull Consumer<POSOrder> updater) { return createOrUpdateByExternalId( externalId, externalId0 -> { throw new AdempiereException("No order found for external id " + externalId); }, updater); } public POSOrder createOrUpdateByExternalId( @NonNull final POSOrderExternalId externalId, @NonNull final Function<POSOrderExternalId, POSOrder> factory, @NonNull final Consumer<POSOrder> updater)
{ return trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().createOrUpdateByExternalId(externalId, factory, updater)); } public void updateById(@NonNull final POSOrderId id, @NonNull final Consumer<POSOrder> updater) { trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().updateById(id, updater)); } public void updatePaymentById(@NonNull final POSOrderAndPaymentId orderAndPaymentId, @NonNull final BiFunction<POSOrder, POSPayment, POSPayment> updater) { updateById(orderAndPaymentId.getOrderId(), order -> order.updatePaymentById(orderAndPaymentId.getPaymentId(), payment -> updater.apply(order, payment))); } public POSOrderId getIdByExternalId(final @NonNull POSOrderExternalId externalId) { return newLoaderAndSaver().getIdByExternalId(externalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrdersRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ScriptType { public static ScriptType ofFileExtension(final String fileExtension) { return scriptTypesByFileExtension.computeIfAbsent( normalizeFileExtension(fileExtension), ScriptType::new); } public static final ScriptType NONE = new ScriptType(""); public static final ScriptType SQL = new ScriptType("sql"); private static final Map<String, ScriptType> scriptTypesByFileExtension = new HashMap<>(); static { scriptTypesByFileExtension.put(NONE.getFileExtension(), NONE); scriptTypesByFileExtension.put(SQL.getFileExtension(), SQL); }
private final String fileExtension; private ScriptType(@NonNull final String fileExtension) { this.fileExtension = normalizeFileExtension(fileExtension); } private static final String normalizeFileExtension(final String fileExtension) { if (fileExtension == null) { return ""; } return fileExtension.trim().toLowerCase(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\ScriptType.java
2
请完成以下Java代码
public List<int[][]> generate(int minLength, int maxLength, int size) { List<int[][]> samples = new ArrayList<int[][]>(size); for (int i = 0; i < size; i++) { samples.add(generate((int) (Math.floor(Math.random() * (maxLength - minLength)) + minLength))); } return samples; } /** * 预测(维特比算法) * * @param o 观测序列 * @param s 预测状态序列(需预先分配内存) * @return 概率的对数,可利用 (float) Math.exp(maxScore) 还原 */ public abstract float predict(int[] o, int[] s); /** * 预测(维特比算法) * * @param o 观测序列 * @param s 预测状态序列(需预先分配内存) * @return 概率的对数,可利用 (float) Math.exp(maxScore) 还原 */ public float predict(int[] o, Integer[] s) { int[] states = new int[s.length]; float p = predict(o, states); for (int i = 0; i < states.length; i++) { s[i] = states[i]; } return p; } public boolean similar(HiddenMarkovModel model) { if (!similar(start_probability, model.start_probability)) return false; for (int i = 0; i < transition_probability.length; i++) { if (!similar(transition_probability[i], model.transition_probability[i])) return false; if (!similar(emission_probability[i], model.emission_probability[i])) return false; } return true;
} protected static boolean similar(float[] A, float[] B) { final float eta = 1e-2f; for (int i = 0; i < A.length; i++) if (Math.abs(A[i] - B[i]) > eta) return false; return true; } protected static Object deepCopy(Object object) { if (object == null) { return null; } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); oos.close(); bos.close(); byte[] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); return new ObjectInputStream(bais).readObject(); } catch (Exception e) { throw new RuntimeException(e); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HiddenMarkovModel.java
1
请完成以下Java代码
public void setpackingmaterialname (java.lang.String packingmaterialname) { set_ValueNoCheck (COLUMNNAME_packingmaterialname, packingmaterialname); } /** Get packingmaterialname. @return packingmaterialname */ @Override public java.lang.String getpackingmaterialname () { return (java.lang.String)get_Value(COLUMNNAME_packingmaterialname); } /** Set Standardpreis. @param PriceStd Standardpreis */ @Override public void setPriceStd (java.math.BigDecimal PriceStd) { set_ValueNoCheck (COLUMNNAME_PriceStd, PriceStd); } /** Get Standardpreis. @return Standardpreis */ @Override public java.math.BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Produktname. @param ProductName Name des Produktes */ @Override public void setProductName (java.lang.String ProductName) { set_ValueNoCheck (COLUMNNAME_ProductName, ProductName); } /** Get Produktname. @return Name des Produktes */ @Override public java.lang.String getProductName () { return (java.lang.String)get_Value(COLUMNNAME_ProductName); } /** Set Produktschlüssel. @param ProductValue
Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (java.lang.String SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public java.lang.String getSeqNo () { return (java.lang.String)get_Value(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_M_PriceList_V.java
1
请在Spring Boot框架中完成以下Java代码
public Inventory complete(Inventory inventory) { final InventoryId inventoryId = inventory.getId(); inventoryService.completeDocument(inventoryId); return inventoryService.getById(inventory.getId()); } public LocatorScannedCodeResolverResult resolveLocator( @NonNull ScannedCode scannedCode, @NonNull WFProcessId wfProcessId, @Nullable InventoryLineId lineId, @NonNull UserId callerId) { final Inventory inventory = getById(wfProcessId, callerId); final Set<LocatorId> eligibleLocatorIds = inventory.getLocatorIdsEligibleForCounting(lineId); if (eligibleLocatorIds.isEmpty()) { return LocatorScannedCodeResolverResult.notFound(LocatorGlobalQRCodeResolverKey.ofString("InventoryJobService"), "no such locator in current inventory"); } return warehouseService.resolveLocator( LocatorScannedCodeResolverRequest.builder() .scannedCode(scannedCode) .context(LocatorScannedCodeResolveContext.builder() .eligibleLocatorIds(eligibleLocatorIds) .build()) .build() ); } public ResolveHUResponse resolveHU(@NonNull final ResolveHURequest request) { return newHUScannedCodeResolveCommand() .scannedCode(request.getScannedCode()) .inventory(getById(request.getWfProcessId(), request.getCallerId())) .lineId(request.getLineId()) .locatorId(request.getLocatorId()) .build() .execute();
} private ResolveHUCommandBuilder newHUScannedCodeResolveCommand() { return ResolveHUCommand.builder() .productService(productService) .huService(huService); } public Inventory reportCounting(@NonNull final JsonCountRequest request, final UserId callerId) { final InventoryId inventoryId = toInventoryId(request.getWfProcessId()); return inventoryService.updateById(inventoryId, inventory -> { inventory.assertHasAccess(callerId); return inventory.updatingLineById(request.getLineId(), line -> { // TODO handle the case when huId is null final Quantity qtyBook = huService.getQty(request.getHuId(), line.getProductId()); final Quantity qtyCount = Quantity.of(request.getQtyCount(), qtyBook.getUOM()); return line.withCounting(InventoryLineCountRequest.builder() .huId(request.getHuId()) .scannedCode(request.getScannedCode()) .qtyBook(qtyBook) .qtyCount(qtyCount) .asiId(productService.createASI(line.getProductId(), request.getAttributesAsMap())) .build()); }); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\job\service\InventoryJobService.java
2
请完成以下Java代码
public CalloutException setCalloutInstance(final ICalloutInstance calloutInstance) { this.calloutInstance = calloutInstance; setParameter("calloutInstance", calloutInstance); return this; } public CalloutException setCalloutInstanceIfAbsent(final ICalloutInstance calloutInstance) { if (this.calloutInstance == null) { setCalloutInstance(calloutInstance); } return this; } public CalloutException setCalloutExecutor(final ICalloutExecutor calloutExecutor) { this.calloutExecutor = calloutExecutor; return this; } public CalloutException setCalloutExecutorIfAbsent(final ICalloutExecutor calloutExecutor) { if (this.calloutExecutor == null) { setCalloutExecutor(calloutExecutor); } return this; } public CalloutException setField(final ICalloutField field) { this.field = field; setParameter("field", field);
return this; } public CalloutException setFieldIfAbsent(final ICalloutField field) { if (this.field == null) { setField(field); } return this; } public ICalloutField getCalloutField() { return field; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\exceptions\CalloutException.java
1
请完成以下Java代码
public ResponseEntity<JsonError> handlePageNotFoundException(@NonNull final PageNotFoundException e) { return logAndCreateError(e, HttpStatus.NOT_FOUND); } @ExceptionHandler(PermissionNotGrantedException.class) public ResponseEntity<JsonError> handlePermissionNotGrantedException(@NonNull final PermissionNotGrantedException e) { return logAndCreateError(e, HttpStatus.FORBIDDEN); } @ExceptionHandler(MissingPropertyException.class) public ResponseEntity<JsonError> handleMissingPropertyException(@NonNull final MissingPropertyException e) { return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(MissingResourceException.class) public ResponseEntity<JsonError> handleMissingResourceException(@NonNull final MissingResourceException e) { return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(InvalidIdentifierException.class) public ResponseEntity<JsonError> InvalidIdentifierException(@NonNull final InvalidIdentifierException e) { final String msg = "Invalid identifier: " + e.getMessage(); final HttpStatus status = e.getMessage().startsWith("tea") ? HttpStatus.I_AM_A_TEAPOT // whohoo, finally found a reason! : HttpStatus.NOT_FOUND; return logAndCreateError( e, msg, status); } @ExceptionHandler(DBUniqueConstraintException.class) public ResponseEntity<JsonError> handleDBUniqueConstraintException(@NonNull final DBUniqueConstraintException e) { return logAndCreateError( e, "At least one record already existed in the system:" + e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(Exception.class) public ResponseEntity<JsonError> handleException(@NonNull final Exception e) { final ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class); if (responseStatus != null) { return logAndCreateError(e, responseStatus.reason(), responseStatus.code()); } return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY); }
private ResponseEntity<JsonError> logAndCreateError( @NonNull final Exception e, @NonNull final HttpStatus status) { return logAndCreateError(e, null, status); } private ResponseEntity<JsonError> logAndCreateError( @NonNull final Exception e, @Nullable final String detail, @NonNull final HttpStatus status) { final String logMessage = coalesceSuppliers( () -> detail, e::getMessage, () -> e.getClass().getSimpleName()); Loggables.withFallbackToLogger(logger, Level.ERROR).addLog(logMessage, e); final String adLanguage = Env.getADLanguageOrBaseLanguage(); final JsonError error = JsonError.builder() .error(JsonErrors.ofThrowable(e, adLanguage, TranslatableStrings.constant(detail))) .build(); return new ResponseEntity<>(error, status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\RestResponseEntityExceptionHandler.java
1
请完成以下Java代码
default String getGender() { return this.getClaimAsString(StandardClaimNames.GENDER); } /** * Returns the user's birth date {@code (birthdate)}. * @return the user's birth date */ default String getBirthdate() { return this.getClaimAsString(StandardClaimNames.BIRTHDATE); } /** * Returns the user's time zone {@code (zoneinfo)}. * @return the user's time zone */ default String getZoneInfo() { return this.getClaimAsString(StandardClaimNames.ZONEINFO); } /** * Returns the user's locale {@code (locale)}. * @return the user's locale */ default String getLocale() { return this.getClaimAsString(StandardClaimNames.LOCALE); } /** * Returns the user's preferred phone number {@code (phone_number)}. * @return the user's preferred phone number */ default String getPhoneNumber() { return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER); } /** * Returns {@code true} if the user's phone number has been verified * {@code (phone_number_verified)}, otherwise {@code false}. * @return {@code true} if the user's phone number has been verified, otherwise * {@code false}
*/ default Boolean getPhoneNumberVerified() { return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED); } /** * Returns the user's preferred postal address {@code (address)}. * @return the user's preferred postal address */ default AddressStandardClaim getAddress() { Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS); return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build() : new DefaultAddressStandardClaim.Builder().build()); } /** * Returns the time the user's information was last updated {@code (updated_at)}. * @return the time the user's information was last updated */ default Instant getUpdatedAt() { return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
1
请在Spring Boot框架中完成以下Java代码
public class AppController { private EndpointRefreshConfigBean endpointRefreshConfigBean; private EnvironmentConfigBean environmentConfigBean; @Autowired public AppController(EndpointRefreshConfigBean endpointRefreshConfigBean, EnvironmentConfigBean environmentConfigBean) { this.endpointRefreshConfigBean = endpointRefreshConfigBean; this.environmentConfigBean = environmentConfigBean; } @GetMapping("/foo") public ResponseEntity<String> fooHandler() { if (endpointRefreshConfigBean.isFoo()) { return ResponseEntity.status(200) .body("foo"); } else { return ResponseEntity.status(503) .body("endpoint is unavailable"); } } @GetMapping("/bar1") public String bar1Handler() { return "bar1"; }
@GetMapping("/bar2") public String bar2Handler() { return "bar2"; } @Bean @ConditionalOnBean(EnvironmentConfigBean.class) public FilterRegistrationBean<DynamicEndpointFilter> dynamicEndpointFilterFilterRegistrationBean(EnvironmentConfigBean environmentConfigBean) { FilterRegistrationBean<DynamicEndpointFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new DynamicEndpointFilter(environmentConfigBean.getEnvironment())); registrationBean.addUrlPatterns("*"); return registrationBean; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-5\src\main\java\com\baeldung\dynamicendpoints\controller\AppController.java
2
请完成以下Java代码
public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getHouseNumber() { return houseNumber; } public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCaptcha() { return captcha; } public void setCaptcha(String captcha) { this.captcha = captcha; } }
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\validationgroup\RegistrationForm.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteJob(JobForm form) throws SchedulerException { scheduler.pauseTrigger(TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName())); scheduler.unscheduleJob(TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName())); scheduler.deleteJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName())); } /** * 暂停定时任务 * * @param form 表单参数 {@link JobForm} * @throws SchedulerException 异常 */ @Override public void pauseJob(JobForm form) throws SchedulerException { scheduler.pauseJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName())); } /** * 恢复定时任务 * * @param form 表单参数 {@link JobForm} * @throws SchedulerException 异常 */ @Override public void resumeJob(JobForm form) throws SchedulerException { scheduler.resumeJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName())); } /** * 重新配置定时任务 * * @param form 表单参数 {@link JobForm} * @throws Exception 异常 */ @Override public void cronJob(JobForm form) throws Exception { try { TriggerKey triggerKey = TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName()); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(form.getCronExpression());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 根据Cron表达式构建一个Trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); // 按新的trigger重新设置job执行 scheduler.rescheduleJob(triggerKey, trigger); } catch (SchedulerException e) { log.error("【定时任务】更新失败!", e); throw new Exception("【定时任务】创建失败!"); } } /** * 查询定时任务列表 * * @param currentPage 当前页 * @param pageSize 每页条数 * @return 定时任务列表 */ @Override public PageInfo<JobAndTrigger> list(Integer currentPage, Integer pageSize) { PageHelper.startPage(currentPage, pageSize); List<JobAndTrigger> list = jobMapper.list(); return new PageInfo<>(list); } }
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\service\impl\JobServiceImpl.java
2
请完成以下Java代码
private boolean isESIndexExists(final FTSConfig config) throws IOException { return configService.elasticsearchClient() .indices() .exists(new GetIndexRequest(config.getEsIndexName()), RequestOptions.DEFAULT); } private void createESIndex(final FTSConfig config) throws IOException { configService.elasticsearchClient() .indices() .create(new CreateIndexRequest(config.getEsIndexName()) .source(config.getCreateIndexCommand().getAsString(), XContentType.JSON), RequestOptions.DEFAULT); } private void addDocumentsToIndex( @NonNull final FTSConfig config, @NonNull final List<ESDocumentToIndexChunk> chunks) throws IOException { for (final ESDocumentToIndexChunk chunk : chunks) { addDocumentsToIndex(config, chunk); } } private void addDocumentsToIndex( @NonNull final FTSConfig config, @NonNull final ESDocumentToIndexChunk chunk) throws IOException { final RestHighLevelClient elasticsearchClient = configService.elasticsearchClient(); final String esIndexName = config.getEsIndexName(); final BulkRequest bulkRequest = new BulkRequest(); for (final String documentIdToDelete : chunk.getDocumentIdsToDelete()) { bulkRequest.add(new DeleteRequest(esIndexName) .id(documentIdToDelete)); } for (final ESDocumentToIndex documentToIndex : chunk.getDocumentsToIndex()) { bulkRequest.add(new IndexRequest(esIndexName) .id(documentToIndex.getDocumentId()) .source(documentToIndex.getJson(), XContentType.JSON)); } if (bulkRequest.numberOfActions() > 0) { elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT); } } @ToString
private static class ConfigAndEvents { @Getter private final FTSConfig config; @Getter private final ImmutableSet<TableName> sourceTableNames; private final ArrayList<ModelToIndex> events = new ArrayList<>(); private ConfigAndEvents( @NonNull final FTSConfig config, @NonNull final ImmutableSet<TableName> sourceTableNames) { this.config = config; this.sourceTableNames = sourceTableNames; } public void addEvent(final ModelToIndex event) { if (!events.contains(event)) { events.add(event); } } public ImmutableList<ModelToIndex> getEvents() { return ImmutableList.copyOf(events); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelToIndexEnqueueProcessor.java
1
请完成以下Java代码
public Object getValueAt(final int rowIndexView, final String columnName) { final int colIndexModel = getColumnModelIndex(columnName); if (colIndexModel < 0) // it starts with 0, not with 1, so it's <0, not <=0 { throw new IllegalArgumentException("No column index found for " + columnName); } final int rowIndexModel = convertRowIndexToModel(rowIndexView); return getModel().getValueAt(rowIndexModel, colIndexModel); } public void setValueAt(final Object value, final int rowIndexView, final String columnName) { final int colIndexModel = getColumnModelIndex(columnName);
if (colIndexModel <= 0) { throw new IllegalArgumentException("No column index found for " + columnName); } final int rowIndexModel = convertRowIndexToModel(rowIndexView); getModel().setValueAt(value, rowIndexModel, colIndexModel); } @Override public void clear() { final PO[] pos = new PO[] {}; loadTable(pos); } } // MiniTable
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\MiniTable.java
1
请完成以下Java代码
default void addPostProcessor(ConsumerPostProcessor<K, V> postProcessor) { } /** * Remove a post processor. * @param postProcessor the post processor. * @return true if removed. * @since 2.5.3 */ default boolean removePostProcessor(ConsumerPostProcessor<K, V> postProcessor) { return false; } /** * Get the current list of post processors. * @return the post processor. * @since 2.5.3 */ default List<ConsumerPostProcessor<K, V>> getPostProcessors() { return Collections.emptyList(); } /** * Update the consumer configuration map; useful for situations such as * credential rotation. * @param updates the configuration properties to update. * @since 2.7 */ default void updateConfigs(Map<String, Object> updates) { } /** * Remove the specified key from the configuration map. * @param configKey the key to remove. * @since 2.7 */
default void removeConfig(String configKey) { } /** * Called whenever a consumer is added or removed. * * @param <K> the key type. * @param <V> the value type. * * @since 2.5 * */ interface Listener<K, V> { /** * A new consumer was created. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer. */ default void consumerAdded(String id, Consumer<K, V> consumer) { } /** * An existing consumer was removed. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer. */ default void consumerRemoved(@Nullable String id, Consumer<K, V> consumer) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ConsumerFactory.java
1
请在Spring Boot框架中完成以下Java代码
private PortMapper getPortMapper() { if (this.portMapper == null) { PortMapperImpl portMapper = new PortMapperImpl(); portMapper.setPortMappings(this.httpsPortMappings); this.portMapper = portMapper; } return this.portMapper; } /** * Allows specifying the HTTPS port for a given HTTP port when redirecting between * HTTP and HTTPS. * * @author Rob Winch * @since 3.2 */ public final class HttpPortMapping { private final int httpPort; /** * Creates a new instance * @param httpPort * @see PortMapperConfigurer#http(int) */
private HttpPortMapping(int httpPort) { this.httpPort = httpPort; } /** * Maps the given HTTP port to the provided HTTPS port and vice versa. * @param httpsPort the HTTPS port to map to * @return the {@link PortMapperConfigurer} for further customization */ public PortMapperConfigurer<H> mapsTo(int httpsPort) { PortMapperConfigurer.this.httpsPortMappings.put(String.valueOf(this.httpPort), String.valueOf(httpsPort)); return PortMapperConfigurer.this; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\PortMapperConfigurer.java
2
请完成以下Java代码
public DataEntryRecordsMap get( final int recordId, @NonNull final Set<DataEntrySubTabId> subTabIds) { Check.assumeGreaterOrEqualToZero(recordId, "recordId"); Check.assumeNotEmpty(subTabIds, "subTabIds is not empty"); final Collection<DataEntryRecord> records = cache.getAllOrLoad(toCacheKeys(recordId, subTabIds), this::loadRecords); return DataEntryRecordsMap.of(records); } private static Set<CacheKey> toCacheKeys( final int recordId, @NonNull final Set<DataEntrySubTabId> subTabIds) { return subTabIds.stream() .map(subTabId -> CacheKey.of(recordId, subTabId)) .collect(ImmutableSet.toImmutableSet()); } private Map<CacheKey, DataEntryRecord> loadRecords(final Collection<CacheKey> keys) { final DataEntryRecordQuery query = toDataEntryRecordQuery(keys); final List<DataEntryRecord> records = recordsRepo.stream(query) .map(DataEntryRecord::copyAsImmutable) .collect(ImmutableList.toImmutableList()); if (records.isEmpty()) { return ImmutableMap.of(); } final Map<CacheKey, DataEntryRecord> recordsMap = Maps.uniqueIndex( records, record -> CollectionUtils.singleElement(cacheIndex.extractCacheKeys(record))); return recordsMap; } private static DataEntryRecordQuery toDataEntryRecordQuery(final Collection<CacheKey> keys) { final int mainRecordId = CollectionUtils.extractSingleElement(keys, CacheKey::getMainRecordId); final ImmutableSet<DataEntrySubTabId> subTabIds = extractSubTabIds(keys); return DataEntryRecordQuery.builder() .dataEntrySubTabIds(subTabIds) .recordId(mainRecordId) .build(); } private static ImmutableSet<DataEntrySubTabId> extractSubTabIds(final Collection<CacheKey> keys) { final ImmutableSet<DataEntrySubTabId> subTabIds = keys.stream() .map(CacheKey::getSubTabId) .collect(ImmutableSet.toImmutableSet()); return subTabIds; } @VisibleForTesting int getDataEntryRecordIdIndexSize() { return cacheIndex.size(); }
@Value(staticConstructor = "of") private static final class CacheKey { int mainRecordId; DataEntrySubTabId subTabId; } @ToString @VisibleForTesting static final class DataEntryRecordIdIndex implements CacheIndexDataAdapter<DataEntryRecordId, CacheKey, DataEntryRecord> { @Override public DataEntryRecordId extractDataItemId(final DataEntryRecord dataItem) { return dataItem.getId().get(); } @Override public ImmutableSet<TableRecordReference> extractRecordRefs(final DataEntryRecord dataItem) { final DataEntryRecordId id = dataItem.getId().orElse(null); return id != null ? ImmutableSet.of(TableRecordReference.of(I_DataEntry_Record.Table_Name, id)) : ImmutableSet.of(); } @Override public List<CacheKey> extractCacheKeys(final DataEntryRecord dataItem) { final CacheKey singleCacheKey = CacheKey.of(dataItem.getMainRecord().getRecord_ID(), dataItem.getDataEntrySubTabId()); return ImmutableList.of(singleCacheKey); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRecordCache.java
1
请在Spring Boot框架中完成以下Java代码
public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public Duration getLockDuration() { return lockDuration; } public void setLockDuration(Duration lockDuration) { this.lockDuration = lockDuration; } public int getNumberOfTasks() { return numberOfTasks; } public void setNumberOfTasks(int numberOfTasks) { this.numberOfTasks = numberOfTasks; } public int getNumberOfRetries() { return numberOfRetries; }
public void setNumberOfRetries(int numberOfRetries) { this.numberOfRetries = numberOfRetries; } public String getWorkerId() { return workerId; } public void setWorkerId(String workerId) { this.workerId = workerId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\AcquireExternalWorkerJobRequest.java
2
请完成以下Java代码
protected Date getPlanItemInstanceEndTime(List<HistoricPlanItemInstance> planItemInstances, PlanItemDefinition planItemDefinition) { return getPlanItemInstance(planItemInstances, planItemDefinition) .map(HistoricPlanItemInstance::getEndedTime) .orElse(null); } protected Optional<HistoricPlanItemInstance> getPlanItemInstance(List<HistoricPlanItemInstance> planItemInstances, PlanItemDefinition planItemDefinition) { HistoricPlanItemInstance planItemInstance = null; for (HistoricPlanItemInstance p : planItemInstances) { if (p.getPlanItemDefinitionId().equals(planItemDefinition.getId())) { if (p.getEndedTime() == null) { planItemInstance = p; // one that's not ended yet has precedence } else if (planItemInstance == null) { planItemInstance = p; } } } return Optional.ofNullable(planItemInstance); } protected class OverviewElement { protected String id; protected String name; protected Integer displayOrder; protected String includeInStageOverview; protected PlanItemDefinition planItemDefinition; public OverviewElement(String id, String name, Integer displayOrder, String includeInStageOverview, PlanItemDefinition planItemDefinition) { this.id = id; this.name = name; this.displayOrder = displayOrder; this.includeInStageOverview = includeInStageOverview; this.planItemDefinition = planItemDefinition; } public String getId() { return id;
} public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getDisplayOrder() { return displayOrder; } public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder; } public String getIncludeInStageOverview() { return includeInStageOverview; } public void setIncludeInStageOverview(String includeInStageOverview) { this.includeInStageOverview = includeInStageOverview; } public PlanItemDefinition getPlanItemDefinition() { return planItemDefinition; } public void setPlanItemDefinition(PlanItemDefinition planItemDefinition) { this.planItemDefinition = planItemDefinition; } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetHistoricStageOverviewCmd.java
1
请完成以下Java代码
protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) { Object value = record.value(); if (value == null) { return KafkaNull.INSTANCE; } Class<?> rawType = ResolvableType.forType(type).resolve(Object.class); if (!rawType.isInterface()) { return this.delegate.extractAndConvertValue(record, type); } InputStream inputStream = new ByteArrayInputStream(getAsByteArray(value)); // The inputStream is closed underneath by the ObjectMapper#_readTreeAndClose() return this.projectionFactory.createProjection(rawType, inputStream); } /** * Return the given source value as byte array. * @param source must not be {@literal null}.
* @return the source instance as byte array. */ private static byte[] getAsByteArray(Object source) { Assert.notNull(source, "Source must not be null"); if (source instanceof String) { return ((String) source).getBytes(StandardCharsets.UTF_8); } if (source instanceof byte[]) { return (byte[]) source; } if (source instanceof Bytes) { return ((Bytes) source).get(); } throw new ConversionException(String.format( "Unsupported payload type '%s'. Expected 'String', 'Bytes', or 'byte[]'", source.getClass()), null); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\ProjectingMessageConverter.java
1
请在Spring Boot框架中完成以下Java代码
public RepositoryDetectionStrategies getDetectionStrategy() { return this.detectionStrategy; } public void setDetectionStrategy(RepositoryDetectionStrategies detectionStrategy) { this.detectionStrategy = detectionStrategy; } public @Nullable MediaType getDefaultMediaType() { return this.defaultMediaType; } public void setDefaultMediaType(@Nullable MediaType defaultMediaType) { this.defaultMediaType = defaultMediaType; } public @Nullable Boolean getReturnBodyOnCreate() { return this.returnBodyOnCreate; } public void setReturnBodyOnCreate(@Nullable Boolean returnBodyOnCreate) { this.returnBodyOnCreate = returnBodyOnCreate; } public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate; } public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate; } public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; } public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) {
this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) { PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Logbook compositesink() { CompositeSink comsink = new CompositeSink(Arrays.asList(new CommonsLogFormatSink(new DefaultHttpLogWriter()), new ExtendedLogFormatSink( new DefaultHttpLogWriter()))); Logbook logbook = Logbook.builder() .sink(comsink) .build(); return logbook; } // to run logstash example set spring.profiles.active=logbooklogstash in application.properties and enable following bean disabling all others //@Bean public Logbook logstashsink() { HttpLogFormatter formatter = new JsonHttpLogFormatter(); LogstashLogbackSink logstashsink = new LogstashLogbackSink(formatter, Level.INFO); Logbook logbook = Logbook.builder() .sink(logstashsink) .build(); return logbook; }
//@Bean public Logbook commonLogFormat() { Logbook logbook = Logbook.builder() .sink(new CommonsLogFormatSink(new DefaultHttpLogWriter())) .build(); return logbook; } //@Bean public Logbook extendedLogFormat() { Logbook logbook = Logbook.builder() .sink(new ExtendedLogFormatSink(new DefaultHttpLogWriter())) .build(); return logbook; } }
repos\tutorials-master\spring-boot-modules\spring-boot-logging-logback\src\main\java\com\baeldung\logbookconfig\LogBookConfig.java
2
请完成以下Java代码
public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }
public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\reactive\model\Employee.java
1
请完成以下Java代码
public int getUOMPrecision() { return getProduct().getUOMPrecision(); } // getUOMPrecision /************************************************************************** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MDistributionRunLine[") .append(get_ID()).append("-") .append(getInfo()) .append ("]"); return sb.toString (); } // toString /**
* Get Info * @return info */ public String getInfo() { StringBuffer sb = new StringBuffer (); sb.append("Line=").append(getLine()) .append (",TotalQty=").append(getTotalQty()) .append(",SumMin=").append(getActualMin()) .append(",SumQty=").append(getActualQty()) .append(",SumAllocation=").append(getActualAllocation()) .append(",MaxAllocation=").append(getMaxAllocation()) .append(",LastDiff=").append(getLastDifference()); return sb.toString (); } // getInfo } // MDistributionRunLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRunLine.java
1
请完成以下Java代码
public int getFrom_Product_ID() { return get_ValueAsInt(COLUMNNAME_From_Product_ID); } @Override public void setMatured_Product_ID (final int Matured_Product_ID) { if (Matured_Product_ID < 1) set_Value (COLUMNNAME_Matured_Product_ID, null); else set_Value (COLUMNNAME_Matured_Product_ID, Matured_Product_ID); } @Override public int getMatured_Product_ID() { return get_ValueAsInt(COLUMNNAME_Matured_Product_ID); } @Override public void setMaturityAge (final int MaturityAge) { set_Value (COLUMNNAME_MaturityAge, MaturityAge); } @Override public int getMaturityAge() { return get_ValueAsInt(COLUMNNAME_MaturityAge); } @Override public org.compiere.model.I_M_Maturing_Configuration getM_Maturing_Configuration() { return get_ValueAsPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class); } @Override public void setM_Maturing_Configuration(final org.compiere.model.I_M_Maturing_Configuration M_Maturing_Configuration) { set_ValueFromPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class, M_Maturing_Configuration); } @Override public void setM_Maturing_Configuration_ID (final int M_Maturing_Configuration_ID) { if (M_Maturing_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, M_Maturing_Configuration_ID);
} @Override public int getM_Maturing_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_ID); } @Override public void setM_Maturing_Configuration_Line_ID (final int M_Maturing_Configuration_Line_ID) { if (M_Maturing_Configuration_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, M_Maturing_Configuration_Line_ID); } @Override public int getM_Maturing_Configuration_Line_ID() { return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_Line_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Maturing_Configuration_Line.java
1
请完成以下Java代码
public T forget() { // https://github.com/metasfresh/metasfresh-webui-api/issues/787 - similar to the code of get(); // if the instance known to not be initialized // then don't attempt to acquire lock (and to other time consuming stuff..) if (initialized) { synchronized (this) { if (initialized) { final T valueOld = this.value; initialized = false; value = null; return valueOld; } } }
return null; } /** * @return true if this supplier has a value memorized */ public boolean isInitialized() { return initialized; } @Override public String toString() { return "ExtendedMemorizingSupplier[" + delegate + "]"; } private static final long serialVersionUID = 0; }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\ExtendedMemorizingSupplier.java
1
请完成以下Java代码
public class C_Invoice_Candidate { /** * Set the IC's <code>QtyEnteredTU</code> from either the referenced object or order line (if available). * * @param ic */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void updateQtyEnteredTU(final I_C_Invoice_Candidate ic) { final Set<Integer> seenIOLs = new HashSet<>(); final BigDecimal qtyEnteredTU; if (TableRecordCacheLocal.isChildModelType(ic, I_M_InOutLine.class)) // if it's 1-to-1 with shipment line, use the Record_ID { final I_M_InOutLine iol = TableRecordCacheLocal.getReferencedValue(ic, I_M_InOutLine.class); if (!Services.get(IDocumentBL.class).isDocumentCompletedOrClosed(iol.getM_InOut())) { qtyEnteredTU = BigDecimal.ZERO; } else if (iol.isPackagingMaterial()) { qtyEnteredTU = iol.getQtyEntered(); // the bound line is the PM line } else { qtyEnteredTU = iol.getQtyEnteredTU(); } } else if (ic.getC_OrderLine_ID() > 0) { qtyEnteredTU = getOrderLineQtyEnteredTU(ic, seenIOLs); } else { qtyEnteredTU = BigDecimal.ZERO; } ic.setQtyEnteredTU(qtyEnteredTU); } /** * @param ic * @param seenIOLs * @return shipped TU qty or ordered (if nothing was shipped) */ private final BigDecimal getOrderLineQtyEnteredTU(final I_C_Invoice_Candidate ic, final Set<Integer> seenIOLs) { BigDecimal qtyEnteredTU = BigDecimal.ZERO; final List<I_M_InOutLine> iols = Services.get(IInvoiceCandDAO.class).retrieveInOutLinesForCandidate(ic, I_M_InOutLine.class); if (iols.isEmpty()) // if no IOLs, fall back to the order line's qty
{ final I_C_OrderLine ol = InterfaceWrapperHelper.create(ic.getC_OrderLine(), I_C_OrderLine.class); final BigDecimal olQtyEnteredTU = ol.getQtyEnteredTU(); if (olQtyEnteredTU != null) // safety { qtyEnteredTU = olQtyEnteredTU; } } for (final I_M_InOutLine iol : iols) { // // Just to be safe and prevent a possible bug, make sure the IOL IDs are unique final int iolId = iol.getM_InOutLine_ID(); if (!seenIOLs.add(iolId)) { continue; } if (!Services.get(IDocumentBL.class).isDocumentCompletedOrClosed(iol.getM_InOut())) { continue; // skip not-completed shipments } final BigDecimal iolQtyEnteredTU; if (iol.isPackagingMaterial()) { iolQtyEnteredTU = iol.getQtyEntered(); // the bound line is the PM line } else { iolQtyEnteredTU = iol.getQtyEnteredTU(); } if (iolQtyEnteredTU != null) // safety { qtyEnteredTU = qtyEnteredTU.add(iolQtyEnteredTU); } } return qtyEnteredTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_Invoice_Candidate.java
1
请完成以下Java代码
public void setCounter_DocBaseType (java.lang.String Counter_DocBaseType) { set_Value (COLUMNNAME_Counter_DocBaseType, Counter_DocBaseType); } /** Get Counter_DocBaseType. @return Counter_DocBaseType */ @Override public java.lang.String getCounter_DocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_Counter_DocBaseType); } /** Set Document BaseType. @param DocBaseType Logical type of document
*/ @Override public void setDocBaseType (java.lang.String DocBaseType) { set_Value (COLUMNNAME_DocBaseType, DocBaseType); } /** Get Document BaseType. @return Logical type of document */ @Override public java.lang.String getDocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_DocBaseType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocBaseType_Counter.java
1
请在Spring Boot框架中完成以下Java代码
private ScheduledPackageable toScheduledPackageable(@NonNull Packageable packageable) { if (query.isScheduledForWorkplaceOnly()) { final PickingJobSchedule schedule = getJobSchedule(packageable.getShipmentScheduleId()).orElse(null); return schedule != null ? ScheduledPackageable.of(packageable, schedule) : null; } else { return ScheduledPackageable.ofPackageable(packageable); } } private Optional<PickingJobSchedule> getJobSchedule(ShipmentScheduleId shipmentScheduleId) { return getJobSchedules().getSingleScheduleByShipmentScheduleId(shipmentScheduleId); } private PickingJobScheduleCollection getJobSchedules() { if (this._onlyPickingJobSchedules == null) { this._onlyPickingJobSchedules = retrieveJobSchedules(); } return this._onlyPickingJobSchedules; } private PickingJobScheduleCollection retrieveJobSchedules() { return query.isScheduledForWorkplaceOnly() ? pickingJobScheduleService.list(query.toPickingJobScheduleQuery()) : PickingJobScheduleCollection.EMPTY; } private PickingJobCandidateList aggregate() { final ImmutableList.Builder<PickingJobCandidate> result = ImmutableList.builder(); orderBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); productBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); deliveryLocationBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); return PickingJobCandidateList.ofList(result.build()); } private void add(@NonNull final ScheduledPackageable item) { final PickingJobAggregationType aggregationType = configService.getAggregationType(item.getCustomerId()); switch (aggregationType) {
case SALES_ORDER: { orderBasedAggregates.computeIfAbsent(OrderBasedAggregationKey.of(item), OrderBasedAggregation::new).add(item); break; } case PRODUCT: { productBasedAggregates.computeIfAbsent(ProductBasedAggregationKey.of(item), ProductBasedAggregation::new).add(item); break; } case DELIVERY_LOCATION: { deliveryLocationBasedAggregates.computeIfAbsent(DeliveryLocationBasedAggregationKey.of(item), DeliveryLocationBasedAggregation::new).add(item); break; } default: { throw new AdempiereException("Unknown aggregation type: " + aggregationType); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\retrieve\PickingJobCandidateRetrieveCommand.java
2
请完成以下Java代码
final class CodecDelegate { private static final ResolvableType MESSAGE_TYPE = ResolvableType.forClass(GraphQlWebSocketMessage.class); private final CodecConfigurer codecConfigurer; private final Decoder<?> decoder; private final Encoder<?> encoder; CodecDelegate(CodecConfigurer configurer) { Assert.notNull(configurer, "CodecConfigurer is required"); this.codecConfigurer = configurer; this.decoder = findJsonDecoder(configurer); this.encoder = findJsonEncoder(configurer); } static Encoder<?> findJsonEncoder(CodecConfigurer configurer) { return findJsonEncoder(configurer.getWriters().stream() .filter((writer) -> writer instanceof EncoderHttpMessageWriter) .map((writer) -> ((EncoderHttpMessageWriter<?>) writer).getEncoder())); } static Decoder<?> findJsonDecoder(CodecConfigurer configurer) { return findJsonDecoder(configurer.getReaders().stream() .filter((reader) -> reader instanceof DecoderHttpMessageReader) .map((reader) -> ((DecoderHttpMessageReader<?>) reader).getDecoder())); } static Encoder<?> findJsonEncoder(List<Encoder<?>> encoders) { return findJsonEncoder(encoders.stream()); } static Decoder<?> findJsonDecoder(List<Decoder<?>> decoders) { return findJsonDecoder(decoders.stream()); } private static Encoder<?> findJsonEncoder(Stream<Encoder<?>> stream) { return stream .filter((encoder) -> encoder.canEncode(MESSAGE_TYPE, MediaType.APPLICATION_JSON)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No JSON Encoder")); } private static Decoder<?> findJsonDecoder(Stream<Decoder<?>> decoderStream) { return decoderStream .filter((decoder) -> decoder.canDecode(MESSAGE_TYPE, MediaType.APPLICATION_JSON)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No JSON Decoder"));
} CodecConfigurer getCodecConfigurer() { return this.codecConfigurer; } @SuppressWarnings("unchecked") <T> WebSocketMessage encode(WebSocketSession session, GraphQlWebSocketMessage message) { DataBuffer buffer = ((Encoder<T>) this.encoder).encodeValue( (T) message, session.bufferFactory(), MESSAGE_TYPE, MimeTypeUtils.APPLICATION_JSON, null); return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer); } @SuppressWarnings("ConstantConditions") @Nullable GraphQlWebSocketMessage decode(WebSocketMessage webSocketMessage) { DataBuffer buffer = DataBufferUtils.retain(webSocketMessage.getPayload()); return (GraphQlWebSocketMessage) this.decoder.decode(buffer, MESSAGE_TYPE, null, null); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\CodecDelegate.java
1
请完成以下Java代码
public void afterPropertiesSet() { Assert.notNull(this.connectionFactory, "ConnectionFactory is required"); } /** * Create a RabbitMQ Connection via this template's ConnectionFactory and its host and port values. * @return the new RabbitMQ Connection * @see ConnectionFactory#createConnection */ protected Connection createConnection() { return this.connectionFactory.createConnection(); } /** * Fetch an appropriate Connection from the given RabbitResourceHolder. * * @param holder the RabbitResourceHolder * @return an appropriate Connection fetched from the holder, or <code>null</code> if none found */ protected @Nullable Connection getConnection(RabbitResourceHolder holder) { return holder.getConnection(); } /** * Fetch an appropriate Channel from the given RabbitResourceHolder. * * @param holder the RabbitResourceHolder * @return an appropriate Channel fetched from the holder, or <code>null</code> if none found */ protected @Nullable Channel getChannel(RabbitResourceHolder holder) { return holder.getChannel(); } protected RabbitResourceHolder getTransactionalResourceHolder() { return ConnectionFactoryUtils.getTransactionalResourceHolder(this.connectionFactory, isChannelTransacted()); }
protected RuntimeException convertRabbitAccessException(Exception ex) { return RabbitExceptionTranslator.convertRabbitAccessException(ex); } protected void obtainObservationRegistry(@Nullable ApplicationContext appContext) { if (appContext != null) { ObjectProvider<ObservationRegistry> registry = appContext.getBeanProvider(ObservationRegistry.class); this.observationRegistry = registry.getIfUnique(() -> this.observationRegistry); } } protected ObservationRegistry getObservationRegistry() { return this.observationRegistry; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitAccessor.java
1
请完成以下Java代码
private static String extractSummary(@NonNull final WFProcess wfProcess) { final WFState state = wfProcess.getState(); String summary = wfProcess.getProcessingResultMessage(); if (Check.isBlank(summary)) { final WFActivity activity = wfProcess.getFirstActivityByWFState(state).orElse(null); if (activity != null) { summary = activity.getTextMsg(); } } if (summary == null || Check.isBlank(summary)) { summary = state.toString(); } return summary; } public void abort(@NonNull final WFProcess wfProcess) { trxManager.runInThreadInheritedTrx(new TrxRunnableAdapter() { @Override public void run(final String localTrxName) { wfProcess.changeWFStateTo(WFState.Aborted); } @Override public void doFinally() { context.save(wfProcess); }
}); } private List<WFProcess> getActiveProcesses() { final List<WFProcessId> wfProcessIds = wfProcessRepository.getActiveProcessIds(context.getDocumentRef()); return getWFProcesses(wfProcessIds); } private List<WFProcess> getWFProcesses(final List<WFProcessId> wfProcessIds) { if (wfProcessIds.isEmpty()) { return ImmutableList.of(); } final ImmutableMap<WFProcessId, WFProcessState> wfProcessStates = wfProcessRepository.getWFProcessStateByIds(wfProcessIds); final ImmutableListMultimap<WFProcessId, WFActivityState> wfActivityStates = wfProcessRepository.getWFActivityStates(wfProcessIds); return wfProcessIds .stream() .map(wfProcessId -> new WFProcess( context, wfProcessStates.get(wfProcessId), wfActivityStates.get(wfProcessId))) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WorkflowExecutor.java
1
请完成以下Java代码
public class LongDataPoint extends AbstractDataPoint { @Getter private final long value; public LongDataPoint(long ts, long value) { super(ts); this.value = value; } @Override public DataType getType() { return DataType.LONG; } @Override public long getLong() { return value; } @Override public double getDouble() { return value; }
@Override public String valueToString() { return Long.toString(value); } @Override public int compareTo(DataPoint dataPoint) { if (dataPoint.getType() == DataType.DOUBLE) { return Double.compare(getDouble(), dataPoint.getDouble()); } else if (dataPoint.getType() == DataType.LONG) { return Long.compare(value, dataPoint.getLong()); } else { return super.compareTo(dataPoint); } } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\dp\LongDataPoint.java
1
请完成以下Java代码
public static Response bearerAuthenticationWithOAuth2AtClientLevel(String token) { Feature feature = OAuth2ClientSupport.feature(token); Client client = ClientBuilder.newBuilder().register(feature).build(); return client.target(TARGET) .path(MAIN_RESOURCE) .request() .get(); } public static Response bearerAuthenticationWithOAuth2AtRequestLevel(String token, String otherToken) { Feature feature = OAuth2ClientSupport.feature(token); Client client = ClientBuilder.newBuilder().register(feature).build(); return client.target(TARGET) .path(MAIN_RESOURCE) .request() .property(OAuth2ClientSupport.OAUTH2_PROPERTY_ACCESS_TOKEN, otherToken) .get(); } public static Response filter() { Client client = ClientBuilder.newBuilder().register(AddHeaderOnRequestFilter.class).build(); return client.target(TARGET) .path(MAIN_RESOURCE) .request() .get(); } public static Response sendRestrictedHeaderThroughDefaultTransportConnector(String headerKey, String headerValue) { ClientConfig clientConfig = new ClientConfig().connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(clientConfig); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); return client.target(TARGET)
.path(MAIN_RESOURCE) .request() .header(headerKey, headerValue) .get(); } public static String simpleSSEHeader() throws InterruptedException { Client client = ClientBuilder.newBuilder() .register(AddHeaderOnRequestFilter.class) .build(); WebTarget webTarget = client.target(TARGET) .path(MAIN_RESOURCE) .path("events"); SseEventSource sseEventSource = SseEventSource.target(webTarget).build(); sseEventSource.register(JerseyClientHeaders::receiveEvent); sseEventSource.open(); Thread.sleep(3_000); sseEventSource.close(); return sseHeaderValue; } private static void receiveEvent(InboundSseEvent event) { sseHeaderValue = event.readData(); } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\client\JerseyClientHeaders.java
1
请完成以下Java代码
public class Tutorial { private String tutId; private String type; private String title; private String description; private String date; private String author; public String getTutId() { return tutId; } @XmlAttribute public void setTutId(String tutId) { this.tutId = tutId; } public String getType() { return type; } @XmlAttribute public void setType(String type) { this.type = type; } public String getTitle() { return title; } @XmlElement public void setTitle(String title) { this.title = title; }
public String getDescription() { return description; } @XmlElement public void setDescription(String description) { this.description = description; } public String getDate() { return date; } @XmlElement public void setDate(String date) { this.date = date; } public String getAuthor() { return author; } @XmlElement public void setAuthor(String author) { this.author = author; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\binding\Tutorial.java
1
请完成以下Java代码
public CompositeScriptScanner addScriptScanner(final IScriptScanner scriptScanner) { if (scriptScanner == null) { throw new IllegalArgumentException("scriptScanner is null"); } if (children.contains(scriptScanner)) { return this; } children.add(scriptScanner); return this; } @Override protected IScriptScanner retrieveNextChildScriptScanner()
{ final int nextIndex = currentIndex + 1; if (nextIndex >= children.size()) { return null; } final IScriptScanner nextScanner = children.get(nextIndex); currentIndex = nextIndex; return nextScanner; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\CompositeScriptScanner.java
1
请完成以下Java代码
public static final AdempiereException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } else if (throwable instanceof PostingExecutionException) { return (PostingExecutionException)throwable; } else { final Throwable cause = extractCause(throwable); if (cause instanceof PostingExecutionException) { return (PostingExecutionException)cause; } else { final String message = extractMessage(cause); return new PostingExecutionException(message, cause); } } } public PostingExecutionException(final String message) { this(message, /* serverStackTrace */(String)null); } private PostingExecutionException(final String message, final String serverStackTrace) { super(buildMessage(message, serverStackTrace)); }
private PostingExecutionException(final String message, final Throwable cause) { super(message, cause); } private static final String buildMessage(final String message, final String serverStackTrace) { final StringBuilder sb = new StringBuilder(); sb.append(!Check.isEmpty(message) ? message.trim() : "unknow error"); if (!Check.isEmpty(serverStackTrace)) { sb.append("\nServer stack trace: ").append(serverStackTrace.trim()); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\PostingExecutionException.java
1
请完成以下Java代码
public <T> IQuery<T> toQuery(Class<T> clazz, String trxName) { return toQueryBuilder(clazz, trxName) .create(); } private <T> IQueryBuilder<T> toQueryBuilder(final Class<T> clazz, final String trxName) { final String tableName = InterfaceWrapperHelper.getTableName(clazz); final POInfo poInfo = POInfo.getPOInfo(tableName); final IQueryBuilder<T> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(clazz, Env.getCtx(), trxName); queryBuilder.addEqualsFilter(COLUMNNAME_AD_Client_ID, this.clientId); queryBuilder.addEqualsFilter(COLUMNNAME_M_Product_ID, this.productId); queryBuilder.addEqualsFilter(COLUMNNAME_M_AttributeSetInstance_ID, attributeSetInstanceId); queryBuilder.addEqualsFilter(COLUMNNAME_C_AcctSchema_ID, this.acctSchemaId); // // Filter by organization, only if it's set and we are querying the M_Cost table. // Else, you can get no results.
// e.g. querying PP_Order_Cost, have this.AD_Org_ID=0 but PP_Order_Costs are created using PP_Order's AD_Org_ID // see http://dewiki908/mediawiki/index.php/07741_Rate_Variance_%28103334042334%29. if (!this.orgId.isAny() || I_M_Cost.Table_Name.equals(tableName)) { queryBuilder.addEqualsFilter(COLUMNNAME_AD_Org_ID, orgId); } if (this.costElementId != null) { queryBuilder.addEqualsFilter(COLUMNNAME_M_CostElement_ID, costElementId); } if (this.costTypeId != null && poInfo.hasColumnName(COLUMNNAME_M_CostType_ID)) { queryBuilder.addEqualsFilter(COLUMNNAME_M_CostType_ID, this.costTypeId); } return queryBuilder; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CopyPriceToStandard.java
1
请完成以下Java代码
public final class ESCommand { @NonNull private final String string; private ESCommand(@NonNull final String string) { final String stringNorm = StringUtils.trimBlankToNull(string); if (stringNorm == null) { throw new AdempiereException("Invalid blank ESCommand string: " + string); } this.string = stringNorm; } public static ESCommand ofString(final String string) {
return new ESCommand(string); } @Override @Deprecated public String toString() { return getAsString(); } public String getAsString() { return string; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\ESCommand.java
1
请完成以下Java代码
public List<WidgetsBundle> findSystemOrTenantWidgetsBundlesByIds(TenantId tenantId, List<WidgetsBundleId> widgetsBundleIds) { log.trace("Executing findSystemOrTenantWidgetsBundlesByIds, tenantId [{}], widgetsBundleIds [{}]", tenantId, widgetsBundleIds); return widgetsBundleDao.findSystemOrTenantWidgetBundlesByIds(tenantId.getId(), toUUIDs(widgetsBundleIds)); } private WidgetTypeDetails updateSystemWidget(JsonNode widgetTypeJson) { WidgetTypeDetails widgetTypeDetails = JacksonUtil.treeToValue(widgetTypeJson, WidgetTypeDetails.class); WidgetType existingWidget = widgetTypeService.findWidgetTypeByTenantIdAndFqn(TenantId.SYS_TENANT_ID, widgetTypeDetails.getFqn()); if (existingWidget != null) { widgetTypeDetails.setId(existingWidget.getId()); widgetTypeDetails.setCreatedTime(existingWidget.getCreatedTime()); } widgetTypeDetails.setTenantId(TenantId.SYS_TENANT_ID); widgetTypeDetails = widgetTypeService.saveWidgetType(widgetTypeDetails); log.debug("{} widget type {}", existingWidget == null ? "Created" : "Updated", widgetTypeDetails.getFqn()); return widgetTypeDetails; } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findWidgetsBundleById(tenantId, new WidgetsBundleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(widgetsBundleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); }
@Override public EntityType getEntityType() { return EntityType.WIDGETS_BUNDLE; } private final PaginatedRemover<TenantId, WidgetsBundle> tenantWidgetsBundleRemover = new PaginatedRemover<>() { @Override protected PageData<WidgetsBundle> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return widgetsBundleDao.findTenantWidgetsBundlesByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, WidgetsBundle entity) { deleteWidgetsBundle(tenantId, new WidgetsBundleId(entity.getUuidId())); } }; }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\widget\WidgetsBundleServiceImpl.java
1
请完成以下Java代码
public class CreateMaterialTrackingReportLineFromMaterialTrackingRefAggregator extends MapReduceAggregator<I_M_Material_Tracking_Report_Line, MaterialTrackingReportAgregationItem> { final IMaterialTrackingReportBL materialTrackingReportBL = Services.get(IMaterialTrackingReportBL.class); /** * Report header containing the report line */ private I_M_Material_Tracking_Report report; public CreateMaterialTrackingReportLineFromMaterialTrackingRefAggregator(final I_M_Material_Tracking_Report report) { super(); this.report = report; } @Override protected I_M_Material_Tracking_Report_Line createGroup( final Object itemHashKey, final MaterialTrackingReportAgregationItem items) { final IMaterialTrackingReportDAO materialTrackingReportDAO = Services.get(IMaterialTrackingReportDAO.class); final I_M_Material_Tracking_Report_Line existingLine = materialTrackingReportDAO.retrieveMaterialTrackingReportLineOrNull(report, itemHashKey.toString()); // Create a report line based on a ref if (existingLine != null) { return existingLine; } final I_M_Material_Tracking_Report_Line newLine; try { newLine = materialTrackingReportBL.createMaterialTrackingReportLine(report, items.getInOutLine(), itemHashKey.toString()); InterfaceWrapperHelper.save(newLine); } catch (final Throwable t) { Loggables.addLog("@Error@: " + t); throw AdempiereException.wrapIfNeeded(t); } return newLine; } @Override protected void closeGroup(final I_M_Material_Tracking_Report_Line reportLine) {
// save the line final BigDecimal qtyReceived = reportLine.getQtyReceived().setScale(1, RoundingMode.HALF_UP); final BigDecimal qtyIssued = reportLine.getQtyIssued().setScale(1, RoundingMode.HALF_UP); final BigDecimal qtyDifference = qtyReceived.subtract(qtyIssued).setScale(1, RoundingMode.HALF_UP); reportLine.setDifferenceQty(qtyDifference); InterfaceWrapperHelper.save(reportLine); } @Override protected void addItemToGroup(final I_M_Material_Tracking_Report_Line reportLine, final MaterialTrackingReportAgregationItem items) { materialTrackingReportBL.createMaterialTrackingReportLineAllocation(reportLine, items); if (items.getPPOrder() != null) { // issue Side reportLine.setQtyIssued(reportLine.getQtyIssued().add(items.getQty())); } else { // receipt side reportLine.setQtyReceived(reportLine.getQtyReceived().add(items.getQty())); } InterfaceWrapperHelper.save(reportLine); } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\CreateMaterialTrackingReportLineFromMaterialTrackingRefAggregator.java
1
请完成以下Java代码
public BigDecimal getBdryAmt() { return bdryAmt; } /** * Sets the value of the bdryAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setBdryAmt(BigDecimal value) { this.bdryAmt = value; } /** * Gets the value of the incl property.
* */ public boolean isIncl() { return incl; } /** * Sets the value of the incl property. * */ public void setIncl(boolean value) { this.incl = 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\AmountRangeBoundary1.java
1
请完成以下Java代码
public Integer getResourceType() { return resourceType; } public void setResourceType(Integer resourceType) { this.resourceType = resourceType; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId;
} public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } private static Permission[] getPermissions(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { int givenResourceType = dbAuthorization.getResourceType(); Permission[] permissionsByResourceType = ((ProcessEngineConfigurationImpl) engineConfiguration).getPermissionProvider().getPermissionsForResource(givenResourceType); return dbAuthorization.getPermissions(permissionsByResourceType); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationDto.java
1
请完成以下Java代码
public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> juelExpressions = transformExpressions(transform, feelExpression, inputName); return joinExpressions(juelExpressions); } protected List<String> collectExpressions(String feelExpression) { return splitExpression(feelExpression); } private List<String> splitExpression(String feelExpression) { return Arrays.asList(feelExpression.split(COMMA_SEPARATOR_REGEX, -1)); } protected List<String> transformExpressions(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> expressions = collectExpressions(feelExpression); List<String> juelExpressions = new ArrayList<String>(); for (String expression : expressions) { if (!expression.trim().isEmpty()) { String juelExpression = transform.transformSimplePositiveUnaryTest(expression, inputName);
juelExpressions.add(juelExpression); } else { throw LOG.invalidListExpression(feelExpression); } } return juelExpressions; } protected String joinExpressions(List<String> juelExpressions) { StringBuilder builder = new StringBuilder(); builder.append("(").append(juelExpressions.get(0)).append(")"); for (int i = 1; i < juelExpressions.size(); i++) { builder.append(" || (").append(juelExpressions.get(i)).append(")"); } return builder.toString(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\transform\ListTransformer.java
1
请在Spring Boot框架中完成以下Java代码
default boolean hasPermission(SecurityUser user, Operation operation) { return false; } default boolean hasPermission(SecurityUser user, Operation operation, I entityId, T entity) { return false; } public class GenericPermissionChecker<I extends EntityId, T extends HasTenantId> implements PermissionChecker<I,T> { private final Set<Operation> allowedOperations; public GenericPermissionChecker(Operation... operations) { allowedOperations = new HashSet<Operation>(Arrays.asList(operations)); } @Override public boolean hasPermission(SecurityUser user, Operation operation) { return allowedOperations.contains(Operation.ALL) || allowedOperations.contains(operation); } @Override public boolean hasPermission(SecurityUser user, Operation operation, I entityId, T entity) { return allowedOperations.contains(Operation.ALL) || allowedOperations.contains(operation); } }
public static PermissionChecker denyAllPermissionChecker = new PermissionChecker() {}; public static PermissionChecker allowAllPermissionChecker = new PermissionChecker<EntityId, HasTenantId>() { @Override public boolean hasPermission(SecurityUser user, Operation operation) { return true; } @Override public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) { return true; } }; }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\permission\PermissionChecker.java
2
请在Spring Boot框架中完成以下Java代码
private static List<AuthenticationConverter> createDefaultAuthenticationConverters() { List<AuthenticationConverter> authenticationConverters = new ArrayList<>(); authenticationConverters.add(new OAuth2DeviceVerificationAuthenticationConverter()); authenticationConverters.add(new OAuth2DeviceAuthorizationConsentAuthenticationConverter()); return authenticationConverters; } private static List<AuthenticationProvider> createDefaultAuthenticationProviders(HttpSecurity builder) { RegisteredClientRepository registeredClientRepository = OAuth2ConfigurerUtils .getRegisteredClientRepository(builder); OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(builder); OAuth2AuthorizationConsentService authorizationConsentService = OAuth2ConfigurerUtils .getAuthorizationConsentService(builder); List<AuthenticationProvider> authenticationProviders = new ArrayList<>(); // @formatter:off OAuth2DeviceVerificationAuthenticationProvider deviceVerificationAuthenticationProvider =
new OAuth2DeviceVerificationAuthenticationProvider( registeredClientRepository, authorizationService, authorizationConsentService); // @formatter:on authenticationProviders.add(deviceVerificationAuthenticationProvider); // @formatter:off OAuth2DeviceAuthorizationConsentAuthenticationProvider deviceAuthorizationConsentAuthenticationProvider = new OAuth2DeviceAuthorizationConsentAuthenticationProvider( registeredClientRepository, authorizationService, authorizationConsentService); // @formatter:on authenticationProviders.add(deviceAuthorizationConsentAuthenticationProvider); return authenticationProviders; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2DeviceVerificationEndpointConfigurer.java
2
请完成以下Java代码
protected void continueThroughMultiInstanceFlowNode(FlowNode flowNode) { if (!flowNode.isAsynchronous()) { executeSynchronous(flowNode); } else { executeAsynchronous(flowNode); } } protected void executeSynchronous(FlowNode flowNode) { // Execution listener if (CollectionUtil.isNotEmpty(flowNode.getExecutionListeners())) { executeExecutionListeners(flowNode, ExecutionListener.EVENTNAME_START); } commandContext.getHistoryManager().recordActivityStart(execution); // Execute actual behavior ActivityBehavior activityBehavior = (ActivityBehavior) flowNode.getBehavior(); if (activityBehavior != null) { logger.debug( "Executing activityBehavior {} on activity '{}' with execution {}", activityBehavior.getClass(), flowNode.getId(), execution.getId() ); if ( Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled() ) { Context.getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createActivityEvent( ActivitiEventType.ACTIVITY_STARTED, execution, flowNode ) ); }
try { activityBehavior.execute(execution); } catch (BpmnError error) { // re-throw business fault so that it can be caught by an Error Intermediate Event or Error Event Sub-Process in the process ErrorPropagation.propagateError(error, execution); } catch (RuntimeException e) { if (LogMDC.isMDCEnabled()) { LogMDC.putMDCExecution(execution); } throw e; } } else { logger.debug("No activityBehavior on activity '{}' with execution {}", flowNode.getId(), execution.getId()); } } protected void executeAsynchronous(FlowNode flowNode) { JobEntity job = commandContext.getJobManager().createAsyncJob(execution, flowNode.isExclusive()); commandContext.getJobManager().scheduleAsyncJob(job); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\ContinueMultiInstanceOperation.java
1
请完成以下Java代码
protected void options() { } public final ExitStatus run(String... args) throws Exception { String[] argsToUse = args.clone(); for (int i = 0; i < argsToUse.length; i++) { if ("-cp".equals(argsToUse[i])) { argsToUse[i] = "--cp"; } argsToUse[i] = this.argumentProcessor.apply(argsToUse[i]); } OptionSet options = getParser().parse(argsToUse); return run(options); } /** * Run the command using the specified parsed {@link OptionSet}. * @param options the parsed option set * @return an ExitStatus * @throws Exception in case of errors */ protected ExitStatus run(OptionSet options) throws Exception { return ExitStatus.OK; } public String getHelp() { if (this.help == null) { getParser().formatHelpWith(new BuiltinHelpFormatter(80, 2)); OutputStream out = new ByteArrayOutputStream(); try { getParser().printHelpOn(out); } catch (IOException ex) { return "Help not available"; } this.help = out.toString().replace(" --cp ", " -cp "); } return this.help; } public Collection<OptionHelp> getOptionsHelp() { if (this.optionHelp == null) { OptionHelpFormatter formatter = new OptionHelpFormatter(); getParser().formatHelpWith(formatter); try { getParser().printHelpOn(new ByteArrayOutputStream()); } catch (Exception ex) { // Ignore and provide no hints } this.optionHelp = formatter.getOptionHelp(); } return this.optionHelp; } private static final class OptionHelpFormatter implements HelpFormatter { private final List<OptionHelp> help = new ArrayList<>(); @Override public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = Comparator .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set<OptionDescriptor> sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor));
} } return ""; } Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } } private static class OptionHelpAdapter implements OptionHelp { private final Set<String> options; private final String description; OptionHelpAdapter(OptionDescriptor descriptor) { this.options = new LinkedHashSet<>(); for (String option : descriptor.options()) { String prefix = (option.length() != 1) ? "--" : "-"; this.options.add(prefix + option); } if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java
1
请完成以下Java代码
public int getM_SerNoCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_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 Prefix. @param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix ()
{ return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtl.java
1
请完成以下Java代码
public java.lang.String getHostKey() { return (java.lang.String)get_Value(COLUMNNAME_HostKey); } @Override public void setIsManualCalibration (boolean IsManualCalibration) { set_Value (COLUMNNAME_IsManualCalibration, Boolean.valueOf(IsManualCalibration)); } @Override public boolean isManualCalibration() { return get_ValueAsBoolean(COLUMNNAME_IsManualCalibration); } @Override public void setMeasurementX (java.math.BigDecimal MeasurementX) { set_Value (COLUMNNAME_MeasurementX, MeasurementX); } @Override public java.math.BigDecimal getMeasurementX() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementX); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setMeasurementY (java.math.BigDecimal MeasurementY) { set_Value (COLUMNNAME_MeasurementY, MeasurementY); } @Override public java.math.BigDecimal getMeasurementY() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementY); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_Calibration.java
1
请完成以下Java代码
public void setMarginTop (int MarginTop) { set_Value (COLUMNNAME_MarginTop, Integer.valueOf(MarginTop)); } /** Get Top Margin. @return Top Space in 1/72 inch */ public int getMarginTop () { Integer ii = (Integer)get_Value(COLUMNNAME_MarginTop); 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 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 Size X. @param SizeX
X (horizontal) dimension size */ public void setSizeX (BigDecimal SizeX) { set_Value (COLUMNNAME_SizeX, SizeX); } /** Get Size X. @return X (horizontal) dimension size */ public BigDecimal getSizeX () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeX); if (bd == null) return Env.ZERO; return bd; } /** Set Size Y. @param SizeY Y (vertical) dimension size */ public void setSizeY (BigDecimal SizeY) { set_Value (COLUMNNAME_SizeY, SizeY); } /** Get Size Y. @return Y (vertical) dimension size */ public BigDecimal getSizeY () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeY); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintPaper.java
1
请完成以下Java代码
protected String doIt() throws Exception { if (p_QtyTU <= 0) { throw new FillMandatoryException("QtyTU"); } topLevelHU = getRecord(I_M_HU.class); // // Get the original receipt line final List<I_M_InOutLine> receiptLines = huAssignmentDAO.retrieveModelsForHU(topLevelHU, I_M_InOutLine.class) .stream() .filter(inoutLine -> !inoutLine.getM_InOut().isSOTrx()) // material receipt .collect(ImmutableList.toImmutableList()); final I_M_InOutLine receiptLine = CollectionUtils.singleElement(receiptLines); // // Split out the TUs we need to return final HUsToNewTUsRequest request = HUsToNewTUsRequest.forSourceHuAndQty(topLevelHU, p_QtyTU); tusToReturn = HUTransformService.newInstance().husToNewTUs(request); if (tusToReturn.getQtyTU().toInt() != p_QtyTU) { throw new AdempiereException(WEBUI_HU_Constants.MSG_NotEnoughTUsFound, p_QtyTU, tusToReturn.getQtyTU()); } // // Assign the split TUs to the receipt line // FIXME: this is a workaround until https://github.com/metasfresh/metasfresh/issues/2392 is implemented tusToReturn.forEach(tu -> huAssignmentBL.createHUAssignmentBuilder() .initializeAssignment(getCtx(), ITrx.TRXNAME_ThreadInherited) .setM_LU_HU(null) .setM_TU_HU(tu.toHU()) .setTopLevelHU(tu.toHU()) .setModel(receiptLine) .build()); // // Actually create the vendor return final Timestamp movementDate = Env.getDate(getCtx()); returnsServiceFacade.createVendorReturnInOutForHUs(tusToReturn.toHURecords(), movementDate); invalidateView(); // we split something off the original HUs and therefore need to refresh our view return MSG_OK;
} @Override protected void postProcess(final boolean success) { // If something failed, don't bother if (!success) { return; } // Remove the TUs from our view (in case of any top level TUs) if (tusToReturn != null && !tusToReturn.isEmpty()) { getView().removeHUIds(tusToReturn.getHuIds()); } // Invalidate the view because the top level LU changed too getView().invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnTUsToVendor.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * InvoicableQtyBasedOn AD_Reference_ID=541023 * Reference name: InvoicableQtyBasedOn */ public static final int INVOICABLEQTYBASEDON_AD_Reference_ID=541023; /** Nominal = Nominal */ public static final String INVOICABLEQTYBASEDON_Nominal = "Nominal"; /** CatchWeight = CatchWeight */ public static final String INVOICABLEQTYBASEDON_CatchWeight = "CatchWeight"; @Override public void setInvoicableQtyBasedOn (final java.lang.String InvoicableQtyBasedOn) { set_Value (COLUMNNAME_InvoicableQtyBasedOn, InvoicableQtyBasedOn); } @Override public java.lang.String getInvoicableQtyBasedOn() { return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @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 setPriceList (final @Nullable BigDecimal PriceList) { set_Value (COLUMNNAME_PriceList, PriceList); } @Override public BigDecimal getPriceList() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceStd (final BigDecimal PriceStd)
{ set_Value (COLUMNNAME_PriceStd, PriceStd); } @Override public BigDecimal getPriceStd() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign_Price.java
1
请完成以下Java代码
protected List<TsKvEntry> convertResultToTsKvEntryList(List<Row> rows) { List<TsKvEntry> entries = new ArrayList<>(rows.size()); if (!rows.isEmpty()) { rows.forEach(row -> entries.add(convertResultToTsKvEntry(row))); } return entries; } private TsKvEntry convertResultToTsKvEntry(Row row) { String key = row.getString(ModelConstants.KEY_COLUMN); long ts = row.getLong(ModelConstants.TS_COLUMN); return new BasicTsKvEntry(ts, toKvEntry(row, key)); } protected TsKvEntry convertResultToTsKvEntry(String key, Row row) { if (row != null) { return getBasicTsKvEntry(key, row); } else { return new BasicTsKvEntry(System.currentTimeMillis(), new StringDataEntry(key, null)); } } protected Optional<TsKvEntry> convertResultToTsKvEntryOpt(String key, Row row) { if (row != null) { return Optional.of(getBasicTsKvEntry(key, row)); } else { return Optional.empty(); } }
private BasicTsKvEntry getBasicTsKvEntry(String key, Row row) { Optional<String> foundKeyOpt = getKey(row); long ts = row.getLong(ModelConstants.TS_COLUMN); return new BasicTsKvEntry(ts, toKvEntry(row, foundKeyOpt.orElse(key))); } private Optional<String> getKey(Row row){ try{ return Optional.ofNullable(row.getString(ModelConstants.KEY_COLUMN)); } catch (IllegalArgumentException e){ return Optional.empty(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\AbstractCassandraBaseTimeseriesDao.java
1
请完成以下Java代码
private Set<RecordHolder<K, R>> addToCollection(ConsumerRecord record, Object correlationId) { Set<RecordHolder<K, R>> set = this.pending.computeIfAbsent(correlationId, id -> new LinkedHashSet<>()); set.add(new RecordHolder<>(record)); return set; } private static final class RecordHolder<K, R> { private final ConsumerRecord<K, R> record; RecordHolder(ConsumerRecord<K, R> record) { this.record = record; } ConsumerRecord<K, R> getRecord() { return this.record; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.record.topic().hashCode() + this.record.partition() + (int) this.record.offset(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") RecordHolder other = (RecordHolder) obj; if (this.record == null) { if (other.record != null) { return false; } } else { return this.record.topic().equals(other.record.topic()) && this.record.partition() == other.record.partition() && this.record.offset() == other.record.offset(); } return false; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\AggregatingReplyingKafkaTemplate.java
1
请完成以下Java代码
public static MResource get(Properties ctx, int S_Resource_ID) { if (S_Resource_ID <= 0) return null; MResource r = s_cache.get(S_Resource_ID); if (r == null) { r = new MResource(ctx, S_Resource_ID, null); if (r.get_ID() == S_Resource_ID) { s_cache.put(S_Resource_ID, r); } } return r; } /** * Standard Constructor * @param ctx context * @param S_Resource_ID id */ public MResource (Properties ctx, int S_Resource_ID, String trxName) { super (ctx, S_Resource_ID, trxName); } // MResource /** * Load Constructor * @param ctx context * @param rs result set */ public MResource (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MResource /** Cached Resource Type */ private MResourceType m_resourceType = null; /** Cached Product */ /** * Get cached Resource Type * @return Resource Type */ public MResourceType getResourceType() { // Use cache if we are outside transaction: if (get_TrxName() == null && getS_ResourceType_ID() > 0) return MResourceType.get(getCtx(), getS_ResourceType_ID()); // if (m_resourceType == null && getS_ResourceType_ID() != 0) {
m_resourceType = new MResourceType (getCtx(), getS_ResourceType_ID(), get_TrxName()); } return m_resourceType; } // getResourceType @Override protected boolean beforeSave (boolean newRecord) { // // Validate Manufacturing Resource if (isManufacturingResource() && MANUFACTURINGRESOURCETYPE_Plant.equals(getManufacturingResourceType()) && getPlanningHorizon() <= 0) { throw new AdempiereException("@"+COLUMNNAME_PlanningHorizon+"@ <= @0@ !"); } return true; } // beforeSave @Override public String toString() { StringBuffer sb = new StringBuffer ("MResource[") .append(get_ID()) .append(", Value=").append(getValue()) .append(", Name=").append(getName()) .append("]"); return sb.toString(); } } // MResource
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MResource.java
1