instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } @Override public String toString() { return "TokenDto [raw=" + raw + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((raw == null) ? 0 : raw.hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TokenDto other = (TokenDto) obj; if (raw == null) { if (other.raw != null) return false; } else if (!raw.equals(other.raw)) return false; return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\TokenDto.java
1
请完成以下Java代码
public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getStartDate())); } /** Set Training Class. @param S_Training_Class_ID The actual training class instance */ public void setS_Training_Class_ID (int S_Training_Class_ID) { if (S_Training_Class_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, Integer.valueOf(S_Training_Class_ID)); }
/** Get Training Class. @return The actual training class instance */ public int getS_Training_Class_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_Class_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Training getS_Training() throws RuntimeException { return (I_S_Training)MTable.get(getCtx(), I_S_Training.Table_Name) .getPO(getS_Training_ID(), get_TrxName()); } /** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Training_Class.java
1
请在Spring Boot框架中完成以下Java代码
public class ExampleConnectionProvider implements MultiTenantConnectionProvider<Object>, HibernatePropertiesCustomizer { @Autowired DataSource dataSource; @Override public Connection getAnyConnection() throws SQLException { return getConnection("PUBLIC"); } @Override public void releaseAnyConnection(Connection connection) throws SQLException { connection.close(); } @Override public Connection getConnection(Object tenantIdentifier) throws SQLException { final Connection connection = dataSource.getConnection(); connection.setSchema(tenantIdentifier.toString()); return connection; } /* * (non-Javadoc) * @see org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider#releaseConnection(java.lang.Object, java.sql.Connection) */ @Override public void releaseConnection(Object tenantIdentifier, Connection connection) throws SQLException { connection.setSchema("PUBLIC"); connection.close(); }
@Override public boolean supportsAggressiveRelease() { return false; } @Override public boolean isUnwrappableAs(Class<?> aClass) { return false; } @Override public <T> T unwrap(Class<T> aClass) { throw new UnsupportedOperationException("Can't unwrap this."); } @Override public void customize(Map<String, Object> hibernateProperties) { hibernateProperties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, this); } }
repos\spring-data-examples-main\jpa\multitenant\schema\src\main\java\example\springdata\jpa\hibernatemultitenant\schema\ExampleConnectionProvider.java
2
请完成以下Java代码
default ValidationEntry addWarning(String problem, String description) { return addWarning(problem, null, null, null, description); } default ValidationEntry addWarning(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description) { return addEntry(problem, caze, caseElement, baseElement, description, ValidationEntry.Level.Warning); } default ValidationEntry addEntry(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description, ValidationEntry.Level level) { ValidationEntry entry = new ValidationEntry(); entry.setLevel(level); if (caze != null) { entry.setCaseDefinitionId(caze.getId()); entry.setCaseDefinitionName(caze.getName()); } if (baseElement != null) { entry.setXmlLineNumber(baseElement.getXmlRowNumber()); entry.setXmlColumnNumber(baseElement.getXmlColumnNumber()); }
entry.setProblem(problem); entry.setDefaultDescription(description); if (caseElement == null && baseElement instanceof CaseElement) { caseElement = (CaseElement) baseElement; } if (caseElement != null) { entry.setItemId(caseElement.getId()); entry.setItemName(caseElement.getName()); } return addEntry(entry); } ValidationEntry addEntry(ValidationEntry entry); }
repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\CaseValidationContext.java
1
请完成以下Java代码
public ChargeBearerTypeSEPACode getChrgBr() { return chrgBr; } /** * Sets the value of the chrgBr property. * * @param value * allowed object is * {@link ChargeBearerTypeSEPACode } * */ public void setChrgBr(ChargeBearerTypeSEPACode value) { this.chrgBr = value; } /** * Gets the value of the cdtrSchmeId property. * * @return * possible object is * {@link PartyIdentificationSEPA3 } * */ public PartyIdentificationSEPA3 getCdtrSchmeId() { return cdtrSchmeId; } /** * Sets the value of the cdtrSchmeId property. * * @param value * allowed object is * {@link PartyIdentificationSEPA3 } * */ public void setCdtrSchmeId(PartyIdentificationSEPA3 value) { this.cdtrSchmeId = value; } /** * Gets the value of the drctDbtTxInf property.
* * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the drctDbtTxInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDrctDbtTxInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DirectDebitTransactionInformationSDD } * * */ public List<DirectDebitTransactionInformationSDD> getDrctDbtTxInf() { if (drctDbtTxInf == null) { drctDbtTxInf = new ArrayList<DirectDebitTransactionInformationSDD>(); } return this.drctDbtTxInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentInstructionInformationSDD.java
1
请在Spring Boot框架中完成以下Java代码
public class ChatController { @Qualifier("openaiRestTemplate") @Autowired private RestTemplate restTemplate; @Value("${openai.model}") private String model; @Value("${openai.api.url}") private String apiUrl; /** * Creates a chat request and sends it to the OpenAI API * Returns the first message from the API response * * @param prompt the prompt to send to the API * @return first message from the API response
*/ @GetMapping("/chat") public String chat(@RequestParam String prompt) { ChatRequest request = new ChatRequest(model, prompt); ChatResponse response = restTemplate.postForObject( apiUrl, request, ChatResponse.class); if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) { return "No response"; } return response.getChoices().get(0).getMessage().getContent(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-2\src\main\java\com\baeldung\openai\controller\ChatController.java
2
请在Spring Boot框架中完成以下Java代码
public Product createProduct(Product product) { return productRepository.save(product); } @Override public Product updateProduct(Product product) { Optional<Product> productDb = this.productRepository.findById(product.getId()); if(productDb.isPresent()) { Product productUpdate = productDb.get(); productUpdate.setId(product.getId()); productUpdate.setName(product.getName()); productUpdate.setDescription(product.getDescription()); productRepository.save(productUpdate); return productUpdate; }else { throw new ResourceNotFoundException("Record not found with id : " + product.getId()); } } @Override public List<Product> getAllProduct() { return this.productRepository.findAll(); } @Override public Product getProductById(long productId) { Optional<Product> productDb = this.productRepository.findById(productId); if(productDb.isPresent()) { return productDb.get();
}else { throw new ResourceNotFoundException("Record not found with id : " + productId); } } @Override public void deleteProduct(long productId) { Optional<Product> productDb = this.productRepository.findById(productId); if(productDb.isPresent()) { this.productRepository.delete(productDb.get()); }else { throw new ResourceNotFoundException("Record not found with id : " + productId); } } }
repos\Spring-Boot-Advanced-Projects-main\springboot-crud-hibernate-example\src\main\java\net\alanbinu\springboot\service\ProductServiceImpl.java
2
请完成以下Java代码
public ReceiveTask newInstance(ModelTypeInstanceContext instanceContext) { return new ReceiveTaskImpl(instanceContext); } }); implementationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION) .defaultValue("##WebService") .build(); instantiateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_INSTANTIATE) .defaultValue(false) .build(); messageRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_MESSAGE_REF) .qNameAttributeReference(Message.class) .build(); operationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OPERATION_REF) .qNameAttributeReference(Operation.class) .build(); typeBuilder.build(); } public ReceiveTaskImpl(ModelTypeInstanceContext context) { super(context); } public ReceiveTaskBuilder builder() { return new ReceiveTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) {
implementationAttribute.setValue(this, implementation); } public boolean instantiate() { return instantiateAttribute.getValue(this); } public void setInstantiate(boolean instantiate) { instantiateAttribute.setValue(this, instantiate); } public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ReceiveTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class X_QRCode_Configuration extends org.compiere.model.PO implements I_QRCode_Configuration, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1807661472L; /** Standard Constructor */ public X_QRCode_Configuration (final Properties ctx, final int QRCode_Configuration_ID, @Nullable final String trxName) { super (ctx, QRCode_Configuration_ID, trxName); } /** Load Constructor */ public X_QRCode_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 setIsOneQRCodeForAggregatedHUs (final boolean IsOneQRCodeForAggregatedHUs) { set_Value (COLUMNNAME_IsOneQRCodeForAggregatedHUs, IsOneQRCodeForAggregatedHUs); } @Override public boolean isOneQRCodeForAggregatedHUs() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForAggregatedHUs); } @Override public void setIsOneQRCodeForMatchingAttributes (final boolean IsOneQRCodeForMatchingAttributes) { set_Value (COLUMNNAME_IsOneQRCodeForMatchingAttributes, IsOneQRCodeForMatchingAttributes); } @Override
public boolean isOneQRCodeForMatchingAttributes() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForMatchingAttributes); } @Override public void setName (final String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID) { if (QRCode_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID); } @Override public int getQRCode_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Configuration.java
2
请完成以下Java代码
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter) { if (I_ESR_Import.COLUMNNAME_ESR_Import_ID.equals(parameter.getColumnName())) { final int esrImportId = parameter.getContextAsInt(I_ESR_Import.COLUMNNAME_ESR_Import_ID); if (esrImportId > 0) { return esrImportId; } } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } @Override @RunOutOfTrx // ...because we might show a dialog to the user protected String doIt() throws Exception { final I_ESR_Import esrImport = retrieveESR_Import(); ESRImportEnqueuer.newInstance() .esrImport(esrImport) .fromDataSource(ESRImportEnqueuerDataSource.ofFile(p_FileName)) // .asyncBatchName(p_AsyncBatchName) .asyncBatchDesc(p_AsyncBatchDesc) .pinstanceId(getPinstanceId()) // .loggable(this) // .execute(); getResult().setRecordToRefreshAfterExecution(TableRecordReference.of(esrImport)); return MSG_OK; }
private final I_ESR_Import retrieveESR_Import() { if (p_ESR_Import_ID <= 0) { if (I_ESR_Import.Table_Name.equals(getTableName())) { p_ESR_Import_ID = getRecord_ID(); } if (p_ESR_Import_ID <= 0) { throw new FillMandatoryException(I_ESR_Import.COLUMNNAME_ESR_Import_ID); } } final I_ESR_Import esrImport = InterfaceWrapperHelper.create(getCtx(), p_ESR_Import_ID, I_ESR_Import.class, get_TrxName()); if (esrImport == null) { throw new AdempiereException("@NotFound@ @ESR_Import_ID@"); } return esrImport; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\ESR_Import_LoadFromFile.java
1
请完成以下Java代码
public void addAll(String[] total) { for (String single : total) { add(single); } } /** * 查找是否有该后缀 * @param suffix * @return */ public int get(String suffix) { suffix = reverse(suffix); Integer length = trie.get(suffix); if (length == null) return 0; return length; } /** * 词语是否以该词典中的某个单词结尾 * @param word * @return */ public boolean endsWith(String word) { word = reverse(word); return trie.commonPrefixSearchWithValue(word).size() > 0; } /** * 获取最长的后缀 * @param word * @return */ public int getLongestSuffixLength(String word) { word = reverse(word); LinkedList<Map.Entry<String, Integer>> suffixList = trie.commonPrefixSearchWithValue(word); if (suffixList.size() == 0) return 0; return suffixList.getLast().getValue();
} private static String reverse(String word) { return new StringBuilder(word).reverse().toString(); } /** * 键值对 * @return */ public Set<Map.Entry<String, Integer>> entrySet() { Set<Map.Entry<String, Integer>> treeSet = new LinkedHashSet<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> entry : trie.entrySet()) { treeSet.add(new AbstractMap.SimpleEntry<String, Integer>(reverse(entry.getKey()), entry.getValue())); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SuffixDictionary.java
1
请完成以下Java代码
public boolean isEmpty() { return connectors.isEmpty(); } private static class ConnectorMetricsState { private final AtomicInteger count; private final AtomicLong gwLatencySum; private final AtomicLong transportLatencySum; private volatile long minGwLatency; private volatile long maxGwLatency; private volatile long minTransportLatency; private volatile long maxTransportLatency; private ConnectorMetricsState() { this.count = new AtomicInteger(0); this.gwLatencySum = new AtomicLong(0); this.transportLatencySum = new AtomicLong(0); } private void update(GatewayMetadata metricsData, long serverReceiveTs) { long gwLatency = metricsData.publishedTs() - metricsData.receivedTs(); long transportLatency = serverReceiveTs - metricsData.publishedTs(); count.incrementAndGet(); gwLatencySum.addAndGet(gwLatency); transportLatencySum.addAndGet(transportLatency); if (minGwLatency == 0 || minGwLatency > gwLatency) { minGwLatency = gwLatency; }
if (maxGwLatency < gwLatency) { maxGwLatency = gwLatency; } if (minTransportLatency == 0 || minTransportLatency > transportLatency) { minTransportLatency = transportLatency; } if (maxTransportLatency < transportLatency) { maxTransportLatency = transportLatency; } } private ConnectorMetricsResult getResult() { long count = this.count.get(); long avgGwLatency = gwLatencySum.get() / count; long avgTransportLatency = transportLatencySum.get() / count; return new ConnectorMetricsResult(avgGwLatency, minGwLatency, maxGwLatency, avgTransportLatency, minTransportLatency, maxTransportLatency); } } public record ConnectorMetricsResult(long avgGwLatency, long minGwLatency, long maxGwLatency, long avgTransportLatency, long minTransportLatency, long maxTransportLatency) { } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\gateway\metrics\GatewayMetricsState.java
1
请完成以下Java代码
public void onDesadvDelete(final I_EDI_Desadv desadv) { final List<I_EDI_DesadvLine> allLines = desadvDAO.retrieveAllDesadvLines(desadv); for (final I_EDI_DesadvLine line : allLines) { InterfaceWrapperHelper.delete(line); } final List<I_M_InOut> allInOuts = desadvDAO.retrieveAllInOuts(desadv); for (final I_M_InOut inOut : allInOuts) { inOut.setEDI_Desadv_ID(0); InterfaceWrapperHelper.save(inOut); } final List<I_C_Order> allIOrders = desadvDAO.retrieveAllOrders(desadv); for (final I_C_Order order : allIOrders) { order.setEDI_Desadv_ID(0); InterfaceWrapperHelper.save(order); } } /** * Update InOuts' export status when their DESADV is changed. Also updates the DESADV's processing and processed flags. */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, // ifColumnsChanged = I_EDI_Desadv.COLUMNNAME_EDI_ExportStatus) public void onDesadvStatusChanged(final I_EDI_Desadv desadv) {
final String exportStatus = desadv.getEDI_ExportStatus(); final boolean processing = I_EDI_Document.EDI_EXPORTSTATUS_Enqueued.equals(exportStatus) || I_EDI_Document.EDI_EXPORTSTATUS_SendingStarted.equals(exportStatus); desadv.setProcessing(processing); final boolean processed = I_EDI_Document.EDI_EXPORTSTATUS_Sent.equals(exportStatus) || I_EDI_Document.EDI_EXPORTSTATUS_DontSend.equals(exportStatus); desadv.setProcessed(processed); desadvBL.propagateEDIStatus(desadv); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_EDI_Desadv.COLUMNNAME_EDIErrorMsg }) public void translateErrorMessage(final I_EDI_Desadv desadv) { final String errorMsgTrl = msgBL.parseTranslation(InterfaceWrapperHelper.getCtx(desadv), desadv.getEDIErrorMsg()); desadv.setEDIErrorMsg(errorMsgTrl); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW }) public void setMinimumSumPercentage(final I_EDI_Desadv desadv) { // set the minimum sum percentage on each new desadv. // Even if the percentage will be changed via sys config, for this desadv it won't change desadvBL.setMinimumPercentage(desadv); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\EDI_Desadv.java
1
请完成以下Java代码
public String getTaskIdVariableName() { return taskIdVariableName; } public void setTaskIdVariableName(String taskIdVariableName) { this.taskIdVariableName = taskIdVariableName; } public String getTaskCompleterVariableName() { return taskCompleterVariableName; } public void setTaskCompleterVariableName(String taskCompleterVariableName) { this.taskCompleterVariableName = taskCompleterVariableName; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public List<FlowableListener> getTaskListeners() { return taskListeners; }
public void setTaskListeners(List<FlowableListener> taskListeners) { this.taskListeners = taskListeners; } @Override public HumanTask clone() { HumanTask clone = new HumanTask(); clone.setValues(this); return clone; } public void setValues(HumanTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setValidateFormFields(otherElement.getValidateFormFields()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setTaskIdVariableName(otherElement.getTaskIdVariableName()); setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java
1
请完成以下Java代码
public class RedisCache<K, V> implements Cache<K, V> { private String cacheName; public RedisCache() { } public RedisCache(String cacheName) { this.cacheName = cacheName; } private RedisTemplate getRedisTemplate() { RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate"); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); return redisTemplate; } @Override public V get(K k) throws CacheException { return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString()); } @Override public V put(K k, V v) throws CacheException { getRedisTemplate().opsForHash().put(this.cacheName,k.toString(), v); return null; }
@Override public V remove(K k) throws CacheException { return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString()); } @Override public void clear() throws CacheException { getRedisTemplate().opsForHash().delete(this.cacheName); } @Override public int size() { return getRedisTemplate().opsForHash().size(this.cacheName).intValue(); } @Override public Set<K> keys() { return getRedisTemplate().opsForHash().keys(this.cacheName); } @Override public Collection<V> values() { return getRedisTemplate().opsForHash().values(this.cacheName); } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\cache\RedisCache.java
1
请完成以下Java代码
public int hashCode() { return m_AD_Language.hashCode(); } // hashcode @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof Language) { final Language other = (Language)obj; return Objects.equals(this.m_AD_Language, other.m_AD_Language); } return false; } // equals private static int timeStyleDefault = DateFormat.MEDIUM; /** * Sets default time style to be used when getting DateTime format or Time format. * * @param timeStyle one of {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, {@link DateFormat#LONG}. */ public static void setDefaultTimeStyle(final int timeStyle) { timeStyleDefault = timeStyle; } public static int getDefaultTimeStyle()
{ return timeStyleDefault; } public int getTimeStyle() { return getDefaultTimeStyle(); } private boolean matchesLangInfo(final String langInfo) { if (langInfo == null || langInfo.isEmpty()) { return false; } return langInfo.equals(getName()) || langInfo.equals(getAD_Language()) || langInfo.equals(getLanguageCode()); } } // Language
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\Language.java
1
请在Spring Boot框架中完成以下Java代码
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { private static final Logger logger = Logger.getLogger(DatasourceProxyBeanPostProcessor.class.getName()); @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof DataSource) { logger.info(() -> "DataSource bean has been found: " + bean); final ProxyFactory proxyFactory = new ProxyFactory(bean); proxyFactory.setProxyTargetClass(true); proxyFactory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); return proxyFactory.getProxy(); } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } private static class ProxyDataSourceInterceptor implements MethodInterceptor { private final DataSource dataSource; public ProxyDataSourceInterceptor(final DataSource dataSource) {
super(); this.dataSource = ProxyDataSourceBuilder.create(dataSource) .name("DATA_SOURCE_PROXY") .logQueryBySlf4j(SLF4JLogLevel.INFO) .multiline() .build(); } @Override public Object invoke(final MethodInvocation invocation) throws Throwable { final Method proxyMethod = ReflectionUtils. findMethod(this.dataSource.getClass(), invocation.getMethod().getName()); if (proxyMethod != null) { return proxyMethod.invoke(this.dataSource, invocation.getArguments()); } return invocation.proceed(); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteCascadeDelete\src\main\java\com\bookstore\config\DatasourceProxyBeanPostProcessor.java
2
请完成以下Java代码
public Vector query(String content) { if (content == null || content.length() == 0) return null; List<Term> termList = segment.seg(content); if (filter) { CoreStopWordDictionary.apply(termList); } Vector result = new Vector(dimension()); int n = 0; for (Term term : termList) { Vector vector = wordVectorModel.vector(term.word); if (vector == null) { continue; } ++n; result.addToSelf(vector); } if (n == 0) { return null; } result.normalize(); return result; } @Override public int dimension() { return wordVectorModel.dimension(); } /** * 文档相似度计算 * * @param what * @param with * @return */ public float similarity(String what, String with) { Vector A = query(what); if (A == null) return -1f; Vector B = query(with);
if (B == null) return -1f; return A.cosineForUnitVector(B); } public Segment getSegment() { return segment; } public void setSegment(Segment segment) { this.segment = segment; } /** * 是否激活了停用词过滤器 * * @return */ public boolean isFilterEnabled() { return filter; } /** * 激活/关闭停用词过滤器 * * @param filter */ public void enableFilter(boolean filter) { this.filter = filter; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java
1
请完成以下Java代码
private NumberFormat createCurrencyNumberFormat(final I_C_Invoice_Candidate ic) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final ICurrencyDAO currencyDAO = Services.get(ICurrencyDAO.class); final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); final BPartnerLocationAndCaptureId billLocation = invoiceCandBL.getBillLocationId(ic, false); final I_C_BPartner_Location billBPLocation = bpartnerDAO.getBPartnerLocationByIdEvenInactive(billLocation.getBpartnerLocationId()); Check.assumeNotNull(billBPLocation, "billBPLocation not null for {}", ic); // We use the language of the bill location to determine the number format. // using the ic's context's language make no sense, because it basically amounts to the login language and can change a lot. final String langInfo = billBPLocation.getC_Location().getC_Country().getAD_Language(); final Locale locale = Language.getLanguage(langInfo).getLocale(); final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale); final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(ic.getC_Currency_ID()); if (currencyId != null) { final CurrencyCode currencyCode = currencyDAO.getCurrencyCodeById(currencyId); numberFormat.setCurrency(Currency.getInstance(currencyCode.toThreeLetterCode())); } return numberFormat; } @Override public boolean isSame(final I_C_Invoice_Candidate model1, final I_C_Invoice_Candidate model2) { final String aggregationKey1 = buildKey(model1);
final String aggregationKey2 = buildKey(model2); return Objects.equals(aggregationKey1, aggregationKey2); } @Override public String getTableName() { return I_C_Invoice_Candidate.Table_Name; } @Override public List<String> getDependsOnColumnNames() { return columnNames; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\agg\key\impl\ICLineAggregationKeyBuilder_OLD.java
1
请完成以下Java代码
public InfoSimple create(boolean modal, int windowNo, String tableName, boolean multiSelection, String whereClause, Map<String, Object> attributes) { final Frame frame = Env.getWindow(windowNo); final String keyColumn = tableName + "_ID"; final String value = ""; final I_AD_InfoWindow infoWindow = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(Env.getCtx(), tableName); if (infoWindow == null) { log.warn("No info window found for " + tableName); return null; } if (!infoWindow.isActive()) { log.warn("No ACTIVE info window found for " + tableName + " (" + infoWindow + ")"); return null; } String className = infoWindow.getClassname(); if (Check.isEmpty(className)) className = InfoSimple.class.getCanonicalName(); try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null)
cl = getClass().getClassLoader(); @SuppressWarnings("unchecked") Class<InfoSimple> clazz = (Class<InfoSimple>)cl.loadClass(className); java.lang.reflect.Constructor<? extends Info> ctor = clazz.getConstructor(Frame.class); InfoSimple infoSimple = (InfoSimple)ctor.newInstance(frame); infoSimple.init(modal, windowNo, infoWindow, keyColumn, value, multiSelection, whereClause); if (attributes != null) { for (Entry<String, Object> e : attributes.entrySet()) infoSimple.setCtxAttribute(e.getKey(), e.getValue()); } return infoSimple; } catch (Exception e) { throw new AdempiereException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimpleFactory.java
1
请完成以下Java代码
public static MEXPFormatLine getFormatLineByValue(Properties ctx, String value, int EXP_Format_ID, String trxName) throws SQLException { MEXPFormatLine result = null; StringBuffer sql = new StringBuffer("SELECT * ") .append(" FROM ").append(X_EXP_FormatLine.Table_Name) .append(" WHERE ").append(X_EXP_Format.COLUMNNAME_Value).append("=?") //.append(" AND IsActive = ?") //.append(" AND AD_Client_ID = ?") .append(" AND ").append(X_EXP_Format.COLUMNNAME_EXP_Format_ID).append(" = ?") ; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql.toString(), trxName); pstmt.setString(1, value); pstmt.setInt(2, EXP_Format_ID); ResultSet rs = pstmt.executeQuery (); if ( rs.next() ) { result = new MEXPFormatLine (ctx, rs, trxName); } rs.close (); pstmt.close (); pstmt = null; } catch (SQLException e) { s_log.error(sql.toString(), e); throw e; } finally {
try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } } return result; } @Override protected boolean afterSave (boolean newRecord, boolean success) { if(!success) { return false; } CacheMgt.get().reset(I_EXP_Format.Table_Name); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPFormatLine.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Role getExportRole() { return get_ValueAsPO(COLUMNNAME_ExportRole_ID, org.compiere.model.I_AD_Role.class); } @Override public void setExportRole(final org.compiere.model.I_AD_Role ExportRole) { set_ValueFromPO(COLUMNNAME_ExportRole_ID, org.compiere.model.I_AD_Role.class, ExportRole); } @Override public void setExportRole_ID (final int ExportRole_ID) { if (ExportRole_ID < 1) set_Value (COLUMNNAME_ExportRole_ID, null); else set_Value (COLUMNNAME_ExportRole_ID, ExportRole_ID); } @Override public int getExportRole_ID() { return get_ValueAsInt(COLUMNNAME_ExportRole_ID); } @Override public void setExportTime (final java.sql.Timestamp ExportTime) { set_Value (COLUMNNAME_ExportTime, ExportTime); } @Override public java.sql.Timestamp getExportTime() { return get_ValueAsTimestamp(COLUMNNAME_ExportTime); } @Override public void setExportUser_ID (final int ExportUser_ID) { if (ExportUser_ID < 1) set_Value (COLUMNNAME_ExportUser_ID, null); else set_Value (COLUMNNAME_ExportUser_ID, ExportUser_ID); } @Override public int getExportUser_ID() { return get_ValueAsInt(COLUMNNAME_ExportUser_ID); } @Override public void setExternalSystem_ExportAudit_ID (final int ExternalSystem_ExportAudit_ID) { if (ExternalSystem_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, ExternalSystem_ExportAudit_ID); } @Override public int getExternalSystem_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ExportAudit_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_ExportAudit.java
1
请在Spring Boot框架中完成以下Java代码
void setExceptionListener(@Nullable ExceptionListener exceptionListener) { this.exceptionListener = exceptionListener; } /** * Set the {@link JmsProperties} to use. * @param jmsProperties the {@link JmsProperties} */ void setJmsProperties(@Nullable JmsProperties jmsProperties) { this.jmsProperties = jmsProperties; } /** * Set the {@link ObservationRegistry} to use. * @param observationRegistry the {@link ObservationRegistry} */ void setObservationRegistry(@Nullable ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } /** * Return the {@link JmsProperties}. * @return the jms properties */ protected JmsProperties getJmsProperties() { Assert.state(this.jmsProperties != null, "'jmsProperties' must not be null"); return this.jmsProperties; } /** * Configure the specified jms listener container factory. The factory can be further * tuned and default settings can be overridden.
* @param factory the {@link AbstractJmsListenerContainerFactory} instance to * configure * @param connectionFactory the {@link ConnectionFactory} to use */ public void configure(T factory, ConnectionFactory connectionFactory) { Assert.notNull(factory, "'factory' must not be null"); Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); JmsProperties properties = getJmsProperties(); JmsProperties.Listener listenerProperties = properties.getListener(); Session sessionProperties = listenerProperties.getSession(); factory.setConnectionFactory(connectionFactory); PropertyMapper map = PropertyMapper.get(); map.from(properties::isPubSubDomain).to(factory::setPubSubDomain); map.from(properties::isSubscriptionDurable).to(factory::setSubscriptionDurable); map.from(properties::getClientId).to(factory::setClientId); map.from(this.destinationResolver).to(factory::setDestinationResolver); map.from(this.messageConverter).to(factory::setMessageConverter); map.from(this.exceptionListener).to(factory::setExceptionListener); map.from(sessionProperties.getAcknowledgeMode()::getMode).to(factory::setSessionAcknowledgeMode); map.from(this.observationRegistry).to(factory::setObservationRegistry); map.from(sessionProperties::getTransacted).to(factory::setSessionTransacted); map.from(listenerProperties::isAutoStartup).to(factory::setAutoStartup); } }
repos\spring-boot-main\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\AbstractJmsListenerContainerFactoryConfigurer.java
2
请完成以下Java代码
public void process(final I_M_HU_Trx_Attribute huTrxAttribute) { // // Check if it was already processed if (huTrxAttribute.isProcessed()) { return; } // // Actually process it process0(huTrxAttribute); // // Flag it as Processed and save it huTrxAttribute.setProcessed(true); save(huTrxAttribute); } private final void save(final I_M_HU_Trx_Attribute huTrxAttribute) { if (!saveTrxAttributes) { return; // don't save it } InterfaceWrapperHelper.save(huTrxAttribute); } /** * Process given {@link I_M_HU_Trx_Attribute} by calling the actual processor.
* * @param huTrxAttribute */ private void process0(final I_M_HU_Trx_Attribute huTrxAttribute) { final Object referencedModel = getReferencedObject(huTrxAttribute); final IHUTrxAttributeProcessor trxAttributeProcessor = getHUTrxAttributeProcessor(referencedModel); final HUTransactionAttributeOperation operation = HUTransactionAttributeOperation.ofCode(huTrxAttribute.getOperation()); if (HUTransactionAttributeOperation.SAVE.equals(operation)) { trxAttributeProcessor.processSave(huContext, huTrxAttribute, referencedModel); } else if (HUTransactionAttributeOperation.DROP.equals(operation)) { trxAttributeProcessor.processDrop(huContext, huTrxAttribute, referencedModel); } else { throw new InvalidAttributeValueException("Invalid operation on trx attribute (" + operation + "): " + huTrxAttribute); } } @Override public void reverseTrxAttributes(final I_M_HU_Trx_Line reversalTrxLine, final I_M_HU_Trx_Line trxLine) { // TODO implement trx line attributes reversal final AdempiereException ex = new AdempiereException("attribute transactions reversal not implemented"); logger.warn(ex.getLocalizedMessage() + ". Skip it for now", ex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeProcessor.java
1
请完成以下Java代码
private static Warehouse ofRecord(@NonNull final I_M_Warehouse warehouseRecord) { return Warehouse.builder() .id(WarehouseId.ofRepoId(warehouseRecord.getM_Warehouse_ID())) .orgId(OrgId.ofRepoId(warehouseRecord.getAD_Org_ID())) .name(warehouseRecord.getName()) .value(warehouseRecord.getValue()) .partnerLocationId(BPartnerLocationId.ofRepoId(warehouseRecord.getC_BPartner_ID(), warehouseRecord.getC_BPartner_Location_ID())) .active(warehouseRecord.isActive()) .build(); } @Override public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull LocatorId locatorId) { return getClientAndOrgIdByLocatorId(locatorId.getWarehouseId()); }
public ClientAndOrgId getClientAndOrgIdByLocatorId(@NonNull WarehouseId warehouseId) { final I_M_Warehouse warehouse = getById(warehouseId); return ClientAndOrgId.ofClientAndOrg(warehouse.getAD_Client_ID(), warehouse.getAD_Org_ID()); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds) { return getLocatorsByRepoIds(ImmutableSet.copyOf(locatorIds)) .stream() .map(LocatorId::ofRecord) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseDAO.java
1
请完成以下Java代码
public static FMeasure evaluate(IClassifier classifier, Map<String, String[]> testingDataSet) { return evaluate(classifier, new MemoryDataSet(classifier.getModel()).add(testingDataSet)); } /** * * @param c 类目数量 * @param size 样本数量 * @param TP 判定为某个类别且判断正确的数量 * @param TP_FP 判定为某个类别的数量 * @param TP_FN 某个类别的样本数量 * @return */ private static FMeasure calculate(int c, int size, double[] TP, double[] TP_FP, double[] TP_FN) { double precision[] = new double[c]; double recall[] = new double[c]; double f1[] = new double[c]; double accuracy[] = new double[c]; FMeasure result = new FMeasure(); result.size = size; for (int i = 0; i < c; i++) { double TN = result.size - TP_FP[i] - (TP_FN[i] - TP[i]); accuracy[i] = (TP[i] + TN) / result.size; if (TP[i] != 0) {
precision[i] = TP[i] / TP_FP[i]; recall[i] = TP[i] / TP_FN[i]; result.average_accuracy += TP[i]; } else { precision[i] = 0; recall[i] = 0; } f1[i] = 2 * precision[i] * recall[i] / (precision[i] + recall[i]); } result.average_precision = MathUtility.average(precision); result.average_recall = MathUtility.average(recall); result.average_f1 = 2 * result.average_precision * result.average_recall / (result.average_precision + result.average_recall); result.average_accuracy /= (double) result.size; result.accuracy = accuracy; result.precision = precision; result.recall = recall; result.f1 = f1; return result; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\evaluations\Evaluator.java
1
请完成以下Java代码
public CurrentPickingTarget withLuPickingTarget(final @Nullable LUPickingTarget luPickingTarget) { if (LUPickingTarget.equals(this.luPickingTarget, luPickingTarget)) { return this; } return toBuilder() .luPickingTarget(luPickingTarget) .tuPickingTarget(luPickingTarget == null ? null : this.tuPickingTarget) .build(); } public CurrentPickingTarget withClosedLUAndTUPickingTarget(@Nullable final LUIdsAndTopLevelTUIdsCollector closedHuIdCollector) { // already closed if (this.luPickingTarget == null && this.tuPickingTarget == null) { return this; } if (closedHuIdCollector != null) { if (luPickingTarget == null || luPickingTarget.isNewLU()) { // collect only top level TUs i.e. no LUs if (tuPickingTarget != null && tuPickingTarget.isExistingTU()) { closedHuIdCollector.addTopLevelTUId(tuPickingTarget.getTuIdNotNull()); } } else if (luPickingTarget.isExistingLU()) { closedHuIdCollector.addLUId(luPickingTarget.getLuIdNotNull()); } } return toBuilder()
.luPickingTarget(null) .tuPickingTarget(null) .build(); } @NonNull public Optional<TUPickingTarget> getTuPickingTarget() {return Optional.ofNullable(tuPickingTarget);} @NonNull public CurrentPickingTarget withTuPickingTarget(@Nullable final TUPickingTarget tuPickingTarget) { return TUPickingTarget.equals(this.tuPickingTarget, tuPickingTarget) ? this : toBuilder().tuPickingTarget(tuPickingTarget).build(); } public boolean matches(@NonNull final HuId huId) { return luPickingTarget != null && HuId.equals(luPickingTarget.getLuId(), huId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\CurrentPickingTarget.java
1
请完成以下Java代码
public ImportProcessResult toResult() { return new ImportProcessResult(this); } public ImportProcessResultCollector importTableName(@NonNull final String importTableName) { this.importTableName = importTableName; return this; } public void setCountImportRecordsDeleted(final int countImportRecordsDeleted) { Check.assumeGreaterOrEqualToZero(countImportRecordsDeleted, "countImportRecordsDeleted"); this.countImportRecordsDeleted.set(countImportRecordsDeleted); } public void setCountImportRecordsWithValidationErrors(final int count) { Check.assumeGreaterOrEqualToZero(count, "count"); this.countImportRecordsWithValidationErrors.set(count); } public void addCountImportRecordsConsidered(final int count) { countImportRecordsConsidered.add(count); } public int getCountImportRecordsConsidered() {return countImportRecordsConsidered.toIntOr(0);} public void addInsertsIntoTargetTable(final int count) { countInsertsIntoTargetTable.add(count); } public void addUpdatesIntoTargetTable(final int count) { countUpdatesIntoTargetTable.add(count); } public void actualImportError(@NonNull final ActualImportRecordsResult.Error error) { actualImportErrors.add(error); } } @EqualsAndHashCode private static final class Counter { private boolean unknownValue; private int value = 0; @Override public String toString() {
return unknownValue ? "N/A" : String.valueOf(value); } public void set(final int value) { if (value < 0) { throw new AdempiereException("value shall NOT be negative: " + value); } this.value = value; this.unknownValue = false; } public void add(final int valueToAdd) { Check.assumeGreaterOrEqualToZero(valueToAdd, "valueToAdd"); set(this.value + valueToAdd); } public OptionalInt toOptionalInt() {return unknownValue ? OptionalInt.empty() : OptionalInt.of(value);} public int toIntOr(final int defaultValue) {return unknownValue ? defaultValue : value;} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportProcessResult.java
1
请完成以下Java代码
public T findOne(final long id) { return entityManager.find(clazz, id); } @SuppressWarnings("unchecked") public List<T> findAll() { return entityManager.createQuery("from " + clazz.getName()).getResultList(); } public void create(final T entity) { entityManager.persist(entity); } public T update(final T entity) { return entityManager.merge(entity); } public void delete(final T entity) { entityManager.remove(entity); } public void deleteById(final long entityId) { final T entity = findOne(entityId); delete(entity); } public long countAllRowsUsingHibernateCriteria() { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.setProjection(Projections.rowCount()); Long count = (Long) criteria.uniqueResult(); return count != null ? count : 0L; } public long getFooCountByBarNameUsingHibernateCriteria(String barName) { Session session = entityManager.unwrap(Session.class);
Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } public long getFooCountByBarNameAndFooNameUsingHibernateCriteria(String barName, String fooName) { Session session = entityManager.unwrap(Session.class); Criteria criteria = session.createCriteria(clazz); criteria.createAlias("bar", "b"); criteria.add(Restrictions.eq("b.name", barName)); criteria.add(Restrictions.eq("name", fooName)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\dao\AbstractJpaDAO.java
1
请完成以下Java代码
public BooleanWithReason getEnabled() { if (Adempiere.isUnitTestMode()) { return DISABLED_BECAUSE_JUNIT_MODE; } // Check if it was disabled by sysconfig if (!sysConfigBL.getBooleanValue(SYSCONFIG_elastic_enable, true)) { return DISABLED_BECAUSE_SYSCONFIG; } return BooleanWithReason.TRUE; } private void assertEnabled() { final BooleanWithReason enabled = getEnabled();
if (enabled.isFalse()) { throw new AdempiereException("Expected elasticsearch feature to be enabled but is disabled because `" + enabled.getReasonAsString() + "`"); } } @Override public RestHighLevelClient elasticsearchClient() { assertEnabled(); RestHighLevelClient elasticsearchClient = this.elasticsearchClient; if (elasticsearchClient == null) { elasticsearchClient = this.elasticsearchClient = SpringContextHolder.instance.getBean(RestHighLevelClient.class); } return elasticsearchClient; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\elasticsearch\impl\ESSystem.java
1
请完成以下Java代码
public class RecordBasedLocationUtils { public static <SELF extends RecordBasedLocationAdapter<SELF>> void updateCapturedLocationAndRenderedAddressIfNeeded( @NonNull RecordBasedLocationAdapter<SELF> locationAdapter, @NonNull final IDocumentLocationBL documentLocationBL) { final Object record = locationAdapter.getWrappedRecord(); // do nothing if we are cloning the record if(InterfaceWrapperHelper.isCopying(record)) { return; } final boolean isNewRecord = InterfaceWrapperHelper.isNew(record); final DocumentLocation currentLocation = locationAdapter.toPlainDocumentLocation(documentLocationBL).orElse(DocumentLocation.EMPTY); final DocumentLocation previousLocation = !isNewRecord ? locationAdapter.toOldValues().toPlainDocumentLocation(documentLocationBL).orElse(DocumentLocation.EMPTY) : DocumentLocation.EMPTY;
final boolean updateCapturedLocation = isNewRecord ? currentLocation.getLocationId() == null : !BPartnerLocationId.equals(currentLocation.getBpartnerLocationId(), previousLocation.getBpartnerLocationId()); final boolean updateRenderedAddress = isNewRecord || updateCapturedLocation || !currentLocation.equalsIgnoringRenderedAddress(previousLocation); if (updateCapturedLocation || updateRenderedAddress) { locationAdapter.toPlainDocumentLocation(documentLocationBL) .map(location -> updateCapturedLocation ? location.withLocationId(null) : location) .map(documentLocationBL::computeRenderedAddress) .ifPresent(locationAdapter::setRenderedAddressAndCapturedLocation); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\RecordBasedLocationUtils.java
1
请在Spring Boot框架中完成以下Java代码
public final class HttpSessionOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository { private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = HttpSessionOAuth2AuthorizedClientRepository.class .getName() + ".AUTHORIZED_CLIENTS"; private final String sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME; @SuppressWarnings("unchecked") @Override public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(request, "request cannot be null"); return (T) this.getAuthorizedClients(request).get(clientRegistrationId); } @Override public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request); authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient); request.getSession().setAttribute(this.sessionAttributeName, authorizedClients); } @Override public void removeAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request, HttpServletResponse response) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(request, "request cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request); if (!authorizedClients.isEmpty()) { if (authorizedClients.remove(clientRegistrationId) != null) { if (!authorizedClients.isEmpty()) { request.getSession().setAttribute(this.sessionAttributeName, authorizedClients); } else { request.getSession().removeAttribute(this.sessionAttributeName); } } } } @SuppressWarnings("unchecked") private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(HttpServletRequest request) { HttpSession session = request.getSession(false); Map<String, OAuth2AuthorizedClient> authorizedClients = (session != null) ? (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName) : null; if (authorizedClients == null) { authorizedClients = new HashMap<>(); } return authorizedClients; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\HttpSessionOAuth2AuthorizedClientRepository.java
2
请完成以下Java代码
public class DeleteJobCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String jobId; public DeleteJobCmd(String jobId) { this.jobId = jobId; } public Object execute(CommandContext commandContext) { ensureNotNull("jobId", jobId); JobEntity job = commandContext.getJobManager().findJobById(jobId); ensureNotNull("No job found with id '" + jobId + "'", "job", job); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateJob(job); }
// We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.getLockOwner() != null || job.getLockExpirationTime() != null) { throw new ProcessEngineException("Cannot delete job when the job is being executed. Try again later."); } commandContext.getOperationLogManager().logJobOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, jobId, job.getJobDefinitionId(), job.getProcessInstanceId(), job.getProcessDefinitionId(), job.getProcessDefinitionKey(), PropertyChange.EMPTY_CHANGE); job.delete(); return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteJobCmd.java
1
请完成以下Java代码
public class PartyIdentificationSEPA4 { @XmlElement(name = "Nm") protected String nm; @XmlElement(name = "Id") protected PartySEPA2 id; /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link PartySEPA2 } *
*/ public PartySEPA2 getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link PartySEPA2 } * */ public void setId(PartySEPA2 value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PartyIdentificationSEPA4.java
1
请完成以下Java代码
ListenableFuture<Optional<TsKvEntity>> findAndAggregateAsync(EntityId entityId, String key, long startTs, long endTs, long ts, Aggregation aggregation) { return service.submit(() -> { TsKvEntity entity = switchAggregation(entityId, key, startTs, endTs, aggregation); if (entity != null && entity.isNotEmpty()) { entity.setEntityId(entityId.getId()); entity.setStrKey(key); entity.setTs(ts); return Optional.of(entity); } else { return Optional.empty(); } }); } protected TsKvEntity switchAggregation(EntityId entityId, String key, long startTs, long endTs, Aggregation aggregation) { var keyId = keyDictionaryDao.getOrSaveKeyId(key); switch (aggregation) { case AVG: return tsKvRepository.findAvg(entityId.getId(), keyId, startTs, endTs); case MAX: var max = tsKvRepository.findNumericMax(entityId.getId(), keyId, startTs, endTs); if (max.isNotEmpty()) { return max; } else {
return tsKvRepository.findStringMax(entityId.getId(), keyId, startTs, endTs); } case MIN: var min = tsKvRepository.findNumericMin(entityId.getId(), keyId, startTs, endTs); if (min.isNotEmpty()) { return min; } else { return tsKvRepository.findStringMin(entityId.getId(), keyId, startTs, endTs); } case SUM: return tsKvRepository.findSum(entityId.getId(), keyId, startTs, endTs); case COUNT: return tsKvRepository.findCount(entityId.getId(), keyId, startTs, endTs); default: throw new IllegalArgumentException("Not supported aggregation type: " + aggregation); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\AbstractChunkedAggregationTimeseriesDao.java
1
请在Spring Boot框架中完成以下Java代码
public PlatformTwoFaSettings savePlatformTwoFaSettings(TenantId tenantId, PlatformTwoFaSettings twoFactorAuthSettings) throws ThingsboardException { ConstraintValidator.validateFields(twoFactorAuthSettings); for (TwoFaProviderConfig providerConfig : twoFactorAuthSettings.getProviders()) { twoFactorAuthService.checkProvider(tenantId, providerConfig.getProviderType()); } if (tenantId.isSysTenantId()) { if (twoFactorAuthSettings.isEnforceTwoFa()) { if (twoFactorAuthSettings.getProviders().isEmpty()) { throw new DataValidationException("At least one 2FA provider is required if enforcing is enabled"); } if (twoFactorAuthSettings.getEnforcedUsersFilter() == null) { throw new DataValidationException("Users filter to enforce 2FA for is required"); } } } else { twoFactorAuthSettings.setEnforceTwoFa(false); twoFactorAuthSettings.setEnforcedUsersFilter(null); } AdminSettings settings = Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) .orElseGet(() -> { AdminSettings newSettings = new AdminSettings(); newSettings.setKey(TWO_FACTOR_AUTH_SETTINGS_KEY); return newSettings; });
settings.setJsonValue(JacksonUtil.valueToTree(twoFactorAuthSettings)); adminSettingsService.saveAdminSettings(tenantId, settings); return twoFactorAuthSettings; } @Override public void deletePlatformTwoFaSettings(TenantId tenantId) { Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY)) .ifPresent(adminSettings -> adminSettingsDao.removeById(tenantId, adminSettings.getId().getId())); } private void checkAccountTwoFaSettings(TenantId tenantId, User user, AccountTwoFaSettings settings) { if (settings.getConfigs().isEmpty()) { if (twoFactorAuthService.isEnforceTwoFaEnabled(tenantId, user)) { throw new DataValidationException("At least one 2FA provider is required"); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\config\DefaultTwoFaConfigManager.java
2
请完成以下Java代码
public Collection<DocumentFilterDescriptor> getFilterDescriptors() { return getFilterDescriptorsProvider().getAll(); } private List<DocumentFilterDescriptor> createFilterDescriptors() { return ImmutableList.of( createIsCustomerFilterDescriptor(), createIsVendorFilterDescriptor()); } private DocumentFilterDescriptor createIsCustomerFilterDescriptor() { return DocumentFilterDescriptor.builder() .setFilterId(FILTERID_IsCustomer) .setFrequentUsed(true) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_IsCustomer) .displayName(Services.get(IMsgBL.class).translatable(PARAM_IsCustomer)) .widgetType(DocumentFieldWidgetType.YesNo)) .build(); } private DocumentFilterDescriptor createIsVendorFilterDescriptor() { return DocumentFilterDescriptor.builder() .setFilterId(FILTERID_IsVendor) .setFrequentUsed(true) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_IsVendor) .displayName(Services.get(IMsgBL.class).translatable(PARAM_IsVendor)) .widgetType(DocumentFieldWidgetType.YesNo)) .build(); } public static Predicate<PricingConditionsRow> isEditableRowOrMatching(final DocumentFilterList filters) { if (filters.isEmpty()) { return Predicates.alwaysTrue(); }
final boolean showCustomers = filters.getParamValueAsBoolean(FILTERID_IsCustomer, PARAM_IsCustomer, false); final boolean showVendors = filters.getParamValueAsBoolean(FILTERID_IsVendor, PARAM_IsVendor, false); final boolean showAll = !showCustomers && !showVendors; if (showAll) { return Predicates.alwaysTrue(); } return row -> row.isEditable() || ((showCustomers && row.isCustomer()) || (showVendors && row.isVendor())); } public DocumentFilterList extractFilters(@NonNull final JSONFilterViewRequest filterViewRequest) { return filterViewRequest.getFiltersUnwrapped(getFilterDescriptorsProvider()); } public DocumentFilterList extractFilters(@NonNull final CreateViewRequest request) { return request.isUseAutoFilters() ? getDefaultFilters() : request.getFiltersUnwrapped(getFilterDescriptorsProvider()); } private DocumentFilterList getDefaultFilters() { if (defaultFilters == null) { final DocumentFilter isCustomer = DocumentFilter.singleParameterFilter(FILTERID_IsCustomer, PARAM_IsCustomer, Operator.EQUAL, true); defaultFilters = DocumentFilterList.of(isCustomer); } return defaultFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFilters.java
1
请完成以下Java代码
public String toString() { return getCode(); } @NonNull @JsonValue public String getCode() { return code; } public static Set<String> toStringSet(@Nullable final Collection<GLN> glns) { if (glns == null || glns.isEmpty()) { return ImmutableSet.of();
} return glns.stream().map(GLN::getCode).collect(ImmutableSet.toImmutableSet()); } @Nullable public static String toCode(@Nullable final GLN gln) { return gln != null ? gln.getCode() : null; } public static boolean equals(@Nullable final GLN gln1, @Nullable final GLN gln2) { return Objects.equals(gln1, gln2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\GLN.java
1
请在Spring Boot框架中完成以下Java代码
public List<QuoteDTO> findByCriteria(QuoteCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specification<Quote> specification = createSpecification(criteria); return quoteMapper.toDto(quoteRepository.findAll(specification)); } /** * Return a {@link Page} of {@link QuoteDTO} which matches the criteria from the database * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. */ @Transactional(readOnly = true) public Page<QuoteDTO> findByCriteria(QuoteCriteria criteria, Pageable page) { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification<Quote> specification = createSpecification(criteria); return quoteRepository.findAll(specification, page) .map(quoteMapper::toDto); } /** * Return the number of matching entities in the database * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @Transactional(readOnly = true) public long countByCriteria(QuoteCriteria criteria) { log.debug("count by criteria : {}", criteria); final Specification<Quote> specification = createSpecification(criteria); return quoteRepository.count(specification); } /** * Function to convert QuoteCriteria to a {@link Specification}
*/ private Specification<Quote> createSpecification(QuoteCriteria criteria) { Specification<Quote> specification = Specification.where(null); if (criteria != null) { if (criteria.getId() != null) { specification = specification.and(buildSpecification(criteria.getId(), Quote_.id)); } if (criteria.getSymbol() != null) { specification = specification.and(buildStringSpecification(criteria.getSymbol(), Quote_.symbol)); } if (criteria.getPrice() != null) { specification = specification.and(buildRangeSpecification(criteria.getPrice(), Quote_.price)); } if (criteria.getLastTrade() != null) { specification = specification.and(buildRangeSpecification(criteria.getLastTrade(), Quote_.lastTrade)); } } return specification; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\QuoteQueryService.java
2
请完成以下Java代码
public Set<Integer> toIntSet() { return toSet(DocumentId::toInt); } public <ID extends RepoIdAware> ImmutableSet<ID> toIds(@NonNull final Function<Integer, ID> idMapper) { return toSet(idMapper.compose(DocumentId::toInt)); } public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper) { return toSet(documentId -> idMapper.apply(documentId.toInt())); } /** * Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order */ public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper) { return toImmutableList(idMapper.compose(DocumentId::toInt)); } public Set<String> toJsonSet() { if (all) { return ALL_StringSet; } return toSet(DocumentId::toJson); } public SelectionSize toSelectionSize() { if (isAll()) { return SelectionSize.ofAll(); } return SelectionSize.ofSize(size()); } public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection) { if (this.isEmpty()) { return documentIdsSelection; } else if (documentIdsSelection.isEmpty()) { return this; }
if (this.all) { return this; } else if (documentIdsSelection.all) { return documentIdsSelection; } final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet()); final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds); if (this.equals(result)) { return this; } else if (documentIdsSelection.equals(result)) { return documentIdsSelection; } else { return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
1
请完成以下Java代码
public void onBeforeSave_WhenNameOrColumnChanged(final I_AD_Field field) { updateFieldFromElement(field); } private void updateFieldFromElement(final I_AD_Field field) { final AdElementId fieldElementId = getFieldElementIdOrNull(field); if (fieldElementId == null) { // Nothing to do. the element was not yet saved. return; } final I_AD_Element fieldElement = Services.get(IADElementDAO.class).getById(fieldElementId.getRepoId()); field.setName(fieldElement.getName()); field.setDescription(fieldElement.getDescription()); field.setHelp(fieldElement.getHelp()); } private void updateTranslationsForElement(final I_AD_Field field) { final AdElementId fieldElementId = getFieldElementIdOrNull(field); if (fieldElementId == null) { // Nothing to do. the element was not yet saved. return; } final IElementTranslationBL elementTranslationBL = Services.get(IElementTranslationBL.class); elementTranslationBL.updateFieldTranslationsFromAD_Name(fieldElementId); } private AdElementId getFieldElementIdOrNull(final I_AD_Field field) { if (field.getAD_Name_ID() > 0) { return AdElementId.ofRepoId(field.getAD_Name_ID()); }
else if (field.getAD_Column_ID() > 0) { // the AD_Name_ID was set to null. Get back to the values from the AD_Column final I_AD_Column fieldColumn = field.getAD_Column(); return AdElementId.ofRepoId(fieldColumn.getAD_Element_ID()); } else { // Nothing to do. the element was not yet saved. return null; } } private void recreateElementLinkForField(final I_AD_Field field) { final AdFieldId adFieldId = AdFieldId.ofRepoIdOrNull(field.getAD_Field_ID()); if (adFieldId != null) { final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.recreateADElementLinkForFieldId(adFieldId); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void onBeforeFieldDelete(final I_AD_Field field) { final AdFieldId adFieldId = AdFieldId.ofRepoId(field.getAD_Field_ID()); final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); adWindowDAO.deleteUIElementsByFieldId(adFieldId); final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class); elementLinksService.deleteExistingADElementLinkForFieldId(adFieldId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\field\model\interceptor\AD_Field.java
1
请完成以下Java代码
public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public String getProcessDefinitionCategory() { return processDefinitionCategory; } public String getProcessDefinitionName() { return processDefinitionName; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public String getProcessDefinitionKey() { return processDefinitionKey; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getActivityId() { return null; // Unused, see dynamic query } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public String getInvolvedUser() { return involvedUser; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) {
this.nameLike = nameLike; } public String getExecutionId() { return executionId; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isWithJobException() { return withJobException; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Method needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String editPmsMenu(HttpServletRequest req, PmsMenu menu, Model model, DwzAjax dwz) { try { PmsMenu parentMenu = menu.getParent(); if (null == parentMenu) { parentMenu = new PmsMenu(); parentMenu.setId(0L); } menu.setParent(parentMenu); pmsMenuService.update(menu); // 记录系统操作日志 return operateSuccess(model, dwz); } catch (Exception e) { // 记录系统操作日志 log.error("== editPmsMenu exception:", e); return operateError("保存菜单出错", model); } } /** * 删除菜单. * * @return */ @RequiresPermissions("pms:menu:delete") @RequestMapping("/delete") public String delPmsMenu(HttpServletRequest req, Long menuId, Model model, DwzAjax dwz) { try { if (menuId == null || menuId == 0) { return operateError("无法获取要删除的数据", model); } PmsMenu menu = pmsMenuService.getById(menuId); if (menu == null) { return operateError("无法获取要删除的数据", model); } Long parentId = menu.getParent().getId(); // 获取父菜单ID // 先判断此菜单下是否有子菜单 List<PmsMenu> childMenuList = pmsMenuService.listByParentId(menuId); if (childMenuList != null && !childMenuList.isEmpty()) {
return operateError("此菜单下关联有【" + childMenuList.size() + "】个子菜单,不能支接删除!", model); } // 删除掉菜单 pmsMenuService.delete(menuId); // 删除菜单后,要判断其父菜单是否还有子菜单,如果没有子菜单了就要装其父菜单设为叶子节点 List<PmsMenu> childList = pmsMenuService.listByParentId(parentId); if (childList == null || childList.isEmpty()) { // 此时要将父菜单设为叶子 PmsMenu parent = pmsMenuService.getById(parentId); parent.setIsLeaf(PublicEnum.YES.name()); pmsMenuService.update(parent); } // 记录系统操作日志 return operateSuccess(model, dwz); } catch (Exception e) { // 记录系统操作日志 log.error("== delPmsMenu exception:", e); return operateError("删除菜单出错", model); } } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\controller\PmsMenuController.java
2
请完成以下Java代码
void configureSSL(Properties props) { if (sslEnabled) { props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, sslTruststoreLocation); props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, sslTruststorePassword); props.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, sslKeystoreLocation); props.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, sslKeystorePassword); props.put(SslConfigs.SSL_KEY_PASSWORD_CONFIG, sslKeyPassword); } } /* * Temporary solution to avoid major code changes. * FIXME: use single instance of Kafka queue admin, don't create a separate one for each consumer/producer * */ public KafkaAdmin getAdmin() { return kafkaAdmin; } protected Properties toAdminProps() { Properties props = toProps(); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, servers); props.put(AdminClientConfig.RETRIES_CONFIG, retries); return props; }
private Map<String, List<TbProperty>> parseTopicPropertyList(String inlineProperties) { Map<String, List<String>> grouped = PropertyUtils.getGroupedProps(inlineProperties); Map<String, List<TbProperty>> result = new HashMap<>(); grouped.forEach((topic, entries) -> { Map<String, String> merged = new LinkedHashMap<>(); for (String entry : entries) { String[] kv = entry.split("=", 2); if (kv.length == 2) { merged.put(kv[0].trim(), kv[1].trim()); } } List<TbProperty> props = merged.entrySet().stream() .map(e -> new TbProperty(e.getKey(), e.getValue())) .toList(); result.put(topic, props); }); return result; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaSettings.java
1
请完成以下Java代码
protected final <T> T getParentModel(final Class<T> modelType) { return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null; } private int getParentID() { return parentPO != null ? parentPO.get_ID() : -1; } /** * Allows other modules to install customer code to be executed each time a record was copied. */ @Override public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!recordCopiedListeners.contains(listener))
{ recordCopiedListeners.add(listener); } return this; } @Override public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!childRecordCopiedListeners.contains(listener)) { childRecordCopiedListeners.add(listener); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java
1
请完成以下Java代码
public String getId() { return this.id; } @Override public void executionId(ExecutionId executionId) { Assert.notNull(executionId, "executionId is required"); this.executionId = executionId; } @Override public @Nullable ExecutionId getExecutionId() { return this.executionId; } @Override public Locale getLocale() { return this.locale; } @Override public void configureExecutionInput(BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer) { this.executionInputConfigurers.add(configurer); } @Override public ExecutionInput toExecutionInput() {
ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput() .query(getDocument()) .operationName(getOperationName()) .variables(getVariables()) .extensions(getExtensions()) .locale(this.locale) .executionId((this.executionId != null) ? this.executionId : ExecutionId.from(this.id)); ExecutionInput executionInput = inputBuilder.build(); for (BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer : this.executionInputConfigurers) { ExecutionInput current = executionInput; executionInput = executionInput.transform((builder) -> configurer.apply(current, builder)); } return executionInput; } @Override public String toString() { return super.toString() + ", id=" + getId() + ", Locale=" + getLocale(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\DefaultExecutionGraphQlRequest.java
1
请完成以下Java代码
default List<String> getTokenRevocationEndpointAuthenticationMethods() { return getClaimAsStringList( OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED); } /** * Returns the {@code URL} of the OAuth 2.0 Token Introspection Endpoint * {@code (introspection_endpoint)}. * @return the {@code URL} of the OAuth 2.0 Token Introspection Endpoint */ default URL getTokenIntrospectionEndpoint() { return getClaimAsURL(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT); } /** * Returns the client authentication methods supported by the OAuth 2.0 Token * Introspection Endpoint {@code (introspection_endpoint_auth_methods_supported)}. * @return the client authentication methods supported by the OAuth 2.0 Token * Introspection Endpoint */ default List<String> getTokenIntrospectionEndpointAuthenticationMethods() { return getClaimAsStringList( OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED); } /** * Returns the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint * {@code (registration_endpoint)}. * @return the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint */ default URL getClientRegistrationEndpoint() { return getClaimAsURL(OAuth2AuthorizationServerMetadataClaimNames.REGISTRATION_ENDPOINT); } /** * Returns the Proof Key for Code Exchange (PKCE) {@code code_challenge_method} values * supported {@code (code_challenge_methods_supported)}. * @return the {@code code_challenge_method} values supported */ default List<String> getCodeChallengeMethods() { return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED); } /**
* Returns {@code true} to indicate support for mutual-TLS client certificate-bound * access tokens {@code (tls_client_certificate_bound_access_tokens)}. * @return {@code true} to indicate support for mutual-TLS client certificate-bound * access tokens, {@code false} otherwise */ default boolean isTlsClientCertificateBoundAccessTokens() { return Boolean.TRUE.equals(getClaimAsBoolean( OAuth2AuthorizationServerMetadataClaimNames.TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS)); } /** * Returns the {@link JwsAlgorithms JSON Web Signature (JWS) algorithms} supported for * DPoP Proof JWTs {@code (dpop_signing_alg_values_supported)}. * @return the {@link JwsAlgorithms JSON Web Signature (JWS) algorithms} supported for * DPoP Proof JWTs */ default List<String> getDPoPSigningAlgorithms() { return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.DPOP_SIGNING_ALG_VALUES_SUPPORTED); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationServerMetadataClaimAccessor.java
1
请完成以下Java代码
public void multiplyIncorrectMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void inverseMatrix() { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2}, {3, 4} }); Inverse m2 = new Inverse(m1); log.info("Inverting a matrix: {}", m2); log.info("Verifying a matrix inverse: {}", m1.multiply(m2));
} public Polynomial createPolynomial() { return new Polynomial(new double[]{3, -5, 1}); } public void evaluatePolynomial(Polynomial p) { // Evaluate using a real number log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5)); // Evaluate using a complex number log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2))); } public void solvePolynomial() { Polynomial p = new Polynomial(new double[]{2, 2, -4}); PolyRootSolver solver = new PolyRoot(); List<? extends Number> roots = solver.solve(p); log.info("Finding polynomial roots: {}", roots); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\suanshu\SuanShuMath.java
1
请完成以下Java代码
public String getEmail() { return email; } @Override public void setEmail(String email) { // Not supported } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getTenantId() { return tenantId; }
@Override public void setTenantId(String tenantId) { // Not supported } @Override public boolean isPictureSet() { return false; } public static UserDto create(User user) { return new UserDto(user.getId(), user.getPassword(), user.getFirstName(), user.getLastName(), user.getDisplayName(), user.getEmail(), user.getTenantId()); } }
repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\UserDto.java
1
请完成以下Java代码
public Collection<Sentry> getExitCriterias() { return exitCriteriaRefCollection.getReferenceTargetElements(this); } public Collection<Sentry> getExitCriteria() { if (!isCmmn11()) { return Collections.unmodifiableCollection(getExitCriterias()); } else { List<Sentry> sentries = new ArrayList<Sentry>(); Collection<ExitCriterion> exitCriterions = getExitCriterions(); for (ExitCriterion exitCriterion : exitCriterions) { Sentry sentry = exitCriterion.getSentry(); if (sentry != null) { sentries.add(sentry); } } return Collections.unmodifiableCollection(sentries); } } public Collection<ExitCriterion> getExitCriterions() { return exitCriterionCollection.get(this); } public PlanningTable getPlanningTable() { return planningTableChild.getChild(this); } public void setPlanningTable(PlanningTable planningTable) { planningTableChild.setChild(this, planningTable); } public Collection<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitionCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Stage.class, CMMN_ELEMENT_STAGE) .namespaceUri(CMMN11_NS) .extendsType(PlanFragment.class) .instanceProvider(new ModelTypeInstanceProvider<Stage>() { public Stage newInstance(ModelTypeInstanceContext instanceContext) { return new StageImpl(instanceContext); } }); autoCompleteAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_AUTO_COMPLETE)
.defaultValue(false) .build(); exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS) .namespace(CMMN10_NS) .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); planningTableChild = sequenceBuilder.element(PlanningTable.class) .build(); planItemDefinitionCollection = sequenceBuilder.elementCollection(PlanItemDefinition.class) .build(); exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\StageImpl.java
1
请在Spring Boot框架中完成以下Java代码
public CustomEndpoint customEndpoint() { return new CustomEndpoint(); } // tag::customization-http-headers-providers[] @Bean public HttpHeadersProvider customHttpHeadersProvider() { return (instance) -> { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("X-CUSTOM", "My Custom Value"); return httpHeaders; }; } // end::customization-http-headers-providers[] @Bean public HttpExchangeRepository httpTraceRepository() {
return new InMemoryHttpExchangeRepository(); } @Bean public AuditEventRepository auditEventRepository() { return new InMemoryAuditEventRepository(); } @Bean public EmbeddedDatabase dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) .addScript("org/springframework/session/jdbc/schema-hsqldb.sql") .build(); } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminServletApplication.java
2
请完成以下Java代码
public class ListLoadedClassesAgent { private static Instrumentation instrumentation; public static void premain(String agentArgs, Instrumentation instrumentation) { ListLoadedClassesAgent.instrumentation = instrumentation; } public static Class<?>[] listLoadedClasses(String classLoaderType) { if (instrumentation == null) { throw new IllegalStateException( "ListLoadedClassesAgent is not initialized."); } return instrumentation.getInitiatedClasses( getClassLoader(classLoaderType)); } private static ClassLoader getClassLoader(String classLoaderType) { ClassLoader classLoader = null;
switch (classLoaderType) { case "SYSTEM": classLoader = ClassLoader.getSystemClassLoader(); break; case "EXTENSION": classLoader = ClassLoader.getSystemClassLoader().getParent(); break; // passing a null value to the Instrumentation : getInitiatedClasses method // defaults to the bootstrap class loader case "BOOTSTRAP": break; default: break; } return classLoader; } }
repos\tutorials-master\core-java-modules\core-java-jvm-2\src\main\java\com\baeldung\loadedclasslisting\ListLoadedClassesAgent.java
1
请完成以下Java代码
public HistoricIdentityLinkLogQuery orderByProcessDefinitionId() { orderBy(HistoricIdentityLinkLogQueryProperty.PROC_DEFINITION_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByProcessDefinitionKey() { orderBy(HistoricIdentityLinkLogQueryProperty.PROC_DEFINITION_KEY); return this; } @Override public HistoricIdentityLinkLogQuery orderByOperationType() { orderBy(HistoricIdentityLinkLogQueryProperty.OPERATION_TYPE); return this; } @Override public HistoricIdentityLinkLogQuery orderByAssignerId() { orderBy(HistoricIdentityLinkLogQueryProperty.ASSIGNER_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByTenantId() { orderBy(HistoricIdentityLinkLogQueryProperty.TENANT_ID); return this; } @Override
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogCountByQueryCriteria(this); } @Override public List<HistoricIdentityLinkLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIdentityLinkLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static class HUPIItemProductLUTUSpec implements LUTUSpec { public static final HUPIItemProductLUTUSpec VIRTUAL = new HUPIItemProductLUTUSpec(HUPIItemProductId.VIRTUAL_HU, null); @NonNull HUPIItemProductId tuPIItemProductId; @Nullable HuPackingInstructionsItemId luPIItemId; public static HUPIItemProductLUTUSpec topLevelTU(@NonNull HUPIItemProductId tuPIItemProductId) { return tuPIItemProductId.isVirtualHU() ? VIRTUAL : new HUPIItemProductLUTUSpec(tuPIItemProductId, null); } public static HUPIItemProductLUTUSpec lu(@NonNull HUPIItemProductId tuPIItemProductId, @NonNull HuPackingInstructionsItemId luPIItemId) { return new HUPIItemProductLUTUSpec(tuPIItemProductId, luPIItemId);
} public boolean isTopLevelVHU() { return tuPIItemProductId.isVirtualHU() && luPIItemId == null; } } @Value(staticConstructor = "of") private static class PreciseTUSpec implements LUTUSpec { @NonNull HuPackingInstructionsId tuPackingInstructionsId; @NonNull Quantity qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\AbstractPPOrderReceiptHUProducer.java
2
请完成以下Java代码
public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_WorkPackage getC_Queue_WorkPackage() { return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_WorkPackage(de.metas.async.model.I_C_Queue_WorkPackage C_Queue_WorkPackage) { set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, C_Queue_WorkPackage); } /** Set WorkPackage Queue. @param C_Queue_WorkPackage_ID WorkPackage Queue */ @Override public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID) { if (C_Queue_WorkPackage_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID)); } /** Get WorkPackage Queue. @return WorkPackage Queue */ @Override public int getC_Queue_WorkPackage_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Workpackage audit/log table. @param C_Queue_WorkPackage_Log_ID Workpackage audit/log table */ @Override public void setC_Queue_WorkPackage_Log_ID (int C_Queue_WorkPackage_Log_ID) { if (C_Queue_WorkPackage_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, Integer.valueOf(C_Queue_WorkPackage_Log_ID)); } /** Get Workpackage audit/log table.
@return Workpackage audit/log table */ @Override public int getC_Queue_WorkPackage_Log_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Log_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Log.java
1
请在Spring Boot框架中完成以下Java代码
public class SnapshottingInstanceRepository extends EventsourcingInstanceRepository { private static final Logger log = LoggerFactory.getLogger(SnapshottingInstanceRepository.class); private final ConcurrentMap<InstanceId, Instance> snapshots = new ConcurrentHashMap<>(); private final Set<InstanceId> outdatedSnapshots = ConcurrentHashMap.newKeySet(); private final InstanceEventStore eventStore; @Nullable private Disposable subscription; public SnapshottingInstanceRepository(InstanceEventStore eventStore) { super(eventStore); this.eventStore = eventStore; } @Override public Flux<Instance> findAll() { return Mono.fromSupplier(this.snapshots::values).flatMapIterable(Function.identity()); } @Override public Mono<Instance> find(InstanceId id) { return Mono.defer(() -> { if (!this.outdatedSnapshots.contains(id)) { return Mono.justOrEmpty(this.snapshots.get(id)); } else { return rehydrateSnapshot(id).doOnSuccess((v) -> this.outdatedSnapshots.remove(v.getId())); } }); } @Override public Mono<Instance> save(Instance instance) { return super.save(instance).doOnError(OptimisticLockingException.class, (e) -> this.outdatedSnapshots.add(instance.getId())); } public void start() { this.subscription = this.eventStore.findAll().concatWith(this.eventStore).subscribe(this::updateSnapshot); } public void stop() { if (this.subscription != null) { this.subscription.dispose(); this.subscription = null;
} } protected Mono<Instance> rehydrateSnapshot(InstanceId id) { return super.find(id).map((instance) -> this.snapshots.compute(id, (key, snapshot) -> { // check if the loaded version hasn't been already outdated by a snapshot if (snapshot == null || instance.getVersion() >= snapshot.getVersion()) { return instance; } else { return snapshot; } })); } protected void updateSnapshot(InstanceEvent event) { try { this.snapshots.compute(event.getInstance(), (key, old) -> { Instance instance = (old != null) ? old : Instance.create(key); if (event.getVersion() > instance.getVersion()) { return instance.apply(event); } return instance; }); } catch (Exception ex) { log.warn("Error while updating the snapshot with event {}", event, ex); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\SnapshottingInstanceRepository.java
2
请完成以下Java代码
class UnboundConfigurationPropertyFailureAnalyzer extends AbstractFailureAnalyzer<UnboundConfigurationPropertiesException> { @Override protected FailureAnalysis analyze(Throwable rootFailure, UnboundConfigurationPropertiesException cause) { BindException exception = findCause(rootFailure, BindException.class); Assert.state(exception != null, "BindException not found"); return analyzeUnboundConfigurationPropertiesException(exception, cause); } private FailureAnalysis analyzeUnboundConfigurationPropertiesException(BindException cause, UnboundConfigurationPropertiesException exception) { StringBuilder description = new StringBuilder( String.format("Binding to target %s failed:%n", cause.getTarget())); for (ConfigurationProperty property : exception.getUnboundProperties()) { buildDescription(description, property); description.append(String.format("%n Reason: %s", exception.getMessage())); } return getFailureAnalysis(description, cause);
} private void buildDescription(StringBuilder description, @Nullable ConfigurationProperty property) { if (property != null) { description.append(String.format("%n Property: %s", property.getName())); description.append(String.format("%n Value: \"%s\"", property.getValue())); description.append(String.format("%n Origin: %s", property.getOrigin())); } } private FailureAnalysis getFailureAnalysis(Object description, BindException cause) { return new FailureAnalysis(description.toString(), "Update your application's configuration", cause); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\UnboundConfigurationPropertyFailureAnalyzer.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrderRequestedEventHandler implements MaterialEventHandler<PPOrderRequestedEvent> { private final IPPOrderBL ppOrderService = Services.get(IPPOrderBL.class); private final IProductBL productBL = Services.get(IProductBL.class); @Override public Collection<Class<? extends PPOrderRequestedEvent>> getHandledEventType() { return ImmutableList.of(PPOrderRequestedEvent.class); } @Override public void handleEvent(@NonNull final PPOrderRequestedEvent event) { createProductionOrder(event); } /** * Creates a production order. Note that it does not fire an event, because production orders can be created and changed for many reasons,<br> * and therefore we leave the event-firing to a model interceptor. */ @VisibleForTesting I_PP_Order createProductionOrder(@NonNull final PPOrderRequestedEvent ppOrderRequestedEvent) { final PPOrder ppOrder = ppOrderRequestedEvent.getPpOrder(); final PPOrderData ppOrderData = ppOrder.getPpOrderData(); final Instant dateOrdered = ppOrderRequestedEvent.getDateOrdered();
final ProductId productId = ProductId.ofRepoId(ppOrderData.getProductDescriptor().getProductId()); final I_C_UOM uom = productBL.getStockUOM(productId); final Quantity qtyRequired = Quantity.of(ppOrderData.getQtyRequired(), uom); return ppOrderService.createOrder(PPOrderCreateRequest.builder() .clientAndOrgId(ppOrderData.getClientAndOrgId()) .productPlanningId(ProductPlanningId.ofRepoIdOrNull(ppOrderData.getProductPlanningId())) .materialDispoGroupId(ppOrderData.getMaterialDispoGroupId()) .plantId(ppOrderData.getPlantId()) .workstationId(ppOrderData.getWorkstationId()) .warehouseId(ppOrderData.getWarehouseId()) // .productId(productId) .attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNone(ppOrderData.getProductDescriptor().getAttributeSetInstanceId())) .qtyRequired(qtyRequired) // .dateOrdered(dateOrdered) .datePromised(ppOrderData.getDatePromised()) .dateStartSchedule(ppOrderData.getDateStartSchedule()) // .shipmentScheduleId(ShipmentScheduleId.ofRepoIdOrNull(ppOrderData.getShipmentScheduleIdAsRepoId())) .salesOrderLineId(OrderLineId.ofRepoIdOrNull(ppOrderData.getOrderLineIdAsRepoId())) // .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\event\PPOrderRequestedEventHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/") .setViewName("index"); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { JsonArgumentResolver jsonArgumentResolver = new JsonArgumentResolver(); argumentResolvers.add(jsonArgumentResolver); } @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } /** Static resource locations */
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/", "/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } @Bean public BeanNameViewResolver beanNameViewResolver() { BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver(); beanNameViewResolver.setOrder(1); return beanNameViewResolver; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-5\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
public ModelQuery createNewModelQuery() { return new ModelQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutor()); } @SuppressWarnings("unchecked") public List<Model> findModelsByQueryCriteria(ModelQueryImpl query, Page page) { return getDbSqlSession().selectList("selectModelsByQueryCriteria", query, page); } public long findModelCountByQueryCriteria(ModelQueryImpl query) { return (Long) getDbSqlSession().selectOne("selectModelCountByQueryCriteria", query); } public ModelEntity findModelById(String modelId) { return (ModelEntity) getDbSqlSession().selectOne("selectModel", modelId); } public byte[] findEditorSourceByModelId(String modelId) { ModelEntity model = findModelById(modelId); if (model == null || model.getEditorSourceValueId() == null) { return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId()); return ref.getBytes(); } public byte[] findEditorSourceExtraByModelId(String modelId) { ModelEntity model = findModelById(modelId); if (model == null || model.getEditorSourceExtraValueId() == null) {
return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId()); return ref.getBytes(); } @SuppressWarnings("unchecked") public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return getDbSqlSession().selectListWithRawParameter("selectModelByNativeQuery", parameterMap, firstResult, maxResults); } public long findModelCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectModelCountByNativeQuery", parameterMap); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityManager.java
1
请完成以下Java代码
public static POSOrderId ofRepoId(final int repoId) { return new POSOrderId(repoId); } @Nullable public static POSOrderId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new POSOrderId(repoId) : null; } public static int toRepoId(@Nullable final OrderId orderId) { return orderId != null ? orderId.getRepoId() : -1; }
@Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final POSOrderId id1, @Nullable final POSOrderId id2) { return Objects.equals(id1, id2); } public TableRecordReference toRecordRef() {return TableRecordReference.of(I_C_POS_Order.Table_Name, repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderId.java
1
请完成以下Java代码
public void save(@NonNull final TreeNode treeNode) { final I_AD_TreeNode existingRecord = retrieveTreeNodeRecord(treeNode.getNodeId(), treeNode.getChartOfAccountsTreeId()); if (existingRecord == null) { createNew(treeNode); } else { updateRecordAndSave(existingRecord, treeNode); } } private void createNew(@NonNull final TreeNode treeNode) { final I_AD_TreeNode record = newInstance(I_AD_TreeNode.class); updateRecordAndSave(record, treeNode); } private void updateRecordAndSave(final I_AD_TreeNode record, final @NonNull TreeNode from) { record.setAD_Tree_ID(from.getChartOfAccountsTreeId().getRepoId()); record.setNode_ID(from.getNodeId().getRepoId()); record.setParent_ID(from.getParentId() != null ? from.getParentId().getRepoId() : 0); record.setSeqNo(from.getSeqNo()); saveRecord(record); } private I_AD_TreeNode retrieveTreeNodeRecord(@NonNull final ElementValueId elementValueId, @NonNull final AdTreeId chartOfAccountsTreeId) { return queryBL.createQueryBuilder(I_AD_TreeNode.class) .addEqualsFilter(I_AD_TreeNode.COLUMNNAME_AD_Tree_ID, chartOfAccountsTreeId) .addEqualsFilter(I_AD_TreeNode.COLUMNNAME_Node_ID, elementValueId) .create() .firstOnly(I_AD_TreeNode.class); } public Optional<TreeNode> getTreeNode(@NonNull final ElementValueId elementValueId, @NonNull final AdTreeId chartOfAccountsTreeId) { final I_AD_TreeNode treeNodeRecord = retrieveTreeNodeRecord(elementValueId, chartOfAccountsTreeId); return treeNodeRecord != null ? Optional.of(toTreeNode(treeNodeRecord)) : Optional.empty(); } public void recreateTree(@NonNull final List<TreeNode> treeNodes) { final AdTreeId chartOfAccountsTreeId = extractSingleChartOfAccountsTreeId(treeNodes); deleteByTreeId(chartOfAccountsTreeId); treeNodes.forEach(this::createNew); } private static AdTreeId extractSingleChartOfAccountsTreeId(final @NonNull List<TreeNode> treeNodes) { final ImmutableSet<AdTreeId> chartOfAccountsTreeIds = treeNodes.stream()
.map(TreeNode::getChartOfAccountsTreeId) .collect(ImmutableSet.toImmutableSet()); return CollectionUtils.singleElement(chartOfAccountsTreeIds); } private void deleteByTreeId(final AdTreeId chartOfAccountsTreeId) { queryBL.createQueryBuilder(I_AD_TreeNode.class) .addEqualsFilter(I_AD_TreeNode.COLUMNNAME_AD_Tree_ID, chartOfAccountsTreeId) .create() .deleteDirectly(); } public ImmutableSet<TreeNode> getByTreeId(final AdTreeId chartOfAccountsTreeId) { return queryBL.createQueryBuilder(I_AD_TreeNode.class) .addEqualsFilter(I_AD_TreeNode.COLUMNNAME_AD_Tree_ID, chartOfAccountsTreeId) .create() .stream() .map(TreeNodeRepository::toTreeNode) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\treenode\TreeNodeRepository.java
1
请完成以下Java代码
public IFacetCollectorResult<ModelType> build() { // If there was nothing added to this builder, return the empty instance (optimization) if (isEmpty()) { return EmptyFacetCollectorResult.getInstance(); } return new FacetCollectorResult<>(this); } /** @return true if this builder is empty */ private final boolean isEmpty() { return facets.isEmpty() && facetCategories.isEmpty(); } public Builder<ModelType> addFacetCategory(final IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null"); facetCategories.add(facetCategory); return this; } public Builder<ModelType> addFacet(final IFacet<ModelType> facet) { Check.assumeNotNull(facet, "facet not null"); facets.add(facet); facetCategories.add(facet.getFacetCategory()); return this; } public Builder<ModelType> addFacets(final Iterable<IFacet<ModelType>> facets) { Check.assumeNotNull(facets, "facet not null"); for (final IFacet<ModelType> facet : facets)
{ addFacet(facet); } return this; } /** @return true if there was added at least one facet */ public boolean hasFacets() { return !facets.isEmpty(); } public Builder<ModelType> addFacetCollectorResult(final IFacetCollectorResult<ModelType> facetCollectorResult) { // NOTE: we need to add the categories first, to make sure we preserve the order of categories this.facetCategories.addAll(facetCollectorResult.getFacetCategories()); this.facets.addAll(facetCollectorResult.getFacets()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCollectorResult.java
1
请在Spring Boot框架中完成以下Java代码
public class GemfireConfiguration { @Autowired EmployeeRepository employeeRepository; @Autowired FunctionExecution functionExecution; @Bean Properties gemfireProperties() { Properties gemfireProperties = new Properties(); gemfireProperties.setProperty("name", "SpringDataGemFireApplication"); gemfireProperties.setProperty("mcast-port", "0"); gemfireProperties.setProperty("log-level", "config"); return gemfireProperties; } @Bean @Autowired CacheFactoryBean gemfireCache() {
CacheFactoryBean gemfireCache = new CacheFactoryBean(); gemfireCache.setClose(true); gemfireCache.setProperties(gemfireProperties()); return gemfireCache; } @Bean(name="employee") @Autowired LocalRegionFactoryBean<String, Employee> getEmployee(final GemFireCache cache) { LocalRegionFactoryBean<String, Employee> employeeRegion = new LocalRegionFactoryBean<String, Employee>(); employeeRegion.setCache(cache); employeeRegion.setClose(false); employeeRegion.setName("employee"); employeeRegion.setPersistent(false); employeeRegion.setDataPolicy(DataPolicy.PRELOADED); return employeeRegion; } }
repos\tutorials-master\persistence-modules\spring-data-gemfire\src\main\java\com\baeldung\spring\data\gemfire\function\GemfireConfiguration.java
2
请完成以下Java代码
public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Post)) { return false; } Post post = (Post) o; return getId().equals(post.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\aggregation\model\Post.java
1
请完成以下Java代码
public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { throw new UnsupportedOperationException(); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamTopLevelRowsByIds(rowIds); } public List<PurchaseRow> getRows() { return rows.getAll(); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { } @Override public void patchViewRow(
@NonNull final RowEditingContext ctx, @NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests) { final PurchaseRowId idOfChangedRow = PurchaseRowId.fromDocumentId(ctx.getRowId()); final PurchaseRowChangeRequest rowChangeRequest = PurchaseRowChangeRequest.of(fieldChangeRequests); patchViewRow(idOfChangedRow, rowChangeRequest); } public void patchViewRow( @NonNull final PurchaseRowId idOfChangedRow, @NonNull final PurchaseRowChangeRequest rowChangeRequest) { rows.patchRow(idOfChangedRow, rowChangeRequest); // notify the frontend final DocumentId groupRowDocumentId = idOfChangedRow.toGroupRowId().toDocumentId(); ViewChangesCollector .getCurrentOrAutoflush() .collectRowChanged(this, groupRowDocumentId); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseView.java
1
请在Spring Boot框架中完成以下Java代码
public Result<String> edit(@RequestBody SysComment sysComment) { sysCommentService.updateById(sysComment); return Result.OK("编辑成功!"); } /** * 通过id删除 * * @param id * @return */ //@AutoLog(value = "系统评论回复表-通过id删除") @Operation(summary = "系统评论回复表-通过id删除") //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:delete") @DeleteMapping(value = "/delete") public Result<String> delete(@RequestParam(name = "id", required = true) String id) { sysCommentService.removeById(id); return Result.OK("删除成功!"); } /** * 批量删除 * * @param ids * @return */ //@AutoLog(value = "系统评论回复表-批量删除") @Operation(summary = "系统评论回复表-批量删除") //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:deleteBatch") @DeleteMapping(value = "/deleteBatch") public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.sysCommentService.removeByIds(Arrays.asList(ids.split(","))); return Result.OK("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ //@AutoLog(value = "系统评论回复表-通过id查询") @Operation(summary = "系统评论回复表-通过id查询") @GetMapping(value = "/queryById") public Result<SysComment> queryById(@RequestParam(name = "id", required = true) String id) { SysComment sysComment = sysCommentService.getById(id); if (sysComment == null) { return Result.error("未找到对应数据"); } return Result.OK(sysComment); } /**
* 导出excel * * @param request * @param sysComment */ //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:exportXls") @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, SysComment sysComment) { return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表"); } /** * 通过excel导入数据 * * @param request * @param response * @return */ //@RequiresPermissions("sys_comment:importExcel") @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, SysComment.class); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCommentController.java
2
请完成以下Java代码
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { // TODO Auto-generated method stub return false; } @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { // TODO Auto-generated method stub return false; } @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { // TODO Auto-generated method stub } @Override public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException { // TODO Auto-generated method stub } @Override public void onCollectionRemove(Object collection, Serializable key) throws CallbackException { // TODO Auto-generated method stub } @Override public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException { // TODO Auto-generated method stub } @Override public void preFlush(Iterator entities) throws CallbackException { // TODO Auto-generated method stub } @Override public void postFlush(Iterator entities) throws CallbackException { // TODO Auto-generated method stub } @Override public Boolean isTransient(Object entity) { // TODO Auto-generated method stub return null; } @Override public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { // TODO Auto-generated method stub return null; } @Override public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException { // TODO Auto-generated method stub return null; }
@Override public String getEntityName(Object object) throws CallbackException { // TODO Auto-generated method stub return null; } @Override public Object getEntity(String entityName, Serializable id) throws CallbackException { // TODO Auto-generated method stub return null; } @Override public void afterTransactionBegin(Transaction tx) { // TODO Auto-generated method stub } @Override public void beforeTransactionCompletion(Transaction tx) { // TODO Auto-generated method stub } @Override public void afterTransactionCompletion(Transaction tx) { // TODO Auto-generated method stub } @Override public String onPrepareStatement(String sql) { // TODO Auto-generated method stub return null; } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\CustomInterceptorImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorShallowRepository authorShallowRepository; private final AuthorDeepRepository authorDeepRepository; public BookstoreService(AuthorShallowRepository authorShallowRepository, AuthorDeepRepository authorDeepRepository) { this.authorShallowRepository = authorShallowRepository; this.authorDeepRepository = authorDeepRepository; } @Transactional public void createAuthors() throws IOException { AuthorDeep mt = new AuthorDeep(); mt.setId(1L); mt.setName("Martin Ticher"); mt.setAge(43); mt.setGenre("Horror"); mt.setAvatar(Files.readAllBytes(new File("avatars/mt.png").toPath())); AuthorDeep cd = new AuthorDeep(); cd.setId(2L); cd.setName("Carla Donnoti"); cd.setAge(31); cd.setGenre("Science Fiction"); cd.setAvatar(Files.readAllBytes(new File("avatars/cd.png").toPath())); AuthorDeep re = new AuthorDeep(); re.setId(3L); re.setName("Rennata Elibol");
re.setAge(46); re.setGenre("Fantasy"); re.setAvatar(Files.readAllBytes(new File("avatars/re.png").toPath())); authorDeepRepository.save(mt); authorDeepRepository.save(cd); authorDeepRepository.save(re); } public List<AuthorShallow> fetchAuthorsShallow() { List<AuthorShallow> authors = authorShallowRepository.findAll(); return authors; } public List<AuthorDeep> fetchAuthorsDeep() { List<AuthorDeep> authors = authorDeepRepository.findAll(); return authors; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSubentities\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
class DeepSeekModelOutputConverter implements StructuredOutputConverter<DeepSeekModelResponse> { private static final Logger logger = LoggerFactory.getLogger(DeepSeekModelOutputConverter.class); private static final String OPENING_THINK_TAG = "<think>"; private static final String CLOSING_THINK_TAG = "</think>"; @Override public DeepSeekModelResponse convert(@NonNull String text) { if (!StringUtils.hasText(text)) { throw new IllegalArgumentException("Text cannot be blank"); } int openingThinkTagIndex = text.indexOf(OPENING_THINK_TAG); int closingThinkTagIndex = text.indexOf(CLOSING_THINK_TAG); if (openingThinkTagIndex != -1 && closingThinkTagIndex != -1 && closingThinkTagIndex > openingThinkTagIndex) { String chainOfThought = text.substring(openingThinkTagIndex + OPENING_THINK_TAG.length(), closingThinkTagIndex); String answer = text.substring(closingThinkTagIndex + CLOSING_THINK_TAG.length()); return new DeepSeekModelResponse(chainOfThought, answer); } else { logger.debug("No <think> tags found in the response. Treating entire text as answer."); return new DeepSeekModelResponse(null, text); } }
/** * This method is used to define instructions for formatting the AI model's response, * which are appended to the user prompt. * See {@link org.springframework.ai.converter.BeanOutputConverter#getFormat()} for reference. * * However, in the current implementation, we extract only the AI response and its chain of thought, * so no formatting instructions are needed. */ @Override public String getFormat() { return null; } }
repos\tutorials-master\spring-ai-modules\spring-ai\src\main\java\com\baeldung\springai\deepseek\DeepSeekModelOutputConverter.java
1
请完成以下Java代码
public void setCodeset ( String codeset ) { this.codeset = codeset; } /** * Gets the codeset for this XhtmlDocument * * @return the codeset */ public String getCodeset() { return this.codeset; } /** Write the container to the OutputStream */ public void output(OutputStream out) { if (doctype != null) { doctype.output(out); try { out.write('\n'); } catch ( Exception e) {} } // XhtmlDocument is just a convient wrapper for html call html.output html.output(out); } /** Write the container to the PrinteWriter */ public void output(PrintWriter out) { if (doctype != null) { doctype.output(out); try { out.write('\n'); } catch ( Exception e) {} } // XhtmlDocument is just a convient wrapper for html call html.output html.output(out); } /** Override the toString() method so that it prints something meaningful. */ public final String toString() { StringBuffer sb = new StringBuffer(); if ( getCodeset() != null ) { if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset()));
return (sb.toString()); } else { if (doctype != null) sb.append (doctype.toString()); sb.append (html.toString()); return(sb.toString()); } } /** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { StringBuffer sb = new StringBuffer(); if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return(sb.toString()); } /** Allows the document to be cloned. Doesn't return an instance of document returns instance of html. NOTE: If you have a doctype set, then it will be lost. Feel free to submit a patch to fix this. It isn't trivial. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlDocument.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { private static final String[] WHITELISTED_API_ENDPOINTS = { "/users" }; private static final String CUSTOM_COMPROMISED_PASSWORD_CHECK_URL = "https://api.example.com/password-check"; @Bean @SneakyThrows public SecurityFilterChain configure(final HttpSecurity http) { http.csrf(csrfConfigurer -> csrfConfigurer.disable()) .sessionManagement( sessionConfigurer -> sessionConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(authManager -> { authManager.requestMatchers(WHITELISTED_API_ENDPOINTS).permitAll().anyRequest().authenticated(); }); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder();
} @Bean @ConditionalOnMissingBean public CompromisedPasswordChecker compromisedPasswordChecker() { return new HaveIBeenPwnedRestApiPasswordChecker(); } @Bean @ConditionalOnMissingBean public CompromisedPasswordChecker customCompromisedPasswordChecker() { RestClient customRestClient = RestClient.builder().baseUrl(CUSTOM_COMPROMISED_PASSWORD_CHECK_URL) .defaultHeader("X-API-KEY", "api-key").build(); HaveIBeenPwnedRestApiPasswordChecker compromisedPasswordChecker = new HaveIBeenPwnedRestApiPasswordChecker(); compromisedPasswordChecker.setRestClient(customRestClient); return compromisedPasswordChecker; } }
repos\tutorials-master\spring-security-modules\spring-security-compromised-password\src\main\java\com\baeldung\security\configuration\SecurityConfiguration.java
2
请完成以下Java代码
public class CandidateStartersDeploymentConfigurer implements ProcessEngineConfigurationConfigurer { private static final String EVERYONE_GROUP = "*"; @Override public void configure(SpringProcessEngineConfiguration processEngineConfiguration) { processEngineConfiguration.setBpmnDeploymentHelper(new CandidateStartersDeploymentHelper()); } public class CandidateStartersDeploymentHelper extends BpmnDeploymentHelper { @Override public void addAuthorizationsForNewProcessDefinition( Process process, ProcessDefinitionEntity processDefinition ) {
super.addAuthorizationsForNewProcessDefinition(process, processDefinition); if ( process != null && !process.isCandidateStarterUsersDefined() && !process.isCandidateStarterGroupsDefined() ) { addAuthorizationsFromIterator( Context.getCommandContext(), List.of(EVERYONE_GROUP), processDefinition, ExpressionType.GROUP ); } } } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\CandidateStartersDeploymentConfigurer.java
1
请完成以下Java代码
public String getName() { return "AD_ChangeLog_ID"; } @Override public String getIcon() { return "ChangeLog16"; } @Override public boolean isAvailable() { return true; } @Override public boolean isRunnable() {
final GridField gridField = getEditor().getField(); if (gridField == null) { return false; } return true; } @Override public void run() { final GridField gridField = getEditor().getField(); FieldRecordInfo.start(gridField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\RecordInfoContextMenuAction.java
1
请完成以下Java代码
public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取HttpServletRequest */ public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } /** * 获取HttpServletResponse */ public static HttpServletResponse getHttpServletResponse() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); } /** * 获取项目根路径 basePath */ public static String getDomain(){ HttpServletRequest request = getHttpServletRequest(); StringBuffer url = request.getRequestURL(); //1.微服务情况下,获取gateway的basePath String basePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH); if(oConvertUtils.isNotEmpty(basePath)){ return basePath; }else{ String domain = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); //2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题 // https://blog.csdn.net/weixin_34376986/article/details/89767950 String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME); if(scheme!=null && !request.getScheme().equals(scheme)){ domain = domain.replace(request.getScheme(),scheme); } return domain; } } public static String getOrigin(){ HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } /** * 通过name获取 Bean. * * @param name * @return
*/ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean. * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SpringContextUtils.java
1
请完成以下Java代码
public class BigramTokenizer implements ITokenizer { public String[] segment(String text) { if (text.length() == 0) return new String[0]; char[] charArray = text.toCharArray(); CharTable.normalization(charArray); // 先拆成字 List<int[]> atomList = new LinkedList<int[]>(); int start = 0; int end = charArray.length; int offsetAtom = start; byte preType = CharType.get(charArray[offsetAtom]); byte curType; while (++offsetAtom < end) { curType = CharType.get(charArray[offsetAtom]); if (preType == CharType.CT_CHINESE) { atomList.add(new int[]{start, offsetAtom - start}); start = offsetAtom; } else if (curType != preType) { // 浮点数识别 if (charArray[offsetAtom] == '.' && preType == CharType.CT_NUM) { while (++offsetAtom < end) { curType = CharType.get(charArray[offsetAtom]); if (curType != CharType.CT_NUM) break; } } if (preType == CharType.CT_NUM || preType == CharType.CT_LETTER) atomList.add(new int[]{start, offsetAtom - start}); start = offsetAtom; } preType = curType; } if (offsetAtom == end) if (preType == CharType.CT_NUM || preType == CharType.CT_LETTER) atomList.add(new int[]{start, offsetAtom - start});
if (atomList.isEmpty()) return new String[0]; // 输出 String[] termArray = new String[atomList.size() - 1]; Iterator<int[]> iterator = atomList.iterator(); int[] pre = iterator.next(); int p = -1; while (iterator.hasNext()) { int[] cur = iterator.next(); termArray[++p] = new StringBuilder(pre[1] + cur[1]).append(charArray, pre[0], pre[1]).append(charArray, cur[0], cur[1]).toString(); pre = cur; } return termArray; } // public static void main(String args[]) // { // BigramTokenizer bws = new BigramTokenizer(); // String[] result = bws.segment("@hankcs你好,广阔的世界2016!\u0000\u0000\t\n\r\n慶祝Coding worlds!"); // for (String str : result) // { // System.out.println(str); // } // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\tokenizers\BigramTokenizer.java
1
请完成以下Java代码
protected static double Gser(double x, double A) { // Good for X<A+1. double T9 = 1 / A; double G = T9; double I = 1; while (T9 > G * 0.00001) { T9 = T9 * x / (A + I); G = G + T9; ++I; } G = G * Math.exp(A * Math.log(x) - x - LogGamma(A)); return G; } /** * 伽马函数 * * @param x * @param a * @return * @throws IllegalArgumentException */ protected static double GammaCdf(double x, double a) throws IllegalArgumentException { if (x < 0) { throw new IllegalArgumentException(); } double GI = 0; if (a > 200) { double z = (x - a) / Math.sqrt(a); double y = GaussCdf(z); double b1 = 2 / Math.sqrt(a); double phiz = 0.39894228 * Math.exp(-z * z / 2); double w = y - b1 * (z * z - 1) * phiz / 6; //Edgeworth1 double b2 = 6 / a; int zXor4 = ((int) z) ^ 4; double u = 3 * b2 * (z * z - 3) + b1 * b1 * (zXor4 - 10 * z * z + 15); GI = w - phiz * z * u / 72; //Edgeworth2 } else if (x < a + 1) { GI = Gser(x, a); } else { GI = Gcf(x, a); } return GI; } /** * 给定卡方分布的p值和自由度,返回卡方值。内部采用二分搜索实现,移植自JS代码:
* http://www.fourmilab.ch/rpkp/experiments/analysis/chiCalc.js * * @param p p值(置信度) * @param df * @return */ public static double ChisquareInverseCdf(double p, int df) { final double CHI_EPSILON = 0.000001; /* Accuracy of critchi approximation */ final double CHI_MAX = 99999.0; /* Maximum chi-square value */ double minchisq = 0.0; double maxchisq = CHI_MAX; double chisqval = 0.0; if (p <= 0.0) { return CHI_MAX; } else if (p >= 1.0) { return 0.0; } chisqval = df / Math.sqrt(p); /* fair first value */ while ((maxchisq - minchisq) > CHI_EPSILON) { if (1 - ChisquareCdf(chisqval, df) < p) { maxchisq = chisqval; } else { minchisq = chisqval; } chisqval = (maxchisq + minchisq) * 0.5; } return chisqval; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\ContinuousDistributions.java
1
请完成以下Java代码
class SumUpUtils { public static POSPaymentProcessResponse extractProcessResponse(final SumUpTransaction sumUpTrx) { return POSPaymentProcessResponse.builder() .status(SumUpUtils.toResponseStatus(sumUpTrx.getStatus(), sumUpTrx.isRefunded())) .config(extractPaymentProcessorConfig(sumUpTrx)) .cardReader(extractCardReader(sumUpTrx.getCardReader())) .transactionId(sumUpTrx.getExternalId().getAsString()) .summary(sumUpTrx.getCard() != null ? sumUpTrx.getCard().getAsString() : null) .build(); } private static POSTerminalPaymentProcessorConfig extractPaymentProcessorConfig(final SumUpTransaction sumUpTrx) { return POSTerminalPaymentProcessorConfig.builder() .type(POSPaymentProcessorType.SumUp) .sumUpConfigId(sumUpTrx.getConfigId()) .build(); } @Nullable private static POSCardReader extractCardReader(@Nullable final SumUpTransaction.CardReader sumUpCardReader) { if(sumUpCardReader == null) { return null; } return POSCardReader.builder() .externalId(POSCardReaderExternalId.ofString(sumUpCardReader.getExternalId().getAsString())) .name(sumUpCardReader.getName()) .build(); } @NonNull public static POSPaymentProcessingStatus toResponseStatus(final @NonNull SumUpTransactionStatus status, final boolean isRefunded) {
if (SumUpTransactionStatus.SUCCESSFUL.equals(status)) { return isRefunded ? POSPaymentProcessingStatus.DELETED : POSPaymentProcessingStatus.SUCCESSFUL; } else if (SumUpTransactionStatus.CANCELLED.equals(status)) { return POSPaymentProcessingStatus.CANCELLED; } else if (SumUpTransactionStatus.FAILED.equals(status)) { return POSPaymentProcessingStatus.FAILED; } else if (SumUpTransactionStatus.PENDING.equals(status)) { return POSPaymentProcessingStatus.PENDING; } else { throw new AdempiereException("Unknown SumUp status: " + status); } } public static SumUpPOSRef toPOSRef(@NonNull final POSOrderAndPaymentId posOrderAndPaymentId) { return SumUpPOSRef.builder() .posOrderId(posOrderAndPaymentId.getOrderId().getRepoId()) .posPaymentId(posOrderAndPaymentId.getPaymentId().getRepoId()) .build(); } @Nullable public static POSOrderAndPaymentId toPOSOrderAndPaymentId(@NonNull final SumUpPOSRef posRef) { return POSOrderAndPaymentId.ofRepoIdsOrNull(posRef.getPosOrderId(), posRef.getPosPaymentId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpUtils.java
1
请在Spring Boot框架中完成以下Java代码
private ImportIssuesRequest buildSpecificRequest(@NonNull final ImmutableList<ExternalProjectReference> allActiveGithubProjects, @Nullable final String issueNumbers, @Nullable final GithubIssueLinkMatcher githubIssueLinkMatcher) { final ExternalProjectReference externalProject = allActiveGithubProjects .stream() .filter(githubProject -> githubProject.getExternalProjectReferenceId().getRepoId() == this.externalProjectReferenceId) .findFirst() .orElseThrow(() -> new AdempiereException("The selected project is not a Github one!") .appendParametersToMessage() .setParameter("Selected externalProjectReferencedId", externalProjectReferenceId)); final ImmutableList<String> issueNoList = Check.isNotBlank(issueNumbers) ? Stream.of( issueNumbers.split(",") ) .filter(Check::isNotBlank) .map(String::trim) .collect(ImmutableList.toImmutableList()) : ImmutableList.of(); return buildImportIssueRequest(externalProject, issueNoList, githubIssueLinkMatcher); } @NonNull private ImportIssuesRequest buildImportIssueRequest(@NonNull final ExternalProjectReference externalProjectReference, @NonNull final ImmutableList<String> issueNoList, @Nullable final GithubIssueLinkMatcher githubIssueLinkMatcher) { return ImportIssuesRequest.builder() .externalProjectType(externalProjectReference.getExternalProjectType()) .externalProjectReferenceId(externalProjectReference.getExternalProjectReferenceId()) .repoId(externalProjectReference.getExternalProjectReference()) .repoOwner(externalProjectReference.getProjectOwner()) .orgId(externalProjectReference.getOrgId()) .projectId(externalProjectReference.getProjectId()) .oAuthToken(githubConfigRepository.getValueByName(ACCESS_TOKEN.getName())) .issueNoList(issueNoList) .dateFrom(this.dateFrom) .githubIssueLinkMatcher(githubIssueLinkMatcher) .build();
} @Nullable private GithubIssueLinkMatcher getGithubLinkMatcher(@NonNull final ImmutableList<ExternalProjectReference> externalProjectReferences) { final Boolean lookForParent = StringUtils.toBooleanOrNull(githubConfigRepository.getValueByName(LOOK_FOR_PARENT.getName())); if (!Boolean.TRUE.equals(lookForParent)) { return null; } final ImmutableSet.Builder<String> owners = ImmutableSet.builder(); final ImmutableSet.Builder<String> projects = ImmutableSet.builder(); externalProjectReferences.forEach(projectRef -> { owners.add(projectRef.getProjectOwner()); projects.add(projectRef.getExternalProjectReference()); }); return GithubIssueLinkMatcher.of(owners.build(), projects.build()); } private boolean importAllProjects() { return externalProjectReferenceId == 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImportProcess.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_Specialization_ID (final int AD_User_Occupation_Specialization_ID) { if (AD_User_Occupation_Specialization_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Specialization_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Specialization_ID, AD_User_Occupation_Specialization_ID); } @Override public int getAD_User_Occupation_Specialization_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Specialization_ID); } @Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation() { return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); } @Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Specialization.java
1
请完成以下Java代码
public boolean tryAdvance(final Consumer<? super List<E>> action) { final List<E> batch = new ArrayList<>(batchSize); for (int i = 0; i < batchSize && base.tryAdvance(batch::add); i++) { ; } if (batch.isEmpty()) { return false; } action.accept(batch); return true; } @Override public Spliterator<List<E>> trySplit() { if (base.estimateSize() <= batchSize) { return null; } final Spliterator<E> splitBase = this.base.trySplit();
return splitBase == null ? null : new BatchSpliterator<>(splitBase, batchSize); } @Override public long estimateSize() { final double baseSize = base.estimateSize(); return baseSize == 0 ? 0 : (long)Math.ceil(baseSize / batchSize); } @Override public int characteristics() { return base.characteristics(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\BatchSpliterator.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurPharmProduct { boolean error; String resultCode; String resultMessage; @Nullable ProductDetails productDetails; @NonNull HuId huId; @Nullable @NonFinal @Setter SecurPharmProductId id; public boolean isActive() { return getProductDetails().isActive(); } public boolean isFraud() {
return getProductDetails().isFraud(); } public boolean isDecommissioned() { return getProductDetails().isDecommissioned(); } public String getDecommissionServerTransactionId() { return getProductDetails().getDecommissionedServerTransactionId(); } public void productDecommissioned(@NonNull final String decommissionedServerTransactionId) { getProductDetails().productDecommissioned(decommissionedServerTransactionId); } public void productDecommissionUndo(@NonNull final String undoDecommissionedServerTransactionId) { getProductDetails().productDecommissionUndo(undoDecommissionedServerTransactionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\SecurPharmProduct.java
2
请完成以下Java代码
private CommissionPoints extractCommissionPointsToInvoice(@NonNull final I_C_Invoice_Candidate icRecord) { final CommissionPoints commissionPointsToInvoice = CommissionPoints.of(icRecord.getNetAmtToInvoice()); return deductTaxAmount(commissionPointsToInvoice, icRecord); } @NonNull private CommissionPoints extractInvoicedCommissionPoints(@NonNull final I_C_Invoice_Candidate icRecord) { final CommissionPoints commissionPointsToInvoice = CommissionPoints.of(icRecord.getNetAmtInvoiced()); return deductTaxAmount(commissionPointsToInvoice, icRecord); } @NonNull private CommissionPoints deductTaxAmount( @NonNull final CommissionPoints commissionPoints, @NonNull final I_C_Invoice_Candidate icRecord) { if (commissionPoints.isZero()) { return commissionPoints; // don't bother going to the DAO layer } final int effectiveTaxRepoId = firstGreaterThanZero(icRecord.getC_Tax_Override_ID(), icRecord.getC_Tax_ID()); if (effectiveTaxRepoId <= 0) { logger.debug("Invoice candidate has effective C_Tax_ID={}; -> return undedacted commissionPoints={}", effectiveTaxRepoId, commissionPoints); return commissionPoints; } final Tax taxRecord = taxDAO.getTaxById(effectiveTaxRepoId); final CurrencyPrecision precision = invoiceCandBL.extractPricePrecision(icRecord); final BigDecimal taxAdjustedAmount = taxRecord.calculateBaseAmt( commissionPoints.toBigDecimal(), icRecord.isTaxIncluded(), precision.toInt()); return CommissionPoints.of(taxAdjustedAmount); }
@NonNull private Optional<BPartnerId> getSalesRepId(@NonNull final I_C_Invoice_Candidate icRecord) { final BPartnerId invoiceCandidateSalesRepId = BPartnerId.ofRepoIdOrNull(icRecord.getC_BPartner_SalesRep_ID()); if (invoiceCandidateSalesRepId != null) { return Optional.of(invoiceCandidateSalesRepId); } final I_C_BPartner customerBPartner = bPartnerDAO.getById(icRecord.getBill_BPartner_ID()); if (customerBPartner.isSalesRep()) { return Optional.of(BPartnerId.ofRepoId(customerBPartner.getC_BPartner_ID())); } return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\commissiontrigger\salesinvoicecandidate\SalesInvoiceCandidateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isCachable() { return true; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return Date.class.isAssignableFrom(value.getClass()); } @Override public Object getValue(ValueFields valueFields) { Long longValue = valueFields.getLongValue();
if (longValue != null) { return new Date(longValue); } return null; } @Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { valueFields.setLongValue(((Date) value).getTime()); } else { valueFields.setLongValue(null); } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\DateType.java
2
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ 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; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java
1
请在Spring Boot框架中完成以下Java代码
public static SupplyRequiredDecreasedEvent createSupplyRequiredDecreasedEvent( @NonNull final Candidate demandCandidate, @NonNull final BigDecimal decreasedQty) { verifyCandidateType(demandCandidate); return SupplyRequiredDecreasedEvent.builder() .supplyRequiredDescriptor(createSupplyRequiredDescriptor( demandCandidate, decreasedQty, null)) .build(); } private static void verifyCandidateType(final Candidate demandCandidate) { final CandidateType candidateType = demandCandidate.getType(); Preconditions.checkArgument(candidateType == CandidateType.DEMAND || candidateType == CandidateType.STOCK_UP, "Given parameter demandCandidate needs to have DEMAND or STOCK_UP as type; demandCandidate=%s", demandCandidate); } @NonNull public static SupplyRequiredDescriptor createSupplyRequiredDescriptor( @NonNull final Candidate demandCandidate, @NonNull final BigDecimal requiredAdditionalQty, @Nullable final CandidateId supplyCandidateId) { final SupplyRequiredDescriptorBuilder descriptorBuilder = createAndInitSupplyRequiredDescriptor( demandCandidate, requiredAdditionalQty); if (supplyCandidateId != null) { descriptorBuilder.supplyCandidateId(supplyCandidateId.getRepoId()); } if (demandCandidate.getDemandDetail() != null) { final DemandDetail demandDetail = demandCandidate.getDemandDetail(); descriptorBuilder .shipmentScheduleId(IdConstants.toRepoId(demandDetail.getShipmentScheduleId())) .forecastId(IdConstants.toRepoId(demandDetail.getForecastId())) .forecastLineId(IdConstants.toRepoId(demandDetail.getForecastLineId())) .orderId(IdConstants.toRepoId(demandDetail.getOrderId())) .orderLineId(IdConstants.toRepoId(demandDetail.getOrderLineId())) .subscriptionProgressId(IdConstants.toRepoId(demandDetail.getSubscriptionProgressId()));
} return descriptorBuilder.build(); } @NonNull private static SupplyRequiredDescriptorBuilder createAndInitSupplyRequiredDescriptor( @NonNull final Candidate candidate, @NonNull final BigDecimal qty) { final PPOrderRef ppOrderRef = candidate.getBusinessCaseDetail(ProductionDetail.class) .map(ProductionDetail::getPpOrderRef) .orElse(null); return SupplyRequiredDescriptor.builder() .demandCandidateId(candidate.getId().getRepoId()) .eventDescriptor(EventDescriptor.ofClientOrgAndTraceId(candidate.getClientAndOrgId(), candidate.getTraceId())) .materialDescriptor(candidate.getMaterialDescriptor().withQuantity(qty)) .fullDemandQty(candidate.getQuantity()) .ppOrderRef(ppOrderRef) .simulated(candidate.isSimulated()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\SupplyRequiredEventCreator.java
2
请在Spring Boot框架中完成以下Java代码
private static class MailboxEntry { @NonNull MailboxId id; boolean active; @NonNull Mailbox mailbox; } private static class MailboxesMap { private final ImmutableMap<MailboxId, MailboxEntry> byId; private MailboxesMap(final List<MailboxEntry> list) { this.byId = Maps.uniqueIndex(list, MailboxEntry::getId); } public Mailbox getById(final MailboxId mailboxId)
{ return getEntryById(mailboxId).getMailbox(); } private MailboxEntry getEntryById(final MailboxId mailboxId) { final MailboxEntry entry = byId.get(mailboxId); if (entry == null) { throw new AdempiereException("No mailbox found for " + mailboxId); } return entry; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\mailboxes\MailboxRepository.java
2
请完成以下Java代码
public void run() { while (true) { try { sleep(); } catch (final InterruptedException e) { logger.info("Got interrupt request. Exiting."); return; } try { processNow(); } catch (final Exception ex) { logger.warn("Failed to process. Ignored.", ex); } } } private void sleep() throws InterruptedException { final Duration pollInterval = getPollInterval(); logger.debug("Sleeping {}", pollInterval); Thread.sleep(pollInterval.toMillis()); } private Duration getPollInterval() { final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1); return pollIntervalInSeconds > 0 ? Duration.ofSeconds(pollIntervalInSeconds) : DEFAULT_PollInterval; } private QueryLimit getRetrieveBatchSize()
{ final int retrieveBatchSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveBatchSize, -1); return retrieveBatchSize > 0 ? QueryLimit.ofInt(retrieveBatchSize) : DEFAULT_RetrieveBatchSize; } @VisibleForTesting FactAcctLogProcessResult processNow() { FactAcctLogProcessResult finalResult = FactAcctLogProcessResult.ZERO; boolean mightHaveMore; do { final QueryLimit retrieveBatchSize = getRetrieveBatchSize(); final FactAcctLogProcessResult result = factAcctLogService.processAll(retrieveBatchSize); finalResult = finalResult.combineWith(result); mightHaveMore = retrieveBatchSize.isLessThanOrEqualTo(result.getProcessedLogRecordsCount()); logger.debug("processNow: retrieveBatchSize={}, result={}, mightHaveMore={}", retrieveBatchSize, result, mightHaveMore); } while (mightHaveMore); logger.debug("processNow: DONE. Processed {}", finalResult); return finalResult; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\FactAcctLogDBTableWatcher.java
1
请在Spring Boot框架中完成以下Java代码
public Payer timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Payer payer = (Payer) o; return Objects.equals(this._id, payer._id) && Objects.equals(this.name, payer.name) && Objects.equals(this.type, payer.type) && Objects.equals(this.ikNumber, payer.ikNumber) && Objects.equals(this.timestamp, payer.timestamp); } @Override public int hashCode() { return Objects.hash(_id, name, type, ikNumber, timestamp); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class Payer {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).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\Payer.java
2
请完成以下Java代码
public Integer getCollectSubjectCount() { return collectSubjectCount; } public void setCollectSubjectCount(Integer collectSubjectCount) { this.collectSubjectCount = collectSubjectCount; } public Integer getCollectTopicCount() { return collectTopicCount; } public void setCollectTopicCount(Integer collectTopicCount) { this.collectTopicCount = collectTopicCount; } public Integer getCollectCommentCount() { return collectCommentCount; } public void setCollectCommentCount(Integer collectCommentCount) { this.collectCommentCount = collectCommentCount; } public Integer getInviteFriendCount() { return inviteFriendCount; } public void setInviteFriendCount(Integer inviteFriendCount) { this.inviteFriendCount = inviteFriendCount; } public Date getRecentOrderTime() { return recentOrderTime; } public void setRecentOrderTime(Date recentOrderTime) { this.recentOrderTime = recentOrderTime; } @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(", memberId=").append(memberId); sb.append(", consumeAmount=").append(consumeAmount); sb.append(", orderCount=").append(orderCount); sb.append(", couponCount=").append(couponCount); sb.append(", commentCount=").append(commentCount); sb.append(", returnOrderCount=").append(returnOrderCount); sb.append(", loginCount=").append(loginCount); sb.append(", attendCount=").append(attendCount); sb.append(", fansCount=").append(fansCount); sb.append(", collectProductCount=").append(collectProductCount); sb.append(", collectSubjectCount=").append(collectSubjectCount); sb.append(", collectTopicCount=").append(collectTopicCount); sb.append(", collectCommentCount=").append(collectCommentCount); sb.append(", inviteFriendCount=").append(inviteFriendCount); sb.append(", recentOrderTime=").append(recentOrderTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberStatisticsInfo.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { AttachmentEntity attachment = commandContext .getDbSqlSession() .selectById(AttachmentEntity.class, attachmentId); commandContext .getDbSqlSession() .delete(attachment); if (attachment.getContentId() != null) { commandContext .getByteArrayEntityManager() .deleteByteArrayById(attachment.getContentId()); } if (attachment.getTaskId() != null) { commandContext.getHistoryManager() .createAttachmentComment(attachment.getTaskId(), attachment.getProcessInstanceId(), attachment.getName(), false); } if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { // Forced to fetch the process-instance to associate the right process definition String processDefinitionId = null;
String processInstanceId = attachment.getProcessInstanceId(); if (attachment.getProcessInstanceId() != null) { ExecutionEntity process = commandContext.getExecutionEntityManager().findExecutionById(processInstanceId); if (process != null) { processDefinitionId = process.getProcessDefinitionId(); } } commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, attachment, processInstanceId, processInstanceId, processDefinitionId), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteAttachmentCmd.java
1
请完成以下Java代码
public UserQuery createNewUserQuery() { return new UserQueryImpl(getCommandExecutor()); } @Override public Boolean checkPassword(String userId, String password, PasswordEncoder passwordEncoder, PasswordSalt salt) { User user = null; if (userId != null) { user = findById(userId); } return (user != null) && (password != null) && passwordEncoder.isMatches(password, user.getPassword(), salt); } @Override public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUsersByNativeQuery(parameterMap); } @Override public long findUserCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findUserCountByNativeQuery(parameterMap); } @Override public boolean isNewUser(User user) { return ((UserEntity) user).getRevision() == 0; } @Override public Picture getUserPicture(User user) { UserEntity userEntity = (UserEntity) user; return userEntity.getPicture(); } @Override public void setUserPicture(User user, Picture picture) { UserEntity userEntity = (UserEntity) user; userEntity.setPicture(picture); dataManager.update(userEntity); }
@Override public List<User> findUsersByPrivilegeId(String name) { return dataManager.findUsersByPrivilegeId(name); } public UserDataManager getUserDataManager() { return dataManager; } public void setUserDataManager(UserDataManager userDataManager) { this.dataManager = userDataManager; } protected IdentityInfoEntityManager getIdentityInfoEntityManager() { return engineConfiguration.getIdentityInfoEntityManager(); } protected MembershipEntityManager getMembershipEntityManager() { return engineConfiguration.getMembershipEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean AsyncTaskExecutor delayedTaskExecutor() { return new ThreadPoolTaskExecutor() { @Override public <T> Future<T> submit(Callable<T> task) { return super.submit(() -> { Thread.sleep(5000); return task.call(); }); } };
} @Bean LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, AsyncTaskExecutor delayedTaskExecutor) { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setPackagesToScan("com.baeldung.boot.bootstrapmode"); factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); factory.setDataSource(dataSource); factory.setBootstrapExecutor(delayedTaskExecutor); Map<String, Object> properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", "create-drop"); factory.setJpaPropertyMap(properties); return factory; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\boot\bootstrapmode\Application.java
2
请完成以下Java代码
public ResponseEntity<FileList> getFiles() { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + LIST_PREFIX).length())); LOG.info("getFiles: {}", filePath); FileList fileInfo = fileService.getFilesInfo(filePath); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(fileInfo); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @PostMapping(UPLOAD_PREFIX + "**") public ResponseEntity<Resource> fileUpload(@RequestParam("file") MultipartFile file) { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + UPLOAD_PREFIX).length())); LOG.info("upload: {}", filePath); fileService.saveFile(filePath, file.getInputStream()); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @DeleteMapping(DELETE_PREFIX + "**") public ResponseEntity<Resource> delete() { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + DELETE_PREFIX).length())); LOG.info("delete: {}", filePath); fileService.delete(filePath); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
} } @PostMapping(CREATEDIR_PREFIX + "**") public ResponseEntity<Resource> createDirectory() { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + CREATEDIR_PREFIX).length())); LOG.info("createDirectory: {}", filePath); fileService.createDirectory(filePath); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
repos\spring-examples-java-17\spring-fileserver\src\main\java\itx\examples\springboot\fileserver\rest\FileServerController.java
1
请完成以下Java代码
public long getReportingIntervalInSeconds() { return reportingIntervalInSeconds; } public void setReportingIntervalInSeconds(long reportingIntervalInSeconds) { this.reportingIntervalInSeconds = reportingIntervalInSeconds; } public MetricsRegistry getMetricsRegistry() { return metricsRegistry; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public MetricsCollectionTask getMetricsCollectionTask() { return metricsCollectionTask; } public void setMetricsCollectionTask(MetricsCollectionTask metricsCollectionTask) { this.metricsCollectionTask = metricsCollectionTask; } public void setReporterId(String reporterId) { this.reporterId = reporterId; if (metricsCollectionTask != null) { metricsCollectionTask.setReporter(reporterId); } }
protected class ReportDbMetricsValueCmd implements Command<Void> { protected String name; protected long value; public ReportDbMetricsValueCmd(String name, long value) { this.name = name; this.value = value; } @Override public Void execute(CommandContext commandContext) { commandContext.getMeterLogManager().insert(new MeterLogEntity(name, reporterId, value, ClockUtil.getCurrentTime())); return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\DbMetricsReporter.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isHostnameVerificationEnabled() { return this.hostnameVerificationEnabled; } public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) { this.hostnameVerificationEnabled = hostnameVerificationEnabled; } public enum TrustStrategy { /** * Trust all certificates. */ TRUST_ALL_CERTIFICATES,
/** * Trust certificates that are signed by a trusted certificate. */ TRUST_CUSTOM_CA_SIGNED_CERTIFICATES, /** * Trust certificates that can be verified through the local system store. */ TRUST_SYSTEM_CA_SIGNED_CERTIFICATES } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java
2
请完成以下Java代码
public Article updateFavoriteByUser(User user) { favorited = userFavorited.contains(user); return this; } public User getAuthor() { return author; } public ArticleContents getContents() { return contents; } public Instant getCreatedAt() { return createdAt; } public Instant getUpdatedAt() { return updatedAt; } public int getFavoritedCount() { return userFavorited.size(); } public boolean isFavorited() {
return favorited; } public Set<Comment> getComments() { return comments; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; var article = (Article) o; return author.equals(article.author) && contents.getTitle().equals(article.contents.getTitle()); } @Override public int hashCode() { return Objects.hash(author, contents.getTitle()); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\Article.java
1
请完成以下Java代码
public class BpmPlatformSubsystemAdd extends AbstractBoottimeAddStepHandler { public static final BpmPlatformSubsystemAdd INSTANCE = new BpmPlatformSubsystemAdd(); /** {@inheritDoc} */ @Override protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { // add deployment processors context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(ModelConstants.SUBSYSTEM_NAME, Phase.PARSE, ProcessApplicationProcessor.PRIORITY, new ProcessApplicationProcessor()); processorTarget.addDeploymentProcessor(ModelConstants.SUBSYSTEM_NAME, Phase.DEPENDENCIES, ModuleDependencyProcessor.PRIORITY, new ModuleDependencyProcessor()); processorTarget.addDeploymentProcessor(ModelConstants.SUBSYSTEM_NAME, Phase.POST_MODULE, ProcessesXmlProcessor.PRIORITY, new ProcessesXmlProcessor()); processorTarget.addDeploymentProcessor(ModelConstants.SUBSYSTEM_NAME, Phase.INSTALL, ProcessEngineStartProcessor.PRIORITY, new ProcessEngineStartProcessor()); processorTarget.addDeploymentProcessor(ModelConstants.SUBSYSTEM_NAME, Phase.INSTALL, ProcessApplicationDeploymentProcessor.PRIORITY, new ProcessApplicationDeploymentProcessor()); } }, OperationContext.Stage.RUNTIME); // create and register the MSC container delegate. ServiceBuilder<?> processEngineBuilder = context.getServiceTarget().addService(ServiceNames.forMscRuntimeContainerDelegate());
Consumer<RuntimeContainerDelegate> delegateProvider = processEngineBuilder.provides(ServiceNames.forMscRuntimeContainerDelegate()); processEngineBuilder.setInitialMode(Mode.ACTIVE); MscRuntimeContainerDelegate processEngineService = new MscRuntimeContainerDelegate(delegateProvider); processEngineBuilder.setInstance(processEngineService); processEngineBuilder.install(); // discover and register Camunda Platform plugins BpmPlatformPlugins plugins = BpmPlatformPlugins.load(getClass().getClassLoader()); ServiceBuilder<?> pluginsBuilder = context.getServiceTarget().addService(ServiceNames.forBpmPlatformPlugins()); Consumer<BpmPlatformPlugins> pluginsProvider = pluginsBuilder.provides(ServiceNames.forBpmPlatformPlugins()); MscBpmPlatformPlugins managedPlugins = new MscBpmPlatformPlugins(plugins, pluginsProvider); pluginsBuilder.setInitialMode(Mode.ACTIVE); pluginsBuilder.setInstance(managedPlugins); pluginsBuilder.install(); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\BpmPlatformSubsystemAdd.java
1
请完成以下Java代码
public void setOrderDescription(String orderDescription) { this.orderDescription = orderDescription; } public void setPaymentDescription(String paymentDescription) { this.paymentDescription = paymentDescription; } public void setBuyerName(String buyerName) { this.buyerName = buyerName; } public String getOrderId() { return orderId; } public String getPaymentId() { return paymentId; }
public String getUserId() { return userId; } public String getOrderDescription() { return orderDescription; } public String getPaymentDescription() { return paymentDescription; } public String getBuyerName() { return buyerName; } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-1\src\main\java\com\baeldung\resttemplate\restcallscompletablefuture\Purchase.java
1
请完成以下Java代码
protected static List<Pinyin> segLongest(char[] charArray, AhoCorasickDoubleArrayTrie<Pinyin[]> trie) { return segLongest(charArray, trie, true); } protected static List<Pinyin> segLongest(char[] charArray, AhoCorasickDoubleArrayTrie<Pinyin[]> trie, boolean remainNone) { final Pinyin[][] wordNet = new Pinyin[charArray.length][]; final int[] lengths = new int[charArray.length]; trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<Pinyin[]>() { @Override public void hit(int begin, int end, Pinyin[] value) { int length = end - begin; if (length == 1 && value.length > 1) { value = new Pinyin[]{value[0]}; } if (length > lengths[begin]) { wordNet[begin] = value; lengths[begin] = length; } } }); List<Pinyin> pinyinList = new ArrayList<Pinyin>(charArray.length); for (int offset = 0; offset < wordNet.length; ) { if (wordNet[offset] == null) { if (remainNone) { pinyinList.add(Pinyin.none5); } ++offset; continue; } for (Pinyin pinyin : wordNet[offset]) { pinyinList.add(pinyin); } offset += lengths[offset]; } return pinyinList; } public static class Searcher extends BaseSearcher<Pinyin[]> { /** * 分词从何处开始,这是一个状态 */ int begin;
DoubleArrayTrie<Pinyin[]> trie; protected Searcher(char[] c, DoubleArrayTrie<Pinyin[]> trie) { super(c); this.trie = trie; } protected Searcher(String text, DoubleArrayTrie<Pinyin[]> trie) { super(text); this.trie = trie; } @Override public Map.Entry<String, Pinyin[]> next() { // 保证首次调用找到一个词语 Map.Entry<String, Pinyin[]> result = null; while (begin < c.length) { LinkedList<Map.Entry<String, Pinyin[]>> entryList = trie.commonPrefixSearchWithValue(c, begin); if (entryList.size() == 0) { ++begin; } else { result = entryList.getLast(); offset = begin; begin += result.getKey().length(); break; } } if (result == null) { return null; } return result; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\PinyinDictionary.java
1