instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public boolean isCached() { return true; } @Override public String getCachePrefix() { return DataEntryListValueDataSourceFetcher.class.getSimpleName(); } @Override public Optional<String> getLookupTableName() { return Optional.of(LOOKUP_TABLE_NAME); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } /** * Does nothing; this class doesn't use a cache; it is disposed as one.
*/ @Override public void cacheInvalidate() { } public DataEntryListValueId getListValueIdForLookup(@Nullable final IntegerLookupValue value) { return id2LookupValue.inverse().get(value); } public Object getLookupForForListValueId(@Nullable final DataEntryListValueId dataEntryListValueId) { return id2LookupValue.get(dataEntryListValueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryListValueDataSourceFetcher.java
1
请完成以下Java代码
class CollectionUtilsDemo { private static final Logger logger = LoggerFactory.getLogger(CollectionUtilsDemo.class); public static void main(String[] args) { CollectionUtils.print("Baeldung"); List<Number> numbers1 = new ArrayList<>(); numbers1.add(5); numbers1.add(10L); List<Number> numbers2 = new ArrayList<>(); numbers2.add(15f); numbers2.add(20.0); List<Number> numbersMerged = CollectionUtils.mergeTypeParameter(numbers1, numbers2); logger.info("Merged numbers: {}", numbersMerged); List<Number> numbers = new ArrayList<>(); numbers.add(5); numbers.add(10L); numbers.add(15f);
numbers.add(20.0); logger.info("Sum: {}", CollectionUtils.sum(numbers)); logger.info("Sum (wildcard): {}", CollectionUtils.sumWildcard(numbers)); logger.info("Sum (type parameter): {}", CollectionUtils.sumTypeParameter(numbers)); List<Integer> integers = new ArrayList<>(); integers.add(5); logger.info("Sum integers (wildcard): {}", CollectionUtils.sumWildcard(integers)); CollectionUtils.addNumber(numbers, 4); CollectionUtils.addNumber(integers, 5); logger.info("Before swap: {}", numbers); CollectionUtils.swap(numbers, 0, 1); logger.info("After swap: {}", numbers); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\generics\CollectionUtilsDemo.java
1
请完成以下Spring Boot application配置
logging.level.root=info logging.file=gaoxi-log/controller-log.log spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://172.17.0.9:3306/gaoxi?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = jishimen.2018 ## Dubbo 服务消费者配
置 spring.dubbo.application.name=controller-consumer spring.dubbo.registry.address=zookeeper://172.17.0.2:2181 spring.dubbo.scan=com.gaoxi
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\resources\application-test.properties
2
请完成以下Java代码
protected void setFormattingTemplates(Templates formattingTemplates) { this.formattingTemplates = formattingTemplates; } private InputStream getFormattingConfiguration() { final InputStream importedConfiguration = this.domXmlDataFormat.getFormattingConfiguration(); if (importedConfiguration != null) { return importedConfiguration; } // default strip-spaces.xsl return DomXmlDataFormatWriter.class.getClassLoader().getResourceAsStream(STRIP_SPACE_XSL); } /** * Returns a configured transformer to write XML and apply indentation (pretty-print) to the xml. * * @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getFormattingTransformer() { try { Transformer transformer = formattingTemplates.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } /** * Returns a configured transformer to write XML as is. *
* @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getTransformer() { TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatWriter.java
1
请完成以下Java代码
private void executeDDL(final String sql) { DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited); addLog("DDL: " + sql); } private void addToTabs(final I_AD_Column column) { final int adTableId = column.getAD_Table_ID(); queryBL.createQueryBuilder(I_AD_Tab.class, column) .addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId) .create() .stream(I_AD_Tab.class) .forEach(tab -> createAD_Field(tab, column)); } private void createAD_Field(final I_AD_Tab tab, final I_AD_Column column) { final String fieldEntityType = null; // auto final I_AD_Field field;
try { final boolean displayedIfNotIDColumn = true; // actually doesn't matter because PK probably is an ID column anyways field = AD_Tab_CreateFields.createADField(tab, column, displayedIfNotIDColumn, fieldEntityType); // log final I_AD_Window window = tab.getAD_Window(); addLog("@Created@ " + window + " -> " + tab + " -> " + field); } catch (final Exception ex) { logger.warn("Failed creating AD_Field for {} in {}", column, tab, ex); addLog("@Error@ creating AD_Field for {} in {}: {}", column, tab, ex.getLocalizedMessage()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\TablePrimaryKeyGenerator.java
1
请完成以下Java代码
public boolean hasData() { return data != null; } public int getNumberOfPages() { Integer numberOfPages = this._numberOfPages; if (numberOfPages == null) { numberOfPages = this._numberOfPages = computeNumberOfPages(); } return numberOfPages; } private int computeNumberOfPages() { if (!hasData()) { return 0; } PdfReader reader = null; try { reader = new PdfReader(getData()); return reader.getNumberOfPages(); } catch (final IOException e) { throw new AdempiereException("Cannot get number of pages for C_Printing_Queue_ID=" + printingQueueItemId.getRepoId(), e); } finally { if (reader != null) { try { reader.close(); } catch (final Exception ignored) { } } } } public PrintingData onlyWithType(@NonNull final OutputType outputType) { final ImmutableList<PrintingSegment> filteredSegments = segments.stream() .filter(segment -> segment.isMatchingOutputType(outputType)) .collect(ImmutableList.toImmutableList()); return toBuilder() .clearSegments()
.segments(filteredSegments) .adjustSegmentPageRanges(false) .build(); } public PrintingData onlyQueuedForExternalSystems() { final ImmutableList<PrintingSegment> filteredSegments = segments.stream() .filter(PrintingSegment::isQueuedForExternalSystems) .collect(ImmutableList.toImmutableList()); return toBuilder() .clearSegments() .segments(filteredSegments) .adjustSegmentPageRanges(false) .build(); } public boolean hasSegments() {return !getSegments().isEmpty();} public int getSegmentsCount() {return getSegments().size();} public ImmutableSet<String> getPrinterNames() { return segments.stream() .map(segment -> segment.getPrinter().getName()) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java
1
请完成以下Java代码
private PathPattern parse(String pattern) { PathPatternParser parser = PathPatternParser.defaultInstance; pattern = parser.initFullPathPattern(pattern); return parser.parse(pattern); } @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); PathContainer path = request.getPath().pathWithinApplication(); if (this.method != null && !this.method.equals(request.getMethod())) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); } }); } PathPattern.PathMatchInfo pathMatchInfo = this.pattern.matchAndExtract(path); if (pathMatchInfo == null) { return MatchResult.notMatch().doOnNext((result) -> { if (logger.isDebugEnabled()) {
logger.debug("Request '" + request.getMethod() + " " + path + "' doesn't match '" + this.method + " " + this.pattern.getPatternString() + "'"); } }); } Map<String, String> pathVariables = pathMatchInfo.getUriVariables(); Map<String, Object> variables = new HashMap<>(pathVariables); if (logger.isDebugEnabled()) { logger .debug("Checking match of request : '" + path + "'; against '" + this.pattern.getPatternString() + "'"); } return MatchResult.match(variables); } @Override public String toString() { return "PathMatcherServerWebExchangeMatcher{" + "pattern='" + this.pattern + '\'' + ", method=" + this.method + '}'; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\PathPatternParserServerWebExchangeMatcher.java
1
请在Spring Boot框架中完成以下Java代码
public class X_M_Maturing_Configuration extends org.compiere.model.PO implements I_M_Maturing_Configuration, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1793777178L; /** Standard Constructor */ public X_M_Maturing_Configuration (final Properties ctx, final int M_Maturing_Configuration_ID, @Nullable final String trxName) { super (ctx, M_Maturing_Configuration_ID, trxName); } /** Load Constructor */ public X_M_Maturing_Configuration (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription()
{ return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Maturing_Configuration_ID (final int M_Maturing_Configuration_ID) { if (M_Maturing_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, M_Maturing_Configuration_ID); } @Override public int getM_Maturing_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Maturing_Configuration.java
2
请完成以下Java代码
protected void createDefaultAuthorizations(UserEntity userEntity) { if(Context.getProcessEngineConfiguration().isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newUser(userEntity)); } } protected void createDefaultAuthorizations(Group group) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newGroup(group)); } } protected void createDefaultAuthorizations(Tenant tenant) { if (isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newTenant(tenant)); } } protected void createDefaultMembershipAuthorizations(String userId, String groupId) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().groupMembershipCreated(groupId, userId)); }
} protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, User user) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, user)); } } protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, Group group) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, group)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbIdentityServiceProvider.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pharmacy pharmacy = (Pharmacy) o; return Objects.equals(this._id, pharmacy._id) && Objects.equals(this.name, pharmacy.name) && Objects.equals(this.address, pharmacy.address) && Objects.equals(this.postalCode, pharmacy.postalCode) && Objects.equals(this.city, pharmacy.city) && Objects.equals(this.phone, pharmacy.phone) && Objects.equals(this.fax, pharmacy.fax) && Objects.equals(this.email, pharmacy.email) && Objects.equals(this.website, pharmacy.website) && Objects.equals(this.timestamp, pharmacy.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, website, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append("class Pharmacy {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" website: ").append(toIndentedString(website)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).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-patient-api\src\main\java\io\swagger\client\model\Pharmacy.java
2
请完成以下Java代码
private ITranslatableString extractCreatedUpdatedInfo( @NonNull final DataEntryRecord dataEntryRecord, @NonNull final DataEntryFieldId dataEntryFieldId) { final Optional<CreatedUpdatedInfo> createdUpdatedInfo = dataEntryRecord.getCreatedUpdatedInfo(dataEntryFieldId); return createdUpdatedInfo .map(this::extractCreatedUpdatedInfo) .orElse(TranslatableStrings.empty()); } private ITranslatableString extractCreatedUpdatedInfo(@NonNull final CreatedUpdatedInfo createdUpdatedInfo) { final User creator = userRepository.getByIdInTrx(createdUpdatedInfo.getCreatedBy()); final User updater = userRepository.getByIdInTrx(createdUpdatedInfo.getUpdatedBy()); final ITranslatableString createdUpdatedInfoString = Services.get(IMsgBL.class) .getTranslatableMsgText( MSG_CREATED_UPDATED_INFO_6P, creator.getName(), Date.from(createdUpdatedInfo.getCreated().toInstant()), Date.from(createdUpdatedInfo.getCreated().toInstant()), updater.getName(), Date.from(createdUpdatedInfo.getUpdated().toInstant()), Date.from(createdUpdatedInfo.getUpdated().toInstant())); return createdUpdatedInfoString; } @Nullable public Object extractFieldValueForDataEntry(@NonNull final IDocumentFieldView fieldView) { final Object value = fieldView.getValue(); final DocumentFieldDescriptor descriptor = fieldView.getDescriptor(); final DataEntryFieldBindingDescriptor dataBinding = descriptor.getDataBindingNotNull(DataEntryFieldBindingDescriptor.class); final FieldType fieldType = dataBinding.getFieldType(); if (value == null) { return null; } final Object result; switch (fieldType) { case DATE: result = fieldType.getClazz().cast(value); break; case LIST: final LookupDescriptor lookupDescriptor = descriptor.getLookupDescriptor().get(); final DataEntryListValueDataSourceFetcher fetcher = (DataEntryListValueDataSourceFetcher)lookupDescriptor.getLookupDataSourceFetcher();
result = fetcher.getListValueIdForLookup((IntegerLookupValue)value); break; case NUMBER: result = fieldType.getClazz().cast(value); break; case TEXT: result = fieldType.getClazz().cast(value); break; case LONG_TEXT: result = fieldType.getClazz().cast(value); break; case YESNO: result = fieldType.getClazz().cast(value); break; case PARENT_LINK_ID: result = fieldType.getClazz().cast(value); break; case SUB_TAB_ID: result = fieldType.getClazz().cast(value); break; default: // this includes CREATED_UPDATED_INFO, PARENT_LINK_ID and SUB_TAB_ID; we don't expect the document repo to try and extract these throw new AdempiereException("Unexpected fieldType=" + fieldType); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryWebuiTools.java
1
请完成以下Java代码
public void setDLM_Partition_ID(final int DLM_Partition_ID) { if (DLM_Partition_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID)); } } /** * Get Partition. * * @return Partition */ @Override public int getDLM_Partition_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set DLM_Partition_Record. * * @param DLM_Partition_Record_V_ID DLM_Partition_Record */ @Override public void setDLM_Partition_Record_V_ID(final int DLM_Partition_Record_V_ID) { if (DLM_Partition_Record_V_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Record_V_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Record_V_ID, Integer.valueOf(DLM_Partition_Record_V_ID)); } } /** * Get DLM_Partition_Record. * * @return DLM_Partition_Record */ @Override public int getDLM_Partition_Record_V_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Record_V_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set DLM aktiviert. * * @param IsDLM * Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public void setIsDLM(final boolean IsDLM) { set_ValueNoCheck(COLUMNNAME_IsDLM, Boolean.valueOf(IsDLM)); } /** * Get DLM aktiviert. * * @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public boolean isDLM() { final Object oo = get_Value(COLUMNNAME_IsDLM); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** * Set Datensatz-ID. * * @param Record_ID * Direct internal record ID
*/ @Override public void setRecord_ID(final int Record_ID) { if (Record_ID < 0) { set_ValueNoCheck(COLUMNNAME_Record_ID, null); } else { set_ValueNoCheck(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } } /** * Get Datensatz-ID. * * @return Direct internal record ID */ @Override public int getRecord_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { set_ValueNoCheck(COLUMNNAME_TableName, TableName); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Record_V.java
1
请完成以下Java代码
public static Collection<AttachmentEntryCreateRequest> fromFiles(@NonNull final Collection<File> files) { return files .stream() .map(AttachmentEntryCreateRequest::fromFile) .collect(ImmutableList.toImmutableList()); } public static AttachmentEntryCreateRequest fromFile(@NonNull final File file) { final String filename = file.getName(); final String contentType = MimeType.getMimeType(filename); final byte[] data = Util.readBytes(file); return builder() .type(AttachmentEntryType.Data)
.filename(filename) .contentType(contentType) .data(data) .build(); } @NonNull AttachmentEntryType type; String filename; String contentType; byte[] data; URI url; AttachmentTags tags; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryCreateRequest.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteIdentityLink(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "family") @PathVariable("family") String family, @ApiParam(name = "identityId") @PathVariable("identityId") String identityId, @ApiParam(name = "type") @PathVariable("type") String type) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); validateIdentityLinkArguments(family, identityId, type); // Check if identitylink to delete exists IdentityLink link = getIdentityLink(family, identityId, type, task.getId()); if (restApiInterceptor != null) { restApiInterceptor.deleteTaskIdentityLink(task, link); } if (CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family)) { taskService.deleteUserIdentityLink(task.getId(), identityId, type); } else { taskService.deleteGroupIdentityLink(task.getId(), identityId, type); } } protected void validateIdentityLinkArguments(String family, String identityId, String type) { if (family == null || (!CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) { throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'."); } if (identityId == null) { throw new FlowableIllegalArgumentException("IdentityId is required.");
} if (type == null) { throw new FlowableIllegalArgumentException("Type is required."); } } protected IdentityLink getIdentityLink(String family, String identityId, String type, String taskId) { boolean isUser = family.equals(CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS); // Perhaps it would be better to offer getting a single identitylink // from the API List<IdentityLink> allLinks = taskService.getIdentityLinksForTask(taskId); for (IdentityLink link : allLinks) { boolean rightIdentity = false; if (isUser) { rightIdentity = identityId.equals(link.getUserId()); } else { rightIdentity = identityId.equals(link.getGroupId()); } if (rightIdentity && link.getType().equals(type)) { return link; } } throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskIdentityLinkResource.java
2
请完成以下Java代码
private PersistentEntityStore openStore() { return PersistentEntityStores.newInstance(DB_PATH); } public TaskEntity findOne(EntityId taskId) { try (PersistentEntityStore entityStore = openStore()) { AtomicReference<TaskEntity> taskEntity = new AtomicReference<>(); entityStore.executeInReadonlyTransaction( txn -> taskEntity.set(mapToTaskEntity(txn.getEntity(taskId)))); return taskEntity.get(); } } private TaskEntity mapToTaskEntity(Entity entity) { return new TaskEntity(entity.getProperty("description").toString(), entity.getProperty("labels").toString());
} public List<TaskEntity> findAll() { try (PersistentEntityStore entityStore = openStore()) { List<TaskEntity> result = new ArrayList<>(); entityStore.executeInReadonlyTransaction(txn -> txn.getAll(ENTITY_TYPE) .forEach(entity -> result.add(mapToTaskEntity(entity)))); return result; } } public void deleteAll() { try (PersistentEntityStore entityStore = openStore()) { entityStore.clear(); } } }
repos\tutorials-master\persistence-modules\persistence-libraries\src\main\java\com\baeldung\jetbrainsxodus\TaskEntityStoreRepository.java
1
请完成以下Java代码
protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; } public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; }
public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Saml2AuthenticationToken convert(HttpServletRequest request) { return this.delegate.convert(request); } /** * Use the given {@link Saml2AuthenticationRequestRepository} to load authentication * request. * @param authenticationRequestRepository the * {@link Saml2AuthenticationRequestRepository} to use */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.delegate.setAuthenticationRequestRepository(authenticationRequestRepository); } /** * Use the given {@link RequestMatcher} to match the request.
* @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.delegate.setRequestMatcher(requestMatcher); } /** * Use the given {@code shouldConvertGetRequests} to convert {@code GET} requests. * Default is {@code true}. * @param shouldConvertGetRequests the {@code shouldConvertGetRequests} to use * @since 7.0 */ public void setShouldConvertGetRequests(boolean shouldConvertGetRequests) { this.delegate.setShouldConvertGetRequests(shouldConvertGetRequests); } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverter.java
2
请完成以下Java代码
public class JMXConfigurator extends AbstractProcessEngineConfigurator { public static final String DEFAUL_JMX_DOMAIN = "DefaultDomain"; // jmx (rmi server connection) port protected Integer connectorPort = -1; // jmx domain name protected String domain = "org.flowable.jmx.Mbeans"; // the domain name for the mbeans protected String mbeanDomain = DEFAUL_JMX_DOMAIN; // JMX service URL path protected String serviceUrlPath = "/jmxrmi/flowable"; protected Boolean createConnector = true; protected ProcessEngineConfiguration processEngineConfig; protected ManagementAgent managementAgent; public ProcessEngineConfiguration getProcessEngineConfig() { return processEngineConfig; } public void setProcessEngineConfig(ProcessEngineConfiguration processEngineConfig) { this.processEngineConfig = processEngineConfig; } private static final Logger LOGGER = LoggerFactory.getLogger(JMXConfigurator.class); // disable jmx private boolean disabled; public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getMbeanDomain() { return mbeanDomain; } public Boolean getCreateConnector() { return createConnector; } public void setCreateConnector(Boolean createConnector) { this.createConnector = createConnector; } public void setMbeanDomain(String mbeanDomain) { this.mbeanDomain = mbeanDomain; }
// jmx (rmi registry) port private Integer registryPort = 1099; public Integer getRegistryPort() { return registryPort; } public void setRegistryPort(Integer registryPort) { this.registryPort = registryPort; } public String getServiceUrlPath() { return serviceUrlPath; } public void setServiceUrlPath(String serviceUrlPath) { this.serviceUrlPath = serviceUrlPath; } public Integer getConnectorPort() { return connectorPort; } public void setConnectorPort(Integer connectorPort) { this.connectorPort = connectorPort; } @Override public void beforeInit(AbstractEngineConfiguration engineConfiguration) { // nothing to do } @Override public void configure(AbstractEngineConfiguration engineConfiguration) { try { this.processEngineConfig = (ProcessEngineConfiguration) engineConfiguration; if (!disabled) { managementAgent = new DefaultManagementAgent(this); managementAgent.doStart(); managementAgent.findAndRegisterMbeans(); } } catch (Exception e) { LOGGER.warn("error in initializing jmx. Continue with partial or no JMX configuration", e); } } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\JMXConfigurator.java
1
请完成以下Java代码
private ElasticCommonSchemaStructuredLogFormatter createEcsFormatter(Instantiator<?> instantiator) { Environment environment = instantiator.getArg(Environment.class); StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class); ContextPairs contextPairs = instantiator.getArg(ContextPairs.class); StructuredLoggingJsonMembersCustomizer.Builder<?> jsonMembersCustomizerBuilder = instantiator .getArg(StructuredLoggingJsonMembersCustomizer.Builder.class); Assert.state(environment != null, "'environment' must not be null"); Assert.state(contextPairs != null, "'contextPairs' must not be null"); Assert.state(jsonMembersCustomizerBuilder != null, "'jsonMembersCustomizerBuilder' must not be null"); return new ElasticCommonSchemaStructuredLogFormatter(environment, stackTracePrinter, contextPairs, jsonMembersCustomizerBuilder); } private GraylogExtendedLogFormatStructuredLogFormatter createGraylogFormatter(Instantiator<?> instantiator) { Environment environment = instantiator.getArg(Environment.class); StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class); ContextPairs contextPairs = instantiator.getArg(ContextPairs.class); StructuredLoggingJsonMembersCustomizer<?> jsonMembersCustomizer = instantiator .getArg(StructuredLoggingJsonMembersCustomizer.class); Assert.state(environment != null, "'environment' must not be null");
Assert.state(contextPairs != null, "'contextPairs' must not be null"); return new GraylogExtendedLogFormatStructuredLogFormatter(environment, stackTracePrinter, contextPairs, jsonMembersCustomizer); } private LogstashStructuredLogFormatter createLogstashFormatter(Instantiator<?> instantiator) { StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class); ContextPairs contextPairs = instantiator.getArg(ContextPairs.class); StructuredLoggingJsonMembersCustomizer<?> jsonMembersCustomizer = instantiator .getArg(StructuredLoggingJsonMembersCustomizer.class); Assert.state(contextPairs != null, "'contextPairs' must not be null"); return new LogstashStructuredLogFormatter(stackTracePrinter, contextPairs, jsonMembersCustomizer); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\StructuredLogLayout.java
1
请在Spring Boot框架中完成以下Java代码
public class Item { @Id private Long id; private String color; private String grade; private String name; public String getColor() { return color; } public String getGrade() { return grade; } public Long getId() { return id; } public String getName() { return name; } public void setColor(String color) { this.color = color;
} public void setGrade(String grade) { this.grade = grade; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\criteria\Item.java
2
请在Spring Boot框架中完成以下Java代码
public JSONDocumentChangeLog getDocumentChangeLog( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentIdStr) { final WindowId windowId = WindowId.fromJson(windowIdStr); final DocumentPath documentPath = DocumentPath.rootDocumentPath(windowId, documentIdStr); return documentChangeLogService.getJSONDocumentChangeLog(documentPath); } @GetMapping("/{windowId}/{documentId}/{tabId}/{rowId}/changeLog") public JSONDocumentChangeLog getDocumentChangeLog( @PathVariable("windowId") final String windowIdStr, @PathVariable("documentId") final String documentIdStr, @PathVariable("tabId") final String tabIdStr, @PathVariable("rowId") final String rowIdStr) { final WindowId windowId = WindowId.fromJson(windowIdStr); final DocumentId documentId = DocumentId.of(documentIdStr); final DetailId tabId = DetailId.fromJson(tabIdStr); final DocumentId rowId = DocumentId.of(rowIdStr); final DocumentPath documentPath = DocumentPath.singleWindowDocumentPath(windowId, documentId, tabId, rowId); return documentChangeLogService.getJSONDocumentChangeLog(documentPath); } @GetMapping("/health") public JsonWindowsHealthCheckResponse healthCheck( @RequestParam(name = "windowIds", required = false) final String windowIdsCommaSeparated
) { return healthCheck(JsonWindowHealthCheckRequest.builder() .onlyAdWindowIds(RepoIdAwares.ofCommaSeparatedSet(windowIdsCommaSeparated, AdWindowId.class)) .checkContextVariables(false) .build()); } @PostMapping("/health") public JsonWindowsHealthCheckResponse healthCheck(@RequestBody JsonWindowHealthCheckRequest request) { return WindowHealthCheckCommand.builder() .documentDescriptorFactory(documentCollection.getDocumentDescriptorFactory()) .request(request) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\WindowRestController.java
2
请完成以下Java代码
public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime;
} public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getDisabled() { return disabled; } public void setDisabled(Integer disabled) { this.disabled = disabled; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\bean\User.java
1
请完成以下Java代码
public class NoContainerException extends AdempiereException { /** * */ private static final long serialVersionUID = 613087606261595301L; public static final String MSG_NO_SUFFICIENT_CONTAINERS = "Kein ausreichendes Verpackungsmaterial"; public static final String MSG_INSUFFICIENT_FEATURES = "Maengel an vorhandenem Verpackungsmaterial:"; /** * * @param warehouseId * the id of the warehouse in which we don't have enough * packaging. * @param maxVolumeExceeded * indicates if there are containers, but their maximum payload * volume is too small * @param maxWeightExceeded * indicates if there are containers, but their maximum payload * weight is too low */ public NoContainerException(final int warehouseId, final boolean maxVolumeExceeded, final boolean maxWeightExceeded) { this(warehouseId, maxVolumeExceeded, maxWeightExceeded, null); } /** * * @param warehouseId * the id of the warehouse in which we don't have enough * packaging. * @param maxVolumeExceeded * indicates if there are containers, but their maximum payload * volume is too small * @param maxWeightExceeded * indicates if there are containers, but their maximum payload * weight is too low */ public NoContainerException(final int warehouseId, final boolean maxVolumeExceeded, final boolean maxWeightExceeded, final NoContainerException originalEx) { super(Msg.translate(Env.getCtx(), buildMsg(warehouseId, maxVolumeExceeded, maxWeightExceeded)), originalEx); } public NoContainerException(final boolean maxVolumeExceeded, final boolean maxWeightExceeded) { this(0, maxVolumeExceeded, maxWeightExceeded, null); } private static String buildMsg(final int warehouseId, final boolean maxVolumeExceeded, final boolean maxWeightExceeded) { final StringBuffer sb = new StringBuffer();
sb.append(Msg.translate(Env.getCtx(), MSG_NO_SUFFICIENT_CONTAINERS)); if (warehouseId > 0) { sb.append("\n@M_Warehouse_ID@ "); sb.append(Services.get(IWarehouseDAO.class).getWarehouseName(WarehouseId.ofRepoId(warehouseId))); } if (maxVolumeExceeded || maxWeightExceeded) { sb.append(Msg.translate(Env.getCtx(), MSG_INSUFFICIENT_FEATURES)); } if (maxVolumeExceeded) { appendExceed(sb, I_M_PackagingContainer.COLUMNNAME_MaxVolume); } if (maxWeightExceeded) { appendExceed(sb, I_M_PackagingContainer.COLUMNNAME_MaxWeight); } return sb.toString(); } private static void appendExceed(final StringBuffer sb, final String colName) { sb.append("\n"); sb.append("@"); sb.append(colName); sb.append("@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\exception\NoContainerException.java
1
请完成以下Java代码
public class TbPackProcessingContext<T> { private final AtomicInteger pendingCount; private final CountDownLatch processingTimeoutLatch; private final ConcurrentMap<UUID, T> ackMap; private final ConcurrentMap<UUID, T> failedMap; public TbPackProcessingContext(CountDownLatch processingTimeoutLatch, ConcurrentMap<UUID, T> ackMap, ConcurrentMap<UUID, T> failedMap) { this.processingTimeoutLatch = processingTimeoutLatch; this.pendingCount = new AtomicInteger(ackMap.size()); this.ackMap = ackMap; this.failedMap = failedMap; } public boolean await(long packProcessingTimeout, TimeUnit milliseconds) throws InterruptedException { return processingTimeoutLatch.await(packProcessingTimeout, milliseconds); } public void onSuccess(UUID id) { boolean empty = false; T msg = ackMap.remove(id); if (msg != null) { empty = pendingCount.decrementAndGet() == 0; } if (empty) { processingTimeoutLatch.countDown(); } else { if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T t : ackMap.values()) { log.trace("left item: {}", t); } } } } public void onFailure(UUID id, Throwable t) { boolean empty = false; T msg = ackMap.remove(id);
if (msg != null) { empty = pendingCount.decrementAndGet() == 0; failedMap.put(id, msg); if (log.isTraceEnabled()) { log.trace("Items left: {}", ackMap.size()); for (T v : ackMap.values()) { log.trace("left item: {}", v); } } } if (empty) { processingTimeoutLatch.countDown(); } } public ConcurrentMap<UUID, T> getAckMap() { return ackMap; } public ConcurrentMap<UUID, T> getFailedMap() { return failedMap; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbPackProcessingContext.java
1
请完成以下Java代码
private void initializeHistoryEventHandlers(final List<HistoryEventHandler> historyEventHandlers) { EnsureUtil.ensureNotNull("History event handler", historyEventHandlers); for (HistoryEventHandler historyEventHandler : historyEventHandlers) { EnsureUtil.ensureNotNull("History event handler", historyEventHandler); this.historyEventHandlers.add(historyEventHandler); } } /** * Adds the {@link HistoryEventHandler} to the list of * {@link HistoryEventHandler} that consume the event. * * @param historyEventHandler * the {@link HistoryEventHandler} that consume the event. */ public void add(final HistoryEventHandler historyEventHandler) { EnsureUtil.ensureNotNull("History event handler", historyEventHandler);
historyEventHandlers.add(historyEventHandler); } @Override public void handleEvent(final HistoryEvent historyEvent) { for (HistoryEventHandler historyEventHandler : historyEventHandlers) { historyEventHandler.handleEvent(historyEvent); } } @Override public void handleEvents(final List<HistoryEvent> historyEvents) { for (HistoryEvent historyEvent : historyEvents) { handleEvent(historyEvent); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\handler\CompositeHistoryEventHandler.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Type AD_Reference_ID=101 */ public static final int TYPE_AD_Reference_ID=101; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Java = J */ public static final String TYPE_Java = "J"; /** Java-Script = E */
public static final String TYPE_Java_Script = "E"; /** Composite = C */ public static final String TYPE_Composite = "C"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule.java
1
请完成以下Java代码
public String toLowerCaseString() { return this.lowerCaseValue; } @Override public String toString() { return this.value; } /** * Factory method to create a new {@link EndpointId} of the specified value. * @param value the endpoint ID value * @return an {@link EndpointId} instance */ public static EndpointId of(String value) { return new EndpointId(value); } /** * Factory method to create a new {@link EndpointId} of the specified value. This * variant will respect the {@code management.endpoints.migrate-legacy-names} property * if it has been set in the {@link Environment}. * @param environment the Spring environment * @param value the endpoint ID value * @return an {@link EndpointId} instance * @since 2.2.0 */ public static EndpointId of(Environment environment, String value) { Assert.notNull(environment, "'environment' must not be null"); return new EndpointId(migrateLegacyId(environment, value)); } private static String migrateLegacyId(Environment environment, String value) { if (environment.getProperty(MIGRATE_LEGACY_NAMES_PROPERTY, Boolean.class, false)) { return value.replaceAll("[-.]+", ""); }
return value; } /** * Factory method to create a new {@link EndpointId} from a property value. More * lenient than {@link #of(String)} to allow for common "relaxed" property variants. * @param value the property value to convert * @return an {@link EndpointId} instance */ public static EndpointId fromPropertyValue(String value) { return new EndpointId(value.replace("-", "")); } static void resetLoggedWarnings() { loggedWarnings.clear(); } private static void logWarning(String value) { if (logger.isWarnEnabled() && loggedWarnings.add(value)) { logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format."); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\EndpointId.java
1
请完成以下Java代码
public class DateAndPlaceOfBirth { @XmlElement(name = "BirthDt", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar birthDt; @XmlElement(name = "PrvcOfBirth") protected String prvcOfBirth; @XmlElement(name = "CityOfBirth", required = true) protected String cityOfBirth; @XmlElement(name = "CtryOfBirth", required = true) protected String ctryOfBirth; /** * Gets the value of the birthDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getBirthDt() { return birthDt; } /** * Sets the value of the birthDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setBirthDt(XMLGregorianCalendar value) { this.birthDt = value; } /** * Gets the value of the prvcOfBirth property. * * @return * possible object is * {@link String } * */ public String getPrvcOfBirth() { return prvcOfBirth; } /** * Sets the value of the prvcOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setPrvcOfBirth(String value) { this.prvcOfBirth = value; }
/** * Gets the value of the cityOfBirth property. * * @return * possible object is * {@link String } * */ public String getCityOfBirth() { return cityOfBirth; } /** * Sets the value of the cityOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setCityOfBirth(String value) { this.cityOfBirth = value; } /** * Gets the value of the ctryOfBirth property. * * @return * possible object is * {@link String } * */ public String getCtryOfBirth() { return ctryOfBirth; } /** * Sets the value of the ctryOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setCtryOfBirth(String value) { this.ctryOfBirth = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DateAndPlaceOfBirth.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_Value (COLUMNNAME_C_TaxCategory_ID, null); else set_Value (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public I_ExternalSystem_Config_ProCareManagement getExternalSystem_Config_ProCareManagement() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, I_ExternalSystem_Config_ProCareManagement.class); } @Override public void setExternalSystem_Config_ProCareManagement(final I_ExternalSystem_Config_ProCareManagement ExternalSystem_Config_ProCareManagement) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, I_ExternalSystem_Config_ProCareManagement.class, ExternalSystem_Config_ProCareManagement); } @Override public void setExternalSystem_Config_ProCareManagement_ID (final int ExternalSystem_Config_ProCareManagement_ID) { if (ExternalSystem_Config_ProCareManagement_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, ExternalSystem_Config_ProCareManagement_ID); }
@Override public int getExternalSystem_Config_ProCareManagement_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID); } @Override public void setExternalSystem_Config_ProCareManagement_TaxCategory_ID (final int ExternalSystem_Config_ProCareManagement_TaxCategory_ID) { if (ExternalSystem_Config_ProCareManagement_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_TaxCategory_ID, ExternalSystem_Config_ProCareManagement_TaxCategory_ID); } @Override public int getExternalSystem_Config_ProCareManagement_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_TaxCategory_ID); } @Override public void setTaxRates (final String TaxRates) { set_Value (COLUMNNAME_TaxRates, TaxRates); } @Override public String getTaxRates() { return get_ValueAsString(COLUMNNAME_TaxRates); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_TaxCategory.java
1
请完成以下Java代码
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } @Override public I_M_ShipmentSchedule getWrappedRecord() { return delegate;
} @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public BillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new BillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_ShipmentSchedule.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\location\adapter\BillLocationAdapter.java
1
请完成以下Java代码
public GlnWithLabel asGlnWithLabel() { Check.assume(Type.GLN_WITH_LABEL.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN_WITH_LABEL, this); final Matcher glnWithLabelMatcher = Type.GLN_WITH_LABEL.pattern.matcher(rawValue); if (glnWithLabelMatcher.find()) { return GlnWithLabel.ofString(glnWithLabelMatcher.group(1)); } else { throw new AdempiereException("External identifier of GLN parsing failed. External Identifier:" + rawValue); } } @NonNull public String asValue() { Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this); final Matcher valueMatcher = Type.VALUE.pattern.matcher(rawValue); if (!valueMatcher.matches()) { throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue); } return valueMatcher.group(1); } @NonNull public String asGTIN() { Check.assume(Type.GTIN.equals(type), "The type of this instance needs to be {}; this={}", Type.GTIN, this);
final Matcher gtinMatcher = Type.GTIN.pattern.matcher(rawValue); if (!gtinMatcher.matches()) { throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue); } return gtinMatcher.group(1); } @AllArgsConstructor @Getter public enum Type { METASFRESH_ID(Pattern.compile("^\\d+$")), EXTERNAL_REFERENCE(Pattern.compile("^ext-([a-zA-Z0-9_]+)-(.+)$")), GLN(Pattern.compile("^gln-(.+)")), /** * GLN with an optional additional label that can be used in case metasfresh has multiple BPartners which share the same GLN. */ GLN_WITH_LABEL(Pattern.compile("^glnl-([^_]+_.+)")), GTIN(Pattern.compile("^gtin-(.+)")), VALUE(Pattern.compile("^val-(.+)")); private final Pattern pattern; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalIdentifier.java
1
请完成以下Java代码
public void setC_Order_ID (int C_Order_ID) { if (C_Order_ID < 1) set_Value (COLUMNNAME_C_Order_ID, null); else set_Value (COLUMNNAME_C_Order_ID, Integer.valueOf(C_Order_ID)); } /** Get Auftrag. @return Order */ public int getC_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Packaging Tree. @param M_PackagingTree_ID Packaging Tree */ public void setM_PackagingTree_ID (int M_PackagingTree_ID) { if (M_PackagingTree_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PackagingTree_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackagingTree_ID, Integer.valueOf(M_PackagingTree_ID)); } /** Get Packaging Tree. @return Packaging Tree */ public int getM_PackagingTree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTree_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_Warehouse getM_Warehouse_Dest() throws RuntimeException { return (org.compiere.model.I_M_Warehouse)MTable.get(getCtx(), org.compiere.model.I_M_Warehouse.Table_Name) .getPO(getM_Warehouse_Dest_ID(), get_TrxName()); } /** Set Ziel-Lager. @param M_Warehouse_Dest_ID Ziel-Lager */ public void setM_Warehouse_Dest_ID (int M_Warehouse_Dest_ID) { if (M_Warehouse_Dest_ID < 1) set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null); else set_Value (COLUMNNAME_M_Warehouse_Dest_ID, Integer.valueOf(M_Warehouse_Dest_ID)); } /** Get Ziel-Lager. @return Ziel-Lager */ public int getM_Warehouse_Dest_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID);
if (ii == null) return 0; return ii.intValue(); } /** * Set Verarbeitet. * * @param Processed * Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public void setProcessed(boolean Processed) { set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** * Get Verarbeitet. * * @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ public boolean isProcessed() { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
1
请完成以下Java代码
protected Runnable createChangeDetectionRunnable() { return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager); } @Override public void shutdown() { destroy(); } @Override public void destroy() { if (threadPoolTaskScheduler != null) { threadPoolTaskScheduler.destroy(); } }
public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() { return eventRegistryChangeDetectionManager; } @Override public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; } public TaskScheduler getTaskScheduler() { return taskScheduler; } public void setTaskScheduler(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\management\DefaultSpringEventRegistryChangeDetectionExecutor.java
1
请完成以下Java代码
public PPOrderCreateRequest build(@NonNull final Quantity qtyRequired) { return PPOrderCreateRequest.builder() .clientAndOrgId(clientAndOrgId.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("clientAndOrgId", list))) .productPlanningId(productPlanningId.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("productPlanningId", list))) .materialDispoGroupId(materialDispoGroupId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) .plantId(plantId.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("plantId", list))) .workstationId(workstationId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) .warehouseId(warehouseId.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("warehouseId", list))) // .productId(productId.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("productId", list))) .attributeSetInstanceId(attributeSetInstanceId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) // .dateOrdered(SystemTime.asInstant()) .datePromised(datePromised.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("datePromised", list))) .dateStartSchedule(dateStartSchedule.getAggregatedValue((list) -> throwErrorOnMoreThanOneUniqueValue("dateStartSchedule", list))) // .salesOrderLineId(salesOrderLineId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) .shipmentScheduleId(shipmentScheduleId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) // .packingMaterialId(packingMaterialId.getAggregatedValue(PPOrderCreateRequestBuilder::returnNullOnMoreThanOneUniqueValue)) .completeDocument(false) .qtyRequired(qtyRequired) .build(); } private static <T> T throwErrorOnMoreThanOneUniqueValue(@NonNull final String fieldName, @NonNull final List<T> values) { throw new AdempiereException("More than one value found for fieldName=" + fieldName) .appendParametersToMessage() .setParameter("values", values.stream().map(String::valueOf).collect(Collectors.joining(","))); } @Nullable private static <T> T returnNullOnMoreThanOneUniqueValue(@NonNull final List<T> values) { return null; } private static class ValueAggregator<T> { @NonNull private final List<T> values = new ArrayList<>(); public void setValue(@Nullable final T newValue)
{ values.add(newValue); } @Nullable public T getAggregatedValue(@NonNull final Function<List<T>, T> onMoreThanOneUniqueValue) { if (values.isEmpty()) { return null; } final T initialValue = values.get(0); for (final T value : values) { if (!Objects.equals(initialValue, value)) { return onMoreThanOneUniqueValue.apply(values); } } return initialValue; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCreateRequestBuilder.java
1
请完成以下Java代码
public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations, @Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, Dialect dialect) { var jdbcTypeFactory = new DefaultJdbcTypeFactory(operations.getJdbcOperations()); return new MappingJdbcConverter(mappingContext, relationResolver, conversions, jdbcTypeFactory) { @Override @SuppressWarnings("all") protected <S> S readAggregate(ConversionContext context, RowDocumentAccessor documentAccessor, TypeInformation<? extends S> typeHint) { RelationalPersistentEntity<?> implementationEntity = getImplementationEntity(mappingContext, mappingContext.getRequiredPersistentEntity(typeHint)); return (S) super.readAggregate(context, documentAccessor, implementationEntity.getTypeInformation()); } }; } /** * Returns if the entity passed as an argument is an interface the implementation provided by Immutable is provided * instead. In all other cases the entity passed as an argument is returned. */ @SuppressWarnings("unchecked") private <T> RelationalPersistentEntity<T> getImplementationEntity(JdbcMappingContext mappingContext, RelationalPersistentEntity<T> entity) {
Class<T> type = entity.getType(); if (type.isInterface()) { var immutableClass = String.format(IMMUTABLE_IMPLEMENTATION_CLASS, type.getPackageName(), type.getSimpleName()); if (ClassUtils.isPresent(immutableClass, resourceLoader.getClassLoader())) { return (RelationalPersistentEntity<T>) mappingContext .getPersistentEntity(ClassUtils.resolveClassName(immutableClass, resourceLoader.getClassLoader())); } } return entity; } } }
repos\spring-data-examples-main\jdbc\immutables\src\main\java\example\springdata\jdbc\immutables\Application.java
1
请完成以下Java代码
public String getPredefinedProcessInstanceId() { return predefinedProcessInstanceId; } public String getOwnerId() { return ownerId; } public String getAssigneeId() { return assigneeId; } public Map<String, Object> getVariables() { return variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } public Map<String, Object> getStartFormVariables() { return startFormVariables;
} public String getOutcome() { return outcome; } public Map<String, Object> getExtraFormVariables() { return extraFormVariables; } public FormInfo getExtraFormInfo() { return extraFormInfo; } public String getExtraFormOutcome() { return extraFormOutcome; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceBuilderImpl.java
1
请完成以下Spring Boot application配置
spring: cloud: gateway: routes: - id: rewrite_with_scrub uri: ${rewrite.backend.uri:http://example.com} predicates: - Path=/v1/customer/** filters: -
RewritePath=/v1/customer/(?<segment>.*),/api/$\{segment} - ScrubResponse=ssn,***
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\resources\application-scrub.yml
2
请完成以下Java代码
public synchronized void createNewToken(PersistentRememberMeToken token) { PersistentRememberMeToken current = this.seriesTokens.get(token.getSeries()); if (current != null) { throw new DataIntegrityViolationException("Series Id '" + token.getSeries() + "' already exists!"); } this.seriesTokens.put(token.getSeries(), token); } @Override public synchronized void updateToken(String series, String tokenValue, Date lastUsed) { PersistentRememberMeToken token = getTokenForSeries(series); if (token == null) { throw new IllegalArgumentException("Token for series '" + series + "' does not exist"); } PersistentRememberMeToken newToken = new PersistentRememberMeToken(token.getUsername(), series, tokenValue, new Date()); // Store it, overwriting the existing one. this.seriesTokens.put(series, newToken); }
@Override public synchronized @Nullable PersistentRememberMeToken getTokenForSeries(String seriesId) { return this.seriesTokens.get(seriesId); } @Override public synchronized void removeUserTokens(String username) { Iterator<String> series = this.seriesTokens.keySet().iterator(); while (series.hasNext()) { String seriesId = series.next(); PersistentRememberMeToken token = this.seriesTokens.get(seriesId); if (token != null && username.equals(token.getUsername())) { series.remove(); } } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\InMemoryTokenRepositoryImpl.java
1
请完成以下Java代码
public static Argon2PasswordEncoder defaultsForSpringSecurity_v5_8() { return new Argon2PasswordEncoder(DEFAULT_SALT_LENGTH, DEFAULT_HASH_LENGTH, DEFAULT_PARALLELISM, DEFAULT_MEMORY, DEFAULT_ITERATIONS); } @Override protected String encodeNonNullPassword(String rawPassword) { byte[] salt = this.saltGenerator.generateKey(); byte[] hash = new byte[this.hashLength]; // @formatter:off Argon2Parameters params = new Argon2Parameters .Builder(Argon2Parameters.ARGON2_id) .withSalt(salt) .withParallelism(this.parallelism) .withMemoryAsKB(this.memory) .withIterations(this.iterations) .build(); // @formatter:on Argon2BytesGenerator generator = new Argon2BytesGenerator(); generator.init(params); generator.generateBytes(rawPassword.toString().toCharArray(), hash); return Argon2EncodingUtils.encode(hash, params); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { Argon2EncodingUtils.Argon2Hash decoded; try { decoded = Argon2EncodingUtils.decode(encodedPassword); } catch (IllegalArgumentException ex) { this.logger.warn("Malformed password hash", ex); return false; } byte[] hashBytes = new byte[decoded.getHash().length]; Argon2BytesGenerator generator = new Argon2BytesGenerator(); generator.init(decoded.getParameters()); generator.generateBytes(rawPassword.toString().toCharArray(), hashBytes); return constantTimeArrayEquals(decoded.getHash(), hashBytes); }
@Override protected boolean upgradeEncodingNonNull(String encodedPassword) { Argon2Parameters parameters = Argon2EncodingUtils.decode(encodedPassword).getParameters(); return parameters.getMemory() < this.memory || parameters.getIterations() < this.iterations; } private static boolean constantTimeArrayEquals(byte[] expected, byte[] actual) { if (expected.length != actual.length) { return false; } int result = 0; for (int i = 0; i < expected.length; i++) { result |= expected[i] ^ actual[i]; } return result == 0; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\argon2\Argon2PasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getLastSeen() { return lastSeen; } public void setLastSeen(Date lastSeen) { this.lastSeen = lastSeen; } public List<Item> getIncomes() { return incomes; } public void setIncomes(List<Item> incomes) { this.incomes = incomes; } public List<Item> getExpenses() { return expenses; } public void setExpenses(List<Item> expenses) { this.expenses = expenses; }
public Saving getSaving() { return saving; } public void setSaving(Saving saving) { this.saving = saving; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\domain\Account.java
2
请完成以下Java代码
public String getSource() { return deployment.getSource(); } public String getTenantId() { return deployment.getTenantId(); } public ProcessApplicationRegistration getProcessApplicationRegistration() { return registration; } @Override public List<ProcessDefinition> getDeployedProcessDefinitions() { return deployment.getDeployedProcessDefinitions(); }
@Override public List<CaseDefinition> getDeployedCaseDefinitions() { return deployment.getDeployedCaseDefinitions(); } @Override public List<DecisionDefinition> getDeployedDecisionDefinitions() { return deployment.getDeployedDecisionDefinitions(); } @Override public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() { return deployment.getDeployedDecisionRequirementsDefinitions(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessApplicationDeploymentImpl.java
1
请完成以下Java代码
public Object get(Object key) throws CacheException { Object value = springCache.get(key); if (value instanceof SimpleValueWrapper) { return ((SimpleValueWrapper) value).get(); } return value; } @Override public Object put(Object key, Object value) throws CacheException { springCache.put(key, value); return value; } @Override public Object remove(Object key) throws CacheException { springCache.evict(key); return null; } @Override public void clear() throws CacheException { springCache.clear(); } @Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); } @SuppressWarnings("unchecked") @Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys());
} throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); } @SuppressWarnings("unchecked") @Override public Collection values() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); List keys = ehcache.getKeys(); if (!CollectionUtils.isEmpty(keys)) { List values = new ArrayList(keys.size()); for (Object key : keys) { Object value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } else { return Collections.emptyList(); } } throw new UnsupportedOperationException("invoke spring cache abstract values method not supported"); } } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\spring\SpringCacheManagerWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public class CONTRLExtensionType { @XmlElement(name = "MessageAcknowledgementCode") protected String messageAcknowledgementCode; @XmlElement(name = "FunctionalGroupAcknowledgementCode") protected String functionalGroupAcknowledgementCode; /** * Gets the value of the messageAcknowledgementCode property. * * @return * possible object is * {@link String } * */ public String getMessageAcknowledgementCode() { return messageAcknowledgementCode; } /** * Sets the value of the messageAcknowledgementCode property. * * @param value * allowed object is * {@link String } * */ public void setMessageAcknowledgementCode(String value) { this.messageAcknowledgementCode = value; } /** * Gets the value of the functionalGroupAcknowledgementCode property. * * @return * possible object is * {@link String } *
*/ public String getFunctionalGroupAcknowledgementCode() { return functionalGroupAcknowledgementCode; } /** * Sets the value of the functionalGroupAcknowledgementCode property. * * @param value * allowed object is * {@link String } * */ public void setFunctionalGroupAcknowledgementCode(String value) { this.functionalGroupAcknowledgementCode = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\CONTRLExtensionType.java
2
请完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; }
@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(", name=").append(name); sb.append(", type=").append(type); sb.append(", pic=").append(pic); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", status=").append(status); sb.append(", clickCount=").append(clickCount); sb.append(", orderCount=").append(orderCount); sb.append(", url=").append(url); sb.append(", note=").append(note); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java
1
请在Spring Boot框架中完成以下Java代码
public class BarMappingExamplesController { public BarMappingExamplesController() { super(); } // API // with @RequestParam @RequestMapping(value = "/bars") @ResponseBody public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) { return "Get a specific Bar with id=" + id; } @RequestMapping(value = "/bars", params = "id") @ResponseBody public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
return "Get a specific Bar with id=" + id; } @RequestMapping(value = "/bars", params = { "id", "second" }) @ResponseBody public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) { return "Get a specific Bar with id=" + id; } // with @PathVariable @RequestMapping(value = "/bars/{numericId:[\\d]+}") @ResponseBody public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) { return "Get a specific Bar with id=" + numericId; } }
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\BarMappingExamplesController.java
2
请完成以下Java代码
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代码
protected UpdateJobSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { UpdateJobSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobSuspensionState(); if (jobId != null) { return selectBuilder.byJobId(jobId); } else if (jobDefinitionId != null) { return selectBuilder.byJobDefinitionId(jobDefinitionId); } else if (processInstanceId != null) { return selectBuilder.byProcessInstanceId(processInstanceId); } else if (processDefinitionId != null) { return selectBuilder.byProcessDefinitionId(processDefinitionId);
} else { UpdateJobSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); if (processDefinitionTenantId != null) { tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); } else if (processDefinitionWithoutTenantId) { tenantBuilder.processDefinitionWithoutTenantId(); } return tenantBuilder; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobSuspensionStateDto.java
1
请在Spring Boot框架中完成以下Java代码
public OAuth2IdentityProviderPlugin identityProviderPlugin() { logger.debug("Registering OAuth2IdentityProviderPlugin"); return new OAuth2IdentityProviderPlugin(); } @Bean @ConditionalOnProperty(name = "identity-provider.group-name-attribute", prefix = OAuth2Properties.PREFIX) protected GrantedAuthoritiesMapper grantedAuthoritiesMapper() { logger.debug("Registering OAuth2GrantedAuthoritiesMapper"); return new OAuth2GrantedAuthoritiesMapper(oAuth2Properties); } @Bean @ConditionalOnProperty(name = "sso-logout.enabled", havingValue = "true", prefix = OAuth2Properties.PREFIX) protected SsoLogoutSuccessHandler ssoLogoutSuccessHandler(ClientRegistrationRepository clientRegistrationRepository) { logger.debug("Registering SsoLogoutSuccessHandler"); return new SsoLogoutSuccessHandler(clientRegistrationRepository, oAuth2Properties); } @Bean protected AuthorizeTokenFilter authorizeTokenFilter(OAuth2AuthorizedClientManager clientManager) { logger.debug("Registering AuthorizeTokenFilter"); return new AuthorizeTokenFilter(clientManager); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, AuthorizeTokenFilter authorizeTokenFilter, @Nullable SsoLogoutSuccessHandler ssoLogoutSuccessHandler) throws Exception {
logger.info("Enabling Camunda Spring Security oauth2 integration"); // @formatter:off http.authorizeHttpRequests(c -> c .requestMatchers(webappPath + "/app/**").authenticated() .requestMatchers(webappPath + "/api/**").authenticated() .anyRequest().permitAll() ) .addFilterAfter(authorizeTokenFilter, OAuth2AuthorizationRequestRedirectFilter.class) .anonymous(AbstractHttpConfigurer::disable) .oidcLogout(c -> c.backChannel(Customizer.withDefaults())) .oauth2Login(Customizer.withDefaults()) .logout(c -> c .clearAuthentication(true) .invalidateHttpSession(true) ) .oauth2Client(Customizer.withDefaults()) .cors(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable); // @formatter:on if (oAuth2Properties.getSsoLogout().isEnabled()) { http.logout(c -> c.logoutSuccessHandler(ssoLogoutSuccessHandler)); } return http.build(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\CamundaSpringSecurityOAuth2AutoConfiguration.java
2
请完成以下Java代码
public void setTrxName(String trxName) { this.trxName = trxName; } public String getTrxName() { return trxName; } public void setSkipCaching() { this.skipCaching = true; } public boolean isSkipCaching() { return skipCaching; }
/** * Advices the caching engine to refresh the cached value, instead of checking the cache. * * NOTE: this option will have NO affect if {@link #isSkipCaching()}. */ public void setCacheReload() { this.cacheReload = true; } /** @return true if instead the underlying method shall be invoked and cache shall be refreshed with that value */ public boolean isCacheReload() { return cacheReload; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheKeyBuilder.java
1
请完成以下Java代码
public Builder setSortNo(final int sortNo) { this.sortNo = sortNo; return this; } public Builder setDisplayName(final Map<String, String> displayNameTrls) { this.displayNameTrls = TranslatableStrings.ofMap(displayNameTrls); return this; } public Builder setDisplayName(final ITranslatableString displayNameTrls) { this.displayNameTrls = displayNameTrls; return this; } public Builder setDisplayName(final String displayName) { displayNameTrls = TranslatableStrings.constant(displayName); return this; } public Builder setDisplayName(final AdMessageKey displayName) { return setDisplayName(TranslatableStrings.adMessage(displayName)); } @Nullable public ITranslatableString getDisplayNameTrls() { if (displayNameTrls != null) { return displayNameTrls; } if (parameters.size() == 1) { return parameters.get(0).getDisplayName(); } return null; } public Builder setFrequentUsed(final boolean frequentUsed) { this.frequentUsed = frequentUsed; return this; } public Builder setInlineRenderMode(final DocumentFilterInlineRenderMode inlineRenderMode) { this.inlineRenderMode = inlineRenderMode; return this; }
private DocumentFilterInlineRenderMode getInlineRenderMode() { return inlineRenderMode != null ? inlineRenderMode : DocumentFilterInlineRenderMode.BUTTON; } public Builder setParametersLayoutType(final PanelLayoutType parametersLayoutType) { this.parametersLayoutType = parametersLayoutType; return this; } private PanelLayoutType getParametersLayoutType() { return parametersLayoutType != null ? parametersLayoutType : PanelLayoutType.Panel; } public Builder setFacetFilter(final boolean facetFilter) { this.facetFilter = facetFilter; return this; } public boolean hasParameters() { return !parameters.isEmpty(); } public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter) { parameters.add(parameter); return this; } public Builder addInternalParameter(final String parameterName, final Object constantValue) { return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue)); } public Builder addInternalParameter(final DocumentFilterParam parameter) { internalParameters.add(parameter); return this; } public Builder putDebugProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put("debug-" + name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class SystemBL implements ISystemBL { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, ADSystemInfo> cache = CCache.<Integer, ADSystemInfo>builder() .tableName(I_AD_System.Table_Name) .build(); @Override public ADSystemInfo get() { return cache.getOrLoad(0, this::retrieveADSystemInfo); } private ADSystemInfo retrieveADSystemInfo() { final I_AD_System record = queryBL.createQueryBuilderOutOfTrx(I_AD_System.class) .create() .firstOnly(I_AD_System.class); // shall not happen if (record == null) { throw new AdempiereException("No AD_System record found"); } return ADSystemInfo.builder() .dbVersion(record.getDBVersion()) .systemStatus(record.getSystemStatus()) .lastBuildInfo(record.getLastBuildInfo()) .failOnMissingModelValidator(record.isFailOnMissingModelValidator()) .build(); } /* * Allow remember me feature * ZK_LOGIN_ALLOW_REMEMBER_ME and SWING_ALLOW_REMEMBER_ME parameter allow the next values * U - Allow remember the username (default for zk) * P - Allow remember the username and password (default for swing) * N - None
* * @return boolean representing if remember me feature is allowed */ public static final String SYSTEM_ALLOW_REMEMBER_USER = "U"; public static final String SYSTEM_ALLOW_REMEMBER_PASSWORD = "P"; @Override public boolean isRememberUserAllowed(@NonNull final String sysConfigKey) { String ca = Services.get(ISysConfigBL.class).getValue(sysConfigKey, SYSTEM_ALLOW_REMEMBER_PASSWORD); return (ca.equalsIgnoreCase(SYSTEM_ALLOW_REMEMBER_USER) || ca.equalsIgnoreCase(SYSTEM_ALLOW_REMEMBER_PASSWORD)); } @Override public boolean isRememberPasswordAllowed(@NonNull final String sysConfigKey) { String ca = Services.get(ISysConfigBL.class).getValue(sysConfigKey, SYSTEM_ALLOW_REMEMBER_PASSWORD); return (ca.equalsIgnoreCase(SYSTEM_ALLOW_REMEMBER_PASSWORD)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\SystemBL.java
2
请在Spring Boot框架中完成以下Java代码
public class Bar implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private String name; private int index; public Bar() { } public Bar(final String name) { this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Bar other = (Bar) obj; return index == other.index && Objects.equals(name, other.name); } public long getId() { return id; } public int getIndex() { return index; } public String getName() { return name; } @Override public int hashCode() { return Objects.hash(index, name);
} public void setId(final long id) { this.id = id; } public void setIndex(int index) { this.index = index; } public void setName(final String name) { this.name = name; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Bar [name=") .append(name) .append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Bar.java
2
请完成以下Java代码
public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_DEFINITIONS; } @Override public boolean hasChildElements() { return false; } @Override protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { CmmnModel model = conversionHelper.getCmmnModel(); model.setId(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_ID)); model.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); model.setExpressionLanguage(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPRESSION_LANGUAGE)); model.setExporter(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER)); model.setExporterVersion(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER_VERSION)); model.setAuthor(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_AUTHOR)); model.setTargetNamespace(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TARGET_NAMESPACE)); String creationDateString = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_CREATION_DATE); if (StringUtils.isNotEmpty(creationDateString)) { try { Date creationDate = new SimpleDateFormat(XSD_DATETIME_FORMAT).parse(creationDateString); model.setCreationDate(creationDate); } catch (ParseException e) { LOGGER.warn("Ignoring creationDate attribute: invalid date format", e); } } for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (StringUtils.isNotEmpty(prefix)) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); } }
for (int i = 0; i < xtr.getAttributeCount(); i++) { ExtensionAttribute extensionAttribute = new ExtensionAttribute(); extensionAttribute.setName(xtr.getAttributeLocalName(i)); extensionAttribute.setValue(xtr.getAttributeValue(i)); String namespace = xtr.getAttributeNamespace(i); if (model.getNamespaces().containsValue(namespace)) { if (StringUtils.isNotEmpty(namespace)) { extensionAttribute.setNamespace(namespace); } if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) { extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i)); } model.addDefinitionsAttribute(extensionAttribute); } } return null; } @Override protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) { } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\DefinitionsXmlConverter.java
1
请完成以下Java代码
protected static class ProcessDataSections { /** * Keeps track of when we added values to which stack (as we do not add * a new value to every stack with every update, but only changed values) */ protected Deque<List<ProcessDataStack>> sections = new ArrayDeque<>(); protected boolean currentSectionSealed = true; /** * Adds a stack to the current section. If the current section is already sealed, * a new section is created. */ public void addToCurrentSection(ProcessDataStack stack) { List<ProcessDataStack> currentSection; if (currentSectionSealed) { currentSection = new ArrayList<>(); sections.addFirst(currentSection); currentSectionSealed = false; } else { currentSection = sections.peekFirst(); } currentSection.add(stack); } /** * Pops the current section and removes the
* current values from the referenced stacks (including updates * to the MDC) */ public void popCurrentSection() { List<ProcessDataStack> section = sections.pollFirst(); if (section != null) { section.forEach(ProcessDataStack::removeCurrentValue); } currentSectionSealed = true; } /** * After a section is sealed, a new section will be created * with the next call to {@link #addToCurrentSection(ProcessDataStack)} */ public void sealCurrentSection() { currentSectionSealed = true; } public int size() { return sections.size(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ProcessDataContext.java
1
请完成以下Java代码
public int getHR_Payroll_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Displayed. @param IsDisplayed Determines, if this field is displayed */ public void setIsDisplayed (boolean IsDisplayed) { set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed)); } /** Get Displayed. @return Determines, if this field is displayed */ public boolean isDisplayed () { Object oo = get_Value(COLUMNNAME_IsDisplayed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Included. @param IsInclude Defines whether this content / template is included into another one */ public void setIsInclude (boolean IsInclude) { set_Value (COLUMNNAME_IsInclude, Boolean.valueOf(IsInclude)); } /** Get Included. @return Defines whether this content / template is included into another one */ public boolean isInclude () { Object oo = get_Value(COLUMNNAME_IsInclude); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Printed. @param IsPrinted Indicates if this document / line is printed */ public void setIsPrinted (boolean IsPrinted) { set_Value (COLUMNNAME_IsPrinted, Boolean.valueOf(IsPrinted)); } /** Get Printed. @return Indicates if this document / line is printed
*/ public boolean isPrinted () { Object oo = get_Value(COLUMNNAME_IsPrinted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_PayrollConcept.java
1
请在Spring Boot框架中完成以下Java代码
private static final class ItemState { private final Reference<TransactionalPackingItem> transactionalItemRef; private final PackingItem state; public ItemState(final TransactionalPackingItem transactionalItem) { super(); // NOTE: we keep a weak reference to our transactional item // because in case nobody is referencing it, there is no point to update on commit. this.transactionalItemRef = new WeakReference<>(transactionalItem); state = transactionalItem.createNewState(); } public PackingItem getState()
{ return state; } public void commit() { final TransactionalPackingItem transactionalItem = transactionalItemRef.get(); if (transactionalItem == null) { // reference already expired return; } transactionalItem.commit(state); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\TransactionalPackingItemSupport.java
2
请完成以下Java代码
public void addBook(Book book) { this.books.add(book); book.setAuthor(this); } public void removeBook(Book book) { book.setAuthor(null); this.books.remove(book); } public void removeBooks() { Iterator<Book> iterator = this.books.iterator(); while (iterator.hasNext()) { Book book = iterator.next(); book.setAuthor(null); iterator.remove(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age;
} public void setAge(int age) { this.age = age; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "name=" + name + ", age=" + age + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyIdClass\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public class NativeUserQueryImpl extends AbstractNativeQuery<NativeUserQuery, User> implements NativeUserQuery { private static final long serialVersionUID = 1L; public NativeUserQueryImpl(CommandContext commandContext) { super(commandContext); } public NativeUserQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } //results ////////////////////////////////////////////////////////////////
public List<User> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) { final DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext); return identityProvider.findUserByNativeQuery(parameterMap, firstResult, maxResults); } public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) { final DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext); return identityProvider.findUserCountByNativeQuery(parameterMap); } private DbReadOnlyIdentityServiceProvider getIdentityProvider(CommandContext commandContext) { return (DbReadOnlyIdentityServiceProvider) commandContext.getReadOnlyIdentityProvider(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\NativeUserQueryImpl.java
1
请完成以下Java代码
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER); if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) { String token = authorizationHeader.replace(BEARER_PREFIX, ""); Optional<String> userId = extractUserIdFromToken(token); if (userId.isPresent()) { var authentication = new UsernamePasswordAuthenticationToken(userId.get(), null, null); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } else { setAuthErrorDetails(response); return; } } filterChain.doFilter(request, response); } private Optional<String> extractUserIdFromToken(String token) { try {
FirebaseToken firebaseToken = firebaseAuth.verifyIdToken(token, true); String userId = String.valueOf(firebaseToken.getClaims().get(USER_ID_CLAIM)); return Optional.of(userId); } catch (FirebaseAuthException exception) { return Optional.empty(); } } private void setAuthErrorDetails(HttpServletResponse response) throws JsonProcessingException, IOException { HttpStatus unauthorized = HttpStatus.UNAUTHORIZED; response.setStatus(unauthorized.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(unauthorized, "Authentication failure: Token missing, invalid or expired"); response.getWriter().write(objectMapper.writeValueAsString(problemDetail)); } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\auth\TokenAuthenticationFilter.java
1
请完成以下Java代码
public double apply(double... args) { return Math.log(args[0]); } } ); userDefinedFunctions.add( new Function("lg") { @Override public double apply(double... args) { return Math.log10(args[0]); } } ); userDefinedFunctions.add( new Function("logab", 2) { @Override public double apply(double... args) { return Math.log(args[1]) / Math.log(args[0]); } } ); userDefinedFunctions.add(Functions.getBuiltinFunction("sin")); userDefinedFunctions.add(Functions.getBuiltinFunction("cos")); userDefinedFunctions.add(Functions.getBuiltinFunction("tan")); userDefinedFunctions.add(Functions.getBuiltinFunction("cot")); userDefinedFunctions.add(Functions.getBuiltinFunction("log")); userDefinedFunctions.add(Functions.getBuiltinFunction("log2")); userDefinedFunctions.add(Functions.getBuiltinFunction("log10")); userDefinedFunctions.add(Functions.getBuiltinFunction("log1p")); userDefinedFunctions.add(Functions.getBuiltinFunction("abs")); userDefinedFunctions.add(Functions.getBuiltinFunction("acos"));
userDefinedFunctions.add(Functions.getBuiltinFunction("asin")); userDefinedFunctions.add(Functions.getBuiltinFunction("atan")); userDefinedFunctions.add(Functions.getBuiltinFunction("cbrt")); userDefinedFunctions.add(Functions.getBuiltinFunction("floor")); userDefinedFunctions.add(Functions.getBuiltinFunction("sinh")); userDefinedFunctions.add(Functions.getBuiltinFunction("sqrt")); userDefinedFunctions.add(Functions.getBuiltinFunction("tanh")); userDefinedFunctions.add(Functions.getBuiltinFunction("cosh")); userDefinedFunctions.add(Functions.getBuiltinFunction("ceil")); userDefinedFunctions.add(Functions.getBuiltinFunction("pow")); userDefinedFunctions.add(Functions.getBuiltinFunction("exp")); userDefinedFunctions.add(Functions.getBuiltinFunction("expm1")); userDefinedFunctions.add(Functions.getBuiltinFunction("signum")); } public static Expression createExpression(String expression, Set<String> variables) { return new ExpressionBuilder(expression) .functions(userDefinedFunctions) .implicitMultiplication(true) .operator() .variables(variables) .build(); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ExpressionUtils.java
1
请完成以下Java代码
public boolean fromXmlNode(I_AD_Migration migration, Element element) { if (!NODENAME.equals(element.getLocalName())) { throw new AdempiereException("XML definition shall start with Migration node."); } final String name = element.getAttribute(NODE_Name); final int seqNo = Integer.parseInt(element.getAttribute(NODE_SeqNo)); final String entityType = element.getAttribute(NODE_EntityType); final String releaseNo = element.getAttribute(NODE_ReleaseNo); final boolean deferrConstraints = Boolean.valueOf(element.getAttribute(NODE_IsDeferredConstraints)); // // Check if there is an old migration final Properties ctx = InterfaceWrapperHelper.getCtx(migration); final String trxName = InterfaceWrapperHelper.getTrxName(migration); if (Services.get(IMigrationDAO.class).existsMigration(ctx, name, seqNo, entityType, trxName)) { logger.info("Migration already imported [IGNORE]"); return false; } migration.setName(name); migration.setSeqNo(seqNo); migration.setEntityType(entityType); migration.setReleaseNo(releaseNo); migration.setIsDeferredConstraints(deferrConstraints); // Comment final Node commentNode = element.getElementsByTagName(NODE_Comments).item(0); if (commentNode != null) { migration.setComments(getElementText(commentNode)); } InterfaceWrapperHelper.save(migration); final NodeList children = element.getElementsByTagName(NODE_Step); for (int i = 0; i < children.getLength(); i++) { final Element stepNode = (Element)children.item(i); if (NODE_Step.equals(stepNode.getTagName()))
{ final I_AD_MigrationStep step = InterfaceWrapperHelper.create(ctx, I_AD_MigrationStep.class, trxName); step.setAD_Migration_ID(migration.getAD_Migration_ID()); Services.get(IXMLHandlerFactory.class) .getHandler(I_AD_MigrationStep.class) .fromXmlNode(step, stepNode); InterfaceWrapperHelper.save(step); } } Services.get(IMigrationBL.class).updateStatus(migration); logger.info("Imported migration: " + Services.get(IMigrationBL.class).getSummary(migration)); return true; } // thx to http://www.java2s.com/Code/Java/XML/DOMUtilgetElementText.htm static String getElementText(final Node element) { final StringBuffer buf = new StringBuffer(); final NodeList list = element.getChildNodes(); boolean found = false; for (int i = 0; i < list.getLength(); i++) { final Node node = list.item(i); if (node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); found = true; } } return found ? buf.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\impl\MigrationHandler.java
1
请完成以下Java代码
public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID) { if (M_HU_QRCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID); } @Override public int getM_HU_QRCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID); } @Override public void setRenderedQRCode (final String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); }
@Override public String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } @Override public void setUniqueId (final String UniqueId) { set_ValueNoCheck (COLUMNNAME_UniqueId, UniqueId); } @Override public String getUniqueId() { return get_ValueAsString(COLUMNNAME_UniqueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode.java
1
请完成以下Java代码
public class PP_Order_SetC_OrderLine extends JavaProcess implements IProcessPrecondition { // services private final IDocumentBL docActionBL = Services.get(IDocumentBL.class); private final IPPOrderBL ppOrderBL = Services.get(IPPOrderBL.class); private final IPPOrderDAO ppOrdersRepo= Services.get(IPPOrderDAO.class); @Param(parameterName = I_C_OrderLine.COLUMNNAME_C_OrderLine_ID, mandatory = true) private int p_C_OrderLine_ID; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.reject(); } final I_PP_Order ppOrder = ppOrderBL.getById(getPPOrderId(context.getSingleSelectedRecordId())); return ProcessPreconditionsResolution.acceptIf(isEligible(ppOrder)); } private static boolean isEligible(@Nullable final I_PP_Order ppOrder) { if (ppOrder == null) { return false; } final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus()); return docStatus.isDraftedOrInProgress(); }
@Override protected String doIt() { final PPOrderId ppOrderId = getPPOrderId(getRecord_ID()); final OrderLineId orderLineId = getOrderLienId(); setC_OrderLine_ID(ppOrderId, orderLineId); return MSG_OK; } private PPOrderId getPPOrderId(int ppOrderId) { return PPOrderId.ofRepoId(ppOrderId); } private OrderLineId getOrderLienId() { return OrderLineId.ofRepoId(p_C_OrderLine_ID); } private void setC_OrderLine_ID(@NonNull final PPOrderId ppOrderId, @NonNull final OrderLineId orderLineId) { ppOrderBL.setC_OrderLine(ppOrderId, orderLineId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_SetC_OrderLine.java
1
请完成以下Java代码
private static class CopyPasteAction extends AbstractAction { private static final Action getCreateAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType) { Action action = copyPasteSupport.getCopyPasteAction(actionType); if (action == null) { action = new CopyPasteAction(copyPasteSupport, actionType); } copyPasteSupport.putCopyPasteAction(actionType, action, actionType.getKeyStroke()); return action; } private static final long serialVersionUID = 1L; private final ICopyPasteSupportEditor copyPasteSupport; private final CopyPasteActionType actionType;
public CopyPasteAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType) { super(); this.copyPasteSupport = copyPasteSupport; this.actionType = actionType; } @Override public void actionPerformed(final ActionEvent e) { copyPasteSupport.executeCopyPasteAction(actionType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookupCopyPasteSupportEditor.java
1
请完成以下Java代码
protected static List<FlowNode> gatherAllFlowNodes(BpmnModel bpmnModel) { List<FlowNode> flowNodes = new ArrayList<FlowNode>(); for (Process process : bpmnModel.getProcesses()) { flowNodes.addAll(gatherAllFlowNodes(process)); } return flowNodes; } protected static List<FlowNode> gatherAllFlowNodes(FlowElementsContainer flowElementsContainer) { List<FlowNode> flowNodes = new ArrayList<FlowNode>(); for (FlowElement flowElement : flowElementsContainer.getFlowElements()) { if (flowElement instanceof FlowNode) { flowNodes.add((FlowNode) flowElement); } if (flowElement instanceof FlowElementsContainer) { flowNodes.addAll(gatherAllFlowNodes((FlowElementsContainer) flowElement)); } } return flowNodes; } public Map<Class<? extends BaseElement>, ActivityDrawInstruction> getActivityDrawInstructions() { return activityDrawInstructions; } public void setActivityDrawInstructions( Map<Class<? extends BaseElement>, ActivityDrawInstruction> activityDrawInstructions ) { this.activityDrawInstructions = activityDrawInstructions; } public Map<Class<? extends BaseElement>, ArtifactDrawInstruction> getArtifactDrawInstructions() {
return artifactDrawInstructions; } public void setArtifactDrawInstructions( Map<Class<? extends BaseElement>, ArtifactDrawInstruction> artifactDrawInstructions ) { this.artifactDrawInstructions = artifactDrawInstructions; } protected interface ActivityDrawInstruction { void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode); } protected interface ArtifactDrawInstruction { void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact); } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\DefaultProcessDiagramGenerator.java
1
请完成以下Java代码
public class KafkaTbQueueMsg implements TbQueueMsg { private static final int UUID_LENGTH = 36; private final UUID key; private final TbQueueMsgHeaders headers; private final byte[] data; public KafkaTbQueueMsg(ConsumerRecord<String, byte[]> record) { if (record.key().length() <= UUID_LENGTH) { this.key = UUID.fromString(record.key()); } else { this.key = UUID.randomUUID(); } TbQueueMsgHeaders headers = new DefaultTbQueueMsgHeaders(); record.headers().forEach(header -> { headers.put(header.key(), header.value()); }); this.headers = headers;
this.data = record.value(); } @Override public UUID getKey() { return key; } @Override public TbQueueMsgHeaders getHeaders() { return headers; } @Override public byte[] getData() { return data; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\KafkaTbQueueMsg.java
1
请完成以下Java代码
public class JSONStickyDocumentFilter { private final String id; private final String caption; public static final List<JSONStickyDocumentFilter> ofStickyFiltersList(final DocumentFilterList filters, final String adLanguage) { if (filters == null || filters.isEmpty()) { return ImmutableList.of(); } return filters.stream() .map(filter -> ofStickyFilterOrNull(filter, adLanguage)) .filter(filter -> filter != null) .collect(GuavaCollectors.toImmutableList()); } private static final JSONStickyDocumentFilter ofStickyFilterOrNull(final DocumentFilter filter, final String adLanguage) {
// Don't expose the sticky filter if it does not have a caption, // because usually that's an internal filter. // (see https://github.com/metasfresh/metasfresh-webui-api/issues/481) final String caption = filter.getCaption(adLanguage); if(Check.isEmpty(caption, true)) { return null; } final String filterId = filter.getFilterId(); return new JSONStickyDocumentFilter(filterId, caption); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\json\JSONStickyDocumentFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void fetchAuthorReadOnlyMode() { Author author = authorRepository.findFirstByGenre("Anthology"); displayInformation("After Fetch", author); author.setAge(40); displayInformation("After Update Entity", author); // force flush - triggering manual flush is a code smell and should be avoided // be default, because we set readOnly=true, flush mode is MANUAL, // therefore no flush will take place authorRepository.flush(); displayInformation("After Flush", author); } @Transactional public void fetchAuthorDtoReadWriteMode() { AuthorDto authorDto = authorRepository.findTopByGenre("Anthology"); System.out.println("Author DTO: " + authorDto.getName() + ", " + authorDto.getAge()); org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext(); System.out.println("No of managed entities : " + persistenceContext.getNumberOfManagedEntities()); } @Transactional(readOnly = true) public void fetchAuthorDtoReadOnlyMode() { AuthorDto authorDto = authorRepository.findTopByGenre("Anthology"); System.out.println("Author DTO: " + authorDto.getName() + ", " + authorDto.getAge()); org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext(); System.out.println("No of managed entities : " + persistenceContext.getNumberOfManagedEntities()); } private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() { SharedSessionContractImplementor sharedSession = entityManager.unwrap( SharedSessionContractImplementor.class ); return sharedSession.getPersistenceContext(); }
private void displayInformation(String phase, Author author) { System.out.println("\n-------------------------------------"); System.out.println("Phase:" + phase); System.out.println("Entity: " + author); System.out.println("-------------------------------------"); org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext(); System.out.println("Has only non read entities : " + persistenceContext.hasNonReadOnlyEntities()); EntityEntry entityEntry = persistenceContext.getEntry(author); Object[] loadedState = entityEntry.getLoadedState(); Status status = entityEntry.getStatus(); System.out.println("Entity entry : " + entityEntry); System.out.println("Status:" + status); System.out.println("Loaded state: " + Arrays.toString(loadedState)); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalReadOnlyMeaning\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public void setMarks(int marks) { this.marks = marks; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StudentClassic that = (StudentClassic) o;
return rollNo == that.rollNo && marks == that.marks && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name, rollNo, marks); } @Override public String toString() { return "StudentClassic{" + "name='" + name + '\'' + ", rollNo=" + rollNo + ", marks=" + marks + '}'; } }
repos\tutorials-master\core-java-modules\core-java-14\src\main\java\com\baeldung\java14\recordscustomconstructors\StudentClassic.java
1
请在Spring Boot框架中完成以下Java代码
public String getPACKAGINGUNITCODE() { return packagingunitcode; } /** * Sets the value of the packagingunitcode property. * * @param value * allowed object is * {@link String } * */ public void setPACKAGINGUNITCODE(String value) { this.packagingunitcode = value; } /** * Gets the value of the pmesu1 property. * * @return * possible object is * {@link PMESU1 } * */ public PMESU1 getPMESU1() { return pmesu1; } /** * Sets the value of the pmesu1 property. * * @param value * allowed object is * {@link PMESU1 } * */ public void setPMESU1(PMESU1 value) { this.pmesu1 = value; } /** * Gets the value of the phand1 property. * * @return * possible object is * {@link PHAND1 } * */ public PHAND1 getPHAND1() { return phand1;
} /** * Sets the value of the phand1 property. * * @param value * allowed object is * {@link PHAND1 } * */ public void setPHAND1(PHAND1 value) { this.phand1 = value; } /** * Gets the value of the detail property. * * @return * possible object is * {@link DETAILXbest } * */ public DETAILXbest getDETAIL() { return detail; } /** * Sets the value of the detail property. * * @param value * allowed object is * {@link DETAILXbest } * */ public void setDETAIL(DETAILXbest value) { this.detail = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\PPACK1.java
2
请完成以下Java代码
public void onReleaseSavepoint(final ITrx trx, final ITrxSavepoint savepoint) { getSavepointsForTrxName(trx.getTrxName()).remove(savepoint); } private static ITrxConstraints getConstraints() { return Services.get(ITrxConstraintsBL.class).getConstraints(); } private Collection<String> getTrxNamesForCurrentThread() { return getTrxNamesForThreadId(Thread.currentThread().getId()); } private Collection<String> getTrxNamesForThreadId(final long threadId) { synchronized (threadId2TrxName) { Collection<String> trxNames = threadId2TrxName.get(threadId); if (trxNames == null) { trxNames = new HashSet<String>(); threadId2TrxName.put(threadId, trxNames); } return trxNames; } } private Collection<ITrxSavepoint> getSavepointsForTrxName(final String trxName) { synchronized (trxName2SavePoint) { Collection<ITrxSavepoint> savepoints = trxName2SavePoint.get(trxName); if (savepoints == null) { savepoints = new HashSet<ITrxSavepoint>(); trxName2SavePoint.put(trxName, savepoints); } return savepoints; } } private String mkStacktraceInfo(final Thread thread, final String beginStacktrace) { final StringBuilder msgSB = new StringBuilder();
msgSB.append(">>> Stacktrace at trx creation, commit or rollback:\n"); msgSB.append(beginStacktrace); msgSB.append(">>> Current stacktrace of the creating thread:\n"); if (thread.isAlive()) { msgSB.append(mkStacktrace(thread)); } else { msgSB.append("\t(Thread already finished)\n"); } final String msg = msgSB.toString(); return msg; } @Override public String getCreationStackTrace(final String trxName) { return trxName2Stacktrace.get(trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\OpenTrxBL.java
1
请完成以下Java代码
public List<I_C_ReferenceNo> retrieveReferenceNos(final Object model, final I_C_ReferenceNo_Type type) { // get all I_C_ReferenceNo_Docs that references 'model' final List<I_C_ReferenceNo_Doc> docs = lookupMap.getRecords(I_C_ReferenceNo_Doc.class, new IPOJOFilter<I_C_ReferenceNo_Doc>() { @Override public boolean accept(I_C_ReferenceNo_Doc pojo) { return pojo.getRecord_ID() == InterfaceWrapperHelper.getId(model) && pojo.getAD_Table_ID() == MTable.getTable_ID(InterfaceWrapperHelper.getModelTableName(model)); } }); // add the C_ReferenceNos into a set to avoid duplicates final Set<I_C_ReferenceNo> refNos = new HashSet<>(); for (final I_C_ReferenceNo_Doc doc : docs) { final I_C_ReferenceNo referenceNo = doc.getC_ReferenceNo(); if (referenceNo.getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID()) { refNos.add(referenceNo); } }
return new ArrayList<>(refNos); } @Override protected List<I_C_ReferenceNo_Doc> retrieveRefNoDocByRefNoAndTableName(final I_C_ReferenceNo referenceNo, final String tableName) { return lookupMap.getRecords(I_C_ReferenceNo_Doc.class, new IPOJOFilter<I_C_ReferenceNo_Doc>() { @Override public boolean accept(I_C_ReferenceNo_Doc pojo) { return pojo.getC_ReferenceNo_ID() == referenceNo.getC_ReferenceNo_ID() && pojo.getAD_Table_ID() == MTable.getTable_ID(tableName); } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\PlainReferenceNoDAO.java
1
请完成以下Java代码
public class AppDictValidator extends JavaProcess { @Override protected void prepare() { return; } @Override protected String doIt() throws Exception { final IADValidatorRegistryBL validatorRegistry = Services.get(IADValidatorRegistryBL.class); final List<Class<?>> registeredClasses = validatorRegistry.getRegisteredClasses(); for (final Class<?> registeredClass : registeredClasses) { final IADValidatorResult errorLog = validatorRegistry.validate(getCtx(), registeredClass);
logAllExceptions(errorLog, validatorRegistry.getValidator(registeredClass)); } return "OK"; } private void logAllExceptions(final IADValidatorResult errorLog, final IADValidator<?> validator) { for (final IADValidatorViolation violation : errorLog.getViolations()) { addLog(validator.getLogMessage(violation)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\process\AppDictValidator.java
1
请完成以下Java代码
public List<Map<String, Object>> getProps() { return props; } public void setProps(List<Map<String, Object>> props) { this.props = props; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public static class User { private String username; private String password; private List<String> roles; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() {
return password; } public void setPassword(String password) { this.password = password; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yamllist\pojo\ApplicationProps.java
1
请完成以下Java代码
public List<Word> toSimpleWordList() { List<Word> wordList = new LinkedList<Word>(); for (IWord word : this.wordList) { if (word instanceof CompoundWord) { wordList.addAll(((CompoundWord) word).innerList); } else { wordList.add((Word) word); } } return wordList; } /** * 获取所有单词构成的数组 * * @return */ public String[] toWordArray() { List<Word> wordList = toSimpleWordList(); String[] wordArray = new String[wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < wordArray.length; i++) { wordArray[i] = iterator.next().value; } return wordArray; } /** * word pos * * @return */ public String[][] toWordTagArray() { List<Word> wordList = toSimpleWordList(); String[][] pair = new String[2][wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < pair[0].length; i++) { Word word = iterator.next(); pair[0][i] = word.value; pair[1][i] = word.label; } return pair; } /** * word pos ner * * @param tagSet
* @return */ public String[][] toWordTagNerArray(NERTagSet tagSet) { List<String[]> tupleList = Utility.convertSentenceToNER(this, tagSet); String[][] result = new String[3][tupleList.size()]; Iterator<String[]> iterator = tupleList.iterator(); for (int i = 0; i < result[0].length; i++) { String[] tuple = iterator.next(); for (int j = 0; j < 3; ++j) { result[j][i] = tuple[j]; } } return result; } public Sentence mergeCompoundWords() { ListIterator<IWord> listIterator = wordList.listIterator(); while (listIterator.hasNext()) { IWord word = listIterator.next(); if (word instanceof CompoundWord) { listIterator.set(new Word(word.getValue(), word.getLabel())); } } return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sentence sentence = (Sentence) o; return toString().equals(sentence.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\Sentence.java
1
请完成以下Java代码
public boolean isStartEvent() { return isStartEvent; } public void setStartEvent(boolean isStartEvent) { this.isStartEvent = isStartEvent; } public String getEventType() { return eventType; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public EventSubscriptionEntity prepareEventSubscriptionEntity(ExecutionEntity execution) { EventSubscriptionEntity eventSubscriptionEntity = null; if ("message".equals(eventType)) { eventSubscriptionEntity = new MessageEventSubscriptionEntity(execution); } else if ("signal".equals(eventType)) { eventSubscriptionEntity = new SignalEventSubscriptionEntity(execution);
} else { throw new ActivitiIllegalArgumentException("Found event definition of unknown type: " + eventType); } eventSubscriptionEntity.setEventName(eventName); if (activityId != null) { ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId); eventSubscriptionEntity.setActivity(activity); } if (configuration != null) { eventSubscriptionEntity.setConfiguration(configuration); } return eventSubscriptionEntity; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java
1
请完成以下Java代码
private PreparedStatement getLatestStmt() { if (latestInsertStmt == null) { latestInsertStmt = prepare(INSERT_INTO + ModelConstants.TS_KV_LATEST_CF + "(" + ModelConstants.ENTITY_TYPE_COLUMN + "," + ModelConstants.ENTITY_ID_COLUMN + "," + ModelConstants.KEY_COLUMN + "," + ModelConstants.TS_COLUMN + "," + ModelConstants.BOOLEAN_VALUE_COLUMN + "," + ModelConstants.STRING_VALUE_COLUMN + "," + ModelConstants.LONG_VALUE_COLUMN + "," + ModelConstants.DOUBLE_VALUE_COLUMN + "," + ModelConstants.JSON_VALUE_COLUMN + ")" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"); } return latestInsertStmt; } private PreparedStatement getFindLatestStmt() { if (findLatestStmt == null) { findLatestStmt = prepare(SELECT_PREFIX + ModelConstants.KEY_COLUMN + "," + ModelConstants.TS_COLUMN + "," + ModelConstants.STRING_VALUE_COLUMN + "," + ModelConstants.BOOLEAN_VALUE_COLUMN + "," + ModelConstants.LONG_VALUE_COLUMN + "," + ModelConstants.DOUBLE_VALUE_COLUMN + "," + ModelConstants.JSON_VALUE_COLUMN + " " + "FROM " + ModelConstants.TS_KV_LATEST_CF + " " + "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.ENTITY_ID_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.KEY_COLUMN + EQUALS_PARAM); }
return findLatestStmt; } private PreparedStatement getFindAllLatestStmt() { if (findAllLatestStmt == null) { findAllLatestStmt = prepare(SELECT_PREFIX + ModelConstants.KEY_COLUMN + "," + ModelConstants.TS_COLUMN + "," + ModelConstants.STRING_VALUE_COLUMN + "," + ModelConstants.BOOLEAN_VALUE_COLUMN + "," + ModelConstants.LONG_VALUE_COLUMN + "," + ModelConstants.DOUBLE_VALUE_COLUMN + "," + ModelConstants.JSON_VALUE_COLUMN + " " + "FROM " + ModelConstants.TS_KV_LATEST_CF + " " + "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + EQUALS_PARAM + "AND " + ModelConstants.ENTITY_ID_COLUMN + EQUALS_PARAM); } return findAllLatestStmt; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\CassandraBaseTimeseriesLatestDao.java
1
请完成以下Java代码
public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public org.compiere.model.I_S_Resource getPP_Plant() { return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class); } @Override public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant) { set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant); } @Override public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); }
@Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请完成以下Java代码
private Optional<ShipperId> getDropShipAddressShipperId(final I_C_Order orderRecord) { if (orderRecord.getDropShip_BPartner_ID() <= 0 || orderRecord.getDropShip_Location_ID() <= 0) { return Optional.empty(); } final Optional<ShipperId> dropShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getDropShip_BPartner_ID(), orderRecord.getDropShip_Location_ID())); return Optional.ofNullable(dropShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getDropShip_BPartner_ID())))); } private ShipperId getDeliveryAddressShipperId(final I_C_Order orderRecord) { final Optional<ShipperId> deliveryShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getC_BPartner_ID(), orderRecord.getC_BPartner_Location_ID())); return deliveryShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID()))); } private ShipperId getPartnerShipperId(@NonNull final BPartnerId partnerId) { return partnerDAO.getShipperId(partnerId); } @Override public PaymentTermId getPaymentTermId(@NonNull final I_C_Order orderRecord) { return PaymentTermId.ofRepoId(orderRecord.getC_PaymentTerm_ID()); }
@Override public Money getGrandTotal(@NonNull final I_C_Order order) { final BigDecimal grandTotal = order.getGrandTotal(); return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID())); } @Override public void save(final I_C_Order order) { orderDAO.save(order); } @Override public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder) { final I_C_Order order = getById(orderId); order.setBLDate(transportOrder.getBLDate()); order.setETA(transportOrder.getETA()); save(order); } @Override public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice) { final I_C_Order order = getById(orderId); order.setInvoiceDate(invoice.getDateInvoiced()); save(order); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return orderDAO.getByQueryFilter(queryFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java
1
请完成以下Java代码
public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("caseDefinitionId", caseDefinitionId); persistentState.put("businessKey", businessKey); persistentState.put("activityId", activityId); persistentState.put("parentId", parentId); persistentState.put("currentState", currentState); persistentState.put("previousState", previousState); persistentState.put("superExecutionId", superExecutionId); return persistentState; } public CmmnModelInstance getCmmnModelInstance() { if(caseDefinitionId != null) { return Context.getProcessEngineConfiguration() .getDeploymentCache() .findCmmnModelInstanceForCaseDefinition(caseDefinitionId); } else { return null; } } public CmmnElement getCmmnModelElementInstance() { CmmnModelInstance cmmnModelInstance = getCmmnModelInstance(); if(cmmnModelInstance != null) { ModelElementInstance modelElementInstance = cmmnModelInstance.getModelElementById(activityId); try { return (CmmnElement) modelElementInstance; } catch(ClassCastException e) { ModelElementType elementType = modelElementInstance.getElementType(); throw new ProcessEngineException("Cannot cast "+modelElementInstance+" to CmmnElement. " + "Is of type "+elementType.getTypeName() + " Namespace " + elementType.getTypeNamespace(), e); } } else { return null;
} } public ProcessEngineServices getProcessEngineServices() { return Context .getProcessEngineConfiguration() .getProcessEngine(); } public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public String getCaseDefinitionTenantId() { CaseDefinitionEntity caseDefinition = (CaseDefinitionEntity) getCaseDefinition(); return caseDefinition.getTenantId(); } public <T extends CoreExecution> void performOperation(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionEntity.java
1
请完成以下Java代码
public String getVersion() { return this.version; } } /** * Information about the Java Virtual Machine the application is running in. */ public static class JavaVirtualMachineInfo { private final String name; private final String vendor; private final String version; public JavaVirtualMachineInfo() { this.name = System.getProperty("java.vm.name"); this.vendor = System.getProperty("java.vm.vendor"); this.version = System.getProperty("java.vm.version"); }
public String getName() { return this.name; } public String getVendor() { return this.vendor; } public String getVersion() { return this.version; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\JavaInfo.java
1
请完成以下Java代码
public void init() { cacheThreadPool = threadPool; cacheRpNotifyService = rpNotifyService; cacheNotifyQueue = notifyQueue; cacheNotifyPersist = notifyPersist; startInitFromDB(); startThread(); } private static void startThread() { LOG.info("startThread"); cacheThreadPool.execute(new Runnable() { public void run() { try { while (true) { Thread.sleep(50);//50毫秒执行一次 // 如果当前活动线程等于最大线程,那么不执行 if (cacheThreadPool.getActiveCount() < cacheThreadPool.getMaxPoolSize()) { final NotifyTask task = tasks.poll(); if (task != null) { cacheThreadPool.execute(new Runnable() { public void run() { LOG.info(cacheThreadPool.getActiveCount() + "---------"); tasks.remove(task); task.run(); } }); } } } } catch (Exception e) { LOG.error("系统异常", e); e.printStackTrace(); } } }); } /** * 从数据库中取一次数据用来当系统启动时初始化 */ @SuppressWarnings("unchecked") private static void startInitFromDB() {
LOG.info("get data from database"); int pageNum = 1; int numPerPage = 500; PageParam pageParam = new PageParam(pageNum, numPerPage); // 查询状态和通知次数符合以下条件的数据进行通知 String[] status = new String[]{"101", "102", "200", "201"}; Integer[] notifyTime = new Integer[]{0, 1, 2, 3, 4}; // 组装查询条件 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("statusList", status); paramMap.put("notifyTimeList", notifyTime); PageBean<RpNotifyRecord> pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); int totalSize = (pager.getNumPerPage() - 1) / numPerPage + 1;//总页数 while (pageNum <= totalSize) { List<RpNotifyRecord> list = pager.getRecordList(); for (int i = 0; i < list.size(); i++) { RpNotifyRecord notifyRecord = list.get(i); notifyRecord.setLastNotifyTime(new Date()); cacheNotifyQueue.addElementToList(notifyRecord); } pageNum++; LOG.info(String.format("调用通知服务.rpNotifyService.queryNotifyRecordListPage(%s, %s, %s)", pageNum, numPerPage, paramMap)); pageParam = new PageParam(pageNum, numPerPage); pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); } } }
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\AppNotifyApplication.java
1
请完成以下Java代码
public static String buildUsername(String host, String deviceId) { return String.format(USERNAME_FORMAT, host, deviceId); } public static String buildSasToken(String host, String sasKey, Clock clock) { try { final String targetUri = URLEncoder.encode(host.toLowerCase(), StandardCharsets.UTF_8); final long expiryTime = buildExpiresOn(clock); String toSign = targetUri + "\n" + expiryTime; byte[] keyBytes = Base64.getDecoder().decode(sasKey.getBytes(StandardCharsets.UTF_8)); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(toSign.getBytes(StandardCharsets.UTF_8)); String signature = URLEncoder.encode(Base64.getEncoder().encodeToString(rawHmac), StandardCharsets.UTF_8); return String.format(SAS_TOKEN_FORMAT, targetUri, signature, expiryTime); } catch (Exception e) { throw new RuntimeException("Failed to build SAS token!", e); } } private static long buildExpiresOn(Clock clock) { return clock.instant().plusSeconds(SAS_TOKEN_VALID_SECS).getEpochSecond(); } public static String getDefaultCaCert() { byte[] fileBytes; if (Files.exists(FULL_FILE_PATH)) { try { fileBytes = Files.readAllBytes(FULL_FILE_PATH); } catch (IOException e) { log.error("Failed to load Default CaCert file!!! [{}]", FULL_FILE_PATH, e); throw new RuntimeException("Failed to load Default CaCert file!!!"); } } else {
Path azureDirectory = FULL_FILE_PATH.getParent(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(azureDirectory)) { Iterator<Path> iterator = stream.iterator(); if (iterator.hasNext()) { Path firstFile = iterator.next(); fileBytes = Files.readAllBytes(firstFile); } else { log.error("Default CaCert file not found in the directory [{}]!!!", azureDirectory); throw new RuntimeException("Default CaCert file not found in the directory!!!"); } } catch (IOException e) { log.error("Failed to load Default CaCert file from the directory [{}]!!!", azureDirectory, e); throw new RuntimeException("Failed to load Default CaCert file from the directory!!!"); } } return new String(fileBytes); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\AzureIotHubUtil.java
1
请完成以下Java代码
final T getAttribute(Method method, @Nullable Class<?> targetClass) { MethodClassKey cacheKey = new MethodClassKey(method, targetClass); return this.cachedAttributes.computeIfAbsent(cacheKey, (k) -> resolveAttribute(method, targetClass)); } /** * Returns the {@link MethodSecurityExpressionHandler}. * @return the {@link MethodSecurityExpressionHandler} to use */ MethodSecurityExpressionHandler getExpressionHandler() { return this.expressionHandler; } void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) { Assert.notNull(expressionHandler, "expressionHandler cannot be null"); this.expressionHandler = expressionHandler; }
abstract void setTemplateDefaults(AnnotationTemplateExpressionDefaults adapter); /** * Subclasses should implement this method to provide the non-null * {@link ExpressionAttribute} for the method and the target class. * @param method the method * @param targetClass the target class * @return {@link ExpressionAttribute} or null if not found. */ abstract @Nullable T resolveAttribute(Method method, @Nullable Class<?> targetClass); Class<?> targetClass(Method method, @Nullable Class<?> targetClass) { return (targetClass != null) ? targetClass : method.getDeclaringClass(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AbstractExpressionAttributeRegistry.java
1
请完成以下Java代码
public java.lang.String getPackVerificationMessage () { return (java.lang.String)get_Value(COLUMNNAME_PackVerificationMessage); } /** Set Produktcode. @param ProductCode Produktcode */ @Override public void setProductCode (java.lang.String ProductCode) { set_ValueNoCheck (COLUMNNAME_ProductCode, ProductCode); } /** Get Produktcode. @return Produktcode */ @Override public java.lang.String getProductCode () { return (java.lang.String)get_Value(COLUMNNAME_ProductCode); } /** Set Kodierungskennzeichen. @param ProductCodeType Kodierungskennzeichen */ @Override public void setProductCodeType (java.lang.String ProductCodeType) { set_ValueNoCheck (COLUMNNAME_ProductCodeType, ProductCodeType); } /** Get Kodierungskennzeichen. @return Kodierungskennzeichen */ @Override public java.lang.String getProductCodeType () { return (java.lang.String)get_Value(COLUMNNAME_ProductCodeType); }
/** * SerialNumber AD_Reference_ID=110 * Reference name: AD_User */ public static final int SERIALNUMBER_AD_Reference_ID=110; /** Set Seriennummer. @param SerialNumber Seriennummer */ @Override public void setSerialNumber (java.lang.String SerialNumber) { set_ValueNoCheck (COLUMNNAME_SerialNumber, SerialNumber); } /** Get Seriennummer. @return Seriennummer */ @Override public java.lang.String getSerialNumber () { return (java.lang.String)get_Value(COLUMNNAME_SerialNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Productdata_Result.java
1
请完成以下Java代码
public class JakartaTransactionContext extends AbstractTransactionContext { protected final TransactionManager transactionManager; public JakartaTransactionContext(TransactionManager transactionManager) { this.transactionManager = transactionManager; } @Override protected void doRollback() throws Exception { // managed transaction, mark rollback-only if not done so already Transaction transaction = getTransaction(); int status = transaction.getStatus(); if (status != Status.STATUS_NO_TRANSACTION && status != Status.STATUS_ROLLEDBACK) { transaction.setRollbackOnly(); } } @Override protected void addTransactionListener(TransactionState transactionState, final TransactionListener transactionListener, CommandContext commandContext) throws Exception{ getTransaction().registerSynchronization(new JtaTransactionStateSynchronization(transactionState, transactionListener, commandContext)); } protected Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch (Exception e) {
throw LOG.exceptionWhileInteractingWithTransaction("getting transaction", e); } } @Override protected boolean isTransactionActiveInternal() throws Exception { return transactionManager.getStatus() != Status.STATUS_MARKED_ROLLBACK && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION; } public static class JtaTransactionStateSynchronization extends TransactionStateSynchronization implements Synchronization { public JtaTransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) { super(transactionState, transactionListener, commandContext); } @Override protected boolean isRolledBack(int status) { return Status.STATUS_ROLLEDBACK == status; } @Override protected boolean isCommitted(int status) { return Status.STATUS_COMMITTED == status; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\JakartaTransactionContext.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getStep() { return this.step; } public void setStep(Duration step) { this.step = step; } public TimeUnit getRateUnits() { return this.rateUnits; } public void setRateUnits(TimeUnit rateUnits) { this.rateUnits = rateUnits; } public TimeUnit getDurationUnits() { return this.durationUnits; } public void setDurationUnits(TimeUnit durationUnits) { this.durationUnits = durationUnits; } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; }
public GraphiteProtocol getProtocol() { return this.protocol; } public void setProtocol(GraphiteProtocol protocol) { this.protocol = protocol; } public Boolean getGraphiteTagsEnabled() { return (this.graphiteTagsEnabled != null) ? this.graphiteTagsEnabled : ObjectUtils.isEmpty(this.tagsAsPrefix); } public void setGraphiteTagsEnabled(Boolean graphiteTagsEnabled) { this.graphiteTagsEnabled = graphiteTagsEnabled; } public String[] getTagsAsPrefix() { return this.tagsAsPrefix; } public void setTagsAsPrefix(String[] tagsAsPrefix) { this.tagsAsPrefix = tagsAsPrefix; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphiteProperties.java
2
请完成以下Java代码
default boolean isValueUpdatedBefore(final I_M_Attribute attribute) { final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue()); return isValueUpdatedBefore(attributeCode); } /** * @param attribute * @return last propagator used for propagating given attribute */ IHUAttributePropagator getLastPropagatorOrNull(@NonNull AttributeCode attributeCode); default IHUAttributePropagator getLastPropagatorOrNull(final I_M_Attribute attribute) { final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue()); return getLastPropagatorOrNull(attributeCode); }
/** * Create a clone of a context with it's <code>parent=this</code>, given propagator, and with <code>updateStorageValue=true</code> * * @param propagatorToUse * @return propagationContext which was cloned */ IHUAttributePropagationContext cloneForPropagation(IAttributeStorage attributeStorage, I_M_Attribute attribute, IHUAttributePropagator propagatorToUse); /** * @return true if this context (for changing an attribute value) was created from outside of this attribute storages hierarchy (i.e. User Input, Attribute Transfer etc) */ boolean isExternalInput(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\IHUAttributePropagationContext.java
1
请完成以下Java代码
public static void addOrMerge(Map<String, Object> source, MutablePropertySources sources) { if (!CollectionUtils.isEmpty(source)) { Map<String, Object> resultingSource = new HashMap<>(); DefaultPropertiesPropertySource propertySource = new DefaultPropertiesPropertySource(resultingSource); if (sources.contains(NAME)) { mergeIfPossible(source, sources, resultingSource); sources.replace(NAME, propertySource); } else { resultingSource.putAll(source); sources.addLast(propertySource); } } } @SuppressWarnings("unchecked") private static void mergeIfPossible(Map<String, Object> source, MutablePropertySources sources, Map<String, Object> resultingSource) { PropertySource<?> existingSource = sources.get(NAME); if (existingSource != null) { Object underlyingSource = existingSource.getSource(); if (underlyingSource instanceof Map) { resultingSource.putAll((Map<String, Object>) underlyingSource); } resultingSource.putAll(source);
} } /** * Move the 'defaultProperties' property source so that it's the last source in the * given {@link ConfigurableEnvironment}. * @param environment the environment to update */ public static void moveToEnd(ConfigurableEnvironment environment) { moveToEnd(environment.getPropertySources()); } /** * Move the 'defaultProperties' property source so that it's the last source in the * given {@link MutablePropertySources}. * @param propertySources the property sources to update */ public static void moveToEnd(MutablePropertySources propertySources) { PropertySource<?> propertySource = propertySources.remove(NAME); if (propertySource != null) { propertySources.addLast(propertySource); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\DefaultPropertiesPropertySource.java
1
请完成以下Java代码
public int getM_CustomsTariff_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CustomsTariff_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () {
return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CustomsTariff.java
1
请完成以下Java代码
public List<MilestoneInstance> findMilestoneInstancesByQueryCriteria(MilestoneInstanceQueryImpl query) { return getDbSqlSession().selectList("selectMilestoneInstancesByQueryCriteria", query, getManagedEntityClass()); } @Override public long findMilestoneInstancesCountByQueryCriteria(MilestoneInstanceQueryImpl query) { return (Long) getDbSqlSession().selectOne("selectMilestoneInstanceCountByQueryCriteria", query); } @Override public void deleteByCaseDefinitionId(String caseDefinitionId) { getDbSqlSession().delete("deleteMilestoneInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass()); } @Override
public void deleteByCaseInstanceId(String caseInstanceId) { bulkDelete("deleteMilestoneInstanceByCaseInstanceId", milestoneInstanceByCaseInstanceIdCachedEntityMatcher, caseInstanceId); } public static class MilestoneInstanceByCaseInstanceIdCachedEntityMatcher extends CachedEntityMatcherAdapter<MilestoneInstanceEntity> { @Override public boolean isRetained(MilestoneInstanceEntity entity, Object param) { String caseInstanceId = (String) param; return caseInstanceId.equals(entity.getCaseInstanceId()); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisMilestoneInstanceDataManager.java
1
请完成以下Java代码
public class UpdateApiReqVo { private Long id; private String app; private List<ApiPredicateItemVo> predicateItems; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getApp() {
return app; } public void setApp(String app) { this.app = app; } public List<ApiPredicateItemVo> getPredicateItems() { return predicateItems; } public void setPredicateItems(List<ApiPredicateItemVo> predicateItems) { this.predicateItems = predicateItems; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\api\UpdateApiReqVo.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return bpartnerId; } @Override public void setC_BPartner_ID(final int bpartnerId) { this.bpartnerId = bpartnerId <= 0 ? -1 : bpartnerId; } @Override public void setPriceListVersionId(final @Nullable PriceListVersionId priceListVersionId) { this.priceListVersionId = priceListVersionId; } @Nullable @Override public PriceListVersionId getPriceListVersionId() { return priceListVersionId; } @Override public void setDate(final ZonedDateTime date) { this.date = date; } @Override public ZonedDateTime getDate() { return date; } @Override public boolean isAllowAnyProduct() { return allowAnyProduct; } @Override public void setAllowAnyProduct(final boolean allowAnyProduct) { this.allowAnyProduct = allowAnyProduct; } @Override public String getHU_UnitType() { return huUnitType; } @Override public void setHU_UnitType(final String huUnitType) { this.huUnitType = huUnitType; } @Override public boolean isAllowVirtualPI() { return allowVirtualPI; } @Override public void setAllowVirtualPI(final boolean allowVirtualPI) { this.allowVirtualPI = allowVirtualPI; } @Override public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI) { this.oneConfigurationPerPI = oneConfigurationPerPI; } @Override public boolean isOneConfigurationPerPI() { return oneConfigurationPerPI;
} @Override public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public void setAllowDifferentCapacities(final boolean allowDifferentCapacities) { this.allowDifferentCapacities = allowDifferentCapacities; } @Override public boolean isAllowInfiniteCapacity() { return allowInfiniteCapacity; } @Override public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity) { this.allowInfiniteCapacity = allowInfiniteCapacity; } @Override public boolean isAllowAnyPartner() { return allowAnyPartner; } @Override public void setAllowAnyPartner(final boolean allowAnyPartner) { this.allowAnyPartner = allowAnyPartner; } @Override public int getM_Product_Packaging_ID() { return packagingProductId; } @Override public void setM_Product_Packaging_ID(final int packagingProductId) { this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
1
请完成以下Java代码
public frame setMarginWidth(String marginwidth) { addAttribute("marginwidth",marginwidth); return this; } /** Sets the marginheight="" attribute @param marginheight the marginheight="" attribute */ public frame setMarginHeight(int marginheight) { setMarginHeight(Integer.toString(marginheight)); return this; } /** Sets the marginheight="" attribute @param marginheight the marginheight="" attribute */ public frame setMarginHeight(String marginheight) { addAttribute("marginheight",marginheight); return this; } /** Sets the scrolling="" attribute @param scrolling the scrolling="" attribute */ public frame setScrolling(String scrolling) { addAttribute("scrolling",scrolling); return this; } /** Sets the noresize value @param noresize true or false */ public frame setNoResize(boolean noresize) { if ( noresize == true ) addAttribute("noresize", "noresize"); else removeAttribute("noresize"); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table
@param element Adds an Element to the element. */ public frame addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public frame addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frame addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frame addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public frame removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frame.java
1
请完成以下Java代码
protected String doIt() throws Exception { final I_C_Period period = getRecord(I_C_Period.class); final String newPeriodStatus = Services.get(IPeriodBL.class).getPeriodStatusForAction(p_PeriodAction); // // Retrieve period controls final List<I_C_PeriodControl> periodControls = Services.get(IQueryBL.class) .createQueryBuilder(I_C_PeriodControl.class, getCtx(), getTrxName()) .addEqualsFilter(I_C_PeriodControl.COLUMN_C_Period_ID, period.getC_Period_ID()) .addOnlyActiveRecordsFilter() .create() .list(); // // Update the period controls for (final I_C_PeriodControl pc : periodControls) { // Don't update permanently closed period controls if (X_C_PeriodControl.PERIODSTATUS_PermanentlyClosed.equals(pc.getPeriodStatus())) { continue; }
pc.setPeriodStatus(newPeriodStatus); pc.setPeriodAction(X_C_PeriodControl.PERIODACTION_NoAction); InterfaceWrapperHelper.save(pc); } return "@Ok@"; } @Override protected void postProcess(boolean success) { // // Reset caches CacheMgt.get().reset(I_C_PeriodControl.Table_Name); final int periodId = getRecord_ID(); CacheMgt.get().reset(I_C_Period.Table_Name, periodId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\PeriodStatus.java
1
请完成以下Java代码
public String getId() { return id; } public String getDefinitionId() { return definitionId; } public String getDefinitionKey() { return definitionKey; } public String getBusinessKey() { return businessKey; } public String getCaseInstanceId() { return caseInstanceId; } public boolean isEnded() { return ended;
} public boolean isSuspended() { return suspended; } public String getTenantId() { return tenantId; } public static ProcessInstanceDto fromProcessInstance(ProcessInstance instance) { return new ProcessInstanceDto(instance); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceDto.java
1
请在Spring Boot框架中完成以下Java代码
public class CxfWebServiceClient implements SyncWebServiceClient { private static final Logger LOGGER = LoggerFactory.getLogger(CxfWebServiceClient.class); protected Client client; public CxfWebServiceClient(String wsdl) { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); Enumeration<URL> xjcBindingUrls; try { xjcBindingUrls = Thread.currentThread().getContextClassLoader() .getResources(CxfWSDLImporter.JAXB_BINDINGS_RESOURCE); if (xjcBindingUrls.hasMoreElements()) { final URL xjcBindingUrl = xjcBindingUrls.nextElement(); if (xjcBindingUrls.hasMoreElements()) { throw new FlowableException("Several JAXB binding definitions found for flowable-cxf: " + CxfWSDLImporter.JAXB_BINDINGS_RESOURCE); } this.client = dcf.createClient(wsdl, Arrays.asList(new String[] { xjcBindingUrl.toString() })); this.client.getRequestContext().put("org.apache.cxf.stax.force-start-document", Boolean.TRUE); } else { throw new FlowableException("The JAXB binding definitions are not found for flowable-cxf: " + CxfWSDLImporter.JAXB_BINDINGS_RESOURCE); } } catch (IOException e) { throw new FlowableException("An error occurs creating a web-service client for WSDL '" + wsdl + "'.", e); } } @Override
public Object[] send(String methodName, Object[] arguments, ConcurrentMap<QName, URL> overridenEndpointAddresses) throws Exception { try { URL newEndpointAddress = null; if (overridenEndpointAddresses != null) { newEndpointAddress = overridenEndpointAddresses .get(this.client.getEndpoint().getEndpointInfo().getName()); } if (newEndpointAddress != null) { this.client.getRequestContext().put(Message.ENDPOINT_ADDRESS, newEndpointAddress.toExternalForm()); } return client.invoke(methodName, arguments); } catch (Fault e) { LOGGER.debug("Technical error calling WS", e); throw new FlowableException(e.getMessage(), e); } catch (RuntimeException e) { LOGGER.debug("Technical error calling WS", e); throw new FlowableException(e.getMessage(), e); } catch (Exception e) { // Other exceptions should be associated to business fault defined in the service WSDL LOGGER.debug("Business error calling WS", e); throw new BpmnError(e.getClass().getName(), e.getMessage()); } } }
repos\flowable-engine-main\modules\flowable-cxf\src\main\java\org\flowable\engine\impl\webservice\CxfWebServiceClient.java
2
请在Spring Boot框架中完成以下Java代码
public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public int getSessionTimeoutInSeconds() { return sessionTimeoutInSeconds; } public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) { this.sessionTimeoutInSeconds = sessionTimeoutInSeconds; } public String getCookieDomain() { return cookieDomain; } public void setCookieDomain(String cookieDomain) { this.cookieDomain = cookieDomain; } } public static class SignatureVerification { /** * Maximum refresh rate for public keys in ms. * We won't fetch new public keys any faster than that to avoid spamming UAA in case * we receive a lot of "illegal" tokens. */ private long publicKeyRefreshRateLimit = 10 * 1000L; /** * Maximum TTL for the public key in ms. * The public key will be fetched again from UAA if it gets older than that. * That way, we make sure that we get the newest keys always in case they are updated there. */ private long ttl = 24 * 60 * 60 * 1000L; /** * Endpoint where to retrieve the public key used to verify token signatures. */ private String publicKeyEndpointUri = "http://uaa/oauth/token_key"; public long getPublicKeyRefreshRateLimit() { return publicKeyRefreshRateLimit; }
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) { this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit; } public long getTtl() { return ttl; } public void setTtl(long ttl) { this.ttl = ttl; } public String getPublicKeyEndpointUri() { return publicKeyEndpointUri; } public void setPublicKeyEndpointUri(String publicKeyEndpointUri) { this.publicKeyEndpointUri = publicKeyEndpointUri; } } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2Properties.java
2
请完成以下Java代码
List<InetAddress> listAllBroadcastAddresses() throws SocketException { List<InetAddress> broadcastList = new ArrayList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } broadcastList.addAll(networkInterface.getInterfaceAddresses() .stream() .filter(address -> address.getBroadcast() != null) .map(address -> address.getBroadcast()) .collect(Collectors.toList())); } return broadcastList; } private void initializeSocketForBroadcasting() throws SocketException { socket = new DatagramSocket(); socket.setBroadcast(true); } private void copyMessageOnBuffer(String msg) { buf = msg.getBytes(); } private void broadcastPacket(InetAddress address) throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); } private int receivePackets() throws IOException { int serversDiscovered = 0;
while (serversDiscovered != expectedServerCount) { receivePacket(); serversDiscovered++; } return serversDiscovered; } private void receivePacket() throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); } public void close() { socket.close(); } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\broadcast\BroadcastingClient.java
1
请完成以下Java代码
public final class IndentingWriterFactory { private final Function<Integer, String> defaultIndentingStrategy; private final Map<String, Function<Integer, String>> indentingStrategies; private IndentingWriterFactory(Builder builder) { this.defaultIndentingStrategy = builder.defaultIndentingStrategy; this.indentingStrategies = new HashMap<>(builder.indentingStrategies); } /** * Create an {@link IndentingWriter} for the specified content and output. * @param contentId the identifier of the content * @param out the output to use * @return a configured {@link IndentingWriter} */ public IndentingWriter createIndentingWriter(String contentId, Writer out) { Function<Integer, String> indentingStrategy = this.indentingStrategies.getOrDefault(contentId, this.defaultIndentingStrategy); return new IndentingWriter(out, indentingStrategy); } /** * Create an {@link IndentingWriterFactory} with a default indentation strategy of 4 * spaces. * @return an {@link IndentingWriterFactory} with default settings */ public static IndentingWriterFactory withDefaultSettings() { return create(new SimpleIndentStrategy(" ")); } /** * Create a {@link IndentingWriterFactory} with a single indenting strategy. * @param defaultIndentingStrategy the default indenting strategy to use * @return an {@link IndentingWriterFactory} */ public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy) { return new IndentingWriterFactory(new Builder(defaultIndentingStrategy)); } /** * Create a {@link IndentingWriterFactory}. * @param defaultIndentingStrategy the default indenting strategy to use * @param factory a consumer of the builder to apply further customizations * @return an {@link IndentingWriterFactory} */ public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy, Consumer<Builder> factory) { Builder factoryBuilder = new Builder(defaultIndentingStrategy); factory.accept(factoryBuilder);
return new IndentingWriterFactory(factoryBuilder); } /** * Settings customizer for {@link IndentingWriterFactory}. */ public static final class Builder { private final Function<Integer, String> defaultIndentingStrategy; private final Map<String, Function<Integer, String>> indentingStrategies = new HashMap<>(); private Builder(Function<Integer, String> defaultIndentingStrategy) { this.defaultIndentingStrategy = defaultIndentingStrategy; } /** * Register an indenting strategy for the specified content. * @param contentId the identifier of the content to configure * @param indentingStrategy the indent strategy for that particular content * @return this for method chaining * @see #createIndentingWriter(String, Writer) */ public Builder indentingStrategy(String contentId, Function<Integer, String> indentingStrategy) { this.indentingStrategies.put(contentId, indentingStrategy); return this; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriterFactory.java
1