instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesByScopeIdAndScopeType(String scopeId, String scopeType, Collection<String> variableNames) { return dataManager.findHistoricalVariableInstancesByScopeIdAndScopeType(scopeId, scopeType, variableNames); } @Override public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesBySubScopeIdAndScopeType(String subScopeId, String scopeType) { return dataManager.findHistoricalVariableInstancesBySubScopeIdAndScopeType(subScopeId, scopeType); } @Override public void deleteHistoricVariableInstancesByTaskId(String taskId) { List<HistoricVariableInstanceEntity> historicProcessVariables = dataManager.findHistoricVariableInstancesByTaskId(taskId); for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) { delete(historicProcessVariable); } } @Override public void bulkDeleteHistoricVariableInstancesByProcessInstanceIds(Collection<String> processInstanceIds) { dataManager.bulkDeleteHistoricVariableInstancesByProcessInstanceIds(processInstanceIds); } @Override public void bulkDeleteHistoricVariableInstancesByTaskIds(Collection<String> taskIds) { dataManager.bulkDeleteHistoricVariableInstancesByTaskIds(taskIds); } @Override public void bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) { dataManager.bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(scopeIds, scopeType); } @Override public void deleteHistoricVariableInstancesForNonExistingProcessInstances() { dataManager.deleteHistoricVariableInstancesForNonExistingProcessInstances(); }
@Override public void deleteHistoricVariableInstancesForNonExistingCaseInstances() { dataManager.deleteHistoricVariableInstancesForNonExistingCaseInstances(); } @Override public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricVariableInstancesByNativeQuery(parameterMap); } @Override public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java
2
请完成以下Java代码
public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getAssigneeId() {
return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public String getInitiatorVariableName() { return initiatorVariableName; } public void setInitiatorVariableName(String initiatorVariableName) { this.initiatorVariableName = initiatorVariableName; } public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } public String getPredefinedProcessInstanceId() { return predefinedProcessInstanceId; } public void setPredefinedProcessInstanceId(String predefinedProcessInstanceId) { this.predefinedProcessInstanceId = predefinedProcessInstanceId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\StartProcessInstanceBeforeContext.java
1
请在Spring Boot框架中完成以下Java代码
public static class App2ConfigurationAdapter { @Bean public UserDetailsService userDetailsServiceApp2() { UserDetails user = User.withUsername("user") .password(encoder().encode("user")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public SecurityFilterChain filterChainApp2(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/user*") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/user*")).hasRole("USER")) // log in .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/loginUser") .loginProcessingUrl("/user_login")
.failureUrl("/loginUser?error=loginError") .defaultSuccessUrl("/userPage")) // logout .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/user_logout") .logoutSuccessUrl("/protectedLinks") .deleteCookies("JSESSIONID")) .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedPage("/403")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multiplelogin\MultipleLoginSecurityConfig.java
2
请完成以下Java代码
private String getParseExceptionInfo(SAXParseException spe) { return "URI=" + spe.getSystemId() + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); } public void warning(SAXParseException spe) { LOGGER.warning(getParseExceptionInfo(spe)); } public void error(SAXParseException spe) throws SAXException { String message = "Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } public void fatalError(SAXParseException spe) throws SAXException { String message = "Fatal Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } } /** * Get an empty DOM document * * @param documentBuilderFactory the factory to build to DOM document * @return the new empty document * @throws ModelParseException if unable to create a new document */ public static DomDocument getEmptyDocument(DocumentBuilderFactory documentBuilderFactory) { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); return new DomDocumentImpl(documentBuilder.newDocument()); } catch (ParserConfigurationException e) { throw new ModelParseException("Unable to create a new document", e); } } /** * Create a new DOM document from the input stream *
* @param documentBuilderFactory the factory to build to DOM document * @param inputStream the input stream to parse * @return the new DOM document * @throws ModelParseException if a parsing or IO error is triggered */ public static DomDocument parseInputStream(DocumentBuilderFactory documentBuilderFactory, InputStream inputStream) { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(new DomErrorHandler()); return new DomDocumentImpl(documentBuilder.parse(inputStream)); } catch (ParserConfigurationException e) { throw new ModelParseException("ParserConfigurationException while parsing input stream", e); } catch (SAXException e) { throw new ModelParseException("SAXException while parsing input stream", e); } catch (IOException e) { throw new ModelParseException("IOException while parsing input stream", e); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\DomUtil.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Date getTime() { return time; } @Override
public void setTime(Date time) { this.time = time; } @Override public String getDetailType() { return detailType; } @Override public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
1
请完成以下Java代码
public String getCase() { return caseRefAttribute.getValue(this); } public void setCase(String caseInstance) { caseRefAttribute.setValue(this, caseInstance); } public CaseRefExpression getCaseExpression() { return caseRefExpressionChild.getChild(this); } public void setCaseExpression(CaseRefExpression caseExpression) { caseRefExpressionChild.setChild(this, caseExpression); } public Collection<ParameterMapping> getParameterMappings() { return parameterMappingCollection.get(this); } public String getCamundaCaseBinding() { return camundaCaseBindingAttribute.getValue(this); } public void setCamundaCaseBinding(String camundaCaseBinding) { camundaCaseBindingAttribute.setValue(this, camundaCaseBinding); } public String getCamundaCaseVersion() { return camundaCaseVersionAttribute.getValue(this); } public void setCamundaCaseVersion(String camundaCaseVersion) { camundaCaseVersionAttribute.setValue(this, camundaCaseVersion); } public String getCamundaCaseTenantId() { return camundaCaseTenantIdAttribute.getValue(this); } public void setCamundaCaseTenantId(String camundaCaseTenantId) { camundaCaseTenantIdAttribute.setValue(this, camundaCaseTenantId);
} public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseTask.class, CMMN_ELEMENT_CASE_TASK) .extendsType(Task.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<CaseTask>() { public CaseTask newInstance(ModelTypeInstanceContext instanceContext) { return new CaseTaskImpl(instanceContext); } }); caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF) .build(); /** camunda extensions */ camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING) .namespace(CAMUNDA_NS) .build(); camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION) .namespace(CAMUNDA_NS) .build(); camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java
1
请完成以下Java代码
public boolean accept(@NonNull final T model) { final Range<Instant> range1 = closedOpenRange( TimeUtil.asInstant(lowerBoundColumnName.getValue(model)), TimeUtil.asInstant(upperBoundColumnName.getValue(model))); final Range<Instant> range2 = closedOpenRange(lowerBoundValue, upperBoundValue); return isOverlapping(range1, range2); } public static Range<Instant> closedOpenRange(@Nullable final Instant lowerBound, @Nullable final Instant upperBound) { if (lowerBound == null) { return upperBound == null ? Range.all() : Range.upTo(upperBound, BoundType.OPEN); } else { return upperBound == null ? Range.downTo(lowerBound, BoundType.CLOSED) : Range.closedOpen(lowerBound, upperBound); } } public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2) { if (!range1.isConnected(range2)) { return false; } return !range1.intersection(range2).isEmpty(); } @Deprecated @Override public String toString() { return getSql(); } @Override public String getSql() { buildSqlIfNeeded(); return sqlWhereClause; } @Override
public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return getSqlParams(); } public List<Object> getSqlParams() { buildSqlIfNeeded(); return sqlParams; } private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql(); } else { sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请完成以下Java代码
public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { final UomId uomId = HandlerTools.retrieveUomId(invoiceCandidateRecord); final I_C_UOM uomRecord = loadOutOfTrx(uomId, I_C_UOM.class); return Quantity.of(ONE, uomRecord); } /** * @return {@link PriceAndTax#NONE} because the tax remains unchanged and the price is updated in {@link CandidateAssignmentService}. */ @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return PriceAndTax.NONE; // no changes to be made } @Override public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction( @Nullable final Consumer<I_C_Invoice_Candidate> IGNORED_defaultImplementation) { return ic -> { final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoId(ic.getRecord_ID());
final RefundContractRepository refundContractRepository = SpringContextHolder.instance.getBean(RefundContractRepository.class); final RefundContract refundContract = refundContractRepository.getById(flatrateTermId); final NextInvoiceDate nextInvoiceDate = refundContract.computeNextInvoiceDate(asLocalDate(ic.getDeliveryDate())); ic.setC_InvoiceSchedule_ID(nextInvoiceDate.getInvoiceSchedule().getId().getRepoId()); ic.setDateToInvoice(asTimestamp(nextInvoiceDate.getDateToInvoice())); }; } /** Just return the record's current date */ @Override public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return invoiceCandidateRecord.getDateOrdered(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\invoicecandidatehandler\FlatrateTermRefund_Handler.java
1
请完成以下Java代码
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final String... urlPatterns) { return registerFilter(filterName, filterClass, null, urlPatterns); } private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final Map<String, String> initParameters, final String... urlPatterns) { FilterRegistration filterRegistration = servletContext.getFilterRegistration(filterName); if (filterRegistration == null) { filterRegistration = servletContext.addFilter(filterName, filterClass); filterRegistration.addMappingForUrlPatterns(DISPATCHER_TYPES, true, urlPatterns); if (initParameters != null) { filterRegistration.setInitParameters(initParameters); } log.debug("Filter {} for URL {} registered.", filterName, urlPatterns); }
return filterRegistration; } private ServletRegistration registerServlet(final String servletName, final Class<?> applicationClass, final String... urlPatterns) { ServletRegistration servletRegistration = servletContext.getServletRegistration(servletName); if (servletRegistration == null) { servletRegistration = servletContext.addServlet(servletName, ServletContainer.class); servletRegistration.addMapping(urlPatterns); servletRegistration.setInitParameters(singletonMap(JAXRS_APPLICATION_CLASS, applicationClass.getName())); log.debug("Servlet {} for URL {} registered.", servletName, urlPatterns); } return servletRegistration; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\CamundaBpmWebappInitializer.java
1
请完成以下Java代码
public TypeRef getTypeRef() { return typeRefChild.getChild(this); } public void setTypeRef(TypeRef typeRef) { typeRefChild.setChild(this, typeRef); } public AllowedValues getAllowedValues() { return allowedValuesChild.getChild(this); } public void setAllowedValues(AllowedValues allowedValues) { allowedValuesChild.setChild(this, allowedValues); } public Collection<ItemComponent> getItemComponents() { return itemComponentCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ItemDefinition.class, DMN_ELEMENT_ITEM_DEFINITION) .namespaceUri(LATEST_DMN_NS) .extendsType(NamedElement.class) .instanceProvider(new ModelTypeInstanceProvider<ItemDefinition>() { public ItemDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new ItemDefinitionImpl(instanceContext); }
}); typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE) .build(); isCollectionAttribute = typeBuilder.booleanAttribute(DMN_ATTRIBUTE_IS_COLLECTION) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); typeRefChild = sequenceBuilder.element(TypeRef.class) .build(); allowedValuesChild = sequenceBuilder.element(AllowedValues.class) .build(); itemComponentCollection = sequenceBuilder.elementCollection(ItemComponent.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ItemDefinitionImpl.java
1
请完成以下Java代码
public class DLM_FindPathBetweenRecords extends JavaProcess { @Param(mandatory = true, parameterName = I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID) private I_DLM_Partition_Config configDB; @Param(mandatory = true, parameterName = "AD_Table_Start_ID") private I_AD_Table adTableStart; @Param(mandatory = true, parameterName = "Record_Start_ID") private int recordIdStart; @Param(mandatory = true, parameterName = "AD_Table_Goal_ID") private I_AD_Table adTableGoal; @Param(mandatory = true, parameterName = "Record_Goal_ID") private int recordIdGoal; @Override protected String doIt() throws Exception { final TableRecordReference startReference = TableRecordReference.of(adTableStart.getAD_Table_ID(), recordIdStart); final TableRecordReference goalReference = TableRecordReference.of(adTableGoal.getAD_Table_ID(), recordIdGoal); final IDLMService dlmService = Services.get(IDLMService.class); final IRecordCrawlerService recordCrawlerService = Services.get(IRecordCrawlerService.class); final FindPathIterateResult findPathIterateResult = new FindPathIterateResult( startReference, goalReference); final PartitionConfig config = dlmService.loadPartitionConfig(configDB); addLog("Starting at start record={}, searching for goal record={}", startReference, goalReference); recordCrawlerService.crawl(config, this, findPathIterateResult); addLog("Search done. Found goal record: {}", findPathIterateResult.isFoundGoalRecord());
// new GraphUI().showGraph(findPathIterateResult); if (!findPathIterateResult.isFoundGoalRecord()) { addLog("Upable to reach the goal record from the given start using DLM_Partition_Config= {}", config.getName()); return MSG_OK; } final List<ITableRecordReference> path = findPathIterateResult.getPath(); if (path == null) { addLog("There is no path between start={} and goal={}", startReference, goalReference); return MSG_OK; } addLog("Records that make up the path from start to goal (size={}):", path.size()); for (int i = 0; i < path.size(); i++) { final ITableRecordReference pathElement = path.get(i); pathElement.getModel(this); // make sure the model is loaded and thus shown in the reference's toString output addLog("{}: {}", i, pathElement); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_FindPathBetweenRecords.java
1
请完成以下Java代码
public int getColumnDisplayLength() { return columnDisplayLength; } public void setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; } public boolean isSameLine() { return sameLine; } public void setSameLine(final boolean sameLine) { this.sameLine = sameLine; } /** * Is this a long (string/text) field (over 60/2=30 characters) * * @return true if long field */ public boolean isLongField() { // if (m_vo.displayType == DisplayType.String // || m_vo.displayType == DisplayType.Text // || m_vo.displayType == DisplayType.Memo // || m_vo.displayType == DisplayType.TextLong // || m_vo.displayType == DisplayType.Image) return displayLength >= MAXDISPLAY_LENGTH / 2; // return false; } // isLongField public int getSpanX() { return spanX; } public int getSpanY() { return spanY; } public static final class Builder { private int displayLength = 0; private int columnDisplayLength = 0; private boolean sameLine = false; private int spanX = 1; private int spanY = 1; private Builder() { super(); }
public GridFieldLayoutConstraints build() { return new GridFieldLayoutConstraints(this); } public Builder setDisplayLength(final int displayLength) { this.displayLength = displayLength; return this; } public Builder setColumnDisplayLength(final int columnDisplayLength) { this.columnDisplayLength = columnDisplayLength; return this; } public Builder setSameLine(final boolean sameLine) { this.sameLine = sameLine; return this; } public Builder setSpanX(final int spanX) { this.spanX = spanX; return this; } public Builder setSpanY(final int spanY) { this.spanY = spanY; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldLayoutConstraints.java
1
请在Spring Boot框架中完成以下Java代码
public AttachmentMetadata createdAt(OffsetDateTime createdAt) { this.createdAt = createdAt; return this; } /** * Der Zeitstempel des Erstellens * @return createdAt **/ @Schema(description = "Der Zeitstempel des Erstellens") public OffsetDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; } public AttachmentMetadata archived(Boolean archived) { this.archived = archived; return this; } /** * Kennzeichen, ob Anlage archiviert ist * @return archived **/ @Schema(example = "false", description = "Kennzeichen, ob Anlage archiviert ist") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AttachmentMetadata attachmentMetadata = (AttachmentMetadata) o; return Objects.equals(this.type, attachmentMetadata.type) &&
Objects.equals(this.therapyId, attachmentMetadata.therapyId) && Objects.equals(this.therapyTypeId, attachmentMetadata.therapyTypeId) && Objects.equals(this.woundLocation, attachmentMetadata.woundLocation) && Objects.equals(this.patientId, attachmentMetadata.patientId) && Objects.equals(this.createdBy, attachmentMetadata.createdBy) && Objects.equals(this.createdAt, attachmentMetadata.createdAt) && Objects.equals(this.archived, attachmentMetadata.archived); } @Override public int hashCode() { return Objects.hash(type, therapyId, therapyTypeId, woundLocation, patientId, createdBy, createdAt, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AttachmentMetadata {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n"); sb.append(" woundLocation: ").append(toIndentedString(woundLocation)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\AttachmentMetadata.java
2
请完成以下Java代码
public void invalidateByOrder(final I_C_Order order) { // Consider only purchase orders if (order.isSOTrx()) { return; } final LocalDate date = extractDate(order); final ImmutableSet<ProductId> productIds = getProductIds(order); invalidateByProducts(productIds, date); } private static LocalDate extractDate(final I_C_Order order) { return order.getDateOrdered().toLocalDateTime().toLocalDate(); } private ImmutableSet<ProductId> getProductIds(final I_C_Order order) { final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); return orderDAO.retrieveOrderLines(orderId) .stream() .map(orderLine -> ProductId.ofRepoId(orderLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } public void invalidateByProducts(@NonNull Set<ProductId> productIds, @NonNull LocalDate date) {
if (productIds.isEmpty()) { return; } final ArrayList<Object> sqlValuesParams = new ArrayList<>(); final StringBuilder sqlValues = new StringBuilder(); for (final ProductId productId : productIds) { if (sqlValues.length() > 0) { sqlValues.append(","); } sqlValues.append("(?,?)"); sqlValuesParams.add(productId); sqlValuesParams.add(date); } final String sql = "INSERT INTO " + TABLENAME_Recompute + " (m_product_id, date)" + "VALUES " + sqlValues; DB.executeUpdateAndThrowExceptionOnFail(sql, sqlValuesParams.toArray(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\stats\purchase_max_price\PurchaseLastMaxPriceService.java
1
请完成以下Java代码
public final class HttpsRedirectFilter extends OncePerRequestFilter { private PortMapper portMapper = new PortMapperImpl(); private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE; private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { if (!isInsecure(request)) { chain.doFilter(request, response); return; } if (!this.requestMatcher.matches(request)) { chain.doFilter(request, response); return; } String redirectUri = createRedirectUri(request); this.redirectStrategy.sendRedirect(request, response, redirectUri); } /** * Use this {@link PortMapper} for mapping custom ports * @param portMapper the {@link PortMapper} to use */ public void setPortMapper(PortMapper portMapper) { Assert.notNull(portMapper, "portMapper cannot be null"); this.portMapper = portMapper; }
/** * Use this {@link RequestMatcher} to narrow which requests are redirected to HTTPS. * * The filter already first checks for HTTPS in the uri scheme, so it is not necessary * to include that check in this matcher. * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } private boolean isInsecure(HttpServletRequest request) { return !"https".equals(request.getScheme()); } private String createRedirectUri(HttpServletRequest request) { String url = UrlUtils.buildFullRequestUrl(request); UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url); UriComponents components = builder.build(); int port = components.getPort(); if (port > 0) { Integer httpsPort = this.portMapper.lookupHttpsPort(port); Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port"); builder.port(httpsPort); } return builder.scheme("https").toUriString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\transport\HttpsRedirectFilter.java
1
请完成以下Java代码
protected void prepare() { // nothing to prepare here } @Override protected String doIt() throws Exception { final IQueryFilter<I_C_Printing_Queue> queryFilter = getProcessInfo().getQueryFilterOrElseFalse(); final Iterator<I_C_Printing_Queue> iterator = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Printing_Queue.class, getCtx(), getTrxName()) .filter(queryFilter) .orderBy().addColumn(I_C_Printing_Queue.COLUMN_C_Printing_Queue_ID) .endOrderBy()
.create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterate(I_C_Printing_Queue.class); final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class); for(final I_C_Printing_Queue item: IteratorUtils.asIterable(iterator)) { printingQueueBL.setItemAggregationKey(item); InterfaceWrapperHelper.save(item); } return "@Success@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Printing_Queue_ResetAggregationKeys.java
1
请完成以下Java代码
public static AlarmStatusFilter from(AlarmStatus alarmStatus) { switch (alarmStatus) { case ACTIVE_UNACK: return new AlarmStatusFilter(Optional.of(false), Optional.of(false)); case ACTIVE_ACK: return new AlarmStatusFilter(Optional.of(false), Optional.of(true)); case CLEARED_UNACK: return new AlarmStatusFilter(Optional.of(true), Optional.of(false)); case CLEARED_ACK: return new AlarmStatusFilter(Optional.of(true), Optional.of(true)); default: return EMPTY; } } public static AlarmStatusFilter empty() { return EMPTY; } public boolean hasAnyFilter() { return clearFilter.isPresent() || ackFilter.isPresent(); } public boolean hasClearFilter() { return clearFilter.isPresent(); } public boolean hasAckFilter() { return ackFilter.isPresent(); } public boolean getClearFilter() { return clearFilter.orElseThrow(() -> new RuntimeException("Clear filter is not set! Use `hasClearFilter` to check.")); } public boolean getAckFilter() { return ackFilter.orElseThrow(() -> new RuntimeException("Ack filter is not set! Use `hasAckFilter` to check.")); }
public static AlarmStatusFilter from(Collection<AlarmSearchStatus> statuses) { if (statuses == null || statuses.isEmpty() || statuses.contains(AlarmSearchStatus.ANY)) { return EMPTY; } boolean clearFilter = statuses.contains(AlarmSearchStatus.CLEARED); boolean activeFilter = statuses.contains(AlarmSearchStatus.ACTIVE); Optional<Boolean> clear = Optional.empty(); if (clearFilter && !activeFilter || !clearFilter && activeFilter) { clear = Optional.of(clearFilter); } boolean ackFilter = statuses.contains(AlarmSearchStatus.ACK); boolean unackFilter = statuses.contains(AlarmSearchStatus.UNACK); Optional<Boolean> ack = Optional.empty(); if (ackFilter && !unackFilter || !ackFilter && unackFilter) { ack = Optional.of(ackFilter); } return new AlarmStatusFilter(clear, ack); } public boolean matches(Alarm alarm) { return ackFilter.map(ackFilter -> ackFilter.equals(alarm.isAcknowledged())).orElse(true) && clearFilter.map(clearedFilter -> clearedFilter.equals(alarm.isCleared())).orElse(true); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\AlarmStatusFilter.java
1
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { return decoratedResolver.getValue(context, base, property); } @Override public Class<?> getType(ELContext context, Object base, Object property) { return decoratedResolver.getType(context, base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { decoratedResolver.setValue(context, base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { return decoratedResolver.invoke(context, base, method, paramTypes, params); }
@Override public boolean isReadOnly(ELContext context, Object base, Object property) { return decoratedResolver.isReadOnly(context, base, property); } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return decoratedResolver.getFeatureDescriptors(context, base); } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return decoratedResolver.getCommonPropertyType(context, base); } }
repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ELResolverDecorator.java
1
请完成以下Java代码
public Map<String, Object> getEntryMap() { Map<String, Object> valueMap = new HashMap<String, Object>(); for (String key : outputValues.keySet()) { valueMap.put(key, get(key)); } return valueMap; } public Map<String, TypedValue> getEntryMapTyped() { return outputValues; } @Override public int size() { return outputValues.size(); } @Override public boolean isEmpty() { return outputValues.isEmpty(); } @Override public boolean containsKey(Object key) { return outputValues.containsKey(key); } @Override public Set<String> keySet() { return outputValues.keySet(); } @Override public Collection<Object> values() { List<Object> values = new ArrayList<Object>(); for (TypedValue typedValue : outputValues.values()) { values.add(typedValue.getValue()); } return values; } @Override public String toString() { return outputValues.toString(); } @Override public boolean containsValue(Object value) { return values().contains(value); } @Override public Object get(Object key) { TypedValue typedValue = outputValues.get(key); if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void clear() { throw new UnsupportedOperationException("decision output is immutable"); }
@Override public Set<Entry<String, Object>> entrySet() { Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) { DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue()); entrySet.add(entry); } return entrySet; } protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> { protected final String key; protected final TypedValue typedValue; public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) { this.key = key; this.typedValue = typedValue; } @Override public String getKey() { return key; } @Override public Object getValue() { if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object setValue(Object value) { throw new UnsupportedOperationException("decision output entry is immutable"); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
1
请完成以下Java代码
public List<TypSondertag> getSondertag() { if (sondertag == null) { sondertag = new ArrayList<TypSondertag>(); } return this.sondertag; } /** * Gets the value of the automatischerAbruf property. * */ public boolean isAutomatischerAbruf() { return automatischerAbruf; } /** * Sets the value of the automatischerAbruf property. * */ public void setAutomatischerAbruf(boolean value) { this.automatischerAbruf = value; } /** * Gets the value of the kundenKennung property. * * @return * possible object is * {@link String } * */ public String getKundenKennung() { return kundenKennung;
} /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAntwort.java
1
请在Spring Boot框架中完成以下Java代码
private InvoicePayScheduleLoaderAndSaver newLoaderAndSaver() { return InvoicePayScheduleLoaderAndSaver.builder() .queryBL(queryBL) .trxManager(trxManager) .build(); } public void create(@NonNull final InvoicePayScheduleCreateRequest request) { request.getLines().forEach(line -> createLine(line, request.getInvoiceId())); } private void createLine(@NonNull final InvoicePayScheduleCreateRequest.Line request, @NonNull final InvoiceId invoiceId) { final I_C_InvoicePaySchedule record = newInstance(I_C_InvoicePaySchedule.class); record.setC_Invoice_ID(invoiceId.getRepoId()); InvoicePayScheduleConverter.updateRecord(record, request); saveRecord(record); } public void deleteByInvoiceId(@NonNull final InvoiceId invoiceId) { queryBL.createQueryBuilder(I_C_InvoicePaySchedule.class) .addEqualsFilter(I_C_InvoicePaySchedule.COLUMNNAME_C_Invoice_ID, invoiceId) .create() .delete(); }
public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateById(invoiceId, updater); } public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateByIds(invoiceIds, updater); } public Optional<InvoicePaySchedule> getByInvoiceId(@NonNull final InvoiceId invoiceId) { return newLoaderAndSaver().loadByInvoiceId(invoiceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleRepository.java
2
请在Spring Boot框架中完成以下Java代码
public static <T> Result<T> newFailureResult(CommonBizException commonBizException, T data){ Result<T> result = new Result<>(); result.isSuccess = false; result.errorCode = commonBizException.getCodeEnum().getCode(); result.message = commonBizException.getCodeEnum().getMessage(); result.data = data; return result; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean success) { isSuccess = success; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" + "isSuccess=" + isSuccess + ", errorCode=" + errorCode + ", message='" + message + '\'' + ", data=" + data + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java
2
请完成以下Java代码
public String getExecutionId() { return null; } // non-supported (v6) @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } @Override public void setScopeId(String scopeId) { } @Override public void setSubScopeId(String subScopeId) {
} @Override public void setScopeType(String scopeType) { } @Override public String getScopeDefinitionId() { return null; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { } @Override public String getMetaInfo() { return null; } @Override public void setMetaInfo(String metaInfo) { } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
1
请在Spring Boot框架中完成以下Java代码
public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public void setParentCaseInstanceId(String parentCaseInstanceId) { this.parentCaseInstanceId = parentCaseInstanceId; } public Boolean getWithoutCallbackId() { return withoutCallbackId; } public void setWithoutCallbackId(Boolean withoutCallbackId) { this.withoutCallbackId = withoutCallbackId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; }
public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } 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 void setSortAsc (boolean ascending) { if (ascending) m_multiplier = 1; else m_multiplier = -1; } // setSortAsc /************************************************************************** * Compare Data of two entities * @param o1 object * @param o2 object * @return comparator */ @Override public int compare (Object o1, Object o2) { // Get Objects to compare Object cmp1 = o1; if (o1 instanceof MSort) cmp1 = ((MSort)o1).data; if (cmp1 instanceof NamePair) cmp1 = ((NamePair)cmp1).getName(); Object cmp2 = o2; if (o2 instanceof MSort) cmp2 = ((MSort)o2).data; if (cmp2 instanceof NamePair) cmp2 = ((NamePair)cmp2).getName(); // Comparing Null values if (cmp1 == null) { if (cmp2 == null) return 0; return -1 * m_multiplier; } if (cmp2 == null) return 1 * m_multiplier; /** * compare different data types */ // String if (cmp1 instanceof String && cmp2 instanceof String) { return m_collator.compare(cmp1, cmp2) * m_multiplier; // teo_sarca [ 1672820 ] } // Date else if (cmp1 instanceof Timestamp && cmp2 instanceof Timestamp) { Timestamp t = (Timestamp)cmp1; return t.compareTo((Timestamp)cmp2) * m_multiplier; } // BigDecimal
else if (cmp1 instanceof BigDecimal && cmp2 instanceof BigDecimal) { BigDecimal d = (BigDecimal)cmp1; return d.compareTo((BigDecimal)cmp2) * m_multiplier; } // Integer else if (cmp1 instanceof Integer && cmp2 instanceof Integer) { Integer d = (Integer)cmp1; return d.compareTo((Integer)cmp2) * m_multiplier; } // Double else if (cmp1 instanceof Double && cmp2 instanceof Double) { Double d = (Double)cmp1; return d.compareTo((Double)cmp2) * m_multiplier; } // Convert to string value String s = cmp1.toString(); return m_collator.compare(s, cmp2.toString()) * m_multiplier; // teo_sarca [ 1672820 ] } // compare /** * Equal (based on data, ignores index) * @param obj object * @return true if equal */ @Override public boolean equals (Object obj) { if (obj instanceof MSort) { MSort ms = (MSort)obj; if (data == ms.data) return true; } return false; } // equals /** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("MSort["); sb.append("Index=").append(index).append(",Data=").append(data); sb.append("]"); return sb.toString(); } // toString } // MSort
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\MSort.java
1
请完成以下Java代码
public void setModelPackage (java.lang.String ModelPackage) { set_Value (COLUMNNAME_ModelPackage, ModelPackage); } /** Get ModelPackage. @return Java Package of the model classes */ @Override public java.lang.String getModelPackage () { return (java.lang.String)get_Value(COLUMNNAME_ModelPackage); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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 Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version);
} /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } /** Set WebUIServletListener Class. @param WebUIServletListenerClass Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener */ @Override public void setWebUIServletListenerClass (java.lang.String WebUIServletListenerClass) { set_Value (COLUMNNAME_WebUIServletListenerClass, WebUIServletListenerClass); } /** Get WebUIServletListener Class. @return Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener */ @Override public java.lang.String getWebUIServletListenerClass () { return (java.lang.String)get_Value(COLUMNNAME_WebUIServletListenerClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_EntityType.java
1
请完成以下Java代码
public Group createPartialGroupFromCompensationLine(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { InvoiceCandidateCompensationGroupUtils.assertCompensationLine(invoiceCandidate); final GroupCompensationLine compensationLine = createCompensationLine(invoiceCandidate); final GroupRegularLine aggregatedRegularLine = GroupRegularLine.builder() .lineNetAmt(compensationLine.getBaseAmt()) .build(); final I_C_Order order = invoiceCandidate.getC_Order(); if (order == null) { throw new AdempiereException("Invoice candidate has no order: " + invoiceCandidate); } return Group.builder() .groupId(extractGroupId(invoiceCandidate)) .pricePrecision(orderBL.getPricePrecision(order)) .amountPrecision(orderBL.getAmountPrecision(order)) .regularLine(aggregatedRegularLine) .compensationLine(compensationLine) .build(); } public InvoiceCandidatesStorage createNotSaveableSingleOrderLineStorage(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{ return InvoiceCandidatesStorage.builder() .groupId(extractGroupId(invoiceCandidate)) .invoiceCandidate(invoiceCandidate) .performDatabaseChanges(false) .build(); } public void invalidateCompensationInvoiceCandidatesOfGroup(final GroupId groupId) { final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesForGroupQuery(groupId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true) // only compensation lines .create(); invoiceCandDAO.invalidateCandsFor(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateGroupRepository.java
1
请在Spring Boot框架中完成以下Java代码
public final class AggregationItem { public enum Type { ModelColumn, Attribute } private final AggregationItemId id; private final ILogicExpression includeLogic; private final Type type; private final String columnName; private final int displayType; private final AggregationAttribute attribute; @Builder private AggregationItem( @NonNull final AggregationItemId id, @NonNull final Type type, @Nullable final String columnName, final int displayType, @Nullable final AggregationAttribute attribute, @NonNull final ILogicExpression includeLogic) { if (type == Type.ModelColumn) { Check.assumeNotEmpty(columnName, "columnName not empty"); } else if (type == Type.Attribute) {
Check.assumeNotNull(attribute, "attribute not null"); } this.id = id; this.type = type; this.includeLogic = includeLogic; this.columnName = columnName; this.displayType = displayType; this.attribute = attribute; } public boolean isInclude(final Evaluatee context) { final ILogicExpression includeLogic = getIncludeLogic(); final Boolean include = includeLogic.evaluate(context, OnVariableNotFound.ReturnNoResult); return include != null && include; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\AggregationItem.java
2
请在Spring Boot框架中完成以下Java代码
public class WebuiASIEditingInfo { public static WebuiASIEditingInfoBuilder builder(@NonNull ASIEditingInfo info) { return new WebuiASIEditingInfoBuilder() .contextWindowType(info.getWindowType()) // .contextDocumentPath(contextDocumentPath) // .attributeSetId(info.getAttributeSetId()) .attributeSetName(info.getM_AttributeSet_Name()) .attributeSetDescription(info.getM_AttributeSet_Description()) // .attributeSetInstanceId(info.getAttributeSetInstanceId() != null ? info.getAttributeSetInstanceId() : AttributeSetInstanceId.NONE) .productId(info.getProductId()) .soTrx(info.getSOTrx()) // .callerTableName(info.getCallerTableName()) .callerAdColumnId(info.getCallerColumnId()) // .attributes(info.getAvailableAttributes()); } public static WebuiASIEditingInfo readonlyASI(final AttributeSetInstanceId attributeSetInstanceId) { final ASIEditingInfo info = ASIEditingInfo.builder() .type(WindowType.StrictASIAttributes) .soTrx(SOTrx.SALES) .attributeSetInstanceId(attributeSetInstanceId) .build(); return builder(info).build(); } public static WebuiASIEditingInfo processParameterASI( final AttributeSetInstanceId attributeSetInstanceId, final DocumentPath documentPath) { final ASIEditingInfo info = ASIEditingInfo.builder() .type(WindowType.ProcessParameter)
.soTrx(SOTrx.SALES) .attributeSetInstanceId(attributeSetInstanceId) .build(); return builder(info) .contextDocumentPath(documentPath) .build(); } @NonNull WindowType contextWindowType; DocumentPath contextDocumentPath; @NonNull AttributeSetId attributeSetId; String attributeSetName; String attributeSetDescription; @NonNull AttributeSetInstanceId attributeSetInstanceId; ProductId productId; @NonNull SOTrx soTrx; String callerTableName; int callerAdColumnId; @NonNull @Singular ImmutableList<Attribute> attributes; public ImmutableSet<AttributeId> getAttributeIds() { return attributes.stream() .map(Attribute::getAttributeId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\WebuiASIEditingInfo.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable File getRollbackFile() { return this.rollbackFile; } public void setRollbackFile(@Nullable File rollbackFile) { this.rollbackFile = rollbackFile; } public boolean isTestRollbackOnUpdate() { return this.testRollbackOnUpdate; } public void setTestRollbackOnUpdate(boolean testRollbackOnUpdate) { this.testRollbackOnUpdate = testRollbackOnUpdate; } public @Nullable String getTag() { return this.tag; } public void setTag(@Nullable String tag) { this.tag = tag; } public @Nullable ShowSummary getShowSummary() { return this.showSummary; } public void setShowSummary(@Nullable ShowSummary showSummary) { this.showSummary = showSummary; } public @Nullable ShowSummaryOutput getShowSummaryOutput() { return this.showSummaryOutput; } public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) { this.showSummaryOutput = showSummaryOutput; } public @Nullable UiService getUiService() { return this.uiService; } public void setUiService(@Nullable UiService uiService) { this.uiService = uiService; } public @Nullable Boolean getAnalyticsEnabled() { return this.analyticsEnabled; } public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) { this.analyticsEnabled = analyticsEnabled; } public @Nullable String getLicenseKey() { return this.licenseKey; } public void setLicenseKey(@Nullable String licenseKey) { this.licenseKey = licenseKey; } /** * Enumeration of types of summary to show. Values are the same as those on * {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum * is not used directly. */ public enum ShowSummary { /** * Do not show a summary. */ OFF, /** * Show a summary. */ SUMMARY, /** * Show a verbose summary. */ VERBOSE } /**
* Enumeration of destinations to which the summary should be output. Values are the * same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards * compatibility, the Liquibase enum is not used directly. */ public enum ShowSummaryOutput { /** * Log the summary. */ LOG, /** * Output the summary to the console. */ CONSOLE, /** * Log the summary and output it to the console. */ ALL } /** * Enumeration of types of UIService. Values are the same as those on * {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is * not used directly. */ public enum UiService { /** * Console-based UIService. */ CONSOLE, /** * Logging-based UIService. */ LOGGER } }
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java
2
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto, HistoricActivityInstance historicActivityInstance) { dto.id = historicActivityInstance.getId(); dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId(); dto.activityId = historicActivityInstance.getActivityId(); dto.activityName = historicActivityInstance.getActivityName(); dto.activityType = historicActivityInstance.getActivityType(); dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId(); dto.processInstanceId = historicActivityInstance.getProcessInstanceId();
dto.executionId = historicActivityInstance.getExecutionId(); dto.taskId = historicActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId(); dto.assignee = historicActivityInstance.getAssignee(); dto.startTime = historicActivityInstance.getStartTime(); dto.endTime = historicActivityInstance.getEndTime(); dto.durationInMillis = historicActivityInstance.getDurationInMillis(); dto.canceled = historicActivityInstance.isCanceled(); dto.completeScope = historicActivityInstance.isCompleteScope(); dto.tenantId = historicActivityInstance.getTenantId(); dto.removalTime = historicActivityInstance.getRemovalTime(); dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityInstanceDto.java
1
请完成以下Java代码
public Inventory updateById(final InventoryId inventoryId, UnaryOperator<Inventory> updater) { return trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().updateById(inventoryId, updater)); } public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater) { trxManager.runInThreadInheritedTrx(() -> newLoaderAndSaver().updateByQuery(query, updater)); } public Stream<InventoryReference> streamReferences(@NonNull final InventoryQuery query) { return newLoaderAndSaver().streamReferences(query); } public void setQtyCountToQtyBookForInventory(@NonNull final InventoryId inventoryId) { // update M_InventoryLine
final ICompositeQueryUpdater<org.compiere.model.I_M_InventoryLine> updaterInventoryLine = queryBL.createCompositeQueryUpdater(org.compiere.model.I_M_InventoryLine.class) .addSetColumnFromColumn(org.compiere.model.I_M_InventoryLine.COLUMNNAME_QtyCount, ModelColumnNameValue.forColumnName(org.compiere.model.I_M_InventoryLine.COLUMNNAME_QtyBook)); queryBL.createQueryBuilder(org.compiere.model.I_M_InventoryLine.class) .addEqualsFilter(org.compiere.model.I_M_InventoryLine.COLUMNNAME_M_Inventory_ID, inventoryId) .create().update(updaterInventoryLine); // update M_InventoryLine_HU final ICompositeQueryUpdater<I_M_InventoryLine_HU> updaterInventoryLineHU = queryBL.createCompositeQueryUpdater(I_M_InventoryLine_HU.class) .addSetColumnFromColumn(I_M_InventoryLine_HU.COLUMNNAME_QtyCount, ModelColumnNameValue.forColumnName(I_M_InventoryLine_HU.COLUMNNAME_QtyBook)); queryBL.createQueryBuilder(I_M_InventoryLine_HU.class) .addEqualsFilter(I_M_InventoryLine_HU.COLUMNNAME_M_Inventory_ID, inventoryId) .create().update(updaterInventoryLineHU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryRepository.java
1
请完成以下Java代码
public class AuthorBookTransformer implements ResultTransformer { private Map<Long, AuthorDto> authorsDtoMap = new HashMap<>(); @Override public Object transformTuple(Object[] os, String[] strings) { Long authorId = ((Number) os[0]).longValue(); AuthorDto authorDto = authorsDtoMap.get(authorId); if (authorDto == null) { authorDto = new AuthorDto(); authorDto.setId(((Number) os[0]).longValue()); authorDto.setName((String) os[1]); authorDto.setAge((int) os[2]); } BookDto bookDto = new BookDto(); bookDto.setId(((Number) os[3]).longValue());
bookDto.setTitle((String) os[4]); authorDto.addBook(bookDto); authorsDtoMap.putIfAbsent(authorDto.getId(), authorDto); return authorDto; } @Override public List<AuthorDto> transformList(List list) { return new ArrayList<>(authorsDtoMap.values()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoCustomResultTransformer\src\main\java\com\bookstore\transformer\AuthorBookTransformer.java
1
请完成以下Java代码
public void fireHistoricIdentityLinkEvent(final HistoryEventType eventType) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); HistoryLevel historyLevel = processEngineConfiguration.getHistoryLevel(); if(historyLevel.isHistoryEventProduced(eventType, this)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { HistoryEvent event = null; if (HistoryEvent.IDENTITY_LINK_ADD.equals(eventType.getEventName())) { event = producer.createHistoricIdentityLinkAddEvent(IdentityLinkEntity.this); } else if (HistoryEvent.IDENTITY_LINK_DELETE.equals(eventType.getEventName())) { event = producer.createHistoricIdentityLinkDeleteEvent(IdentityLinkEntity.this); } return event; } }); } } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (processDefId != null) { referenceIdAndClass.put(processDefId, ProcessDefinitionEntity.class); } if (taskId != null) { referenceIdAndClass.put(taskId, TaskEntity.class); } return referenceIdAndClass; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", type=" + type + ", userId=" + userId + ", groupId=" + groupId + ", taskId=" + taskId + ", processDefId=" + processDefId + ", task=" + task + ", processDef=" + processDef + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityLinkEntity.java
1
请完成以下Java代码
public int getSqlType() { return Types.VARCHAR; } @Override public Class<Salary> returnedClass() { return Salary.class; } @Override public boolean equals(Salary x, Salary y) { if (x == y) return true; if (Objects.isNull(x) || Objects.isNull(y)) return false; return x.equals(y); } @Override public int hashCode(Salary x) { return x.hashCode(); } @Override public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); String salaryValue = rs.getString(position); salary.setAmount(Long.parseLong(salaryValue.split(" ")[1])); salary.setCurrency(salaryValue.split(" ")[0]); return salary; } @Override public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.VARCHAR); else { Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(), value.getCurrency(), localCurrency); st.setString(index, value.getCurrency() + " " + salaryValue); } }
@Override public Salary deepCopy(Salary value) { if (Objects.isNull(value)) return null; Salary newSal = new Salary(); newSal.setAmount(value.getAmount()); newSal.setCurrency(value.getCurrency()); return newSal; } @Override public boolean isMutable() { return true; } @Override public Serializable disassemble(Salary value) { return deepCopy(value); } @Override public Salary assemble(Serializable cached, Object owner) { return deepCopy((Salary) cached); } @Override public Salary replace(Salary detached, Salary managed, Object owner) { return detached; } @Override public void setParameterValues(Properties parameters) { this.localCurrency = parameters.getProperty("currency"); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java
1
请完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); }
@Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Activity.java
1
请完成以下Java代码
protected IExternalSystemChildConfigId getExternalChildConfigId() { final int id; if (this.childConfigId > 0) { id = this.childConfigId; } else { final IExternalSystemChildConfig childConfig = externalSystemConfigDAO.getChildByParentIdAndType(ExternalSystemParentConfigId.ofRepoId(getRecord_ID()), getExternalSystemType()) .orElseThrow(() -> new AdempiereException("No childConfig found for type WooCommerce and parent config") .appendParametersToMessage() .setParameter("externalSystemParentConfigId:", ExternalSystemParentConfigId.ofRepoId(getRecord_ID()))); id = childConfig.getId().getRepoId(); } return ExternalSystemWooCommerceConfigId.ofRepoId(id); } @Override protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final ExternalSystemWooCommerceConfig woocommerceConfig = ExternalSystemWooCommerceConfig.cast(externalSystemParentConfig.getChildConfig()); if (EmptyUtil.isEmpty(woocommerceConfig.getCamelHttpResourceAuthKey())) { throw new AdempiereException("camelHttpResourceAuthKey for childConfig should not be empty at this point") .appendParametersToMessage() .setParameter("childConfigId", woocommerceConfig.getId()); } final Map<String, String> parameters = new HashMap<>(); parameters.put(PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY, woocommerceConfig.getCamelHttpResourceAuthKey());
parameters.put(PARAM_CHILD_CONFIG_VALUE, woocommerceConfig.getValue()); return parameters; } @Override protected String getTabName() { return ExternalSystemType.WOO.getValue(); } @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.WOO; } @Override protected long getSelectedRecordCount(@NonNull final IProcessPreconditionsContext context) { return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_ExternalSystem_Config_WooCommerce.Table_Name.equals(recordRef.getTableName())) .count(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeWooCommerceAction.java
1
请完成以下Java代码
public String host() { return host; } public void setHost(String host) { this.host = host; } @Override public int port() { return port; } public void setPort(int port) { this.port = port; } @Override public Transport transport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } @Override public boolean isStartTlsEnabled() { return startTlsEnabled;
} public void setStartTlsEnabled(boolean startTlsEnabled) { this.startTlsEnabled = startTlsEnabled; } @Override public String user() { return user; } public void setUser(String user) { this.user = user; } @Override public String password() { return password; } public void setPassword(String password) { this.password = password; } }
repos\flowable-engine-main\modules\flowable-mail\src\main\java\org\flowable\mail\common\impl\BaseMailHostServerConfiguration.java
1
请完成以下Java代码
public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Grand Total. @param GrandTotal Total amount of document */ public void setGrandTotal (BigDecimal GrandTotal) { set_Value (COLUMNNAME_GrandTotal, GrandTotal); } /** Get Grand Total. @return Total amount of document */ public BigDecimal getGrandTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal); if (bd == null) return Env.ZERO; return bd; } /** Set Include All Currencies. @param IsAllCurrencies Report not just foreign currency Invoices */ public void setIsAllCurrencies (boolean IsAllCurrencies) { set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies)); } /** Get Include All Currencies. @return Report not just foreign currency Invoices */ public boolean isAllCurrencies () {
Object oo = get_Value(COLUMNNAME_IsAllCurrencies); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open Amount. @param OpenAmt Open item amount */ public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Percent. @param Percent Percentage */ public void setPercent (BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } /** Get Percent. @return Percentage */ public BigDecimal getPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent); 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_T_InvoiceGL.java
1
请完成以下Java代码
public class AuthorizationCheckResultDto { protected String permissionName; protected String resourceName; protected String resourceId; protected Boolean isAuthorized; public AuthorizationCheckResultDto() { } public AuthorizationCheckResultDto(boolean userAuthorized, String permissionName, ResourceUtil resource, String resourceId) { isAuthorized = userAuthorized; this.permissionName = permissionName; resourceName = resource.resourceName(); this.resourceId = resourceId; } public String getPermissionName() { return permissionName; } public void setPermissionName(String permissionName) { this.permissionName = permissionName; } public Boolean isAuthorized() { return isAuthorized; }
public void setAuthorized(Boolean isAuthorized) { this.isAuthorized = isAuthorized; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationCheckResultDto.java
1
请在Spring Boot框架中完成以下Java代码
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 void updateMobileApplicationTrl(final MobileApplicationRepoId mobileApplicationRepoId, @NonNull final String adLanguage) { DB.executeFunctionCallEx( ITrx.TRXNAME_ThreadInherited, addUpdateFunctionCall(FUNCTION_update_Mobile_Application_TRLs, mobileApplicationRepoId, adLanguage), null); } @SuppressWarnings("SameParameterValue") private String addUpdateFunctionCall(final String functionCall, final MobileApplicationRepoId mobileApplicationRepoId, final String adLanguage) { return MigrationScriptFileLoggerHolder.DDL_PREFIX + " select " + functionCall + "(" + mobileApplicationRepoId.getRepoId() + "," + DB.TO_STRING(adLanguage) + ") "; } // // // // // private static class MobileApplicationInfoMap { @NonNull private final ImmutableList<MobileApplicationInfo> list; @NonNull private final ImmutableMap<MobileApplicationId, MobileApplicationInfo> byApplicationId; private MobileApplicationInfoMap(@NonNull final List<MobileApplicationInfo> list) { this.list = ImmutableList.copyOf(list);
this.byApplicationId = Maps.uniqueIndex(list, MobileApplicationInfo::getId); } public MobileApplicationInfo getById(final MobileApplicationId applicationId) { final MobileApplicationInfo applicationInfo = byApplicationId.get(applicationId); if (applicationInfo == null) { throw new AdempiereException("No application info found for " + applicationId); } return applicationInfo; } public List<MobileApplicationInfo> toList() { return list; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\repository\MobileApplicationInfoRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class DunningConfig implements IDunningEditableConfig { private IDunnableSourceFactory dunnableSourceFactory; private IDunningCandidateProducerFactory dunningCandidateProducerFactory; private Class<? extends IDunningCandidateSource> dunningCandidateSourceClass; private Class<? extends IDunningProducer> dunningProducerClass; public DunningConfig() { // Set defaults dunnableSourceFactory = new DefaultDunnableSourceFactory(); dunningCandidateProducerFactory = new DefaultDunningCandidateProducerFactory(); dunningCandidateSourceClass = DefaultDunningCandidateSource.class; dunningProducerClass = DefaultDunningProducer.class; } @Override public IDunnableSourceFactory getDunnableSourceFactory() { return dunnableSourceFactory; } @Override public void setDunnableSourceFactory(IDunnableSourceFactory dunnableSourceFactory) { Check.assume(dunnableSourceFactory != null, "dunnableSourceFactory is not null"); this.dunnableSourceFactory = dunnableSourceFactory; } @Override public IDunningCandidateProducerFactory getDunningCandidateProducerFactory() { return dunningCandidateProducerFactory; } @Override public void setDunningCandidateProducerFactory(IDunningCandidateProducerFactory dunningCandidateProducerFactory) { Check.assume(dunningCandidateProducerFactory != null, "dunningCandidateProducerFactory is not null"); this.dunningCandidateProducerFactory = dunningCandidateProducerFactory; } @Override public IDunningProducer createDunningProducer() { try { final IDunningProducer producer = dunningProducerClass.newInstance(); return producer; } catch (Exception e) { throw new DunningException("Cannot create " + IDunningProducer.class + " for " + dunningProducerClass, e); } }
@Override public void setDunningProducerClass(Class<IDunningProducer> dunningProducerClass) { Check.assume(dunningProducerClass != null, "dunningProducerClass is not null"); this.dunningProducerClass = dunningProducerClass; } @Override public IDunningCandidateSource createDunningCandidateSource() { try { final IDunningCandidateSource source = dunningCandidateSourceClass.newInstance(); return source; } catch (Exception e) { throw new DunningException("Cannot create " + IDunningCandidateSource.class + " for " + dunningCandidateSourceClass, e); } } @Override public void setDunningCandidateSourceClass(Class<? extends IDunningCandidateSource> dunningCandidateSourceClass) { Check.assume(dunningCandidateSourceClass != null, "dunningCandidateSourceClass is not null"); this.dunningCandidateSourceClass = dunningCandidateSourceClass; } @Override public String toString() { return "DunningConfig [" + "dunnableSourceFactory=" + dunnableSourceFactory + ", dunningCandidateProducerFactory=" + dunningCandidateProducerFactory + ", dunningCandidateSourceClass=" + dunningCandidateSourceClass + ", dunningProducerClass=" + dunningProducerClass + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningConfig.java
2
请完成以下Java代码
public class TreeReverser { public void reverseRecursive(TreeNode treeNode) { if (treeNode == null) { return; } TreeNode temp = treeNode.getLeftChild(); treeNode.setLeftChild(treeNode.getRightChild()); treeNode.setRightChild(temp); reverseRecursive(treeNode.getLeftChild()); reverseRecursive(treeNode.getRightChild()); } public void reverseIterative(TreeNode treeNode) { LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); if (treeNode != null) { queue.add(treeNode); } while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.getLeftChild() != null) queue.add(node.getLeftChild()); if (node.getRightChild() != null) queue.add(node.getRightChild());
TreeNode temp = node.getLeftChild(); node.setLeftChild(node.getRightChild()); node.setRightChild(temp); } } public String toString(TreeNode root) { if (root == null) { return ""; } StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" "); buffer.append(toString(root.getLeftChild())); buffer.append(toString(root.getRightChild())); return buffer.toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\reversingtree\TreeReverser.java
1
请完成以下Java代码
private final void assertEditing() { Check.assume(isEditing(), HUException.class, "Editor shall be in editing mode"); } @Override public ILUTUConfigurationEditor save() { assertEditing(); final I_M_HU_LUTU_Configuration lutuConfigurationInitial = getLUTUConfiguration(); final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); // // Check if we need to use the new configuration or we are ok with the old one final I_M_HU_LUTU_Configuration lutuConfigurationToUse; if (InterfaceWrapperHelper.isNew(lutuConfigurationInitial)) { lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing; } else if (lutuFactory.isSameForHUProducer(lutuConfigurationInitial, lutuConfigurationEditing)) { // Copy all values from our new configuration to initial configuration InterfaceWrapperHelper.copyValues(lutuConfigurationEditing, lutuConfigurationInitial, false); // honorIsCalculated=false lutuFactory.save(lutuConfigurationInitial); lutuConfigurationToUse = lutuConfigurationInitial; } else { lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing;
} _lutuConfigurationInitial = lutuConfigurationToUse; _lutuConfigurationEditing = null; // stop editing mode return this; } @Override public ILUTUConfigurationEditor pushBackToModel() { if (isEditing()) { save(); } final I_M_HU_LUTU_Configuration lutuConfiguration = getLUTUConfiguration(); lutuConfigurationManager.setCurrentLUTUConfigurationAndSave(lutuConfiguration); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\LUTUConfigurationEditor.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonOLCandCreateBulkRequest { public static JsonOLCandCreateBulkRequest of(@NonNull final JsonOLCandCreateRequest request) { return new JsonOLCandCreateBulkRequest(ImmutableList.of(request)); } @JsonProperty("requests") List<JsonOLCandCreateRequest> requests; @JsonCreator @Builder private JsonOLCandCreateBulkRequest(@JsonProperty("requests") @Singular final List<JsonOLCandCreateRequest> requests) { this.requests = ImmutableList.copyOf(requests); } public JsonOLCandCreateBulkRequest validate() { for (final JsonOLCandCreateRequest request : requests) { request.validate(); } return this; }
private JsonOLCandCreateBulkRequest map(@NonNull final UnaryOperator<JsonOLCandCreateRequest> mapper) { if (requests.isEmpty()) { return this; } final ImmutableList<JsonOLCandCreateRequest> newRequests = this.requests.stream() .map(mapper) .collect(ImmutableList.toImmutableList()); return new JsonOLCandCreateBulkRequest(newRequests); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v2\request\JsonOLCandCreateBulkRequest.java
2
请在Spring Boot框架中完成以下Java代码
public class C_Flatrate_RefundConfig { private final RefundConfigRepository refundConfigRepository; public C_Flatrate_RefundConfig(@NonNull final RefundConfigRepository refundConfigRepository) { this.refundConfigRepository = refundConfigRepository; Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_C_Flatrate_RefundConfig.COLUMNNAME_RefundBase) public void resetRefundValue(@NonNull final I_C_Flatrate_RefundConfig configRecord) { final String refundBase = configRecord.getRefundBase(); if (X_C_Flatrate_RefundConfig.REFUNDBASE_Percentage.equals(refundBase)) { configRecord.setRefundAmt(null); } else if (X_C_Flatrate_RefundConfig.REFUNDBASE_Amount.equals(refundBase)) { configRecord.setRefundPercent(null); } else { Check.fail("Unsupported C_Flatrate_RefundConfig.RefundBase value={}; configRecord={}", refundBase, configRecord); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void assertValid(@NonNull final I_C_Flatrate_RefundConfig configRecord) { if (configRecord.getC_Flatrate_Conditions_ID() <= 0) { return;
} final RefundConfigQuery query = RefundConfigQuery .builder() .conditionsId(ConditionsId.ofRepoId(configRecord.getC_Flatrate_Conditions_ID())) .build(); final List<RefundConfig> existingRefundConfigs = refundConfigRepository.getByQuery(query); final RefundConfig newRefundConfig = refundConfigRepository.ofRecord(configRecord); final ArrayList<RefundConfig> allRefundConfigs = new ArrayList<>(existingRefundConfigs); allRefundConfigs.add(newRefundConfig); RefundConfigs.assertValid(allRefundConfigs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\interceptor\C_Flatrate_RefundConfig.java
2
请完成以下Java代码
protected String getFileResourceName(Resource resource) { try { return resource.getFile().getAbsolutePath(); } catch (IOException e) { return resource.getFilename(); } } @Override public ProcessEngineConfigurationImpl setDataSource(DataSource dataSource) { if(dataSource instanceof TransactionAwareDataSourceProxy) { return super.setDataSource(dataSource); } else { // Wrap datasource in Transaction-aware proxy DataSource proxiedDataSource = new TransactionAwareDataSourceProxy(dataSource); return super.setDataSource(proxiedDataSource); } } public PlatformTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; }
public Resource[] getDeploymentResources() { return deploymentResources; } public void setDeploymentResources(Resource[] deploymentResources) { this.deploymentResources = deploymentResources; } public String getDeploymentTenantId() { return deploymentTenantId; } public void setDeploymentTenantId(String deploymentTenantId) { this.deploymentTenantId = deploymentTenantId; } public boolean isDeployChangedOnly() { return deployChangedOnly; } public void setDeployChangedOnly(boolean deployChangedOnly) { this.deployChangedOnly = deployChangedOnly; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringTransactionsProcessEngineConfiguration.java
1
请完成以下Java代码
public C_AggregationItem_Builder setAD_Column(@Nullable final String columnName) { if (isBlank(columnName)) { this.adColumnId = null; } else { this.adColumnId = Services.get(IADTableDAO.class).retrieveColumnId(adTableId, columnName); } return this; } private AdColumnId getAD_Column_ID() { return adColumnId; } public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation) { this.includedAggregation = includedAggregation; return this; } private I_C_Aggregation getIncluded_Aggregation() { return includedAggregation; } public C_AggregationItem_Builder setIncludeLogic(final String includeLogic) { this.includeLogic = includeLogic;
return this; } private String getIncludeLogic() { return includeLogic; } public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute) { this.attribute = attribute; return this; } private I_C_Aggregation_Attribute getC_Aggregation_Attribute() { return this.attribute; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java
1
请完成以下Java代码
private static class ExtendTermsResult { int extendedCounter = 0; int errorCounter = 0; public void addToThis(@NonNull final C_Flatrate_Term_Extend_And_Notify_User.ExtendTermsResult other) { extendedCounter += other.extendedCounter; errorCounter += other.errorCounter; } public int getCounterSum() { return extendedCounter + errorCounter; } } private boolean tryExtendTerm(@NonNull final ContractExtendingRequest context) {
try { flatrateBL.extendContractAndNotifyUser(context); return true; } catch (final RuntimeException e) { final I_C_Flatrate_Term contract = context.getContract(); final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e); addLog("Error extending C_FlatrateTerm_ID={} with C_Flatrate_Data_ID={}; AD_Issue_ID={}; {} with message={}", contract.getC_Flatrate_Term_ID(), contract.getC_Flatrate_Data_ID(), issueId, e.getClass().getName(), e.getMessage()); return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Extend_And_Notify_User.java
1
请完成以下Java代码
public BigDecimal getQtyCapacity() { return capacityTotal.toBigDecimal(); } @Override public IAllocationRequest addQty(final IAllocationRequest request) { throw new AdempiereException("Adding Qty is not supported on this level"); } @Override public IAllocationRequest removeQty(final IAllocationRequest request) { throw new AdempiereException("Removing Qty is not supported on this level"); } /** * Returns always false because negative storages are not supported (see {@link #removeQty(IAllocationRequest)}) * * @return false */ @Override public boolean isAllowNegativeStorage() { return false; } @Override public void markStaled()
{ // nothing, so far, itemStorage is always database coupled, no in memory values } @Override public boolean isEmpty() { return huStorage.isEmpty(getProductId()); } @Override public I_M_HU getM_HU() { return huStorage.getM_HU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUProductStorage.java
1
请完成以下Java代码
protected void scheduleProcessDefinitionActivation(CommandContext commandContext, DeploymentEntity deployment) { for (ProcessDefinitionEntity processDefinitionEntity : deployment.getDeployedArtifacts(ProcessDefinitionEntity.class)) { // If activation date is set, we first suspend all the process definition SuspendProcessDefinitionCmd suspendProcessDefinitionCmd = new SuspendProcessDefinitionCmd(processDefinitionEntity, false, null, deployment.getTenantId()); suspendProcessDefinitionCmd.execute(commandContext); // And we schedule an activation at the provided date ActivateProcessDefinitionCmd activateProcessDefinitionCmd = new ActivateProcessDefinitionCmd( processDefinitionEntity, false, deploymentBuilder.getProcessDefinitionsActivationDate(), deployment.getTenantId()); activateProcessDefinitionCmd.execute(commandContext); } } // private boolean resourcesDiffer(ByteArrayEntity value, ByteArrayEntity other) { // if (value == null && other == null) { // return false; // } // String bytes = createKey(value.getBytes()); // String savedBytes = other == null ? null : createKey(other.getBytes()); // return !bytes.equals(savedBytes); // }
// // private String createKey(byte[] bytes) { // if (bytes == null) { // return ""; // } // MessageDigest digest; // try { // digest = MessageDigest.getInstance("MD5"); // } catch (NoSuchAlgorithmException e) { // throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK)."); // } // bytes = digest.digest(bytes); // return String.format("%032x", new BigInteger(1, bytes)); // } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\DeployCmd.java
1
请完成以下Java代码
public void setContentClassIdFieldName(String contentClassIdFieldName) { this.contentClassIdFieldName = contentClassIdFieldName; } public String getKeyClassIdFieldName() { return this.keyClassIdFieldName; } /** * Configure header name for map key type information. * @param keyClassIdFieldName the header name. * @since 2.1.3 */ public void setKeyClassIdFieldName(String keyClassIdFieldName) { this.keyClassIdFieldName = keyClassIdFieldName; } public void setIdClassMapping(Map<String, Class<?>> idClassMapping) { this.idClassMapping.putAll(idClassMapping); createReverseMap(); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected @Nullable ClassLoader getClassLoader() { return this.classLoader; } protected void addHeader(Headers headers, String headerName, Class<?> clazz) { if (this.classIdMapping.containsKey(clazz)) { headers.add(new RecordHeader(headerName, this.classIdMapping.get(clazz))); } else { headers.add(new RecordHeader(headerName, clazz.getName().getBytes(StandardCharsets.UTF_8))); } } protected String retrieveHeader(Headers headers, String headerName) { String classId = retrieveHeaderAsString(headers, headerName); if (classId == null) { throw new MessageConversionException( "failed to convert Message content. Could not resolve " + headerName + " in header"); } return classId; }
protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) { Header header = headers.lastHeader(headerName); if (header != null) { String classId = null; if (header.value() != null) { classId = new String(header.value(), StandardCharsets.UTF_8); } return classId; } return null; } private void createReverseMap() { this.classIdMapping.clear(); for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) { String id = entry.getKey(); Class<?> clazz = entry.getValue(); this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8)); } } public Map<String, Class<?>> getIdClassMapping() { return Collections.unmodifiableMap(this.idClassMapping); } /** * Configure the TypeMapper to use default key type class. * @param isKey Use key type headers if true * @since 2.1.3 */ public void setUseForKey(boolean isKey) { if (isKey) { setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME); setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME); setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java
1
请完成以下Java代码
public class SysCategoryModel { /**主键*/ private java.lang.String id; /**父级节点*/ private java.lang.String pid; /**类型名称*/ private java.lang.String name; /**类型编码*/ private java.lang.String code; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; }
public void setPid(String pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysCategoryModel.java
1
请完成以下Java代码
public boolean isVerfuegbarkeitEinzelnSpezifischeRueckmeldungVereinbart() { return verfuegbarkeitEinzelnSpezifischeRueckmeldungVereinbart; } /** * Sets the value of the verfuegbarkeitEinzelnSpezifischeRueckmeldungVereinbart property. * */ public void setVerfuegbarkeitEinzelnSpezifischeRueckmeldungVereinbart(boolean value) { this.verfuegbarkeitEinzelnSpezifischeRueckmeldungVereinbart = value; } /** * Gets the value of the verfuegbarkeitBulkVereinbart property. * */ public boolean isVerfuegbarkeitBulkVereinbart() { return verfuegbarkeitBulkVereinbart; } /** * Sets the value of the verfuegbarkeitBulkVereinbart property. * */ public void setVerfuegbarkeitBulkVereinbart(boolean value) { this.verfuegbarkeitBulkVereinbart = value; } /** * Gets the value of the ruecknahmeangebotVereinbart property. * */ public boolean isRuecknahmeangebotVereinbart() { return ruecknahmeangebotVereinbart; } /** * Sets the value of the ruecknahmeangebotVereinbart property. * */ public void setRuecknahmeangebotVereinbart(boolean value) { this.ruecknahmeangebotVereinbart = value; } /** * Gets the value of the gueltigAb property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getGueltigAb() { return gueltigAb;
} /** * Sets the value of the gueltigAb property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setGueltigAb(XMLGregorianCalendar value) { this.gueltigAb = value; } /** * Gets the value of the kundenKennung property. * * @return * possible object is * {@link String } * */ public String getKundenKennung() { return kundenKennung; } /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenAntwort.java
1
请完成以下Java代码
public Class<?> getModelClass() { return modelClass; } @Override public String getTableName() { return tableName; } @Override public final IModelMethodInfo getMethodInfo(final Method method) { modelMethodInfosLock.lock(); try { final Map<Method, IModelMethodInfo> methodInfos = getMethodInfos0(); IModelMethodInfo methodInfo = methodInfos.get(method); // // If methodInfo was not found, try to create it now if (methodInfo == null) { methodInfo = introspector.createModelMethodInfo(method); if (methodInfo == null) { throw new IllegalStateException("No method info was found for " + method + " in " + this); } methodInfos.put(method, methodInfo); } return methodInfo; } finally { modelMethodInfosLock.unlock(); } } /** * Gets the inner map of {@link Method} to {@link IModelMethodInfo}. * * NOTE: this method is not thread safe * * @return */ private final Map<Method, IModelMethodInfo> getMethodInfos0() { if (_modelMethodInfos == null) { _modelMethodInfos = introspector.createModelMethodInfos(getModelClass()); } return _modelMethodInfos; } @Override public synchronized final Set<String> getDefinedColumnNames() { if (_definedColumnNames == null) {
_definedColumnNames = findDefinedColumnNames(); } return _definedColumnNames; } @SuppressWarnings("unchecked") private final Set<String> findDefinedColumnNames() { // // Collect all columnnames final ImmutableSet.Builder<String> columnNamesBuilder = ImmutableSet.builder(); ReflectionUtils.getAllFields(modelClass, new Predicate<Field>() { @Override public boolean apply(final Field field) { final String fieldName = field.getName(); if (fieldName.startsWith("COLUMNNAME_")) { final String columnName = fieldName.substring("COLUMNNAME_".length()); columnNamesBuilder.add(columnName); } return false; } }); return columnNamesBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassInfo.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, Object> getKeysSize() throws Exception { return redisService.getKeysSize(); } /** * 获取redis key数量 for 报表 * @return * @throws Exception */ @GetMapping("/keysSizeForReport") public Map<String, JSONArray> getKeysSizeReport() throws Exception { return redisService.getMapForReport("1"); } /** * 获取redis 内存 for 报表 * * @return * @throws Exception */ @GetMapping("/memoryForReport") public Map<String, JSONArray> memoryForReport() throws Exception { return redisService.getMapForReport("2"); } /** * 获取redis 全部信息 for 报表 * @return * @throws Exception */ @GetMapping("/infoForReport") public Map<String, JSONArray> infoForReport() throws Exception { return redisService.getMapForReport("3"); } @GetMapping("/memoryInfo") public Map<String, Object> getMemoryInfo() throws Exception { return redisService.getMemoryInfo(); } /** * @功能:获取磁盘信息
* @param request * @param response * @return */ @GetMapping("/queryDiskInfo") public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){ Result<List<Map<String,Object>>> res = new Result<>(); try { // 当前文件系统类 FileSystemView fsv = FileSystemView.getFileSystemView(); // 列出所有windows 磁盘 File[] fs = File.listRoots(); log.info("查询磁盘信息:"+fs.length+"个"); List<Map<String,Object>> list = new ArrayList<>(); for (int i = 0; i < fs.length; i++) { if(fs[i].getTotalSpace()==0) { continue; } Map<String,Object> map = new HashMap(5); map.put("name", fsv.getSystemDisplayName(fs[i])); map.put("max", fs[i].getTotalSpace()); map.put("rest", fs[i].getFreeSpace()); map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace()); list.add(map); log.info(map.toString()); } res.setResult(list); res.success("查询成功"); } catch (Exception e) { res.error500("查询失败"+e.getMessage()); } return res; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\controller\ActuatorRedisController.java
2
请完成以下Java代码
public static Vertex newPersonInstance(String realWord) { return newPersonInstance(realWord, 1000); } /** * 创建一个音译人名实例 * * @param realWord * @return */ public static Vertex newTranslatedPersonInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_PEOPLE, realWord, new CoreDictionary.Attribute(Nature.nrf, frequency)); } /** * 创建一个日本人名实例 * * @param realWord * @return */ public static Vertex newJapanesePersonInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_PEOPLE, realWord, new CoreDictionary.Attribute(Nature.nrj, frequency)); } /** * 创建一个人名实例 * * @param realWord * @param frequency * @return */ public static Vertex newPersonInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_PEOPLE, realWord, new CoreDictionary.Attribute(Nature.nr, frequency)); } /** * 创建一个地名实例 * * @param realWord * @param frequency * @return */ public static Vertex newPlaceInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_PLACE, realWord, new CoreDictionary.Attribute(Nature.ns, frequency)); } /** * 创建一个机构名实例 * * @param realWord * @param frequency * @return */ public static Vertex newOrganizationInstance(String realWord, int frequency) { return new Vertex(Predefine.TAG_GROUP, realWord, new CoreDictionary.Attribute(Nature.nt, frequency)); } /** * 创建一个时间实例 * * @param realWord 时间对应的真实字串 * @return 时间顶点
*/ public static Vertex newTimeInstance(String realWord) { return new Vertex(Predefine.TAG_TIME, realWord, new CoreDictionary.Attribute(Nature.t, 1000)); } /** * 生成线程安全的起始节点 * @return */ public static Vertex newB() { return new Vertex(Predefine.TAG_BIGIN, " ", new CoreDictionary.Attribute(Nature.begin, Predefine.TOTAL_FREQUENCY / 10), CoreDictionary.getWordID(Predefine.TAG_BIGIN)); } /** * 生成线程安全的终止节点 * @return */ public static Vertex newE() { return new Vertex(Predefine.TAG_END, " ", new CoreDictionary.Attribute(Nature.end, Predefine.TOTAL_FREQUENCY / 10), CoreDictionary.getWordID(Predefine.TAG_END)); } public int length() { return realWord.length(); } @Override public String toString() { return realWord; // return "WordNode{" + // "word='" + word + '\'' + // (word.equals(realWord) ? "" : (", realWord='" + realWord + '\'')) + //// ", attribute=" + attribute + // '}'; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\Vertex.java
1
请完成以下Java代码
public int getP_TradeDiscountRec_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_TradeDiscountRec_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getP_UsageVariance_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_UsageVariance_A(org.compiere.model.I_C_ValidCombination P_UsageVariance_A) { set_ValueFromPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class, P_UsageVariance_A); } /** Set Usage Variance. @param P_UsageVariance_Acct The Usage Variance account is the account used Manufacturing Order */ @Override public void setP_UsageVariance_Acct (int P_UsageVariance_Acct) { set_Value (COLUMNNAME_P_UsageVariance_Acct, Integer.valueOf(P_UsageVariance_Acct)); } /** Get Usage Variance. @return The Usage Variance account is the account used Manufacturing Order */ @Override public int getP_UsageVariance_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_UsageVariance_Acct); if (ii == null) return 0; return ii.intValue();
} @Override public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A) { set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A); } /** Set Work In Process. @param P_WIP_Acct The Work in Process account is the account used Manufacturing Order */ @Override public void setP_WIP_Acct (int P_WIP_Acct) { set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct)); } /** Get Work In Process. @return The Work in Process account is the account used Manufacturing Order */ @Override public int getP_WIP_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_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_M_Product_Acct.java
1
请完成以下Java代码
public void setIsMandatory (final boolean IsMandatory) { set_Value (COLUMNNAME_IsMandatory, IsMandatory); } @Override public boolean isMandatory() { return get_ValueAsBoolean(COLUMNNAME_IsMandatory); } @Override public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex) { set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex); } @Override public boolean isPartUniqueIndex() { return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPosition (final int Position) { set_Value (COLUMNNAME_Position, Position); } @Override public int getPosition() { return get_ValueAsInt(COLUMNNAME_Position); } /** * Type AD_Reference_ID=53241 * Reference name: EXP_Line_Type */ public static final int TYPE_AD_Reference_ID=53241; /** XML Element = E */ public static final String TYPE_XMLElement = "E";
/** XML Attribute = A */ public static final String TYPE_XMLAttribute = "A"; /** Embedded EXP Format = M */ public static final String TYPE_EmbeddedEXPFormat = "M"; /** Referenced EXP Format = R */ public static final String TYPE_ReferencedEXPFormat = "R"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
1
请完成以下Java代码
public class FCHtmlEditorKit extends HTMLEditorKit { /** * */ private static final long serialVersionUID = -3371176452691681668L; public ViewFactory getViewFactory() { if (defaultFactory == null) { defaultFactory = new FCHtmlFactory(super.getViewFactory()); } return defaultFactory; } private static class FCHtmlFactory implements ViewFactory { public FCHtmlFactory(ViewFactory factory) { oldFactory = factory; } public View create(Element elem) { View result; result = oldFactory.create(elem); if (result instanceof ImageView) { String src = (String)elem.getAttributes(). getAttribute(HTML.Attribute.SRC); if ("res:".equals(src.substring(0, 4))) { result = new NewImageView(elem); } } return result; } private static class NewImageView extends ImageView { Element elem; public NewImageView(Element elem) { super(elem); this.elem=elem; } public Image getImage() { //return smile image //java.awt.Toolkit.getDefaultToolkit().getImage(getImageURL()).flush(); //if (smileImage == null) { String src = (String)elem.getAttributes(). getAttribute(HTML.Attribute.SRC); //System.out.println("img load: " + src.substring(4)); URL url = getClass().getClassLoader(). getResource(src.substring(4)); //getResource("at/freecom/apps/images/freecom.gif"); //getResource("javax/swing/text/html/icons/image-delayed.gif"); if (url == null) return null; smileImage = Toolkit.getDefaultToolkit().getImage(url);
if (smileImage==null) return null; //forcing image to load synchronously ImageIcon ii = new ImageIcon(); ii.setImage(smileImage); //} return smileImage; } public URL getImageURL() { // here we return url to some image. It might be any // existing image. we need to move ImageView to the // state where it thinks that image was loaded. // ImageView is calling getImage to get image for // measurement and painting when image was loaded if (false) { return getClass().getClassLoader(). getResource("javax/swing/text/html/icons/image-delayed.gif"); } else { String src = (String)elem.getAttributes(). getAttribute(HTML.Attribute.SRC); //System.out.println("img load: " + src.substring(4)); URL url = getClass().getClassLoader(). getResource(src.substring(4)); if (url != null) { // System.out.println("load image: " + url); return url; } } return null; } private static Image smileImage = null; } private ViewFactory oldFactory; } private static ViewFactory defaultFactory = null; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\FCHtmlEditorKit.java
1
请完成以下Java代码
void set(int id, byte value) { _buf[id] = value; } /** * 是否为空 * @return true表示为空 */ boolean empty() { return (_size == 0); } /** * 缓冲区大小 * @return 大小 */ int size() { return _size; } /** * 清空缓存 */ void clear() { resize(0); _buf = null; _size = 0; _capacity = 0; } /** * 在末尾加一个值 * @param value 值 */ void add(byte value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } /** * 将最后一个值去掉 */ void deleteLast() { --_size; } /** * 重设大小 * @param size 大小 */ void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size; } /** * 重设大小,并且在末尾加一个值 * @param size 大小 * @param value 值 */ void resize(int size, byte value)
{ if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } /** * 增加容量 * @param size 容量 */ void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } /** * 设置缓冲区大小 * @param size 大小 */ private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } byte[] buf = new byte[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } /** * 缓冲区 */ private byte[] _buf; /** * 大小 */ private int _size; /** * 容量 */ private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java
1
请完成以下Java代码
public List<WidgetsBundleWidget> findWidgetsBundleWidgetsByWidgetsBundleId(UUID tenantId, UUID widgetsBundleId) { return DaoUtil.convertDataList(widgetsBundleWidgetRepository.findAllByWidgetsBundleId(widgetsBundleId)); } @Override public void saveWidgetsBundleWidget(WidgetsBundleWidget widgetsBundleWidget) { widgetsBundleWidgetRepository.save(new WidgetsBundleWidgetEntity(widgetsBundleWidget)); } @Override public void removeWidgetTypeFromWidgetsBundle(UUID widgetsBundleId, UUID widgetTypeId) { widgetsBundleWidgetRepository.deleteById(new WidgetsBundleWidgetCompositeKey(widgetsBundleId, widgetTypeId)); } @Override public PageData<WidgetTypeId> findAllWidgetTypesIds(PageLink pageLink) { return DaoUtil.pageToPageData(widgetTypeRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(WidgetTypeId::new)); } @Override public List<WidgetTypeInfo> findByTenantAndImageLink(TenantId tenantId, String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByTenantAndImageUrl(tenantId.getId(), imageUrl, limit)); } @Override public List<WidgetTypeInfo> findByImageLink(String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByImageUrl(imageUrl, limit)); }
@Override public PageData<WidgetTypeDetails> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<WidgetTypeFields> findNextBatch(UUID id, int batchSize) { return widgetTypeRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit)); } @Override public List<EntityInfo> findByResource(String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByResourceLink(reference, PageRequest.of(0, limit)); } @Override public EntityType getEntityType() { return EntityType.WIDGET_TYPE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\widget\JpaWidgetTypeDao.java
1
请完成以下Java代码
public SignalRestService getSignalRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); SignalRestServiceImpl subResource = new SignalRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public ConditionRestService getConditionRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); ConditionRestServiceImpl subResource = new ConditionRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public OptimizeRestService getOptimizeRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); OptimizeRestService subResource = new OptimizeRestService(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public VersionRestService getVersionRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); VersionRestService subResource = new VersionRestService(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public SchemaLogRestService getSchemaLogRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString();
SchemaLogRestServiceImpl subResource = new SchemaLogRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public EventSubscriptionRestService getEventSubscriptionRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); EventSubscriptionRestServiceImpl subResource = new EventSubscriptionRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public TelemetryRestService getTelemetryRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); TelemetryRestServiceImpl subResource = new TelemetryRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } protected abstract URI getRelativeEngineUri(String engineName); protected ObjectMapper getObjectMapper() { return ProvidersUtil .resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\AbstractProcessEngineRestServiceImpl.java
1
请完成以下Java代码
private Mono<Void> removeSessionFromIndex(String indexKey, String sessionId) { return this.sessionRedisOperations.opsForSet().remove(indexKey, sessionId).then(); } Mono<Map<String, String>> getIndexes(String sessionId) { String sessionIndexesKey = getSessionIndexesKey(sessionId); return this.sessionRedisOperations.opsForSet() .members(sessionIndexesKey) .cast(String.class) .collectMap((indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[0], (indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[1]); } Flux<String> getSessionIds(String indexName, String indexValue) { String indexKey = getIndexKey(indexName, indexValue); return this.sessionRedisOperations.opsForSet().members(indexKey).cast(String.class); } private void updateIndexKeyPrefix() { this.indexKeyPrefix = this.namespace + "sessions:index:"; } private String getSessionIndexesKey(String sessionId) { return this.namespace + "sessions:" + sessionId + ":idx"; }
private String getIndexKey(String indexName, String indexValue) { return this.indexKeyPrefix + indexName + ":" + indexValue; } void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be empty"); this.namespace = namespace; updateIndexKeyPrefix(); } void setIndexResolver(IndexResolver<Session> indexResolver) { Assert.notNull(indexResolver, "indexResolver cannot be null"); this.indexResolver = indexResolver; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionIndexer.java
1
请在Spring Boot框架中完成以下Java代码
public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @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 setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductName (final java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override
public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode) { set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode); } @Override public java.lang.String getScannedBarcode() { return get_ValueAsString(COLUMNNAME_ScannedBarcode); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java
2
请完成以下Java代码
public Builder targetUri(String targetUri) { this.targetUri = targetUri; return this; } /** * Sets the access token if the request is a Protected Resource request. * @param accessToken the access token if the request is a Protected Resource * request * @return the {@link Builder} */ public Builder accessToken(OAuth2Token accessToken) { this.accessToken = accessToken; return this; } /** * Builds a new {@link DPoPProofContext}. * @return a {@link DPoPProofContext} */ public DPoPProofContext build() { validate(); return new DPoPProofContext(this.dPoPProof, this.method, this.targetUri, this.accessToken); } private void validate() { Assert.hasText(this.method, "method cannot be empty"); Assert.hasText(this.targetUri, "targetUri cannot be empty"); if (!"GET".equals(this.method) && !"HEAD".equals(this.method) && !"POST".equals(this.method) && !"PUT".equals(this.method) && !"PATCH".equals(this.method) && !"DELETE".equals(this.method) && !"OPTIONS".equals(this.method) && !"TRACE".equals(this.method)) { throw new IllegalArgumentException("method is invalid"); }
URI uri; try { uri = new URI(this.targetUri); uri.toURL(); } catch (Exception ex) { throw new IllegalArgumentException("targetUri must be a valid URL", ex); } if (uri.getQuery() != null || uri.getFragment() != null) { throw new IllegalArgumentException("targetUri cannot contain query or fragment parts"); } } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\DPoPProofContext.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescritpion() { return descritpion; } public void setDescritpion(String descritpion) { this.descritpion = descritpion; } public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } }
repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\domain\Permission.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getOrderAmount() { return orderAmount; } public void setOrderAmount(BigDecimal orderAmount) { this.orderAmount = orderAmount; } public BigDecimal getPlatIncome() { return platIncome; } public void setPlatIncome(BigDecimal platIncome) { this.platIncome = platIncome; } public BigDecimal getFeeRate() { return feeRate; } public void setFeeRate(BigDecimal feeRate) { this.feeRate = feeRate; } public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime;
} public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public class Video { private UUID id; private String title; private Instant creationDate; public Video(UUID id, String title, Instant creationDate) { this.id = id; this.title = title; this.creationDate = creationDate; } public Video(String title, Instant creationDate) { this.title = title; this.creationDate = creationDate; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) {
this.title = title; } public Instant getCreationDate() { return creationDate; } public void setCreationDate(Instant creationDate) { this.creationDate = creationDate; } @Override public String toString() { return "[id:" + id.toString() + ", title:" + title + ", creationDate: " + creationDate.toString() + "]"; } }
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\datastax\cassandra\domain\Video.java
1
请完成以下Java代码
public boolean shouldInclude(Term term) { // 除掉停用词 String nature = term.nature != null ? term.nature.toString() : "空"; char firstChar = nature.charAt(0); switch (firstChar) { case 'm': case 'b': case 'c': case 'e': case 'o': case 'p': case 'q': case 'u': case 'y': case 'z': case 'r': case 'w': { return false; } default: { if (!CoreStopWordDictionary.contains(term.word)) { return true; } } break; } return false; } }; /** * 是否应当将这个term纳入计算 * * @param term * @return 是否应当 */ public static boolean shouldInclude(Term term) { return FILTER.shouldInclude(term); } /** * 是否应当去掉这个词 * @param term 词 * @return 是否应当去掉 */ public static boolean shouldRemove(Term term) {
return !shouldInclude(term); } /** * 加入停用词到停用词词典中 * @param stopWord 停用词 * @return 词典是否发生了改变 */ public static boolean add(String stopWord) { return dictionary.add(stopWord); } /** * 从停用词词典中删除停用词 * @param stopWord 停用词 * @return 词典是否发生了改变 */ public static boolean remove(String stopWord) { return dictionary.remove(stopWord); } /** * 对分词结果应用过滤 * @param termList */ public static List<Term> apply(List<Term> termList) { ListIterator<Term> listIterator = termList.listIterator(); while (listIterator.hasNext()) { if (shouldRemove(listIterator.next())) listIterator.remove(); } return termList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\stopword\CoreStopWordDictionary.java
1
请完成以下Java代码
public class ExportAccountInfos extends JavaProcess { final SpreadsheetExporterService spreadsheetExporterService = SpringContextHolder.instance.getBean(SpreadsheetExporterService.class); final ElementValueService elementValueService = SpringContextHolder.instance.getBean(ElementValueService.class); final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class); final IOrgDAO orgDAO = Services.get(IOrgDAO.class); @Param(parameterName = "C_AcctSchema_ID", mandatory = true) private AcctSchemaId p_C_AcctSchema_ID; @Param(parameterName = "DateAcctFrom", mandatory = true) private Instant p_DateAcctFrom; @Param(parameterName = "DateAcctTo", mandatory = true) private Instant p_DateAcctTo; @Param(parameterName = "Function", mandatory = true) private String p_Function; @Override protected String doIt() throws IOException { final String fileNameSuffix = getDateAcctFrom() + "_" + getDateAcctTo(); final List<ElementValueId> accountIds = factAcctDAO.retrieveAccountsForTimeFrame(p_C_AcctSchema_ID, p_DateAcctFrom, p_DateAcctTo); final List<File> files = new ArrayList<>(); for (final ElementValueId accountId : accountIds) { final String sql = getSql(accountId); final ElementValue ev = elementValueService.getById(accountId); final String fileName = ev.getValue() + "_" + fileNameSuffix; final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder() .ctx(getCtx()) .translateHeaders(true) .applyFormatting(true) .fileNamePrefix(fileName) .build(); spreadsheetExporterService.processDataFromSQL(sql, Evaluatees.empty(), jdbcExcelExporter); final File resultFile = jdbcExcelExporter.getResultFile(); files.add(resultFile); } final String zipFileName = getDateAcctFrom() + "_" + getDateAcctTo() + ".zip";
final File zipFile = FileUtil.zip(files); getResult().setReportData(zipFile, zipFileName); return MSG_OK; } private String getSql(final ElementValueId accountId) { return "SELECT * FROM " + p_Function + "(" + "p_Account_ID := " + accountId.getRepoId() + ", " + "p_C_AcctSchema_ID := " + p_C_AcctSchema_ID.getRepoId() + ", " + "p_DateAcctFrom := '" + getDateAcctFrom() + "', " + "p_DateAcctTo := '" + getDateAcctTo() + "')"; } @Nullable private LocalDate getDateAcctFrom() { final ZoneId zoneId = orgDAO.getTimeZone(Env.getOrgId()); return asLocalDate(p_DateAcctFrom, zoneId); } @Nullable private LocalDate getDateAcctTo() { final ZoneId zoneId = orgDAO.getTimeZone(Env.getOrgId()); return asLocalDate(p_DateAcctTo, zoneId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\ExportAccountInfos.java
1
请完成以下Java代码
public static long filesCompareByLine(Path path1, Path path2) throws IOException { if (path1.getFileSystem() .provider() .isSameFile(path1, path2)) { return -1; } try (BufferedReader bf1 = Files.newBufferedReader(path1); BufferedReader bf2 = Files.newBufferedReader(path2)) { long lineNumber = 1; String line1 = "", line2 = ""; while ((line1 = bf1.readLine()) != null) { line2 = bf2.readLine(); if (line2 == null || !line1.equals(line2)) { return lineNumber; } lineNumber++; } if (bf2.readLine() == null) { return -1; } else {
return lineNumber; } } } public static boolean compareByMemoryMappedFiles(Path path1, Path path2) throws IOException { try (RandomAccessFile randomAccessFile1 = new RandomAccessFile(path1.toFile(), "r"); RandomAccessFile randomAccessFile2 = new RandomAccessFile(path2.toFile(), "r")) { FileChannel ch1 = randomAccessFile1.getChannel(); FileChannel ch2 = randomAccessFile2.getChannel(); if (ch1.size() != ch2.size()) { return false; } long size = ch1.size(); MappedByteBuffer m1 = ch1.map(FileChannel.MapMode.READ_ONLY, 0L, size); MappedByteBuffer m2 = ch2.map(FileChannel.MapMode.READ_ONLY, 0L, size); return m1.equals(m2); } } }
repos\tutorials-master\core-java-modules\core-java-12\src\main\java\com\baeldung\file\content\comparison\CompareFileContents.java
1
请完成以下Java代码
private static class DocBaseTypeCountersMap { public static DocBaseTypeCountersMap ofMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map) { return !map.isEmpty() ? new DocBaseTypeCountersMap(map) : EMPTY; } private static final DocBaseTypeCountersMap EMPTY = new DocBaseTypeCountersMap(ImmutableMap.of()); private final ImmutableMap<DocBaseType, DocBaseType> counterDocBaseTypeByDocBaseType; private DocBaseTypeCountersMap(@NonNull final ImmutableMap<DocBaseType, DocBaseType> map) { this.counterDocBaseTypeByDocBaseType = map; }
public Optional<DocBaseType> getCounterDocBaseTypeByDocBaseType(@NonNull final DocBaseType docBaseType) { return Optional.ofNullable(counterDocBaseTypeByDocBaseType.get(docBaseType)); } } @NonNull private ImmutableSet<DocTypeId> retrieveDocTypeIdsByInvoicingPoolId(@NonNull final DocTypeInvoicingPoolId docTypeInvoicingPoolId) { return queryBL.createQueryBuilder(I_C_DocType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_DocType.COLUMNNAME_C_DocType_Invoicing_Pool_ID, docTypeInvoicingPoolId) .create() .idsAsSet(DocTypeId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeDAO.java
1
请完成以下Java代码
public String docValidate(@NonNull final PO po, final int timing) { Check.assume(isDocument(), "PO '{}' is a document", po); if (!acceptDocument(po)) { return null; } if (timing == ModelValidator.TIMING_AFTER_COMPLETE && !Services.get(IDocumentBL.class).isReversalDocument(po)) { createDocOutbound(po); } if (timing == ModelValidator.TIMING_AFTER_VOID || timing == ModelValidator.TIMING_AFTER_REVERSEACCRUAL || timing == ModelValidator.TIMING_AFTER_REVERSECORRECT) { voidDocOutbound(po); } return null; } /** * @return true if the given PO was just processed */ private boolean isJustProcessed(final PO po, final int changeType) { if (!po.isActive()) { return false; }
final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW; final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed); final boolean processedColumnAvailable = idxProcessed > 0; final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true; if (processedColumnAvailable) { if (isNew) { return processed; } else if (po.is_ValueChanged(idxProcessed)) { return processed; } else { return false; } } else // Processed column is not available { // If is not available, we always consider the record as processed right after it was created // This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters) return isNew; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java
1
请完成以下Java代码
public void logout() throws ServletException { List<LogoutHandler> handlers = HttpServlet3RequestFactory.this.logoutHandlers; if (CollectionUtils.isEmpty(handlers)) { HttpServlet3RequestFactory.this.logger .debug("logoutHandlers is null, so allowing original HttpServletRequest to handle logout"); super.logout(); return; } Authentication authentication = HttpServlet3RequestFactory.this.securityContextHolderStrategy.getContext() .getAuthentication(); for (LogoutHandler handler : handlers) { handler.logout(this, this.response, authentication); } } private boolean isAuthenticated() { return getUserPrincipal() != null; } } private static class SecurityContextAsyncContext implements AsyncContext { private final AsyncContext asyncContext; SecurityContextAsyncContext(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public ServletRequest getRequest() { return this.asyncContext.getRequest(); } @Override public ServletResponse getResponse() { return this.asyncContext.getResponse(); } @Override public boolean hasOriginalRequestAndResponse() { return this.asyncContext.hasOriginalRequestAndResponse(); } @Override public void dispatch() { this.asyncContext.dispatch(); } @Override public void dispatch(String path) { this.asyncContext.dispatch(path); } @Override public void dispatch(ServletContext context, String path) {
this.asyncContext.dispatch(context, path); } @Override public void complete() { this.asyncContext.complete(); } @Override public void start(Runnable run) { this.asyncContext.start(new DelegatingSecurityContextRunnable(run)); } @Override public void addListener(AsyncListener listener) { this.asyncContext.addListener(listener); } @Override public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) { this.asyncContext.addListener(listener, request, response); } @Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { return this.asyncContext.createListener(clazz); } @Override public long getTimeout() { return this.asyncContext.getTimeout(); } @Override public void setTimeout(long timeout) { this.asyncContext.setTimeout(timeout); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\HttpServlet3RequestFactory.java
1
请完成以下Java代码
public synchronized void unsubscribe(final WebsocketSubscriptionId subscriptionId) { activeSubscriptionIds.remove(subscriptionId); logger.trace("{}: subscription {} unsubscribed", this, subscriptionId); stopIfNoSubscription(); } public synchronized void unsubscribe(@NonNull final WebsocketSessionId sessionId) { final boolean removed = activeSubscriptionIds.removeIf(subscriptionId -> subscriptionId.isMatchingSessionId(sessionId)); logger.trace("{}: session {} unsubscribed", this, sessionId); if (removed) { stopIfNoSubscription(); } } public synchronized boolean hasActiveSubscriptions() { return !activeSubscriptionIds.isEmpty(); } public synchronized boolean isShallBeDestroyed() { return destroyIfNoActiveSubscriptions && !hasActiveSubscriptions(); } private WebSocketProducerInstance toNullIfShallBeDestroyed() { return isShallBeDestroyed() ? null : this; } private void stopIfNoSubscription() { if (hasActiveSubscriptions()) { return; } final boolean wasRunning = running.getAndSet(false); if (wasRunning) { producerControls.onStop(); } stopScheduledFuture(); logger.debug("{} stopped", this); } private void startScheduledFutureIfApplies() { // Does not apply if (onPollingEventsSupplier == null) { return; } // // Check if the producer was already scheduled if (scheduledFuture != null) { return; } // // Schedule producer final long initialDelayMillis = 1000; final long periodMillis = 1000; scheduledFuture = scheduler.scheduleAtFixedRate(this::pollAndPublish, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS);
logger.trace("{}: start producing using initialDelayMillis={}, periodMillis={}", this, initialDelayMillis, periodMillis); } private void stopScheduledFuture() { if (scheduledFuture == null) { return; } try { scheduledFuture.cancel(true); } catch (final Exception ex) { logger.warn("{}: Failed stopping scheduled future: {}. Ignored and considering it as stopped", this, scheduledFuture, ex); } scheduledFuture = null; } private void pollAndPublish() { if (onPollingEventsSupplier == null) { return; } try { final List<?> events = onPollingEventsSupplier.produceEvents(); if (events != null && !events.isEmpty()) { for (final Object event : events) { websocketSender.convertAndSend(topicName, event); logger.trace("Event sent to {}: {}", topicName, event); } } else { logger.trace("Got no events from {}", onPollingEventsSupplier); } } catch (final Exception ex) { logger.warn("Failed producing event for {}. Ignored.", this, ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducersRegistry.java
1
请完成以下Java代码
public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; }
public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } public Set<String> getRoles() { return roles; } public void setRoles(Set<String> roles) { this.roles = roles; } public Set<String> getPerms() { return perms; } public void setPerms(Set<String> perms) { this.perms = perms; } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\User.java
1
请完成以下Java代码
public int getMSV3_BestellungPosition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungPosition_ID); if (ii == null) return 0; return ii.intValue(); } /** * MSV3_Liefervorgabe AD_Reference_ID=540821 * Reference name: MSV3_Liefervorgabe */ public static final int MSV3_LIEFERVORGABE_AD_Reference_ID=540821; /** Normal = Normal */ public static final String MSV3_LIEFERVORGABE_Normal = "Normal"; /** MaxVerbund = MaxVerbund */ public static final String MSV3_LIEFERVORGABE_MaxVerbund = "MaxVerbund"; /** MaxNachlieferung = MaxNachlieferung */ public static final String MSV3_LIEFERVORGABE_MaxNachlieferung = "MaxNachlieferung"; /** MaxDispo = MaxDispo */ public static final String MSV3_LIEFERVORGABE_MaxDispo = "MaxDispo"; /** Set Liefervorgabe. @param MSV3_Liefervorgabe Liefervorgabe */ @Override public void setMSV3_Liefervorgabe (java.lang.String MSV3_Liefervorgabe) { set_Value (COLUMNNAME_MSV3_Liefervorgabe, MSV3_Liefervorgabe); } /** Get Liefervorgabe. @return Liefervorgabe */ @Override public java.lang.String getMSV3_Liefervorgabe () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Liefervorgabe); } /** Set MSV3_Menge. @param MSV3_Menge MSV3_Menge */ @Override public void setMSV3_Menge (int MSV3_Menge) { set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge)); } /** Get MSV3_Menge. @return MSV3_Menge */ @Override
public int getMSV3_Menge () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3_Pzn. @param MSV3_Pzn MSV3_Pzn */ @Override public void setMSV3_Pzn (java.lang.String MSV3_Pzn) { set_Value (COLUMNNAME_MSV3_Pzn, MSV3_Pzn); } /** Get MSV3_Pzn. @return MSV3_Pzn */ @Override public java.lang.String getMSV3_Pzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungPosition.java
1
请完成以下Java代码
private static boolean extractAlwaysUpdateable(final GridFieldVO gridFieldVO) { if (gridFieldVO.isVirtualColumn() || !gridFieldVO.isUpdateable()) { return false; } // HARDCODED: DocAction shall always be updateable if (WindowConstants.FIELDNAME_DocAction.equals(gridFieldVO.getColumnName())) { return true; } return gridFieldVO.isAlwaysUpdateable(); } private static ILogicExpression extractMandatoryLogic(@NonNull final GridFieldVO gridFieldVO) { if (gridFieldVO.isMandatoryLogicExpression()) { return gridFieldVO.getMandatoryLogic(); } else if (gridFieldVO.isMandatory()) { // consider it mandatory only if is displayed return gridFieldVO.getDisplayLogic(); } else { return ConstantLogicExpression.FALSE; } } private void collectSpecialField(final DocumentFieldDescriptor.Builder field) { if (_specialFieldsCollector == null) { return; } _specialFieldsCollector.collect(field); } private void collectSpecialFieldsDone() { if (_specialFieldsCollector == null) { return; } _specialFieldsCollector.collectFinish(); } @Nullable public DocumentFieldDescriptor.Builder getSpecialField_DocumentSummary() { return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocumentSummary(); }
@Nullable public Map<Characteristic, DocumentFieldDescriptor.Builder> getSpecialField_DocSatusAndDocAction() { return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocStatusAndDocAction(); } private WidgetTypeStandardNumberPrecision getStandardNumberPrecision() { WidgetTypeStandardNumberPrecision standardNumberPrecision = this._standardNumberPrecision; if (standardNumberPrecision == null) { standardNumberPrecision = this._standardNumberPrecision = WidgetTypeStandardNumberPrecision.builder() .quantityPrecision(getPrecisionFromSysConfigs(SYSCONFIG_QUANTITY_DEFAULT_PRECISION)) .build() .fallbackTo(WidgetTypeStandardNumberPrecision.DEFAULT); } return standardNumberPrecision; } @SuppressWarnings("SameParameterValue") private OptionalInt getPrecisionFromSysConfigs(@NonNull final String sysconfigName) { final int precision = sysConfigBL.getIntValue(sysconfigName, -1); return precision > 0 ? OptionalInt.of(precision) : OptionalInt.empty(); } private boolean isSkipField(@NonNull final String fieldName) { switch (fieldName) { case FIELDNAME_AD_Org_ID: return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true); case FIELDNAME_AD_Client_ID: return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GridTabVOBasedDocumentEntityDescriptorFactory.java
1
请完成以下Spring Boot application配置
# rocketmq 配置项,对应 RocketMQProperties 配置类 rocketmq: name-server: 127.0.0.1:9876 # RocketMQ Namesrv # Producer 配置项 producer: group: demo-producer-group # 生产者分组 send-message-timeout: 3000 # 发送消息超时时间,单位:毫秒。默认为 3000 。 compress-message-body-threshold: 4096 # 消息压缩阀值,当消息体的大小超过该阀值后,进行消息压缩。默认为 4 * 1024B max-message-size: 4194304 # 消息体的最大允许大小。。默认为 4 * 1024 * 1024B retry-times-when-send-failed: 2 # 同步发送消息时,失败重试次数。默认为 2 次。 retry-times-when-send-async-failed: 2 # 异步发送消息时,失败重试次数。默认为 2 次。 retry-next-server: false # 发送消息给 Broker 时,如果发送失败,是否重试另外一台 Broker 。默认为 false access-key: # Access Key ,可阅读 https://github.com/apache/rocketmq/blob/master/docs/cn/acl/user_guide.md 文档 secret-key: # Secret Key enable-msg-trace: true # 是否开启消息轨迹功能。默认为 true 开启。可阅读 https://github.com/apache/rocke
tmq/blob/master/docs/cn/msg_trace/user_guide.md 文档 customized-trace-topic: RMQ_SYS_TRACE_TOPIC # 自定义消息轨迹的 Topic 。默认为 RMQ_SYS_TRACE_TOPIC 。 # Consumer 配置项 consumer: listeners: # 配置某个消费分组,是否监听指定 Topic 。结构为 Map<消费者分组, <Topic, Boolean>> 。默认情况下,不配置表示监听。 test-consumer-group: topic1: false # 关闭 test-consumer-group 对 topic1 的监听消费
repos\SpringBoot-Labs-master\lab-31\lab-31-rocketmq-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public static void log(final Logger logger, final Level level, final String msg, final Object... msgParameters) { if (logger == null) { System.err.println(msg + " -- " + (msgParameters == null ? "" : Arrays.asList(msgParameters))); } else if (level == Level.ERROR) { logger.error(msg, msgParameters); } else if (level == Level.WARN) { logger.warn(msg, msgParameters); } else if (level == Level.INFO) {
logger.info(msg, msgParameters); } else if (level == Level.DEBUG) { logger.debug(msg, msgParameters); } else { logger.trace(msg, msgParameters); } } private LoggingHelper() { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\logging\LoggingHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Doc_Outbound_Config { private final static Logger logger = LogManager.getLogger(C_Doc_Outbound_Config.class); public static final C_Doc_Outbound_Config instance = new C_Doc_Outbound_Config(); private C_Doc_Outbound_Config() { } /** * If <code>IsCreatePrintJob</code> is set to <code>true</code>, then also set <code>IsDirectEnqueue</code>, because without a printing queue, there is no print job. * <p> * Note that this is mainly for the user. The business logics (=>AD_Archive) already behave like this for some time. * task http://dewiki908/mediawiki/index.php/09417_Massendruck_-_Sofort-Druckjob_via_Ausgehende-Belege_konfig_einstellbar_%28101934367465%29 */ @CalloutMethod(columnNames = { I_C_Doc_Outbound_Config.COLUMNNAME_IsDirectProcessQueueItem }) public void onIsCreatePrintJobChange(final I_C_Doc_Outbound_Config config) { if (config.isDirectProcessQueueItem() && !config.isDirectEnqueue()) { logger.debug("C_Doc_Outbound_Config.isDirectProcessQueueItem is 'Y'; -> set isDirectEnqueue also to 'Y'"); config.setIsDirectEnqueue(true);
} } /** * If <code>IsDirectEnqueue</code> is set to <code>false</code>, then also unset <code>IsCreatePrintJob</code>, because without a printing queue, there is no print job. * <p> * Note that this is mainly for the user. The business logics (=>AD_Archive) already behave like this for some time. * task http://dewiki908/mediawiki/index.php/09417_Massendruck_-_Sofort-Druckjob_via_Ausgehende-Belege_konfig_einstellbar_%28101934367465%29 */ @CalloutMethod(columnNames = { I_C_Doc_Outbound_Config.COLUMNNAME_IsDirectEnqueue }) public void onIsDirectEnqueueChange(final I_C_Doc_Outbound_Config config) { if (!config.isDirectEnqueue() && config.isDirectProcessQueueItem()) { logger.debug("C_Doc_Outbound_Config.isDirectEnqueue is 'N'; -> set isDirectProcessQueueItem also to 'N'"); config.setIsDirectProcessQueueItem(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\callout\C_Doc_Outbound_Config.java
2
请完成以下Java代码
public KPIField getGroupByFieldOrNull() { return groupByField; } public boolean hasCompareOffset() { return compareOffset != null; } public Set<CtxName> getRequiredContextParameters() { if (elasticsearchDatasource != null) { return elasticsearchDatasource.getRequiredContextParameters(); } else if (sqlDatasource != null) { return sqlDatasource.getRequiredContextParameters(); }
else { throw new AdempiereException("Unknown datasource type: " + datasourceType); } } public boolean isZoomToDetailsAvailable() { return sqlDatasource != null; } @NonNull public SQLDatasourceDescriptor getSqlDatasourceNotNull() { return Check.assumeNotNull(getSqlDatasource(), "Not an SQL data source: {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPI.java
1
请完成以下Java代码
public void start() { Assert.notNull(connector, "connector is null"); thread = new Thread(new Runnable() { public void run() { logger.info("destination:{} running", destination); process(); } }); thread.setUncaughtExceptionHandler(handler); thread.start(); running = true; } public void stop() { if (!running) { return; } running = false; } private void process() { int batchSize = 4 * 1024; while (running) { try { MDC.put("destination", destination); connector.connect(); connector.subscribe(); while (running) { Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据 long batchId = message.getId();
int size = message.getEntries().size(); if (batchId != -1 && size > 0) { logger.info(canal_get, batchId, size); // for (CanalEntry.Entry entry : message.getEntries()) { // logger.info("parse event has an data:" + entry.toString()); // } MessageHandler messageHandler = SpringUtil.getBean("messageHandler", MessageHandler.class); messageHandler.execute(message.getEntries()); logger.info(canal_ack, batchId); } connector.ack(batchId); // 提交确认 } } catch (Exception e) { logger.error("process error!", e); } finally { connector.disconnect(); MDC.remove("destination"); } } } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\canal\CanalClient.java
1
请完成以下Java代码
protected boolean isQualified(@Nullable Resource resource) { return resource != null; } /** * Action to perform when the {@link Resource} identified at the specified {@link String location} is missing, * or was not {@link #isQualified(Resource) qualified}. * * @param resource missing {@link Resource}. * @param location {@link String} containing the location identifying the missing {@link Resource}. * @throws ResourceNotFoundException if the {@link Resource} cannot be found at the specified {@link String location}. * @return a different {@link Resource}, possibly. Alternatively, this method may throw * a {@link ResourceNotFoundException}. * @see #isQualified(Resource) */ protected @Nullable Resource onMissingResource(@Nullable Resource resource, @NonNull String location) { throw new ResourceNotFoundException(String.format("Failed to resolve Resource [%1$s] at location [%2$s]", ResourceUtils.nullSafeGetDescription(resource), location)); } /** * Method used by subclasses to process the loaded {@link Resource} as determined by * the {@link #getResourceLoader() ResourceLoader}. * * @param resource {@link Resource} to post-process. * @return the {@link Resource}. * @see org.springframework.core.io.Resource */ protected Resource postProcess(Resource resource) { return resource; } /** * Tries to resolve a {@link Resource} at the given {@link String location} using a Spring {@link ResourceLoader}, * such as a Spring {@link ApplicationContext}. * * The targeted, identified {@link Resource} can be further {@link #isQualified(Resource) qualified} by subclasses * based on application requirements or use case (UC).
* * In the event that a {@link Resource} cannot be identified at the given {@link String location}, then applications * have 1 last opportunity to handle the missing {@link Resource} event, and either return a different or default * {@link Resource} or throw a {@link ResourceNotFoundException}. * * @param location {@link String location} identifying the {@link Resource} to resolve; * must not be {@literal null}. * @throws IllegalArgumentException if {@link String location} is not specified. * @return an {@link Optional} {@link Resource} handle for the given {@link String location}. * @see org.springframework.core.io.Resource * @see #isQualified(Resource) * @see #onMissingResource(Resource, String) * @see #postProcess(Resource) * @see java.util.Optional */ @Override public Optional<Resource> resolve(@NonNull String location) { Assert.hasText(location, () -> String.format("The location [%s] of the Resource to resolve must be specified", location)); Resource resource = getResourceLoader().getResource(location); resource = postProcess(resource); Resource resolvedResource = isQualified(resource) ? resource : onMissingResource(resource, location); return Optional.ofNullable(resolvedResource); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\ResourceLoaderResourceResolver.java
1
请完成以下Java代码
public String mkAddress( I_C_Location location, boolean isLocalAddress, final I_C_BPartner bPartner, String bPartnerBlock, String userBlock) { final String adLanguage; final OrgId orgId; if (bPartner == null) { adLanguage = countryDAO.getDefault(Env.getCtx()).getAD_Language(); orgId = Env.getOrgId(); } else { adLanguage = bPartner.getAD_Language(); orgId = OrgId.ofRepoId(bPartner.getAD_Org_ID()); } return AddressBuilder.builder() .orgId(orgId)
.adLanguage(adLanguage) .build() .buildAddressString(location, isLocalAddress, bPartnerBlock, userBlock); } @Override public I_C_Location duplicate(@NonNull final I_C_Location location) { final I_C_Location locationNew = InterfaceWrapperHelper.newInstance(I_C_Location.class, location); InterfaceWrapperHelper.copyValues(location, locationNew); InterfaceWrapperHelper.save(locationNew); return locationNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\LocationBL.java
1
请完成以下Java代码
public class MigrationSortSteps extends JavaProcess { private I_AD_Migration migration; @Override protected void prepare() { if (I_AD_Migration.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { this.migration = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_AD_Migration.class, get_TrxName()); } if (I_AD_MigrationStep.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { final I_AD_MigrationStep step = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_AD_MigrationStep.class, get_TrxName()); migration = step.getAD_Migration(); }
} @Override protected String doIt() throws Exception { if (migration == null || migration.getAD_Migration_ID() <= 0) { throw new AdempiereException("@NotFound@ @AD_Migration_ID@"); } Services.get(IMigrationBL.class).sortStepsByCreated(migration); return "OK"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\process\MigrationSortSteps.java
1
请完成以下Java代码
public IProductStorage getStorage() { return storage; } private I_M_HU_Item getM_HU_Item() { return huItem; } private I_M_HU_Item getVHU_Item() { // TODO: implement: get VHU Item or create it return huItem; } public Object getReferenceModel() { return referenceModel;
} @Override public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { final IAllocationRequest request = AllocationUtils.createQtyRequest(huContext, storage.getProductId(), // product storage.getQty(), // qty huContext.getDate() // date ); final IAllocationResult result = unload(request); return Collections.singletonList(ImmutablePair.of(request, result)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractAllocationSourceDestination.java
1
请完成以下Java代码
protected Map<String, String> matchRequestUri(String requestUri) { Matcher matcher = pattern.matcher(requestUri); if (!matcher.matches()) { return null; } HashMap<String, String> attributes = new HashMap<String, String>(); for (int i = 0; i < matcher.groupCount(); i++) { attributes.put(groups[i], matcher.group(i + 1)); } return attributes; } /** * Sets the uri pattern for this matcher * @param pattern */ protected final void setPattern(String pattern, String applicationPath) { String[] parts = pattern.split("/"); ArrayList<String> groupList = new ArrayList<String>(); StringBuilder regexBuilder = new StringBuilder(); if (!applicationPath.isEmpty()) { regexBuilder.append(applicationPath); } boolean first = true; for (String part: parts) { String group = null;
String regex = part; // parse group if (part.startsWith("{") && part.endsWith("}")) { String groupStr = part.substring(1, part.length() - 1); String[] groupSplit = groupStr.split(":"); if (groupSplit.length > 2) { throw new IllegalArgumentException("cannot parse uri part " + regex + " in " + pattern + ": expected {asdf(:pattern)}"); } group = groupSplit[0]; if (groupSplit.length > 1) { regex = "(" + groupSplit[1] + ")"; } else { regex = "([^/]+)"; } } if (!first) { regexBuilder.append("/"); } else { first = false; } regexBuilder.append(regex); if (group != null) { groupList.add(group); } } this.groups = groupList.toArray(new String[0]); this.pattern = Pattern.compile(regexBuilder.toString()); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\RequestFilter.java
1
请完成以下Java代码
public final class StatusInfo implements Serializable { public static final String STATUS_UNKNOWN = "UNKNOWN"; public static final String STATUS_OUT_OF_SERVICE = "OUT_OF_SERVICE"; public static final String STATUS_UP = "UP"; public static final String STATUS_DOWN = "DOWN"; public static final String STATUS_OFFLINE = "OFFLINE"; public static final String STATUS_RESTRICTED = "RESTRICTED"; private static final List<String> STATUS_ORDER = asList(STATUS_DOWN, STATUS_OUT_OF_SERVICE, STATUS_OFFLINE, STATUS_UNKNOWN, STATUS_RESTRICTED, STATUS_UP); private final String status; private final Map<String, Object> details; private StatusInfo(String status, @Nullable Map<String, ?> details) { Assert.hasText(status, "'status' must not be empty."); this.status = status.toUpperCase(); this.details = (details != null) ? new HashMap<>(details) : Collections.emptyMap(); } public static StatusInfo valueOf(String statusCode, @Nullable Map<String, ?> details) { return new StatusInfo(statusCode, details); } public static StatusInfo valueOf(String statusCode) { return valueOf(statusCode, null); } public static StatusInfo ofUnknown() { return valueOf(STATUS_UNKNOWN, null); } public static StatusInfo ofUp() { return ofUp(null); } public static StatusInfo ofDown() { return ofDown(null); } public static StatusInfo ofOffline() { return ofOffline(null); } public static StatusInfo ofUp(@Nullable Map<String, Object> details) { return valueOf(STATUS_UP, details); } public static StatusInfo ofDown(@Nullable Map<String, Object> details) { return valueOf(STATUS_DOWN, details); } public static StatusInfo ofOffline(@Nullable Map<String, Object> details) { return valueOf(STATUS_OFFLINE, details); } public Map<String, Object> getDetails() { return Collections.unmodifiableMap(details); } public boolean isUp() { return STATUS_UP.equals(status); } public boolean isOffline() {
return STATUS_OFFLINE.equals(status); } public boolean isDown() { return STATUS_DOWN.equals(status); } public boolean isUnknown() { return STATUS_UNKNOWN.equals(status); } public static Comparator<String> severity() { return Comparator.comparingInt(STATUS_ORDER::indexOf); } @SuppressWarnings("unchecked") public static StatusInfo from(Map<String, ?> body) { Map<String, ?> details = Collections.emptyMap(); /* * Key "details" is present when accessing Spring Boot Actuator Health using * Accept-Header {@link org.springframework.boot.actuate.endpoint.ApiVersion#V2}. */ if (body.containsKey("details")) { details = (Map<String, ?>) body.get("details"); } else if (body.containsKey("components")) { details = (Map<String, ?>) body.get("components"); } return StatusInfo.valueOf((String) body.get("status"), details); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\StatusInfo.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getFlashOrderOvertime() { return flashOrderOvertime; } public void setFlashOrderOvertime(Integer flashOrderOvertime) { this.flashOrderOvertime = flashOrderOvertime; } public Integer getNormalOrderOvertime() { return normalOrderOvertime; } public void setNormalOrderOvertime(Integer normalOrderOvertime) { this.normalOrderOvertime = normalOrderOvertime; } public Integer getConfirmOvertime() { return confirmOvertime; } public void setConfirmOvertime(Integer confirmOvertime) { this.confirmOvertime = confirmOvertime; } public Integer getFinishOvertime() { return finishOvertime; } public void setFinishOvertime(Integer finishOvertime) { this.finishOvertime = finishOvertime; } public Integer getCommentOvertime() {
return commentOvertime; } public void setCommentOvertime(Integer commentOvertime) { this.commentOvertime = commentOvertime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", flashOrderOvertime=").append(flashOrderOvertime); sb.append(", normalOrderOvertime=").append(normalOrderOvertime); sb.append(", confirmOvertime=").append(confirmOvertime); sb.append(", finishOvertime=").append(finishOvertime); sb.append(", commentOvertime=").append(commentOvertime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderSetting.java
1
请完成以下Java代码
private String buildLockKey(ZooLock lock, Method method, Object[] args) throws NoSuchFieldException, IllegalAccessException { StringBuilder key = new StringBuilder(KEY_SEPARATOR + KEY_PREFIX + lock.key()); // 迭代全部参数的注解,根据使用LockKeyParam的注解的参数所在的下标,来获取args中对应下标的参数值拼接到前半部分key上 Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { // 循环该参数全部注解 for (Annotation annotation : parameterAnnotations[i]) { // 注解不是 @LockKeyParam if (!annotation.annotationType().isInstance(LockKeyParam.class)) { continue; } // 获取所有fields String[] fields = ((LockKeyParam) annotation).fields(); if (ArrayUtil.isEmpty(fields)) { // 普通数据类型直接拼接 if (ObjectUtil.isNull(args[i])) { throw new RuntimeException("动态参数不能为null"); } key.append(KEY_SEPARATOR).append(args[i]); } else {
// @LockKeyParam的fields值不为null,所以当前参数应该是对象类型 for (String field : fields) { Class<?> clazz = args[i].getClass(); Field declaredField = clazz.getDeclaredField(field); declaredField.setAccessible(true); Object value = declaredField.get(clazz); key.append(KEY_SEPARATOR).append(value); } } } } return key.toString(); } }
repos\spring-boot-demo-master\demo-zookeeper\src\main\java\com\xkcoding\zookeeper\aspectj\ZooLockAspect.java
1
请完成以下Java代码
public XMLGregorianCalendar getDateBegin() { return dateBegin; } /** * Sets the value of the dateBegin property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateBegin(XMLGregorianCalendar value) { this.dateBegin = value; } /** * Gets the value of the dateEnd property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDateEnd() { return dateEnd; } /** * Sets the value of the dateEnd property. * * @param value * allowed object is * {@link XMLGregorianCalendar } *
*/ public void setDateEnd(XMLGregorianCalendar value) { this.dateEnd = value; } /** * Gets the value of the acid property. * * @return * possible object is * {@link String } * */ public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CaseDetailType.java
1
请在Spring Boot框架中完成以下Java代码
private static class ParentLink { @NonNull String linkColumnName; @NonNull String parentTableName; } @Nullable private ParentLink getParentLink_HeaderForLine(@NonNull final POInfo poInfo) { final String tableName = poInfo.getTableName(); if (!tableName.endsWith("Line")) { return null; } final String parentTableName = tableName.substring(0, tableName.length() - "Line".length()); final String parentLinkColumnName = parentTableName + "_ID"; if (!poInfo.hasColumnName(parentLinkColumnName)) { return null; } // virtual column parent link is not supported if (poInfo.isVirtualColumn(parentLinkColumnName)) { return null; } return ParentLink.builder() .linkColumnName(parentLinkColumnName) .parentTableName(parentTableName) .build(); }
@Nullable private ParentLink getParentLink_SingleParentColumn(@NonNull final POInfo poInfo) { final String parentLinkColumnName = poInfo.getSingleParentColumnName().orElse(null); if (parentLinkColumnName == null) { return null; } // virtual column parent link is not supported if (poInfo.isVirtualColumn(parentLinkColumnName)) { return null; } final String parentTableName = poInfo.getReferencedTableNameOrNull(parentLinkColumnName); if (parentTableName == null) { return null; } return ParentLink.builder() .linkColumnName(parentLinkColumnName) .parentTableName(parentTableName) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\DefaultGenericZoomIntoTableInfoRepository.java
2
请完成以下Java代码
public class JasperReportsPdfExporter implements JasperReportsExporter { /** * Generates a ByteArrayOutputStream from the provided JasperReport using * the {@link JRPdfExporter}. After that, the generated bytes array is * written in the {@link HttpServletResponse} * * @param jp * The generated JasperReport. * @param fileName * The fileName of the exported JasperReport * @param response * The HttpServletResponse where generated report has been * written * @throws JRException * during JasperReport export. * @throws IOException * when writes the ByteArrayOutputStream into the * HttpServletResponse */ @Override public void export(JasperPrint jp, String fileName, HttpServletResponse response) throws JRException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Create a JRPdfExporter instance JRPdfExporter exporter = new JRPdfExporter(); // Here we assign the parameters jp and baos to the exporter exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); // Retrieve the exported report in PDF format exporter.exportReport(); // Specifies the response header
response.setHeader("Content-Disposition", "inline; filename=" + fileName); // Make sure to set the correct content type // Each format has its own content type response.setContentType("application/pdf"); response.setContentLength(baos.size()); // Retrieve the output stream ServletOutputStream outputStream = response.getOutputStream(); // Write to the output stream baos.writeTo(outputStream); // Flush the stream outputStream.flush(); } }
repos\tutorials-master\spring-roo\src\main\java\com\baeldung\web\reports\JasperReportsPdfExporter.java
1
请完成以下Java代码
public static boolean equals(final DocumentQueryOrderByList list1, final DocumentQueryOrderByList list2) { return Objects.equals(list1, list2); } public Stream<DocumentQueryOrderBy> stream() { return list.stream(); } public void forEach(@NonNull final Consumer<DocumentQueryOrderBy> consumer) { list.forEach(consumer); }
public <T extends IViewRow> Comparator<T> toComparator( @NonNull final FieldValueExtractor<T> fieldValueExtractor, @NonNull final JSONOptions jsonOpts) { // used in case orderBys is empty or whatever else goes wrong final Comparator<T> noopComparator = (o1, o2) -> 0; return stream() .map(orderBy -> orderBy.asComparator(fieldValueExtractor, jsonOpts)) .reduce(Comparator::thenComparing) .orElse(noopComparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQueryOrderByList.java
1
请完成以下Java代码
public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } public String getTextFormat() { return textFormatAttribute.getValue(this); } public void setTextFormat(String textFormat) { textFormatAttribute.setValue(this, textFormat); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Documentation.class, CMMN_ELEMENT_DOCUMENTATION) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Documentation>() { public Documentation newInstance(ModelTypeInstanceContext instanceContext) { return new DocumentationImpl(instanceContext);
} }); idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID) .idAttribute() .build(); textFormatAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TEXT_FORMAT) .defaultValue("text/plain") .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DocumentationImpl.java
1
请完成以下Java代码
public final class AttestationConveyancePreference { /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-attestationconveyancepreference-none">none</a> * preference indicates that the Relying Party is not interested in * <a href="https://www.w3.org/TR/webauthn-3/#authenticator">authenticator</a> * <a href="https://www.w3.org/TR/webauthn-3/#attestation">attestation</a>. */ public static final AttestationConveyancePreference NONE = new AttestationConveyancePreference("none"); /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-attestationconveyancepreference-indirect">indirect</a> * preference indicates that the Relying Party wants to receive a verifiable * <a href="https://www.w3.org/TR/webauthn-3/#attestation-statement">attestation * statement</a>, but allows the client to decide how to obtain such an attestation * statement. */ public static final AttestationConveyancePreference INDIRECT = new AttestationConveyancePreference("indirect"); /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-attestationconveyancepreference-direct">direct</a> * preference indicates that the Relying Party wants to receive the * <a href="https://www.w3.org/TR/webauthn-3/#attestation-statement">attestation * statement</a> as generated by the * <a href="https://www.w3.org/TR/webauthn-3/#authenticator">authenticator</a>. */ public static final AttestationConveyancePreference DIRECT = new AttestationConveyancePreference("direct"); /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-attestationconveyancepreference-enterprise">enterprise</a> * preference indicates that the Relying Party wants to receive an * <a href="https://www.w3.org/TR/webauthn-3/#attestation-statement">attestation * statement</a> that may include uniquely identifying information. */
public static final AttestationConveyancePreference ENTERPRISE = new AttestationConveyancePreference("enterprise"); private final String value; AttestationConveyancePreference(String value) { this.value = value; } /** * Gets the String value of the preference. * @return the String value of the preference. */ public String getValue() { return this.value; } /** * Gets an instance of {@link AttestationConveyancePreference} * @param value the {@link #getValue()} * @return an {@link AttestationConveyancePreference} */ public static AttestationConveyancePreference valueOf(String value) { switch (value) { case "none": return NONE; case "indirect": return INDIRECT; case "direct": return DIRECT; case "enterprise": return ENTERPRISE; default: return new AttestationConveyancePreference(value); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AttestationConveyancePreference.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(href, limit, next, offset, paymentDisputeSummaries, prev, total); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DisputeSummaryResponse {\n"); sb.append(" href: ").append(toIndentedString(href)).append("\n"); sb.append(" limit: ").append(toIndentedString(limit)).append("\n"); sb.append(" next: ").append(toIndentedString(next)).append("\n"); sb.append(" offset: ").append(toIndentedString(offset)).append("\n"); sb.append(" paymentDisputeSummaries: ").append(toIndentedString(paymentDisputeSummaries)).append("\n"); sb.append(" prev: ").append(toIndentedString(prev)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\DisputeSummaryResponse.java
2