instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private void setData (int row, int col, TextLayout layout, AttributedCharacterIterator iter) { if (layout == null) return; if (p_sizeCalculated) throw new IllegalStateException("Size already calculated"); if (row < 0 || row >= m_rows) throw new ArrayIndexOutOfBoundsException("Row Index=" + row + " Rows=" + m_rows); if (col < 0 || col >= m_cols) throw new ArrayIndexOutOfBoundsException("Column Index=" + col + " Cols=" + m_cols); // m_textLayout[row][col] = layout; m_iterator[row][col] = iter; // Set Size int height = (int)(layout.getAscent() + layout.getDescent() + layout.getLeading())+1; int width = (int)layout.getAdvance()+1; if (m_rowHeight[row] < height) m_rowHeight[row] = height; if (m_colWidth[col] < width) m_colWidth[col] = width; } // setData /** * Set Rpw/Column gap * @param rowGap row gap * @param colGap column gap */ public void setGap (int rowGap, int colGap) { m_rowGap = rowGap; m_colGap = colGap; } // setGap /************************************************************************** * Layout & Calculate Image Size. * Set p_width & p_height * @return true if calculated */ protected boolean calculateSize() { p_height = 0; for (int r = 0; r < m_rows; r++) { p_height += m_rowHeight[r]; if (m_rowHeight[r] > 0) p_height += m_rowGap; } p_height -= m_rowGap; // remove last p_width = 0; for (int c = 0; c < m_cols; c++) { p_width += m_colWidth[c]; if (m_colWidth[c] > 0) p_width += m_colGap; } p_width -= m_colGap; // remove last return true; } // calculateSize /** * Paint it * @param g2D Graphics * @param pageStart top left Location of page * @param pageNo page number for multi page support (0 = header/footer) - ignored * @param ctx print context
* @param isView true if online view (IDs are links) */ public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView) { Point2D.Double location = getAbsoluteLocation(pageStart); float y = (float)location.y; // for (int row = 0; row < m_rows; row++) { float x = (float)location.x; for (int col = 0; col < m_cols; col++) { if (m_textLayout[row][col] != null) { float yy = y + m_textLayout[row][col].getAscent(); // if (m_iterator[row][col] != null) // g2D.drawString(m_iterator[row][col], x, yy); // else m_textLayout[row][col].draw(g2D, x, yy); } x += m_colWidth[col]; if (m_colWidth[col] > 0) x += m_colGap; } y += m_rowHeight[row]; if (m_rowHeight[row] > 0) y += m_rowGap; } } // paint } // GridElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\GridElement.java
1
请完成以下Java代码
private void executeTask() { ArrayList<T> itemsToConsume = null; final long remaining; final int bufferSize; synchronized (lock) { // we don't use SystemTime because in our usual tests it's rigged to return a fixed value. Fee free to use it here, too - maybe with an enhanced Timesource - when it makes sense remaining = dueTime - System.currentTimeMillis(); bufferSize = buffer.size(); // // Re-schedule task if (remaining > 0 && bufferSize > 0 && (bufferMaxSize <= 0 || bufferMaxSize > bufferSize)) { //System.out.println("" + this + " - executeTask:Rescheduling in " + remaining + " ms(bufferSize = " + bufferSize + ") "); executor.schedule(this::executeTask, remaining, TimeUnit.MILLISECONDS); } // // Mark as terminated and invoke the consumer else { dueTime = -1; if (bufferSize > 0) { itemsToConsume = new ArrayList<>(buffer); buffer.clear(); } } } if (itemsToConsume != null) { //System.out.println("" + this + " - executeTask: consuming " + bufferSize + " items(remaining was" + remaining + "ms) "); consumer.accept(itemsToConsume); } } public int getCurrentBufferSize() { synchronized (lock) { return buffer.size(); } } public void processAndClearBufferSync() { synchronized (lock) { if (!buffer.isEmpty()) { final ArrayList<T> itemsToConsume = new ArrayList<>(buffer);
consumer.accept(itemsToConsume); buffer.clear(); } } } public void purgeBuffer() { synchronized (lock) { buffer.clear(); } } public void shutdown() { executor.shutdown(); } /* public static void main(String[] args) throws InterruptedException { final Debouncer<Integer> debouncer = Debouncer.<Integer>builder() .name("test-debouncer") .delayInMillis(500) .bufferMaxSize(500) .consumer(items -> System.out.println("Got " + items.size() + " items: " + items.get(0) + "..." + items.get(items.size() - 1))) .build(); System.out.println("Start sending events..."); for (int i = 1; i <= 100; i++) { debouncer.add(i); //Thread.yield(); Thread.sleep(0, 1); } System.out.println("Enqueuing done. Waiting a bit to finish..."); Thread.sleep(5000); } */ }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\async\Debouncer.java
1
请完成以下Java代码
public LinearModel getModel() { return model; } /** * 在线学习 * * @param instance * @return */ public boolean learn(Instance instance) { if (instance == null) return false; model.update(instance); return true; } /** * 在线学习 * * @param sentence * @return */ public boolean learn(Sentence sentence)
{ return learn(createInstance(sentence, model.featureMap)); } /** * 性能测试 * * @param corpora 数据集 * @return 默认返回accuracy,有些子类可能返回P,R,F1 * @throws IOException */ public double[] evaluate(String corpora) throws IOException { return evaluate(corpora, this.getModel()); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronTagger.java
1
请完成以下Java代码
public void attachState(MigratingScopeInstance owningActivityInstance) { ExecutionEntity representativeExecution = owningActivityInstance.resolveRepresentativeExecution(); ScopeImpl currentScope = owningActivityInstance.getCurrentScope(); ExecutionEntity newOwningExecution = representativeExecution; if (currentScope.isScope() && isConcurrentLocalInParentScope) { newOwningExecution = representativeExecution.getParent(); } newOwningExecution.addVariableInternal(variable); } @Override public void attachState(MigratingTransitionInstance owningActivityInstance) { ExecutionEntity representativeExecution = owningActivityInstance.resolveRepresentativeExecution(); representativeExecution.addVariableInternal(variable); } @Override public void migrateState() { migrateHistory(); } protected void migrateHistory() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_MIGRATE, this)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableMigrateEvt(variable); } }); } } @Override public void migrateDependentEntities() { // nothing to do } public String getVariableName() { return variable.getName(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingVariableInstance.java
1
请完成以下Java代码
public class MIndexValidator implements ModelValidator { private int m_AD_Client_ID = -1; @Override public int getAD_Client_ID() { return m_AD_Client_ID; } /** * Does nothing, the code is commented out. See the javadoc of {@link #modelChange(PO, int)}. */ @Override public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) m_AD_Client_ID = client.getAD_Client_ID(); // // @formatter:off // final Map<String, List<MIndexTable>> indexes = MIndexTable.getAllByTable(Env.getCtx(), true); // for (Entry<String, List<MIndexTable>> e : indexes.entrySet()) // { // String tableName = e.getKey(); // engine.addModelChange(tableName, this); // } // @formatter:on } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } /** * Does nothing, the code is commented out for the time being. Probably the whole class will be removed.<br> * Don't use this stuff. We have a physical DB-index, and if a DBUniqueConstraintException is thrown anywhere in ADempiere, the exception code will identify the MIndexTable (if any) and get its * errorMsg (if any). */ @Override public String modelChange(PO po, int type) throws Exception { // @formatter:off // if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE) // { // final List<MIndexTable> indexes = MIndexTable.getAllByTable(po.getCtx(), false).get(po.get_TableName()); // if (indexes != null) // { // final Properties ctx = po.getCtx(); // final String trxName = po.get_TrxName(); // final String poWhereClause = po.get_WhereClause(true); // // for (final MIndexTable index : indexes)
// { // // Skip inactive indexes // if (!index.isActive()) // { // continue; // } // // // Only UNIQUE indexes need to be validated // if (!index.isUnique()) // { // continue; // } // // if (!index.isWhereClauseMatched(ctx, poWhereClause, trxName)) // { // // there is no need to go with further validation since our PO is not subject of current index // continue; // } // // index.validateData(po, trxName); // } // } // } // @formatter:on return null; } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexValidator.java
1
请完成以下Java代码
private ActivityImpl getCurrentActivity(CommandContext commandContext, Job job) { String type = job.getJobHandlerType(); ActivityImpl activity = null; if (TimerExecuteNestedActivityJobHandler.TYPE.equals(type) || TimerCatchIntermediateEventJobHandler.TYPE.equals(type)) { ExecutionEntity execution = fetchExecutionEntity(commandContext, job.getExecutionId()); if (execution != null) { activity = execution.getProcessDefinition().findActivity(job.getJobHandlerConfiguration()); } } else if (TimerStartEventJobHandler.TYPE.equals(type)) { DeploymentManager deploymentManager = commandContext.getProcessEngineConfiguration().getDeploymentManager(); if (TimerEventHandler.hasRealActivityId(job.getJobHandlerConfiguration())) { ProcessDefinition processDefinition = deploymentManager.findDeployedProcessDefinitionById(job.getProcessDefinitionId()); String activityId = TimerEventHandler.getActivityIdFromConfiguration(job.getJobHandlerConfiguration()); activity = ((ProcessDefinitionEntity) processDefinition).findActivity(activityId); } else { String processId = job.getJobHandlerConfiguration(); if (job instanceof TimerJobEntity) { processId = TimerEventHandler.getActivityIdFromConfiguration(job.getJobHandlerConfiguration()); } ProcessDefinition processDefinition = null; if (job.getTenantId() != null && job.getTenantId().length() > 0) { processDefinition = deploymentManager.findDeployedLatestProcessDefinitionByKeyAndTenantId(processId, job.getTenantId()); } else { processDefinition = deploymentManager.findDeployedLatestProcessDefinitionByKey(processId); } if (processDefinition != null) { activity = ((ProcessDefinitionEntity) processDefinition).getInitial();
} } } else if (AsyncContinuationJobHandler.TYPE.equals(type)) { ExecutionEntity execution = fetchExecutionEntity(commandContext, job.getExecutionId()); if (execution != null) { activity = execution.getActivity(); } } else { // nop, because activity type is not supported } return activity; } private String getExceptionStacktrace() { StringWriter stringWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } private ExecutionEntity fetchExecutionEntity(CommandContext commandContext, String executionId) { return commandContext.getExecutionEntityManager().findExecutionById(executionId); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\JobRetryCmd.java
1
请完成以下Spring Boot application配置
# # Copyright 2015-2023 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KI
ND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # logging.level.root=INFO logging.level.sample.mybatis.web.mapper=TRACE
repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-web\src\main\resources\application.properties
2
请完成以下Java代码
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcess(@NonNull final Class<ImportRecordType> modelImportClass) { final IImportProcess<ImportRecordType> importProcess = newImportProcessOrNull(modelImportClass); if (importProcess == null) { throw new AdempiereException("No import process found for " + modelImportClass); } return importProcess; } @Nullable private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessOrNull(@NonNull final Class<ImportRecordType> modelImportClass) { final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByModelImportClassOrNull(modelImportClass); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass) { try { @SuppressWarnings("unchecked") final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance(); return importProcess; } catch (final Exception e) {
throw new AdempiereException("Failed instantiating " + importProcessClass, e); } } @Nullable private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableNameOrNull(@NonNull final String importTableName) { final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByImportTableNameOrNull(importTableName); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableName(@NonNull final String importTableName) { final IImportProcess<ImportRecordType> importProcess = newImportProcessForTableNameOrNull(importTableName); if (importProcess == null) { throw new AdempiereException("No import process found for " + importTableName); } return importProcess; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportProcessFactory.java
1
请完成以下Java代码
public final IClientUIInvoker setOnFail(OnFail onFail) { Check.assumeNotNull(onFail, "onFail not null"); this.onFail = onFail; return this; } private final OnFail getOnFail() { return onFail; } @Override public final IClientUIInvoker setExceptionHandler(IExceptionHandler exceptionHandler) { Check.assumeNotNull(exceptionHandler, "exceptionHandler not null"); this.exceptionHandler = exceptionHandler; return this; } private final IExceptionHandler getExceptionHandler() { return exceptionHandler; } @Override public abstract IClientUIInvoker setParentComponent(final Object parentComponent); @Override public abstract IClientUIInvoker setParentComponentByWindowNo(final int windowNo); protected final void setParentComponent(final int windowNo, final Object component) { this.parentWindowNo = windowNo; this.parentComponent = component; }
protected final Object getParentComponent() { return parentComponent; } protected final int getParentWindowNo() { return parentWindowNo; } @Override public final IClientUIInvoker setRunnable(final Runnable runnable) { this.runnable = runnable; return this; } private final Runnable getRunnable() { return runnable; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUIInvoker.java
1
请完成以下Java代码
public AttributesIncludedTabData updateByKey( @NonNull final AttributesIncludedTabDataKey key, @NonNull final Collection<AttributeId> attributeIds, @NonNull final BiFunction<AttributeId, AttributesIncludedTabDataField, AttributesIncludedTabDataField> mapper) { final HashMap<AttributeId, I_Record_Attribute> recordsByAttributeId = streamRecords(key) .collect(GuavaCollectors.toHashMapByKey(record -> AttributeId.ofRepoId(record.getM_Attribute_ID()))); final HashMap<AttributeId, AttributesIncludedTabDataField> fields = new HashMap<>(); for (final AttributeId attributeId : attributeIds) { I_Record_Attribute record = recordsByAttributeId.remove(attributeId); final AttributesIncludedTabDataField fieldBeforeChange = record != null ? fromRecord(record) : null; final AttributesIncludedTabDataField field = mapper.apply(attributeId, fieldBeforeChange); if (field == null || field.isNullValues()) { if (record != null) { InterfaceWrapperHelper.delete(record); } } else if (!AttributesIncludedTabDataField.equals(field, fieldBeforeChange)) { if (record == null)
{ record = InterfaceWrapperHelper.newInstance(I_Record_Attribute.class); } updateRecord(record, field, key); InterfaceWrapperHelper.save(record); } if (field != null) { fields.put(attributeId, field); } } InterfaceWrapperHelper.deleteAll(recordsByAttributeId.values()); return AttributesIncludedTabData.builder() .key(key) .fields(fields) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\data\AttributesIncludedTabDataRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class Contact { @Id @GeneratedValue private Long id; @NotBlank private String name; @Email private String email; @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}") private String phone; public Contact() { } public Contact(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Contact {" + "id=" + id + ", name='" + name + "'" + ", email='" + email + "'" + ", phone='" + phone + "'" + " }"; } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\data\Contact.java
2
请完成以下Java代码
public abstract class BaseScorer<T extends ISentenceKey> implements IScorer { public BaseScorer() { storage = new TreeMap<T, Set<String>>(); } /** * 储存 */ protected Map<T, Set<String>> storage; /** * 权重 */ public double boost = 1.0; /** * 设置权重 * @param boost * @return */ public BaseScorer setBoost(double boost) { this.boost = boost; return this; } @Override public void addSentence(String sentence) { T key = generateKey(sentence); if (key == null) return; Set<String> set = storage.get(key); if (set == null) { set = new TreeSet<String>(); storage.put(key, set); } set.add(sentence); } /** * 生成能够代表这个句子的键 * @param sentence * @return */ protected abstract T generateKey(String sentence);
@Override public Map<String, Double> computeScore(String outerSentence) { TreeMap<String, Double> result = new TreeMap<String, Double>(Collections.reverseOrder()); T keyOuter = generateKey(outerSentence); if (keyOuter == null) return result; for (Map.Entry<T, Set<String>> entry : storage.entrySet()) { T key = entry.getKey(); Double score = keyOuter.similarity(key); for (String sentence : entry.getValue()) { result.put(sentence, score); } } return result; } @Override public void removeAllSentences() { storage.clear(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\suggest\scorer\BaseScorer.java
1
请完成以下Java代码
private static boolean isSimpleType(Class<?> type) { return isPrimitiveOrWrapper(type) || type == String.class || type == BigDecimal.class || type == BigInteger.class || type == Date.class || type == URL.class || type == Class.class ; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(Environment environment) { if (environment instanceof ConfigurableEnvironment) { this.environment = (ConfigurableEnvironment) environment; } } protected Map<String, Object> resolveBeanMetadata(final Object bean) { final Map<String, Object> beanMetadata = new LinkedHashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) { String name = Introspector.decapitalize(propertyDescriptor.getName()); Object value = readMethod.invoke(bean); beanMetadata.put(name, value);
} } } catch (Exception e) { throw new RuntimeException(e); } return beanMetadata; } protected Map<String, ServiceBean> getServiceBeansMap() { return beansOfTypeIncludingAncestors(applicationContext, ServiceBean.class); } protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() { return applicationContext.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); } protected Map<String, ProtocolConfig> getProtocolConfigsBeanMap() { return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class); } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\AbstractDubboMetadata.java
1
请在Spring Boot框架中完成以下Java代码
public static class Ssl { /** * Whether to enable SSL support. Enabled automatically if a "bundle" is provided * unless specified otherwise. */ private @Nullable Boolean enabled; /** * SSL bundle name. */ private @Nullable String bundle; public Boolean getEnabled() { return (this.enabled != null) ? this.enabled : StringUtils.hasText(this.bundle); } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } public static class Timeouts { /** * Bucket connect timeout. */ private Duration connect = Duration.ofSeconds(10); /** * Bucket disconnect timeout. */ private Duration disconnect = Duration.ofSeconds(10); /** * Timeout for operations on a specific key-value. */ private Duration keyValue = Duration.ofMillis(2500); /** * Timeout for operations on a specific key-value with a durability level. */ private Duration keyValueDurable = Duration.ofSeconds(10); /** * N1QL query operations timeout. */ private Duration query = Duration.ofSeconds(75); /** * Regular and geospatial view operations timeout. */ private Duration view = Duration.ofSeconds(75); /** * Timeout for the search service. */ private Duration search = Duration.ofSeconds(75); /** * Timeout for the analytics service. */ private Duration analytics = Duration.ofSeconds(75); /** * Timeout for the management operations. */ private Duration management = Duration.ofSeconds(75); public Duration getConnect() { return this.connect;
} public void setConnect(Duration connect) { this.connect = connect; } public Duration getDisconnect() { return this.disconnect; } public void setDisconnect(Duration disconnect) { this.disconnect = disconnect; } public Duration getKeyValue() { return this.keyValue; } public void setKeyValue(Duration keyValue) { this.keyValue = keyValue; } public Duration getKeyValueDurable() { return this.keyValueDurable; } public void setKeyValueDurable(Duration keyValueDurable) { this.keyValueDurable = keyValueDurable; } public Duration getQuery() { return this.query; } public void setQuery(Duration query) { this.query = query; } public Duration getView() { return this.view; } public void setView(Duration view) { this.view = view; } public Duration getSearch() { return this.search; } public void setSearch(Duration search) { this.search = search; } public Duration getAnalytics() { return this.analytics; } public void setAnalytics(Duration analytics) { this.analytics = analytics; } public Duration getManagement() { return this.management; } public void setManagement(Duration management) { this.management = management; } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java
2
请完成以下Java代码
public void setSupervisor(org.compiere.model.I_AD_User Supervisor) { set_ValueFromPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class, Supervisor); } /** Set Vorgesetzter. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ @Override public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Vorgesetzter. @return Supervisor for this user/organization - used for escalation and approval */ @Override public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } /** * WeekDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int WEEKDAY_AD_Reference_ID=167; /** Sonntag = 7 */ public static final String WEEKDAY_Sonntag = "7"; /** Montag = 1 */ public static final String WEEKDAY_Montag = "1"; /** Dienstag = 2 */ public static final String WEEKDAY_Dienstag = "2"; /** Mittwoch = 3 */ public static final String WEEKDAY_Mittwoch = "3"; /** Donnerstag = 4 */ public static final String WEEKDAY_Donnerstag = "4"; /** Freitag = 5 */ public static final String WEEKDAY_Freitag = "5"; /** Samstag = 6 */
public static final String WEEKDAY_Samstag = "6"; /** Set Day of the Week. @param WeekDay Day of the Week */ @Override public void setWeekDay (java.lang.String WeekDay) { set_Value (COLUMNNAME_WeekDay, WeekDay); } /** Get Day of the Week. @return Day of the Week */ @Override public java.lang.String getWeekDay () { return (java.lang.String)get_Value(COLUMNNAME_WeekDay); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Skript. @param Script Dynamic Java Language Script to calculate result */ @Override public void setScript (java.lang.String Script) { set_Value (COLUMNNAME_Script, Script); } /** Get Skript. @return Dynamic Java Language Script to calculate result */ @Override public java.lang.String getScript () { return (java.lang.String)get_Value(COLUMNNAME_Script); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge.
@return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Start No. @param StartNo Starting number/position */ @Override public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ @Override public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); 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_AD_ImpFormat_Row.java
1
请在Spring Boot框架中完成以下Java代码
public class ChunksConfig { @Bean public ItemReader<Line> itemReader() { return new LineReader(); } @Bean public ItemProcessor<Line, Line> itemProcessor() { return new LineProcessor(); } @Bean public ItemWriter<Line> itemWriter() { return new LinesWriter(); } @Bean(name = "processLines") protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader<Line> reader, ItemProcessor<Line, Line> processor, ItemWriter<Line> writer) {
return new StepBuilder("processLines", jobRepository).<Line, Line> chunk(2, transactionManager) .reader(reader) .processor(processor) .writer(writer) .build(); } @Bean(name = "chunksJob") public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("chunksJob", jobRepository) .start(processLines(jobRepository, transactionManager, itemReader(), itemProcessor(), itemWriter())) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\config\ChunksConfig.java
2
请在Spring Boot框架中完成以下Java代码
class EmployeeRowMapper implements RowMapper < Employee > { @Override public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getLong("id")); employee.setFirstName(rs.getString("first_name")); employee.setLastName(rs.getString("last_name")); employee.setEmailId(rs.getString("email_address")); return employee; } } public List < Employee > findAll() { return jdbcTemplate.query("select * from employees", new EmployeeRowMapper()); } public Optional < Employee > findById(long id) { return Optional.of(jdbcTemplate.queryForObject("select * from employees where id=?", new Object[] { id }, new BeanPropertyRowMapper < Employee > (Employee.class))); }
public int deleteById(long id) { return jdbcTemplate.update("delete from employees where id=?", new Object[] { id }); } public int insert(Employee employee) { return jdbcTemplate.update("insert into employees (id, first_name, last_name, email_address) " + "values(?, ?, ?, ?)", new Object[] { employee.getId(), employee.getFirstName(), employee.getLastName(), employee.getEmailId() }); } public int update(Employee employee) { return jdbcTemplate.update("update employees " + " set first_name = ?, last_name = ?, email_address = ? " + " where id = ?", new Object[] { employee.getFirstName(), employee.getLastName(), employee.getEmailId(), employee.getId() }); } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jdbc-crud-mysql-example\src\main\java\net\alanbinu\springboot2\jdbc\repository\EmployeeJDBCRepository.java
2
请完成以下Java代码
public void parseParams() { String disabled = initParams.get(DISABLED_PARAM); if (ServletFilterUtil.isEmpty(disabled)) { setDisabled(false); } else { setDisabled(Boolean.parseBoolean(disabled)); } String value = initParams.get(VALUE_PARAM); if (!isDisabled()) { if (!ServletFilterUtil.isEmpty(value)) {
setValue(value); } else { setValue(HEADER_DEFAULT_VALUE); } } } @Override public String getHeaderName() { return HEADER_NAME; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentTypeOptionsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public void setResetDate(Instant resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } return id != null && id.equals(((User) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
2
请完成以下Java代码
public int getCaretPosition() { return m_textArea.getCaretPosition(); } /** * Set Text Editable * @param edit */ public void setEditable (boolean edit) { m_textArea.setEditable(edit); } /** * Is Text Editable * @return true if editable */ public boolean isEditable() { return m_textArea.isEditable(); } /** * Set Text Line Wrap * @param wrap */ public void setLineWrap (boolean wrap) { m_textArea.setLineWrap (wrap); } /** * Set Text Wrap Style Word * @param word */ public void setWrapStyleWord (boolean word) { m_textArea.setWrapStyleWord (word); } /** * Set Opaque * @param isOpaque */ @Override public void setOpaque (boolean isOpaque) { // JScrollPane & Viewport is always not Opaque if (m_textArea == null) // during init of JScrollPane super.setOpaque(isOpaque); else m_textArea.setOpaque(isOpaque); } // setOpaque /** * Set Text Margin * @param m insets */ public void setMargin (Insets m) { if (m_textArea != null) m_textArea.setMargin(m); } // setMargin /** * AddFocusListener * @param l */ @Override public void addFocusListener (FocusListener l) { if (m_textArea == null) // during init super.addFocusListener(l); else m_textArea.addFocusListener(l); }
/** * Add Text Mouse Listener * @param l */ @Override public void addMouseListener (MouseListener l) { m_textArea.addMouseListener(l); } /** * Add Text Key Listener * @param l */ @Override public void addKeyListener (KeyListener l) { m_textArea.addKeyListener(l); } /** * Add Text Input Method Listener * @param l */ @Override public void addInputMethodListener (InputMethodListener l) { m_textArea.addInputMethodListener(l); } /** * Get text Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textArea.getInputMethodRequests(); } /** * Set Text Input Verifier * @param l */ @Override public void setInputVerifier (InputVerifier l) { m_textArea.setInputVerifier(l); } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } } // CTextArea
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
1
请完成以下Java代码
public ILUTUConfigurationEditor save() { assertEditing(); final I_M_HU_LUTU_Configuration lutuConfigurationInitial = getLUTUConfiguration(); final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); // // Check if we need to use the new configuration or we are ok with the old one final I_M_HU_LUTU_Configuration lutuConfigurationToUse; if (InterfaceWrapperHelper.isNew(lutuConfigurationInitial)) { lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing; } else if (lutuFactory.isSameForHUProducer(lutuConfigurationInitial, lutuConfigurationEditing)) { // Copy all values from our new configuration to initial configuration InterfaceWrapperHelper.copyValues(lutuConfigurationEditing, lutuConfigurationInitial, false); // honorIsCalculated=false lutuFactory.save(lutuConfigurationInitial); lutuConfigurationToUse = lutuConfigurationInitial; } else { lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing;
} _lutuConfigurationInitial = lutuConfigurationToUse; _lutuConfigurationEditing = null; // stop editing mode return this; } @Override public ILUTUConfigurationEditor pushBackToModel() { if (isEditing()) { save(); } final I_M_HU_LUTU_Configuration lutuConfiguration = getLUTUConfiguration(); lutuConfigurationManager.setCurrentLUTUConfigurationAndSave(lutuConfiguration); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\LUTUConfigurationEditor.java
1
请完成以下Java代码
public Segment enableTranslatedNameRecognize(boolean enable) { config.translatedNameRecognize = enable; config.updateNerConfig(); return this; } /** * 是否启用日本人名识别 * * @param enable */ public Segment enableJapaneseNameRecognize(boolean enable) { config.japaneseNameRecognize = enable; config.updateNerConfig(); return this; } /** * 是否启用偏移量计算(开启后Term.offset才会被计算) * * @param enable * @return */ public Segment enableOffset(boolean enable) { config.offset = enable; return this; } /** * 是否启用数词和数量词识别<br> * 即[二, 十, 一] => [二十一],[十, 九, 元] => [十九元] * * @param enable * @return */ public Segment enableNumberQuantifierRecognize(boolean enable) { config.numberQuantifierRecognize = enable; return this; } /** * 是否启用所有的命名实体识别 * * @param enable * @return */ public Segment enableAllNamedEntityRecognize(boolean enable) { config.nameRecognize = enable; config.japaneseNameRecognize = enable; config.translatedNameRecognize = enable; config.placeRecognize = enable; config.organizationRecognize = enable; config.updateNerConfig(); return this; } class WorkThread extends Thread { String[] sentenceArray; List<Term>[] termListArray; int from;
int to; public WorkThread(String[] sentenceArray, List<Term>[] termListArray, int from, int to) { this.sentenceArray = sentenceArray; this.termListArray = termListArray; this.from = from; this.to = to; } @Override public void run() { for (int i = from; i < to; ++i) { termListArray[i] = segSentence(sentenceArray[i].toCharArray()); } } } /** * 开启多线程 * * @param enable true表示开启[系统CPU核心数]个线程,false表示单线程 * @return */ public Segment enableMultithreading(boolean enable) { if (enable) config.threadNumber = Runtime.getRuntime().availableProcessors(); else config.threadNumber = 1; return this; } /** * 开启多线程 * * @param threadNumber 线程数量 * @return */ public Segment enableMultithreading(int threadNumber) { config.threadNumber = threadNumber; return this; } /** * 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存 */ public Segment enableNormalization(boolean normalization) { config.normalization = normalization; return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Segment.java
1
请在Spring Boot框架中完成以下Java代码
public void setRepair_VHU_ID (final int Repair_VHU_ID) { if (Repair_VHU_ID < 1) set_Value (COLUMNNAME_Repair_VHU_ID, null); else set_Value (COLUMNNAME_Repair_VHU_ID, Repair_VHU_ID); } @Override public int getRepair_VHU_ID() { return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID); } /** * Status AD_Reference_ID=541245 * Reference name: C_Project_Repair_Task_Status */ public static final int STATUS_AD_Reference_ID=541245; /** Not Started = NS */ public static final String STATUS_NotStarted = "NS"; /** In Progress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus()
{ return get_ValueAsString(COLUMNNAME_Status); } /** * Type AD_Reference_ID=541243 * Reference name: C_Project_Repair_Task_Type */ public static final int TYPE_AD_Reference_ID=541243; /** ServiceRepairOrder = W */ public static final String TYPE_ServiceRepairOrder = "W"; /** SpareParts = P */ public static final String TYPE_SpareParts = "P"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
2
请完成以下Java代码
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { for (ProcessEnginePlugin plugin : plugins) { plugin.preInit(processEngineConfiguration); } } @Override public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) { for (ProcessEnginePlugin plugin : plugins) { plugin.postInit(processEngineConfiguration); } } @Override public void postProcessEngineBuild(ProcessEngine processEngine) { for (ProcessEnginePlugin plugin : plugins) { plugin.postProcessEngineBuild(processEngine); } } /** * Get all plugins. *
* @return the configured plugins */ public List<ProcessEnginePlugin> getPlugins() { return plugins; } @Override public String toString() { return this.getClass().getSimpleName() + plugins; } private static List<ProcessEnginePlugin> toList(ProcessEnginePlugin plugin, ProcessEnginePlugin... additionalPlugins) { final List<ProcessEnginePlugin> plugins = new ArrayList<ProcessEnginePlugin>(); plugins.add(plugin); if (additionalPlugins != null && additionalPlugins.length > 0) { plugins.addAll(Arrays.asList(additionalPlugins)); } return plugins; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\CompositeProcessEnginePlugin.java
1
请完成以下Spring Boot application配置
server: port: 8080 servlet: context-path: / spring: application: name: Api-Gateway cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "https://www.baeldung.com" allowedMethods: - GET allowedHeaders: "*" routes: - id: product_service_route predicates: - Path=/product/** uri: http://localhost:8081 method: GET - id: user_service_route predicates: - Path=/user/** uri: http://localhost:8081 method: GET metadata: cors: allowedOrigins: 'https://www.baeldung.com,http://localhost:3000' allowedMethods
: - GET allowedHeaders: '*' springdoc: api-docs: enabled: true path: /v3/api-docs swagger-ui: enabled: true config-url: /v3/api-docs/swagger-config urls: - name: gateway-service url: /v3/api-docs - name: product-service url: /product/v3/api-docs
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-3\spring-cloud-gateway-service\src\main\resources\application.yml
2
请完成以下Java代码
public class ScriptTypeTaskListener implements TaskListener { private static final long serialVersionUID = -8915149072830499057L; protected Expression script; protected Expression language; protected Expression resultVariable; public ScriptTypeTaskListener() { } public ScriptTypeTaskListener(Expression language, Expression script) { this.script = script; this.language = language; } @Override public void notify(DelegateTask delegateTask) { validateParameters(); ScriptingEngines scriptingEngines = CommandContextUtil.getCmmnEngineConfiguration().getScriptingEngines(); String language = Objects.toString(this.language.getValue(delegateTask), null); if (language == null) { throw new FlowableIllegalStateException("'language' evaluated to null for taskListener of type 'script'"); } String script = Objects.toString(this.script.getValue(delegateTask), null); if (script == null) { throw new FlowableIllegalStateException("Script content is null or evaluated to null for taskListener of type 'script'"); } ScriptEngineRequest.Builder request = ScriptEngineRequest.builder() .script(script) .language(language) .scopeContainer(delegateTask) .traceEnhancer(trace -> trace.addTraceTag("type", "taskListener"));
Object result = scriptingEngines.evaluate(request.build()).getResult(); if (resultVariable != null) { String resultVariable = Objects.toString(this.resultVariable.getValue(delegateTask), null); if (resultVariable != null) { delegateTask.setVariable(resultVariable, result); } } } protected void validateParameters() { if (script == null) { throw new IllegalArgumentException("The field 'script' should be set on the TaskListener"); } if (language == null) { throw new IllegalArgumentException("The field 'language' should be set on the TaskListener"); } } public void setScript(Expression script) { this.script = script; } public void setLanguage(Expression language) { this.language = language; } public void setResultVariable(Expression resultVariable) { this.resultVariable = resultVariable; } public Expression getResultVariable() { return resultVariable; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\listener\ScriptTypeTaskListener.java
1
请完成以下Java代码
public String getSpData() { return spData; } public void setSpData(String spData) { this.spData = spData; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id);
sb.append(", productId=").append(productId); sb.append(", skuCode=").append(skuCode); sb.append(", price=").append(price); sb.append(", stock=").append(stock); sb.append(", lowStock=").append(lowStock); sb.append(", pic=").append(pic); sb.append(", sale=").append(sale); sb.append(", promotionPrice=").append(promotionPrice); sb.append(", lockStock=").append(lockStock); sb.append(", spData=").append(spData); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsSkuStock.java
1
请在Spring Boot框架中完成以下Java代码
public GrpcChannelProperties getChannel(final String name) { final GrpcChannelProperties properties = getRawChannel(name); properties.copyDefaultsFrom(getGlobalChannel()); return properties; } /** * Gets the global channel properties. Global properties are used, if the channel properties don't overwrite them. * If neither the global nor the per client properties are set then default values will be used. * * @return The global channel properties. */ public final GrpcChannelProperties getGlobalChannel() { // This cannot be moved to its own field, // as Spring replaces the instance in the map and inconsistencies would occur. return getRawChannel(GLOBAL_PROPERTIES_KEY); } /** * Gets or creates the channel properties for the given client. * * @param name The name of the channel to get the properties for. * @return The properties for the given channel name. */ private GrpcChannelProperties getRawChannel(final String name) { return this.client.computeIfAbsent(name, key -> new GrpcChannelProperties()); }
private String defaultScheme; /** * Get the default scheme that should be used, if the client doesn't specify a scheme/address. * * @return The default scheme to use or null. * @see #setDefaultScheme(String) */ public String getDefaultScheme() { return this.defaultScheme; } /** * Sets the default scheme to use, if the client doesn't specify a scheme/address. If not specified it will default * to the default scheme of the {@link io.grpc.NameResolver.Factory}. Examples: {@code dns}, {@code discovery}. * * @param defaultScheme The default scheme to use or null. */ public void setDefaultScheme(String defaultScheme) { this.defaultScheme = defaultScheme; } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\config\GrpcChannelsProperties.java
2
请完成以下Java代码
public class SessionFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init filter"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Cookie[] allCookies = req.getCookies(); if (allCookies != null) { Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null);
if (session != null) { session.setHttpOnly(true); session.setSecure(true); res.addCookie(session); } } chain.doFilter(req, res); } @Override public void destroy() { System.out.println("destroy filter"); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\session\filter\SessionFilter.java
1
请完成以下Java代码
public void remove() { lexiographicallyOrderedScriptsSupplier.get().remove(); } @SuppressWarnings("unused") private void dumpTofile(SortedSet<IScript> lexiagraphicallySortedScripts) { FileWriter writer; try { writer = new FileWriter(GloballyOrderedScannerDecorator.class.getName() + "_sorted_scripts.txt"); for (final IScript script : lexiagraphicallySortedScripts) { writer.write(script.toString() + "\n"); } writer.close();
} catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(getInternalScanner()) .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\GloballyOrderedScannerDecorator.java
1
请完成以下Java代码
public void destroy() throws Exception { if (cmmnEngine != null) { cmmnEngine.close(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public CmmnEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (cmmnEngineConfiguration.getBeans() == null) { cmmnEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.cmmnEngine = cmmnEngineConfiguration.buildCmmnEngine(); return this.cmmnEngine; } protected void configureExternallyManagedTransactions() { if (cmmnEngineConfiguration instanceof SpringCmmnEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringCmmnEngineConfiguration engineConfiguration = (SpringCmmnEngineConfiguration) cmmnEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { cmmnEngineConfiguration.setTransactionsExternallyManaged(true); } } }
@Override public Class<CmmnEngine> getObjectType() { return CmmnEngine.class; } @Override public boolean isSingleton() { return true; } public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-cmmn-spring\src\main\java\org\flowable\cmmn\spring\CmmnEngineFactoryBean.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentJdbcRepository { @Autowired JdbcTemplate jdbcTemplate; class StudentRowMapper implements RowMapper<Student> { @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setId(rs.getLong("id")); student.setName(rs.getString("name")); student.setPassportNumber(rs.getString("passport_number")); return student; } } public List<Student> findAll() { return jdbcTemplate.query("select * from student", new StudentRowMapper()); } public Student findById(long id) {
return jdbcTemplate.queryForObject("select * from student where id=?", new Object[] { id }, new BeanPropertyRowMapper<Student>(Student.class)); } public int deleteById(long id) { return jdbcTemplate.update("delete from student where id=?", new Object[] { id }); } public int insert(Student student) { return jdbcTemplate.update("insert into student (id, name, passport_number) " + "values(?, ?, ?)", new Object[] { student.getId(), student.getName(), student.getPassportNumber() }); } public int update(Student student) { return jdbcTemplate.update("update student " + " set name = ?, passport_number = ? " + " where id = ?", new Object[] { student.getName(), student.getPassportNumber(), student.getId() }); } }
repos\Spring-Boot-Advanced-Projects-main\spring-boot-2-jdbc-with-h2\src\main\java\com\alanbinu\springboot\jdbc\h2\example\student\StudentJdbcRepository.java
2
请完成以下Java代码
public Criteria andShowStatusNotBetween(Integer value1, Integer value2) { addCriterion("show_status not between", value1, value2, "showStatus"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition;
this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaExample.java
1
请在Spring Boot框架中完成以下Java代码
public void stop(StopContext context) { // nothing to do } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } public boolean schedule(Runnable runnable, boolean isLongRunning) { if(isLongRunning) { return scheduleLongRunningWork(runnable); } else { return scheduleShortRunningWork(runnable); } } protected boolean scheduleShortRunningWork(Runnable runnable) { ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); try { managedQueueExecutorService.executeBlocking(runnable); return true; } catch (InterruptedException e) { // the the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (Exception e) { // we must be able to schedule this log.log(Level.WARNING, "Cannot schedule long running work.", e); } return false;
} protected boolean scheduleLongRunningWork(Runnable runnable) { final ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); boolean rejected = false; try { // wait for 2 seconds for the job to be accepted by the pool. managedQueueExecutorService.executeBlocking(runnable, 2, TimeUnit.SECONDS); } catch (InterruptedException e) { // the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (ExecutionTimedOutException e) { rejected = true; } catch (RejectedExecutionException e) { rejected = true; } catch (Exception e) { // if it fails for some other reason, log a warning message long now = System.currentTimeMillis(); // only log every 60 seconds to prevent log flooding if((now-lastWarningLogged) >= (60*1000)) { log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e); } else { log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e); } } return !rejected; } public InjectedValue<ManagedQueueExecutorService> getManagedQueueInjector() { return managedQueueInjector; } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
2
请完成以下Java代码
public IQueryOrderByBuilder<T> addColumn(final String columnName) { final Direction direction = Direction.Ascending; final Nulls nulls = getNulls(direction); return addColumn(columnName, direction, nulls); } @Override public IQueryOrderByBuilder<T> addColumn(ModelColumn<T, ?> column) { final String columnName = column.getColumnName(); return addColumn(columnName); } @Override public IQueryOrderByBuilder<T> addColumnAscending(@NonNull final String columnName) { final Direction direction = Direction.Ascending; final Nulls nulls = getNulls(direction); return addColumn(columnName, direction, nulls); } @Override public IQueryOrderByBuilder<T> addColumnDescending(@NonNull final String columnName) { final Direction direction = Direction.Descending; final Nulls nulls = getNulls(direction); return addColumn(columnName, direction, nulls); } @Override public IQueryOrderByBuilder<T> addColumn( @NonNull final String columnName, @NonNull final Direction direction, @NonNull final Nulls nulls) { final QueryOrderByItem orderByItem = new QueryOrderByItem(columnName, direction, nulls); orderBys.add(orderByItem); return this; }
@Override public IQueryOrderByBuilder<T> addColumn(@NonNull final ModelColumn<T, ?> column, final Direction direction, final Nulls nulls) { final String columnName = column.getColumnName(); return addColumn(columnName, direction, nulls); } private Nulls getNulls(final Direction direction) { // NOTE: keeping backward compatibility // i.e. postgresql 9.1. specifications: // "By default, null values sort as if larger than any non-null value; // that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise." // // see https://www.postgresql.org/docs/9.5/queries-order.html if (direction == Direction.Descending) { return Nulls.First; } else { return Nulls.Last; } } @Override public IQueryOrderBy createQueryOrderBy() { final QueryOrderBy orderBy = new QueryOrderBy(orderBys); return orderBy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderByBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public final class ProductMasterDataProvider { private final IProductBL productsBL = Services.get(IProductBL.class); @NonNull private final ExternalIdentifierProductLookupService productLookupService; @Value private static class ProductCacheKey { @NonNull OrgId orgId; @NonNull ExternalIdentifier productExternalIdentifier; } @Value @Builder public static class ProductInfo { @NonNull ProductId productId; @NonNull HUPIItemProductId hupiItemProductId; @NonNull UomId uomId; @With boolean justCreated; } private final CCache<ProductCacheKey, ProductInfo> productInfoCache = CCache .<ProductCacheKey, ProductInfo>builder() .cacheName(this.getClass().getSimpleName() + "-productInfoCache") .tableName(I_M_Product.Table_Name) .build(); public ProductInfo getProductInfo(
@NonNull final ExternalIdentifier productExternalIdentifier, @NonNull final OrgId orgId) { return productInfoCache.getOrLoad( new ProductCacheKey(orgId, productExternalIdentifier), this::getProductInfo0); } private ProductInfo getProductInfo0(@NonNull final ProductCacheKey key) { final ExternalIdentifier productIdentifier = key.getProductExternalIdentifier(); final ProductAndHUPIItemProductId productAndHUPIItemProductId = productLookupService .resolveProductExternalIdentifier(productIdentifier, key.getOrgId()) .orElseThrow(() -> MissingResourceException.builder() .resourceName("productIdentifier") .resourceIdentifier(productIdentifier.getRawValue()) .build()); final UomId uomId = productsBL.getStockUOMId(productAndHUPIItemProductId.getProductId()); return ProductInfo.builder() .productId(productAndHUPIItemProductId.getProductId()) .hupiItemProductId(productAndHUPIItemProductId.getHupiItemProductId()) .uomId(uomId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\ProductMasterDataProvider.java
2
请完成以下Java代码
public class Shift { private LocalDateTime start; private LocalDateTime end; private String requiredSkill; @PlanningVariable private Employee employee; // A no-arg constructor is required for @PlanningEntity annotated classes public Shift() { } public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill) { this(start, end, requiredSkill, null); } public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill, Employee employee) { this.start = start; this.end = end; this.requiredSkill = requiredSkill; this.employee = employee; } @Override public String toString() { return start + " - " + end; } public LocalDateTime getStart() {
return start; } public LocalDateTime getEnd() { return end; } public String getRequiredSkill() { return requiredSkill; } public Employee getEmployee() { return employee; } }
repos\tutorials-master\timefold-solver\src\main\java\com\baeldung\timefoldsolver\Shift.java
1
请完成以下Java代码
public class FilterRules { public static List<SecurityFilterRule> load(InputStream configFileResource, String applicationPath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); SecurityFilterConfig config = objectMapper.readValue(configFileResource, SecurityFilterConfig.class); return createFilterRules(config, applicationPath); } public static List<SecurityFilterRule> createFilterRules(SecurityFilterConfig config, String applicationPath) { PathFilterConfig pathFilter = config.getPathFilter(); PathFilterRule rule = createPathFilterRule(pathFilter, applicationPath); return new ArrayList<>(Collections.singletonList(rule)); } protected static PathFilterRule createPathFilterRule(PathFilterConfig pathFilter, String applicationPath) { PathFilterRule pathFilterRule = new PathFilterRule(); for (PathMatcherConfig pathMatcherConfig : pathFilter.getDeniedPaths()) { pathFilterRule.getDeniedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath)); } for (PathMatcherConfig pathMatcherConfig : pathFilter.getAllowedPaths()) { pathFilterRule.getAllowedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath)); } return pathFilterRule; } protected static RequestMatcher transformPathMatcher(PathMatcherConfig pathMatcherConfig, String applicationPath) { RequestFilter requestMatcher = new RequestFilter( pathMatcherConfig.getPath(), applicationPath, pathMatcherConfig.getParsedMethods()); RequestAuthorizer requestAuthorizer = RequestAuthorizer.AUTHORIZE_ANNONYMOUS; if (pathMatcherConfig.getAuthorizer() != null) { String authorizeCls = pathMatcherConfig.getAuthorizer(); requestAuthorizer = (RequestAuthorizer) ReflectUtil.instantiate(authorizeCls); } return new RequestMatcher(requestMatcher, requestAuthorizer); }
/** * Iterate over a number of filter rules and match them against * the given request. * * @param requestMethod * @param requestUri * @param filterRules * * @return the checked request with authorization information attached */ public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) { Authorization authorization; for (SecurityFilterRule filterRule : filterRules) { authorization = filterRule.authorize(requestMethod, requestUri); if (authorization != null) { return authorization; } } // grant if no filter disallows it return Authorization.granted(Authentication.ANONYMOUS); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\util\FilterRules.java
1
请在Spring Boot框架中完成以下Java代码
public ForecastExtensionType getForecastExtension() { return forecastExtension; } /** * Sets the value of the forecastExtension property. * * @param value * allowed object is * {@link ForecastExtensionType } * */ public void setForecastExtension(ForecastExtensionType value) { this.forecastExtension = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ControlTotalQualifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="ControlTotalValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "controlTotalQualifier", "controlTotalValue" }) public static class ControlTotal { @XmlElement(name = "ControlTotalQualifier") protected String controlTotalQualifier; @XmlElement(name = "ControlTotalValue") protected String controlTotalValue; /** * Gets the value of the controlTotalQualifier property. * * @return * possible object is * {@link String } * */ public String getControlTotalQualifier() { return controlTotalQualifier; } /** * Sets the value of the controlTotalQualifier property. * * @param value * allowed object is
* {@link String } * */ public void setControlTotalQualifier(String value) { this.controlTotalQualifier = value; } /** * Gets the value of the controlTotalValue property. * * @return * possible object is * {@link String } * */ public String getControlTotalValue() { return controlTotalValue; } /** * Sets the value of the controlTotalValue property. * * @param value * allowed object is * {@link String } * */ public void setControlTotalValue(String value) { this.controlTotalValue = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DocumentExtensionType.java
2
请完成以下Java代码
public class InOutCost { @NonNull private final InOutCostId id; @Setter @Nullable InOutCostId reversalId; @NonNull private final OrgId orgId; @NonNull private final OrderCostDetailId orderCostDetailId; @NonNull private final OrderAndLineId orderAndLineId; @NonNull private final SOTrx soTrx; @NonNull private final InOutAndLineId inoutAndLineId; @Nullable private final BPartnerId bpartnerId; @NonNull private final OrderCostTypeId costTypeId; @NonNull private final CostElementId costElementId; @NonNull private final Quantity qty; @NonNull private final Money costAmount; @NonNull private Money costAmountInvoiced; private boolean isInvoiced; @Builder private InOutCost( @NonNull final InOutCostId id, @Nullable final InOutCostId reversalId, @NonNull final OrgId orgId, @NonNull final OrderCostDetailId orderCostDetailId, @NonNull final OrderAndLineId orderAndLineId, @NonNull final SOTrx soTrx, @NonNull final InOutAndLineId inoutAndLineId, @Nullable final BPartnerId bpartnerId, @NonNull final OrderCostTypeId costTypeId, @NonNull final CostElementId costElementId, @NonNull final Quantity qty, @NonNull final Money costAmount, @NonNull final Money costAmountInvoiced, boolean isInvoiced) { this.soTrx = soTrx; Money.assertSameCurrency(costAmount, costAmountInvoiced); this.id = id; this.reversalId = reversalId; this.orgId = orgId; this.orderCostDetailId = orderCostDetailId; this.orderAndLineId = orderAndLineId; this.inoutAndLineId = inoutAndLineId; this.bpartnerId = bpartnerId; this.costTypeId = costTypeId; this.costElementId = costElementId; this.qty = qty; this.costAmount = costAmount; this.costAmountInvoiced = costAmountInvoiced; this.isInvoiced = isInvoiced; } public OrderCostId getOrderCostId() {return orderCostDetailId.getOrderCostId();} public OrderId getOrderId() {return orderAndLineId.getOrderId();} public OrderLineId getOrderLineId() {return orderAndLineId.getOrderLineId();} public InOutId getInOutId() {return inoutAndLineId.getInOutId();}
public InOutLineId getInOutLineId() {return inoutAndLineId.getInOutLineId();} public void addCostAmountInvoiced(@NonNull final Money amtToAdd) { this.costAmountInvoiced = this.costAmountInvoiced.add(amtToAdd); this.isInvoiced = this.costAmount.isEqualByComparingTo(this.costAmountInvoiced); } public Money getCostAmountToInvoice() { return costAmount.subtract(costAmountInvoiced); } public Money getCostAmountForQty(final Quantity qty, CurrencyPrecision precision) { if (qty.equalsIgnoreSource(this.qty)) { return costAmount; } else if (qty.isZero()) { return costAmount.toZero(); } else { final Money price = costAmount.divide(this.qty.toBigDecimal(), CurrencyPrecision.ofInt(12)); return price.multiply(qty.toBigDecimal()).round(precision); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCost.java
1
请完成以下Java代码
private String createCardContent(InstanceEvent event, Instance instance) { String content = this.createContent(event, instance); Map<String, Object> header = new HashMap<>(); header.put("template", StringUtils.hasText(this.card.getThemeColor()) ? "red" : this.card.getThemeColor()); Map<String, String> titleContent = new HashMap<>(); titleContent.put("tag", "plain_text"); titleContent.put("content", this.card.getTitle()); header.put("title", titleContent); List<Map<String, Object>> elements = new ArrayList<>(); Map<String, Object> item = new HashMap<>(); item.put("tag", "div"); Map<String, String> text = new HashMap<>(); text.put("tag", "plain_text"); text.put("content", content); item.put("text", text); elements.add(item); if (this.atAll) { Map<String, Object> atItem = new HashMap<>(); atItem.put("tag", "div"); Map<String, String> atText = new HashMap<>(); atText.put("tag", "lark_md"); atText.put("content", "<at id=all></at>"); atItem.put("text", atText); elements.add(atItem); } Map<String, Object> cardContent = new HashMap<>(); cardContent.put("header", header); cardContent.put("elements", elements); return this.toJsonString(cardContent); } private String toJsonString(Object o) { try { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); return objectMapper.writeValueAsString(o); } catch (Exception ex) { log.warn("Failed to serialize JSON object", ex); } return null; } public URI getWebhookUrl() { return this.webhookUrl; } public void setWebhookUrl(URI webhookUrl) { this.webhookUrl = webhookUrl; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public boolean isAtAll() { return atAll; } public void setAtAll(boolean atAll) { this.atAll = atAll; } public String getSecret() { return secret; }
public void setSecret(String secret) { this.secret = secret; } public MessageType getMessageType() { return messageType; } public void setMessageType(MessageType messageType) { this.messageType = messageType; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public enum MessageType { text, interactive } public static class Card { /** * This is header title. */ private String title = "Codecentric's Spring Boot Admin notice"; private String themeColor = "red"; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getThemeColor() { return themeColor; } public void setThemeColor(String themeColor) { this.themeColor = themeColor; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\FeiShuNotifier.java
1
请完成以下Java代码
public abstract class AgentReloader { private static final Set<String> AGENT_CLASSES; static { Set<String> agentClasses = new LinkedHashSet<>(); agentClasses.add("org.zeroturnaround.javarebel.Integration"); agentClasses.add("org.zeroturnaround.javarebel.ReloaderFactory"); agentClasses.add("org.hotswap.agent.HotswapAgent"); AGENT_CLASSES = Collections.unmodifiableSet(agentClasses); } private AgentReloader() { } /** * Determine if any agent reloader is active. * @return true if agent reloading is active */
public static boolean isActive() { return isActive(null) || isActive(AgentReloader.class.getClassLoader()) || isActive(ClassLoader.getSystemClassLoader()); } private static boolean isActive(@Nullable ClassLoader classLoader) { for (String agentClass : AGENT_CLASSES) { if (ClassUtils.isPresent(agentClass, classLoader)) { return true; } } return false; } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\AgentReloader.java
1
请完成以下Java代码
public class CorrelationPropertyRetrievalExpressionImpl extends BaseElementImpl implements CorrelationPropertyRetrievalExpression { protected static AttributeReference<Message> messageRefAttribute; protected static ChildElement<MessagePath> messagePathChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CorrelationPropertyRetrievalExpression.class, BPMN_ELEMENT_CORRELATION_PROPERTY_RETRIEVAL_EXPRESSION) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<CorrelationPropertyRetrievalExpression>() { public CorrelationPropertyRetrievalExpression newInstance(ModelTypeInstanceContext instanceContext) { return new CorrelationPropertyRetrievalExpressionImpl(instanceContext); } }); messageRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_MESSAGE_REF) .required() .qNameAttributeReference(Message.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); messagePathChild = sequenceBuilder.element(MessagePath.class) .required() .build(); typeBuilder.build(); } public CorrelationPropertyRetrievalExpressionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext);
} public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public MessagePath getMessagePath() { return messagePathChild.getChild(this); } public void setMessagePath(MessagePath messagePath) { messagePathChild.setChild(this, messagePath); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CorrelationPropertyRetrievalExpressionImpl.java
1
请完成以下Java代码
public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } @Override public void addIncomingAssociation(Association association) { this.incomingAssociations.add(association); } @Override public List<Association> getIncomingAssociations() { return incomingAssociations; } @Override public void setIncomingAssociations(List<Association> incomingAssociations) { this.incomingAssociations = incomingAssociations; } @Override public void addOutgoingAssociation(Association association) { this.outgoingAssociations.add(association); } @Override public List<Association> getOutgoingAssociations() { return outgoingAssociations; } @Override
public void setOutgoingAssociations(List<Association> outgoingAssociations) { this.outgoingAssociations = outgoingAssociations; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); if (isEntryCriterion) { stringBuilder.append("Entry criterion"); } else { stringBuilder.append("Exit criterion"); } stringBuilder.append(" with id '").append(id).append("'"); return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Criterion.java
1
请完成以下Java代码
private JsonNode createDetails(AlarmRuleState ruleState) { JsonNode alarmDetails; String alarmDetailsStr = ruleState.getAlarmRule().getAlarmDetails(); DashboardId dashboardId = ruleState.getAlarmRule().getDashboardId(); if (StringUtils.isNotEmpty(alarmDetailsStr) || dashboardId != null) { ObjectNode newDetails = JacksonUtil.newObjectNode(); if (StringUtils.isNotEmpty(alarmDetailsStr)) { for (var keyFilter : ruleState.getAlarmRule().getCondition().getCondition()) { EntityKeyValue entityKeyValue = dataSnapshot.getValue(keyFilter.getKey()); if (entityKeyValue != null) { alarmDetailsStr = alarmDetailsStr.replaceAll(String.format("\\$\\{%s}", keyFilter.getKey().getKey()), getValueAsString(entityKeyValue)); } } newDetails.put("data", alarmDetailsStr); } if (dashboardId != null) { newDetails.put("dashboardId", dashboardId.getId().toString()); } alarmDetails = newDetails; } else if (currentAlarm != null) { alarmDetails = currentAlarm.getDetails(); } else { alarmDetails = JacksonUtil.newObjectNode(); } return alarmDetails; } private static String getValueAsString(EntityKeyValue entityKeyValue) { Object result = null; switch (entityKeyValue.getDataType()) { case STRING: result = entityKeyValue.getStrValue(); break; case JSON: result = entityKeyValue.getJsonValue(); break; case LONG: result = entityKeyValue.getLngValue(); break; case DOUBLE: result = entityKeyValue.getDblValue(); break; case BOOLEAN: result = entityKeyValue.getBoolValue();
break; } return String.valueOf(result); } public boolean processAlarmClear(TbContext ctx, Alarm alarmNf) { boolean updated = false; if (currentAlarm != null && currentAlarm.getId().equals(alarmNf.getId())) { currentAlarm = null; for (AlarmRuleState state : createRulesSortedBySeverityDesc) { updated = clearAlarmState(updated, state); } } return updated; } public void processAckAlarm(Alarm alarm) { if (currentAlarm != null && currentAlarm.getId().equals(alarm.getId())) { currentAlarm.setAcknowledged(alarm.isAcknowledged()); currentAlarm.setAckTs(alarm.getAckTs()); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\AlarmState.java
1
请完成以下Java代码
class CassandraDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<CassandraConnectionDetails> { private static final int CASSANDRA_PORT = 9042; CassandraDockerComposeConnectionDetailsFactory() { super("cassandra"); } @Override protected CassandraConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new CassandraDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link CassandraConnectionDetails} backed by a {@code Cassandra} * {@link RunningService}. */ static class CassandraDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements CassandraConnectionDetails { private final List<Node> contactPoints;
private final String datacenter; CassandraDockerComposeConnectionDetails(RunningService service) { super(service); CassandraEnvironment cassandraEnvironment = new CassandraEnvironment(service.env()); this.contactPoints = List.of(new Node(service.host(), service.ports().get(CASSANDRA_PORT))); this.datacenter = cassandraEnvironment.getDatacenter(); } @Override public List<Node> getContactPoints() { return this.contactPoints; } @Override public String getLocalDatacenter() { return this.datacenter; } } }
repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\docker\compose\CassandraDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public static TaxId ofRepoId(final int repoId) { return new TaxId(repoId); } @Nullable public static TaxId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<TaxId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final TaxId id) { return id != null ? id.getRepoId() : -1; } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static int toRepoId(@Nullable final Optional<TaxId> optional) { //noinspection OptionalAssignedToNull final TaxId id = optional != null ? optional.orElse(null) : null; return toRepoId(id); } public static int toRepoIdOrNoTaxId(@Nullable final TaxId id) { return id != null ? id.getRepoId() : Tax.C_TAX_ID_NO_TAX_FOUND; } int repoId;
private TaxId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Tax_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isNoTaxId() { return repoId == Tax.C_TAX_ID_NO_TAX_FOUND; } public static boolean equals(@Nullable TaxId id1, @Nullable TaxId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\TaxId.java
1
请完成以下Java代码
public List<Attachment> findAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); return getDbSqlSession().selectList("selectAttachmentsByTaskId", taskId); } @SuppressWarnings("unchecked") public void deleteAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); List<AttachmentEntity> attachments = getDbSqlSession().selectList("selectAttachmentsByTaskId", taskId); boolean dispatchEvents = getProcessEngineConfiguration().getEventDispatcher().isEnabled(); String processInstanceId = null; String processDefinitionId = null; String executionId = null; if (dispatchEvents && attachments != null && !attachments.isEmpty()) { // Forced to fetch the task to get hold of the process definition for event-dispatching, if available Task task = getTaskManager().findTaskById(taskId); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); processInstanceId = task.getProcessInstanceId(); executionId = task.getExecutionId(); } } for (AttachmentEntity attachment : attachments) {
String contentId = attachment.getContentId(); if (contentId != null) { getByteArrayManager().deleteByteArrayById(contentId); } getDbSqlSession().delete(attachment); if (dispatchEvents) { getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, attachment, executionId, processInstanceId, processDefinitionId), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } } protected void checkHistoryEnabled() { if (!getHistoryManager().isHistoryEnabled()) { throw new ActivitiException("In order to use attachments, history should be enabled"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityManager.java
1
请完成以下Java代码
public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public Map<String, Object> getTransientVariables() { return transientVariables; } public void setTransientVariables(Map<String, Object> transientVariables) { this.transientVariables = transientVariables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getAssigneeId() {
return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public String getInitiatorVariableName() { return initiatorVariableName; } public void setInitiatorVariableName(String initiatorVariableName) { this.initiatorVariableName = initiatorVariableName; } public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } public String getPredefinedCaseInstanceId() { return predefinedCaseInstanceId; } public void setPredefinedCaseInstanceId(String predefinedCaseInstanceId) { this.predefinedCaseInstanceId = predefinedCaseInstanceId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\StartCaseInstanceBeforeContext.java
1
请完成以下Java代码
public class ProcessStartedListenerDelegate implements ActivitiEventListener { private List<ProcessRuntimeEventListener<ProcessStartedEvent>> listeners; private ToAPIProcessStartedEventConverter processInstanceStartedEventConverter; public ProcessStartedListenerDelegate( List<ProcessRuntimeEventListener<ProcessStartedEvent>> listeners, ToAPIProcessStartedEventConverter processInstanceStartedEventConverter ) { this.listeners = listeners; this.processInstanceStartedEventConverter = processInstanceStartedEventConverter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiProcessStartedEvent) {
processInstanceStartedEventConverter .from((ActivitiProcessStartedEvent) event) .ifPresent(convertedEvent -> { for (ProcessRuntimeEventListener<ProcessStartedEvent> listener : listeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ProcessStartedListenerDelegate.java
1
请在Spring Boot框架中完成以下Java代码
public DecisionDefinitionQuery orderByVersionTag() { return orderBy(DecisionDefinitionQueryProperty.VERSION_TAG); } //results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { if (isDmnEnabled(commandContext)) { checkQueryOk(); return commandContext .getDecisionDefinitionManager() .findDecisionDefinitionCountByQueryCriteria(this); } return 0; } @Override public List<DecisionDefinition> executeList(CommandContext commandContext, Page page) { if (isDmnEnabled(commandContext)) { checkQueryOk(); return commandContext .getDecisionDefinitionManager() .findDecisionDefinitionsByQueryCriteria(this, page); } return Collections.emptyList(); } @Override public void checkQueryOk() { super.checkQueryOk(); // latest() makes only sense when used with key() or keyLike() if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){ throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)"); } } private boolean isDmnEnabled(CommandContext commandContext) { return commandContext .getProcessEngineConfiguration() .isDmnEnabled(); } // getters //////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId;
} public Date getDeployedAfter() { return deployedAfter; } public Date getDeployedAt() { return deployedAt; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public Integer getVersion() { return version; } public String getVersionTag() { return versionTag; } public String getVersionTagLike() { return versionTagLike; } public boolean isLatest() { return latest; } public boolean isShouldJoinDeploymentTable() { return shouldJoinDeploymentTable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java
2
请完成以下Java代码
public class XmlValidator { private static final Logger LOGGER = LoggerFactory.getLogger(XmlValidator.class); private String xsdPath; private String xmlPath; public XmlValidator(String xsdPath, String xmlPath) { this.xsdPath = xsdPath; this.xmlPath = xmlPath; } public boolean isValid() throws IOException, SAXException { Validator validator = initValidator(xsdPath); try { validator.validate(new StreamSource(getFile(xmlPath))); return true; } catch (SAXException e) { return false; } } public List<SAXParseException> listParsingExceptions() throws IOException, SAXException {
XmlErrorHandler xsdErrorHandler = new XmlErrorHandler(); Validator validator = initValidator(xsdPath); validator.setErrorHandler(xsdErrorHandler); try { validator.validate(new StreamSource(getFile(xmlPath))); } catch (SAXParseException e) {} xsdErrorHandler.getExceptions().forEach(e -> LOGGER.info(String.format("Line number: %s, Column number: %s. %s", e.getLineNumber(), e.getColumnNumber(), e.getMessage()))); return xsdErrorHandler.getExceptions(); } private Validator initValidator(String xsdPath) throws SAXException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile = new StreamSource(getFile(xsdPath)); Schema schema = factory.newSchema(schemaFile); return schema.newValidator(); } private File getFile(String location) { return new File(getClass().getClassLoader().getResource(location).getFile()); } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\validation\XmlValidator.java
1
请完成以下Java代码
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Referenz. @param Reference Reference for this record */ @Override public void setReference (java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Referenz. @return Reference for this record */ @Override public java.lang.String getReference () { return (java.lang.String)get_Value(COLUMNNAME_Reference); } /** Set Mitteilung. @param TextMsg Text Message */ @Override public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message */ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set View ID. @param ViewId View ID */ @Override public void setViewId (java.lang.String ViewId) { set_Value (COLUMNNAME_ViewId, ViewId); } /** Get View ID. @return View ID */ @Override public java.lang.String getViewId () { return (java.lang.String)get_Value(COLUMNNAME_ViewId); } /** Set Sql WHERE. @param WhereClause
Fully qualified SQL WHERE clause */ @Override public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); } /** * NotificationSeverity AD_Reference_ID=541947 * Reference name: NotificationSeverity */ public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947; /** Notice = Notice */ public static final String NOTIFICATIONSEVERITY_Notice = "Notice"; /** Warning = Warning */ public static final String NOTIFICATIONSEVERITY_Warning = "Warning"; /** Error = Error */ public static final String NOTIFICATIONSEVERITY_Error = "Error"; @Override public void setNotificationSeverity (final java.lang.String NotificationSeverity) { set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity); } @Override public java.lang.String getNotificationSeverity() { return get_ValueAsString(COLUMNNAME_NotificationSeverity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); }
/** Set Registername. @param TabName Registername */ @Override public void setTabName (java.lang.String TabName) { set_Value (COLUMNNAME_TabName, TabName); } /** Get Registername. @return Registername */ @Override public java.lang.String getTabName () { return (java.lang.String)get_Value(COLUMNNAME_TabName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_SubTab.java
1
请完成以下Java代码
public class FTSDocumentFilterConverter implements SqlDocumentFilterConverter { public static final FTSDocumentFilterConverter instance = new FTSDocumentFilterConverter(); @Override public boolean canConvert(final String filterId) { return FTSDocumentFilterDescriptorsProviderFactory.FILTER_ID.equals(filterId); } @Nullable @Override public FilterSql getSql( @NonNull final DocumentFilter filter, @NonNull final SqlOptions sqlOpts, @NonNull final SqlDocumentFilterConverterContext context) { final String searchText = filter.getParameterValueAsString(FTSDocumentFilterDescriptorsProviderFactory.PARAM_SearchText, null); if (searchText == null || Check.isBlank(searchText)) { return FilterSql.ALLOW_ALL; } final FTSFilterContext ftsContext = filter.getParameterValueAs(FTSDocumentFilterDescriptorsProviderFactory.PARAM_Context); Check.assumeNotNull(ftsContext, "Parameter ftsContext is not null"); // shall not happen final FTSFilterDescriptor ftsFilterDescriptor = ftsContext.getFilterDescriptor(); final FTSSearchService searchService = ftsContext.getSearchService(); final FTSConfig ftsConfig = searchService.getConfigById(ftsFilterDescriptor.getFtsConfigId()); final FTSSearchResult ftsResult = searchService.search(FTSSearchRequest.builder() .searchId(extractSearchId(context)) .searchText(searchText) .esIndexName(ftsConfig.getEsIndexName()) .userRolePermissionsKey(context.getUserRolePermissionsKey()) .filterDescriptor(ftsFilterDescriptor) .build()); if (ftsResult.isEmpty()) {
return FilterSql.allowNoneWithComment("no FTS result"); } // final SqlAndParams whereClause = SqlAndParams.builder() // .append("EXISTS (") // .append(" SELECT 1 FROM ").append(I_T_ES_FTS_Search_Result.Table_Name) // .append(" WHERE ") // .append(" ").append(I_T_ES_FTS_Search_Result.COLUMNNAME_Search_UUID).append("=?", ftsResult.getSearchId()) // .append(" AND ").append(ftsFilterDescriptor.getJoinColumns().buildJoinCondition(sqlOpts.getTableNameOrAlias(), "")) // .append(")") // .build(); return FilterSql.builder() .filterByFTS(FilterSql.FullTextSearchResult.builder() .searchId(ftsResult.getSearchId()) .joinColumns(ftsFilterDescriptor.getJoinColumns()) .build()) .build(); } private static String extractSearchId(@NonNull final SqlDocumentFilterConverterContext context) { final ViewId viewId = context.getViewId(); if (viewId == null) { throw new AdempiereException("viewId shall be provided in " + context); } return viewId.toJson(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\fullTextSearch\FTSDocumentFilterConverter.java
1
请完成以下Java代码
public int getAndIncrementRuleNodeCounter() { return ruleNodeExecCounter.getAndIncrement(); } public TbMsgProcessingCtx copy() { if (stack == null || stack.isEmpty()) { return new TbMsgProcessingCtx(ruleNodeExecCounter.get()); } else { return new TbMsgProcessingCtx(ruleNodeExecCounter.get(), new LinkedList<>(stack)); } } public void push(RuleChainId ruleChainId, RuleNodeId ruleNodeId) { if (stack == null) { stack = new LinkedList<>(); } stack.add(new TbMsgProcessingStackItem(ruleChainId, ruleNodeId)); } public TbMsgProcessingStackItem pop() { if (stack == null || stack.isEmpty()) { return null; } return stack.removeLast(); } public static TbMsgProcessingCtx fromProto(MsgProtos.TbMsgProcessingCtxProto ctx) { int ruleNodeExecCounter = ctx.getRuleNodeExecCounter(); if (ctx.getStackCount() > 0) { LinkedList<TbMsgProcessingStackItem> stack = new LinkedList<>(); for (MsgProtos.TbMsgProcessingStackItemProto item : ctx.getStackList()) { stack.add(TbMsgProcessingStackItem.fromProto(item)); } return new TbMsgProcessingCtx(ruleNodeExecCounter, stack); } else {
return new TbMsgProcessingCtx(ruleNodeExecCounter); } } public MsgProtos.TbMsgProcessingCtxProto toProto() { var ctxBuilder = MsgProtos.TbMsgProcessingCtxProto.newBuilder(); ctxBuilder.setRuleNodeExecCounter(ruleNodeExecCounter.get()); if (stack != null) { for (TbMsgProcessingStackItem item : stack) { ctxBuilder.addStack(item.toProto()); } } return ctxBuilder.build(); } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsgProcessingCtx.java
1
请完成以下Java代码
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 Message.
@param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Convention.java
1
请完成以下Java代码
public void setBooks(List<BookList> books) { this.books = books; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) {
return false; } return id != null && id.equals(((AuthorList) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\AuthorList.java
1
请在Spring Boot框架中完成以下Java代码
public DeploymentEntity getDeployment() { return deployment; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public boolean isDeployChangedOnly() { return deployChangedOnly; } public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; }
public String getNameFromDeployment() { return nameFromDeployment; } public Set<String> getDeployments() { return deployments; } public Map<String, Set<String>> getDeploymentResourcesById() { return deploymentResourcesById; } public Map<String, Set<String>> getDeploymentResourcesByName() { return deploymentResourcesByName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeploymentBuilderImpl.java
2
请完成以下Java代码
public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId(); result.timestamp = historicExternalTaskLog.getTimestamp(); result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries();
result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请在Spring Boot框架中完成以下Java代码
public class WebInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ApplicationConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(ctx)); ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } // @Override // public void onStartup(ServletContext container) {
// // Create the 'root' Spring application context // AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); // rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); // // // Manage the lifecycle of the root application context // container.addListener(new ContextLoaderListener(rootContext)); // // // Create the dispatcher servlet's Spring application context // AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); // dispatcherServlet.register(MvcConfig.class); // // // Register and map the dispatcher servlet // ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); // dispatcher.setLoadOnStartup(1); // dispatcher.addMapping("/"); // // } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\springmvcforms\configuration\WebInitializer.java
2
请完成以下Java代码
public CompletableFuture<String> doTaskOne() throws Exception { log.info("开始做任务一"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任务一,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务一完成"); } @Async public CompletableFuture<String> doTaskTwo() throws Exception { log.info("开始做任务二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务二完成"); } @Async public CompletableFuture<String> doTaskThree() throws Exception { log.info("开始做任务三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任务三,耗时:" + (end - start) + "毫秒"); return CompletableFuture.completedFuture("任务三完成"); } }
repos\SpringBoot-Learning-master\2.x\chapter7-6\src\main\java\com\didispace\chapter76\AsyncTasks.java
1
请完成以下Java代码
public void searchUsers() { logger.info("Searching users in Keycloak {}", keycloak.serverInfo() .getInfo() .getSystemInfo() .getVersion()); searchByUsername("user1", true); searchByUsername("user", false); searchByUsername("1", false); searchByEmail("user2@test.com", true); searchByAttributes("DOB:2000-01-05"); searchByGroup("c67643fb-514e-488a-a4b4-5c0bdf2e7477"); searchByRole("user"); } private void searchByUsername(String username, boolean exact) { logger.info("Searching by username: {} (exact {})", username, exact); List<UserRepresentation> users = keycloak.realm(REALM_NAME) .users() .searchByUsername(username, exact); logger.info("Users found by username {}", users.stream() .map(user -> user.getUsername()) .collect(Collectors.toList())); } private void searchByEmail(String email, boolean exact) { logger.info("Searching by email: {} (exact {})", email, exact); List<UserRepresentation> users = keycloak.realm(REALM_NAME) .users() .searchByEmail(email, exact); logger.info("Users found by email {}", users.stream() .map(user -> user.getEmail()) .collect(Collectors.toList())); }
private void searchByAttributes(String query) { logger.info("Searching by attributes: {}", query); List<UserRepresentation> users = keycloak.realm(REALM_NAME) .users() .searchByAttributes(query); logger.info("Users found by attributes {}", users.stream() .map(user -> user.getUsername() + " " + user.getAttributes()) .collect(Collectors.toList())); } private void searchByGroup(String groupId) { logger.info("Searching by group: {}", groupId); List<UserRepresentation> users = keycloak.realm(REALM_NAME) .groups() .group(groupId) .members(); logger.info("Users found by group {}", users.stream() .map(user -> user.getUsername()) .collect(Collectors.toList())); } private void searchByRole(String roleName) { logger.info("Searching by role: {}", roleName); List<UserRepresentation> users = keycloak.realm(REALM_NAME) .roles() .get(roleName) .getUserMembers(); logger.info("Users found by role {}", users.stream() .map(user -> user.getUsername()) .collect(Collectors.toList())); } }
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-2\src\main\java\com\baeldung\keycloak\adminclient\AdminClientService.java
1
请完成以下Java代码
public void updateLogAndLinesDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus) { updateLogDocStatus(tableRecordReference, docStatus); updateLogLineDocStatus(tableRecordReference, docStatus); } private void updateLogDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus) { final ICompositeQueryUpdater<I_C_Doc_Outbound_Log> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_Doc_Outbound_Log.class) .addSetColumnValue(I_C_Doc_Outbound_Log.COLUMNNAME_DocStatus, DocStatus.toCodeOrNull(docStatus)); queryBL.createQueryBuilder(I_C_Doc_Outbound_Log.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Doc_Outbound_Log.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId()) .addEqualsFilter(I_C_Doc_Outbound_Log.COLUMN_Record_ID, tableRecordReference.getRecord_ID()) .create() .update(queryUpdater); } private void updateLogLineDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus) { final ICompositeQueryUpdater<I_C_Doc_Outbound_Log_Line> queryUpdaterLogLine = queryBL.createCompositeQueryUpdater(I_C_Doc_Outbound_Log_Line.class) .addSetColumnValue(I_C_Doc_Outbound_Log_Line.COLUMNNAME_DocStatus, DocStatus.toCodeOrNull(docStatus)); queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId()) .addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMN_Record_ID, tableRecordReference.getRecord_ID()) .create() .update(queryUpdaterLogLine); }
@Override @NonNull public ImmutableList<LogWithLines> retrieveLogsWithLines(@NonNull final ImmutableList<I_C_Doc_Outbound_Log> logs) { if (logs.isEmpty()) { return ImmutableList.of(); } final ImmutableSet<DocOutboundLogId> ids = logs.stream() .map(log -> DocOutboundLogId.ofRepoId(log.getC_Doc_Outbound_Log_ID())) .collect(ImmutableSet.toImmutableSet()); final Map<Integer, List<I_C_Doc_Outbound_Log_Line>> linesByLogId = queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class) .addInArrayFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_C_Doc_Outbound_Log_ID, ids) .create() .list() .stream() .collect(Collectors.groupingBy(I_C_Doc_Outbound_Log_Line::getC_Doc_Outbound_Log_ID)); return logs.stream() .map(log -> LogWithLines.builder() .log(log) .lines(linesByLogId.getOrDefault(log.getC_Doc_Outbound_Log_ID(), Collections.emptyList())) .build()) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundDAO.java
1
请完成以下Java代码
public IntegrationFlow fileMoverWithPriorityChannel() { return IntegrationFlow.from(sourceDirectory()) .filter(onlyJpgs()) .channel("alphabetically") .handle(targetDirectory()) .get(); } @Bean public MessageHandler anotherTargetDirectory() { FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2)); handler.setExpectReply(false); // end of pipeline, reply not needed return handler; } @Bean public MessageChannel holdingTank() { return MessageChannels.queue().get(); } // @Bean public IntegrationFlow fileReader() { return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); } // @Bean public IntegrationFlow fileWriter() { return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit())))) .handle(targetDirectory()) .get(); } // @Bean public IntegrationFlow anotherFileWriter() { return IntegrationFlow.from("holdingTank") .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit())))) .handle(anotherTargetDirectory()) .get(); } public static void main(final String... args) { final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); System.out.print("Please enter a string and press <enter>: "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { context.close(); scanner.close(); break; } } System.exit(0); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java
1
请在Spring Boot框架中完成以下Java代码
class RestApi { @GetMapping("/blocking") Mono<String> getBlocking() { return Mono.fromCallable(() -> { try { Thread.sleep(2_000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "foo"; }); } @GetMapping("/non-blocking") Mono<String> getNonBlocking() { return Mono.just("bar") .delayElement(Duration.ofSeconds(2)); } @SuppressWarnings("BlockingMethodInNonBlockingContext") @GetMapping("/warning") Mono<String> warning() { Mono<String> data = fetchData(); String response = "retrieved data: " + data.block(); return Mono.just(response); } private Mono<String> fetchData() { return Mono.just("bar"); }
@GetMapping("/blocking-with-scheduler") Mono<String> getBlockingWithDedicatedScheduler() { return Mono.fromCallable(this::fetchDataBlocking) .subscribeOn(Schedulers.boundedElastic()) .map(data -> "retrieved data: " + data); } private String fetchDataBlocking() { try { Thread.sleep(2_000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "foo"; } } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\threadstarvation\ThreadStarvationApp.java
2
请完成以下Java代码
public class Reader { private Integer id; private String firstname; private String lastname; private String randomNum; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname == null ? null : firstname.trim(); } public String getLastname() {
return lastname; } public void setLastname(String lastname) { this.lastname = lastname == null ? null : lastname.trim(); } public String getRandomNum() { return randomNum; } public void setRandomNum(String randomNum) { this.randomNum = randomNum == null ? null : randomNum.trim(); } }
repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\entity\secondary\Reader.java
1
请完成以下Java代码
public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } public org.compiere.model.I_EXP_Processor getEXP_Processor() throws RuntimeException { return (org.compiere.model.I_EXP_Processor)MTable.get(getCtx(), org.compiere.model.I_EXP_Processor.Table_Name) .getPO(getEXP_Processor_ID(), get_TrxName()); } /** Set Export Processor. @param EXP_Processor_ID Export Processor */ public void setEXP_Processor_ID (int EXP_Processor_ID) { if (EXP_Processor_ID < 1) set_Value (COLUMNNAME_EXP_Processor_ID, null); else set_Value (COLUMNNAME_EXP_Processor_ID, Integer.valueOf(EXP_Processor_ID)); } /** Get Export Processor. @return Export Processor */ public int getEXP_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () {
return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationStrategy.java
1
请在Spring Boot框架中完成以下Java代码
protected void setDistributedSystemId(Integer distributedSystemId) { this.distributedSystemId = Optional.ofNullable(distributedSystemId) .filter(id -> id > -1) .orElse(this.distributedSystemId); } protected Optional<Integer> getDistributedSystemId() { return Optional.ofNullable(this.distributedSystemId) .filter(id -> id > -1); } protected Logger getLogger() { return this.logger; } private int validateDistributedSystemId(int distributedSystemId) { Assert.isTrue(distributedSystemId >= -1 && distributedSystemId < 256, String.format("Distributed System ID [%d] must be between -1 and 255", distributedSystemId)); return distributedSystemId; } @Bean ClientCacheConfigurer clientCacheDistributedSystemIdConfigurer() { return (beanName, clientCacheFactoryBean) -> getDistributedSystemId().ifPresent(distributedSystemId -> { Logger logger = getLogger();
if (logger.isWarnEnabled()) { logger.warn("Distributed System Id [{}] was set on the ClientCache instance, which will not have any effect", distributedSystemId); } }); } @Bean PeerCacheConfigurer peerCacheDistributedSystemIdConfigurer() { return (beanName, cacheFactoryBean) -> getDistributedSystemId().ifPresent(id -> cacheFactoryBean.getProperties() .setProperty(GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY, String.valueOf(validateDistributedSystemId(id)))); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DistributedSystemIdConfiguration.java
2
请完成以下Java代码
public <ReqT, RespT> Listener<ReqT> interceptCall( final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { try { final GrpcExceptionServerCall<ReqT, RespT> handledCall = new GrpcExceptionServerCall<>(call, this.exceptionHandler); final Listener<ReqT> delegate = next.startCall(handledCall, headers); return new GrpcExceptionListener<>(delegate, call, this.exceptionHandler); } catch (final Throwable error) { // For errors from grpc method implementation methods directly (Not via StreamObserver) this.exceptionHandler.handleError(call, error); // Required to close streaming calls return noOpCallListener();
} } /** * Creates a new no-op call listener because you can neither return null nor throw an exception in * {@link #interceptCall(ServerCall, Metadata, ServerCallHandler)}. * * @param <ReqT> The type of the request. * @return The newly created dummy listener. */ protected <ReqT> Listener<ReqT> noOpCallListener() { return new Listener<ReqT>() {}; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\error\GrpcExceptionInterceptor.java
1
请完成以下Java代码
public Map<String, Object> getProperties() { return properties; } public String getPropertiesInternal() { return JsonUtil.asString(properties); } public Filter setProperties(Map<String, Object> properties) { this.properties = properties; return this; } public void setPropertiesInternal(String properties) { if (properties != null) { JsonObject json = JsonUtil.asObject(properties); this.properties = JsonUtil.asMap(json); } else { this.properties = null; } } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public int getRevisionNext() { return revision + 1; } @SuppressWarnings("unchecked") public <T extends Query<?, ?>> Filter extend(T extendingQuery) { ensureNotNull(NotValidException.class, "extendingQuery", extendingQuery); if (!extendingQuery.getClass().equals(query.getClass())) { throw LOG.queryExtensionException(query.getClass().getName(), extendingQuery.getClass().getName()); } FilterEntity copy = copyFilter(); copy.setQuery(query.extend(extendingQuery)); return copy; } @SuppressWarnings("unchecked") protected <T> JsonObjectConverter<T> getConverter() { JsonObjectConverter<T> converter = (JsonObjectConverter<T>) queryConverter.get(resourceType); if (converter != null) { return converter; } else { throw LOG.unsupportedResourceTypeException(resourceType); }
} public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("name", this.name); persistentState.put("owner", this.owner); persistentState.put("query", this.query); persistentState.put("properties", this.properties); return persistentState; } protected FilterEntity copyFilter() { FilterEntity copy = new FilterEntity(getResourceType()); copy.setName(getName()); copy.setOwner(getOwner()); copy.setQueryInternal(getQueryInternal()); copy.setPropertiesInternal(getPropertiesInternal()); return copy; } public void postLoad() { if (query != null) { query.addValidator(StoredQueryValidator.get()); } } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\FilterEntity.java
1
请在Spring Boot框架中完成以下Java代码
public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public boolean isCompletable() { return completable; } public void setCompletable(boolean completable) { this.completable = completable; } public String getEntryCriterionId() { return entryCriterionId; } public void setEntryCriterionId(String entryCriterionId) { this.entryCriterionId = entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getFormKey() { return formKey; }
public void setFormKey(String formKey) { this.formKey = formKey; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getCompletedBy() { return completedBy; } public void setCompletedBy(String completedBy) { this.completedBy = completedBy; } public String getExtraValue() { return extraValue; } public void setExtraValue(String extraValue) { this.extraValue = extraValue; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java
2
请完成以下Java代码
public static Function<ServerRequest, ServerRequest> stripPrefix() { return stripPrefix(1); } public static Function<ServerRequest, ServerRequest> stripPrefix(int parts) { return request -> { MvcUtils.addOriginalRequestUrl(request, request.uri()); // TODO: gateway url attributes String path = request.uri().getRawPath(); // TODO: begin duplicate code from StripPrefixGatewayFilterFactory String[] originalParts = StringUtils.tokenizeToStringArray(path, "/"); // all new paths start with / StringBuilder newPath = new StringBuilder("/"); for (int i = 0; i < originalParts.length; i++) { if (i >= parts) { // only append slash if this is the second part or greater if (newPath.length() > 1) { newPath.append('/'); } newPath.append(originalParts[i]); } } if (newPath.length() > 1 && path.endsWith("/")) { newPath.append('/'); } // TODO: end duplicate code from StripPrefixGatewayFilterFactory URI prefixedUri = UriComponentsBuilder.fromUri(request.uri()) .replacePath(newPath.toString()) .build(true) .toUri(); return ServerRequest.from(request).uri(prefixedUri).build(); }; } public static Function<ServerRequest, ServerRequest> uri(String uri) { return uri(URI.create(uri)); } public static Function<ServerRequest, ServerRequest> uri(URI uri) { return request -> { MvcUtils.setRequestUrl(request, uri); return request; }; } public static class FallbackHeadersConfig { private String executionExceptionTypeHeaderName = CB_EXECUTION_EXCEPTION_TYPE; private String executionExceptionMessageHeaderName = CB_EXECUTION_EXCEPTION_MESSAGE;
private String rootCauseExceptionTypeHeaderName = CB_ROOT_CAUSE_EXCEPTION_TYPE; private String rootCauseExceptionMessageHeaderName = CB_ROOT_CAUSE_EXCEPTION_MESSAGE; public String getExecutionExceptionTypeHeaderName() { return executionExceptionTypeHeaderName; } public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) { this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName; } public String getExecutionExceptionMessageHeaderName() { return executionExceptionMessageHeaderName; } public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) { this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName; } public String getRootCauseExceptionTypeHeaderName() { return rootCauseExceptionTypeHeaderName; } public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) { this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName; } public String getRootCauseExceptionMessageHeaderName() { return rootCauseExceptionMessageHeaderName; } public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) { this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\BeforeFilterFunctions.java
1
请完成以下Java代码
static Builder<?> builder(String url, WebSocketClient webSocketClient) { return new DefaultWebSocketGraphQlClientBuilder(url, webSocketClient); } /** * Return a builder for a {@link WebSocketGraphQlClient}. * @param url the GraphQL endpoint URL * @param webSocketClient the underlying transport client to use */ static Builder<?> builder(URI url, WebSocketClient webSocketClient) { return new DefaultWebSocketGraphQlClientBuilder(url, webSocketClient); } /** * Builder for a GraphQL over WebSocket client. * @param <B> the builder type */ interface Builder<B extends Builder<B>> extends WebGraphQlClient.Builder<B> {
/** * Configure how frequently to send ping messages. * <p>By default, this is not set, and ping messages are not sent. * @param keepAlive the value to use * @since 1.3.0 */ Builder<B> keepAlive(Duration keepAlive); /** * Build the {@code WebSocketGraphQlClient}. */ @Override WebSocketGraphQlClient build(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\WebSocketGraphQlClient.java
1
请完成以下Java代码
static final class Builder implements Authentication.Builder<Builder> { private final Log logger = LogFactory.getLog(getClass()); private final Collection<GrantedAuthority> authorities = new LinkedHashSet<>(); private @Nullable Object principal; private @Nullable Object credentials; private @Nullable Object details; private boolean authenticated; Builder(Authentication authentication) { this.logger.debug("Creating a builder which will result in exchanging an authentication of type " + authentication.getClass() + " for " + SimpleAuthentication.class.getSimpleName() + ";" + " consider implementing " + authentication.getClass().getSimpleName() + "#toBuilder"); this.authorities.addAll(authentication.getAuthorities()); this.principal = authentication.getPrincipal(); this.credentials = authentication.getCredentials(); this.details = authentication.getDetails(); this.authenticated = authentication.isAuthenticated(); } @Override public Builder authorities(Consumer<Collection<GrantedAuthority>> authorities) { authorities.accept(this.authorities); return this; } @Override public Builder details(@Nullable Object details) { this.details = details; return this; } @Override public Builder principal(@Nullable Object principal) { this.principal = principal; return this; }
@Override public Builder credentials(@Nullable Object credentials) { this.credentials = credentials; return this; } @Override public Builder authenticated(boolean authenticated) { this.authenticated = authenticated; return this; } @Override public Authentication build() { return new SimpleAuthentication(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\SimpleAuthentication.java
1
请完成以下Java代码
private PickingJobStep withChangedPickFroms(@NonNull final UnaryOperator<PickingJobStepPickFromMap> mapper) { final PickingJobStepPickFromMap newPickFroms = mapper.apply(this.pickFroms); return !Objects.equals(this.pickFroms, newPickFroms) ? toBuilder().pickFroms(newPickFroms).build() : this; } public ImmutableSet<PickingJobStepPickFromKey> getPickFromKeys() { return pickFroms.getKeys(); } public PickingJobStepPickFrom getPickFrom(@NonNull final PickingJobStepPickFromKey key) { return pickFroms.getPickFrom(key); } public PickingJobStepPickFrom getPickFromByHUQRCode(@NonNull final HUQRCode qrCode)
{ return pickFroms.getPickFromByHUQRCode(qrCode); } @NonNull public List<HuId> getPickedHUIds() { return pickFroms.getPickedHUIds(); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHU() { return pickFroms.getLastPickedHU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStep.java
1
请完成以下Java代码
private static final class ColumnNamePair { @lombok.NonNull String columnName; @lombok.NonNull String subQueryColumnName; @lombok.NonNull IQueryFilterModifier modifier; } public static final class Builder<T> { private String tableName; private final List<ColumnNamePair> matchers = new ArrayList<>(); private IQuery<?> subQuery; private Builder() { } public InSubQueryFilter<T> build() { return new InSubQueryFilter<>(this); } public Builder<T> tableName(final String tableName) { this.tableName = tableName; return this; } public Builder<T> subQuery(final IQuery<?> subQuery) { this.subQuery = subQuery; return this; }
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier) { matchers.add(ColumnNamePair.builder() .columnName(columnName) .subQueryColumnName(subQueryColumnName) .modifier(modifier) .build()); return this; } public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName) { return matchingColumnNames(columnName, subQueryColumnName, NullQueryFilterModifier.instance); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
private void updateSOCreditStatus(@NonNull final BPartnerStats bpStats) { final IBPartnerStatsBL bpartnerStatsBL = Services.get(IBPartnerStatsBL.class); // load the statistics final I_C_BPartner_Stats stats = loadDataRecord(bpStats); final BigDecimal creditUsed = stats.getSO_CreditUsed(); final BPartnerCreditLimitRepository creditLimitRepo = Adempiere.getBean(BPartnerCreditLimitRepository.class); final BigDecimal creditLimit = creditLimitRepo.retrieveCreditLimitByBPartnerId(bpStats.getBpartnerId().getRepoId(), SystemTime.asDayTimestamp()); final String initialCreditStatus = bpStats.getSOCreditStatus(); String creditStatusToSet; // Nothing to do if (X_C_BPartner_Stats.SOCREDITSTATUS_NoCreditCheck.equals(initialCreditStatus) || X_C_BPartner_Stats.SOCREDITSTATUS_CreditStop.equals(initialCreditStatus) || BigDecimal.ZERO.compareTo(creditLimit) == 0) { return; } // Above Credit Limit if (creditLimit.compareTo(creditUsed) < 0) { creditStatusToSet = X_C_BPartner_Stats.SOCREDITSTATUS_CreditHold; } else { // Above Watch Limit final BigDecimal watchAmt = creditLimit.multiply(bpartnerStatsBL.getCreditWatchRatio(bpStats)); if (watchAmt.compareTo(creditUsed) < 0) { creditStatusToSet = X_C_BPartner_Stats.SOCREDITSTATUS_CreditWatch; } else { // is OK creditStatusToSet = X_C_BPartner_Stats.SOCREDITSTATUS_CreditOK; } }
setSOCreditStatus(bpStats, creditStatusToSet); } private void updateCreditLimitIndicator(@NonNull final BPartnerStats bstats) { // load the statistics final I_C_BPartner_Stats stats = loadDataRecord(bstats); final BigDecimal creditUsed = stats.getSO_CreditUsed(); final BPartnerCreditLimitRepository creditLimitRepo = Adempiere.getBean(BPartnerCreditLimitRepository.class); final BigDecimal creditLimit = creditLimitRepo.retrieveCreditLimitByBPartnerId(stats.getC_BPartner_ID(), SystemTime.asDayTimestamp()); final BigDecimal percent = creditLimit.signum() == 0 ? BigDecimal.ZERO : creditUsed.divide(creditLimit, 2, BigDecimal.ROUND_HALF_UP); final Locale locale = Locale.getDefault(); final NumberFormat fmt = NumberFormat.getPercentInstance(locale); fmt.setMinimumFractionDigits(1); fmt.setMaximumFractionDigits(1); final String percentSring = fmt.format(percent); stats.setCreditLimitIndicator(percentSring); saveRecord(stats); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerStatsDAO.java
2
请在Spring Boot框架中完成以下Java代码
protected CandidatesQuery createPreExistingCandidatesQuery( @NonNull final AbstractDDOrderEvent ddOrderEvent, @NonNull final DDOrderLine ddOrderLine, @NonNull final CandidateType candidateType) { final SupplyRequiredDescriptor supplyRequiredDescriptor = ddOrderEvent.getSupplyRequiredDescriptor(); if (supplyRequiredDescriptor != null && supplyRequiredDescriptor.getSupplyCandidateId() > 0) { return CandidatesQuery.fromId(CandidateId.ofRepoId(supplyRequiredDescriptor.getSupplyCandidateId())); } final DDOrderCreatedEvent ddOrderCreatedEvent = DDOrderCreatedEvent.cast(ddOrderEvent); final DDOrder ddOrder = ddOrderCreatedEvent.getDdOrder(); final MaterialDispoGroupId groupId = ddOrder.getMaterialDispoGroupId(); if (groupId == null) { // returned false, but don't write another log message; we already logged in the other createQuery() method
return CandidatesQuery.FALSE; } return CandidatesQuery.builder() .type(candidateType) .businessCase(CandidateBusinessCase.DISTRIBUTION) .groupId(groupId) .materialDescriptorQuery(toMaterialDescriptorQuery(ddOrderLine.getProductDescriptor())) .build(); } private static MaterialDescriptorQuery toMaterialDescriptorQuery(@NonNull final ProductDescriptor productDescriptor) { return MaterialDescriptorQuery.builder() .productId(productDescriptor.getProductId()) .storageAttributesKey(productDescriptor.getStorageAttributesKey()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderCreatedHandler.java
2
请完成以下Java代码
public class HistoricActivityStatisticsDto { protected String id; protected long instances; protected long canceled; protected long finished; protected long completeScope; protected long openIncidents; protected long resolvedIncidents; protected long deletedIncidents; public HistoricActivityStatisticsDto () {} public String getId() { return id; } public long getInstances() { return instances; } public long getCanceled() { return canceled; } public long getFinished() { return finished; } public long getCompleteScope() { return completeScope; } public long getOpenIncidents() { return openIncidents; } public long getResolvedIncidents() { return resolvedIncidents;
} public long getDeletedIncidents() { return deletedIncidents; } public static HistoricActivityStatisticsDto fromHistoricActivityStatistics(HistoricActivityStatistics statistics) { HistoricActivityStatisticsDto result = new HistoricActivityStatisticsDto(); result.id = statistics.getId(); result.instances = statistics.getInstances(); result.canceled = statistics.getCanceled(); result.finished = statistics.getFinished(); result.completeScope = statistics.getCompleteScope(); result.openIncidents = statistics.getOpenIncidents(); result.resolvedIncidents = statistics.getResolvedIncidents(); result.deletedIncidents = statistics.getDeletedIncidents(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityStatisticsDto.java
1
请完成以下Java代码
public void setProductType (final @Nullable java.lang.String ProductType) { set_Value (COLUMNNAME_ProductType, ProductType); } @Override public java.lang.String getProductType() { return get_ValueAsString(COLUMNNAME_ProductType); } /** * VATType AD_Reference_ID=540842 * Reference name: VATType */ public static final int VATTYPE_AD_Reference_ID=540842; /** RegularVAT = N */ public static final String VATTYPE_RegularVAT = "N"; /** ReducedVAT = R */
public static final String VATTYPE_ReducedVAT = "R"; /** TaxExempt = E */ public static final String VATTYPE_TaxExempt = "E"; @Override public void setVATType (final @Nullable java.lang.String VATType) { set_Value (COLUMNNAME_VATType, VATType); } @Override public java.lang.String getVATType() { return get_ValueAsString(COLUMNNAME_VATType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxCategory.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDeployResources() { return deployResources; } public void setDeployResources(boolean deployResources) { this.deployResources = deployResources; } public boolean isEnableChangeDetection() { return enableChangeDetection; } public void setEnableChangeDetection(boolean enableChangeDetection) { this.enableChangeDetection = enableChangeDetection; } public Duration getChangeDetectionInitialDelay() { return changeDetectionInitialDelay; } public void setChangeDetectionInitialDelay(Duration changeDetectionInitialDelay) { this.changeDetectionInitialDelay = changeDetectionInitialDelay; } public Duration getChangeDetectionDelay() { return changeDetectionDelay; } public void setChangeDetectionDelay(Duration changeDetectionDelay) {
this.changeDetectionDelay = changeDetectionDelay; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\FlowableEventRegistryProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); RedissonClient redisson = context.getBean(RedissonClient.class); RBloomFilter bf = redisson.getBloomFilter("test-bloom-filter"); bf.tryInit(100000L, 0.03); Set<String> set = new HashSet<String>(1000); List<String> list = new ArrayList<String>(1000); //Fill the Bloom filter with data. To test the reality, we recorded 1000 uuids and another 9000 as interference data. for (int i = 0; i < 10000; i++) { String uuid = UUID.randomUUID().toString(); if(i<1000){ set.add(uuid); list.add(uuid); } bf.add(uuid); } int wrong = 0; // Number of false positives by the Bloom filter int right = 0;// Bloom filter correct times
for (int i = 0; i < 10000; i++) { String str = i % 10 == 0 ? list.get(i / 10) : UUID.randomUUID().toString(); System.out.println(str); if (bf.contains(str)) { if (set.contains(str)) { right++; } else { wrong++; } } } //right is 1000 System.out.println("right:" + right); //Because the error rate is 3%, the wrong value of 10,000 data is about 30. System.out.println("wrong:" + wrong); //Filter remaining space size System.out.println(bf.count()); } }
repos\springboot-demo-master\BloomFilter\src\main\java\com\et\DemoApplication.java
2
请完成以下Java代码
protected HistoricActivityInstanceEventEntity loadActivityInstanceEventEntity(ExecutionEntity execution) { final String activityInstanceId = execution.getActivityInstanceId(); HistoricActivityInstanceEventEntity cachedEntity = findInCache(HistoricActivityInstanceEventEntity.class, activityInstanceId); if(cachedEntity != null) { return cachedEntity; } else { return newActivityInstanceEventEntity(execution); } } protected HistoricProcessInstanceEventEntity loadProcessInstanceEventEntity(ExecutionEntity execution) { final String processInstanceId = execution.getProcessInstanceId(); HistoricProcessInstanceEventEntity cachedEntity = findInCache(HistoricProcessInstanceEventEntity.class, processInstanceId); if(cachedEntity != null) { return cachedEntity; } else { return newProcessInstanceEventEntity(execution); } } protected HistoricTaskInstanceEventEntity loadTaskInstanceEvent(DelegateTask task) { final String taskId = task.getId(); HistoricTaskInstanceEventEntity cachedEntity = findInCache(HistoricTaskInstanceEventEntity.class, taskId); if(cachedEntity != null) { return cachedEntity; } else { return newTaskInstanceEventEntity(task); } } protected HistoricIncidentEventEntity loadIncidentEvent(Incident incident) { String incidentId = incident.getId(); HistoricIncidentEventEntity cachedEntity = findInCache(HistoricIncidentEventEntity.class, incidentId); if(cachedEntity != null) { return cachedEntity; } else { return newIncidentEventEntity(incident); } } protected HistoricBatchEntity loadBatchEntity(BatchEntity batch) { String batchId = batch.getId();
HistoricBatchEntity cachedEntity = findInCache(HistoricBatchEntity.class, batchId); if(cachedEntity != null) { return cachedEntity; } else { return newBatchEventEntity(batch); } } /** find a cached entity by primary key */ protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) { return Context.getCommandContext() .getDbEntityManager() .getCachedEntity(type, id); } @Override protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { CommandContext commandContext = Context.getCommandContext(); ProcessDefinitionEntity entity = null; if(commandContext != null) { entity = commandContext .getDbEntityManager() .getCachedEntity(ProcessDefinitionEntity.class, processDefinitionId); } return (entity != null) ? entity : super.getProcessDefinitionEntity(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareHistoryEventProducer.java
1
请在Spring Boot框架中完成以下Java代码
private void initToken(final long refreshTime) { LOG.debug("开始初始化access_token........"); //记住原本的时间,用于出错回滚 final long oldTime = this.weixinTokenStartTime; this.weixinTokenStartTime = refreshTime; String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.appid + "&secret=" + this.secret; NetWorkCenter.get(url, null, (resultCode, resultJson) -> { if (HttpStatus.SC_OK == resultCode) { GetTokenResponse response = JSON.parseObject(resultJson, GetTokenResponse.class); LOG.debug("获取access_token:{}", response.getAccessToken()); if (null == response.getAccessToken()) { //刷新时间回滚 weixinTokenStartTime = oldTime; throw new WeixinException( "微信公众号token获取出错,错误信息:" + response.getErrcode() + "," + response.getErrmsg()); } accessToken = response.getAccessToken(); //设置通知点 setChanged(); notifyObservers(new ConfigChangeNotice(appid, ChangeType.ACCESS_TOKEN, accessToken)); } }); //刷新工作做完,将标识设置回false this.tokenRefreshing.set(false); } /** * 初始化微信JS-SDK,获取JS-SDK token * * @param refreshTime 刷新时间 */
private void initJSToken(final long refreshTime) { LOG.debug("初始化 jsapi_ticket........"); //记住原本的时间,用于出错回滚 final long oldTime = this.jsTokenStartTime; this.jsTokenStartTime = refreshTime; String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"; NetWorkCenter.get(url, null, new NetWorkCenter.ResponseCallback() { @Override public void onResponse(int resultCode, String resultJson) { if (HttpStatus.SC_OK == resultCode) { GetJsApiTicketResponse response = JSON.parseObject(resultJson, GetJsApiTicketResponse.class); LOG.debug("获取jsapi_ticket:{}", response.getTicket()); if (StringUtils.isBlank(response.getTicket())) { //刷新时间回滚 jsTokenStartTime = oldTime; throw new WeixinException( "微信公众号jsToken获取出错,错误信息:" + response.getErrcode() + "," + response.getErrmsg()); } jsApiTicket = response.getTicket(); //设置通知点 setChanged(); notifyObservers(new ConfigChangeNotice(appid, ChangeType.JS_TOKEN, jsApiTicket)); } } }); //刷新工作做完,将标识设置回false this.jsRefreshing.set(false); } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\config\ApiConfig.java
2
请完成以下Java代码
public List<IInvoiceLineAttribute> aggregate() { final ImmutableSet<IInvoiceLineAttribute> finalIntersectionResult = currentIntersectionResult == null ? ImmutableSet.of() : ImmutableSet.copyOf(currentIntersectionResult); final LinkedHashSet<IInvoiceLineAttribute> result = new LinkedHashSet<>(currentUnionResult); result.addAll(finalIntersectionResult); return ImmutableList.copyOf(result); } @Override public void addToIntersection(@NonNull final Set<IInvoiceLineAttribute> invoiceLineAttributesToAdd) { // NOTE: we also consider empty sets because those shall also count. // Adding an empty set will turn our result to be an empty set, for good. // Case: current result is not set, so we are actually adding the first set if (currentIntersectionResult == null)
{ currentIntersectionResult = new LinkedHashSet<>(invoiceLineAttributesToAdd); } // Case: already have a current result, so we just need to intersect it with the set we got as parameter. else { currentIntersectionResult = Sets.intersection(currentIntersectionResult, invoiceLineAttributesToAdd); } } @Override public void addToUnion(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributesToAdd) { currentUnionResult.addAll(invoiceLineAttributesToAdd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\DefaultInvoiceLineAttributeAggregator.java
1
请完成以下Java代码
private JsonOLCand toJson( @NonNull final OLCand olCand, @NonNull final MasterdataProvider masterdataProvider) { final OrgId orgId = OrgId.ofRepoId(olCand.getAD_Org_ID()); final ZoneId orgTimeZone = masterdataProvider.getOrgTimeZone(orgId); final String orgCode = orgDAO.retrieveOrgValue(orgId); final OrderLineGroup orderLineGroup = olCand.getOrderLineGroup(); final JsonOrderLineGroup jsonOrderLineGroup = orderLineGroup == null ? null : JsonOrderLineGroup.builder() .groupKey(orderLineGroup.getGroupKey()) .isGroupMainItem(orderLineGroup.isGroupMainItem()) .build(); return JsonOLCand.builder() .id(olCand.getId()) .poReference(olCand.getPOReference()) .externalLineId(olCand.getExternalLineId()) .externalHeaderId(olCand.getExternalHeaderId()) // .orgCode(orgCode) // .bpartner(toJson(orgCode, olCand.getBPartnerInfo(), masterdataProvider)) .billBPartner(toJson(orgCode, olCand.getBillBPartnerInfo(), masterdataProvider)) .dropShipBPartner(toJson(orgCode, olCand.getDropShipBPartnerInfo().orElse(null), masterdataProvider)) .handOverBPartner(toJson(orgCode, olCand.getHandOverBPartnerInfo().orElse(null), masterdataProvider)) // .dateCandidate(TimeUtil.asLocalDate(olCand.unbox().getDateCandidate(), SystemTime.zoneId())) .dateOrdered(olCand.getDateOrdered()) .datePromised(TimeUtil.asLocalDate(olCand.getDatePromised(), orgTimeZone)) .flatrateConditionsId(olCand.getFlatrateConditionsId()) // .productId(olCand.getM_Product_ID()) .productDescription(olCand.getProductDescription()) .qty(olCand.getQty().toBigDecimal()) .uomId(olCand.getQty().getUomId().getRepoId()) .qtyItemCapacity(Quantitys.toBigDecimalOrNull(olCand.getQtyItemCapacityEff())) .huPIItemProductId(olCand.getHUPIProductItemId()) //
.pricingSystemId(PricingSystemId.toRepoId(olCand.getPricingSystemId())) .price(olCand.getPriceActual()) .discount(olCand.getDiscount()) // .warehouseDestId(WarehouseId.toRepoId(olCand.getWarehouseDestId())) // .jsonOrderLineGroup(jsonOrderLineGroup) .description(olCand.unbox().getDescription()) .adIssueId(Optional.ofNullable(olCand.getAdIssueId()) .map(AdIssueId::getRepoId) .map(JsonMetasfreshId::of) .orElse(null)) .line(olCand.getLine()) .build(); } @NonNull private static AssignSalesRepRule getAssignSalesRepRule(@NonNull final JsonApplySalesRepFrom jsonApplySalesRepFrom) { switch (jsonApplySalesRepFrom) { case Candidate: return AssignSalesRepRule.Candidate; case BPartner: return AssignSalesRepRule.BPartner; case CandidateFirst: return AssignSalesRepRule.CandidateFirst; default: throw new AdempiereException("Unsupported JsonApplySalesRepFrom " + jsonApplySalesRepFrom); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\JsonConverters.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { private List<User> users = Arrays.asList( new User("ana@yahoo.com", "pass", "Ana", 20), new User("bob@yahoo.com", "pass", "Bob", 30), new User("john@yahoo.com", "pass", "John", 40), new User("mary@yahoo.com", "pass", "Mary", 30)); @GetMapping("/userPage") public String getUserProfilePage() { return "user"; } @PostMapping("/user") @ResponseBody public ResponseEntity<Object> saveUser(@Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { final List<String> errors = result.getAllErrors().stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); return new ResponseEntity<>(errors, HttpStatus.OK); } else {
if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) { return new ResponseEntity<>(Collections.singletonList("Email already exists!"), HttpStatus.CONFLICT); } else { users.add(user); return new ResponseEntity<>(HttpStatus.CREATED); } } } @GetMapping("/users") @ResponseBody public List<User> getUsers() { return users; } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\springmvcforms\controller\UserController.java
2
请完成以下Java代码
public class BasicMapperUtils { private static final String START_PLACEHOLDER_PREFIX = "%{"; private static final String END_PLACEHOLDER_PREFIX = "}"; public static OAuth2User getOAuth2User(String email, Map<String, Object> attributes, OAuth2MapperConfig config) { OAuth2User oauth2User = new OAuth2User(); oauth2User.setEmail(email); oauth2User.setTenantName(getTenantName(email, attributes, config)); if (!StringUtils.isEmpty(config.getBasic().getLastNameAttributeKey())) { String lastName = getStringAttributeByKey(attributes, config.getBasic().getLastNameAttributeKey()); oauth2User.setLastName(lastName); } if (!StringUtils.isEmpty(config.getBasic().getFirstNameAttributeKey())) { String firstName = getStringAttributeByKey(attributes, config.getBasic().getFirstNameAttributeKey()); oauth2User.setFirstName(firstName); } if (!StringUtils.isEmpty(config.getBasic().getCustomerNamePattern())) { StrSubstitutor sub = new StrSubstitutor(attributes, START_PLACEHOLDER_PREFIX, END_PLACEHOLDER_PREFIX); String customerName = sub.replace(config.getBasic().getCustomerNamePattern()); oauth2User.setCustomerName(customerName); } oauth2User.setAlwaysFullScreen(config.getBasic().isAlwaysFullScreen()); if (!StringUtils.isEmpty(config.getBasic().getDefaultDashboardName())) { oauth2User.setDefaultDashboardName(config.getBasic().getDefaultDashboardName()); } return oauth2User; } public static String getTenantName(String email, Map<String, Object> attributes, OAuth2MapperConfig config) { switch (config.getBasic().getTenantNameStrategy()) { case EMAIL: return email; case DOMAIN: return email.substring(email .indexOf("@") + 1); case CUSTOM:
StrSubstitutor sub = new StrSubstitutor(attributes, START_PLACEHOLDER_PREFIX, END_PLACEHOLDER_PREFIX); return sub.replace(config.getBasic().getTenantNamePattern()); default: throw new RuntimeException("Tenant Name Strategy with type " + config.getBasic().getTenantNameStrategy() + " is not supported!"); } } public static String getStringAttributeByKey(Map<String, Object> attributes, String key) { String result = null; try { result = (String) attributes.get(key); } catch (Exception e) { log.warn("Can't convert attribute to String by key " + key); } return result; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\BasicMapperUtils.java
1
请完成以下Java代码
public class SentryPartInstanceEntityImpl extends AbstractCmmnEngineEntity implements SentryPartInstanceEntity { protected String caseDefinitionId; protected String caseInstanceId; protected String planItemInstanceId; protected String onPartId; protected String ifPartId; protected Date timeStamp; @Override public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<>(); persistentState.put("caseDefinitionId", caseDefinitionId); persistentState.put("caseInstanceId", caseInstanceId); persistentState.put("planItemInstanceId", planItemInstanceId); persistentState.put("onPartId", onPartId); persistentState.put("ifPart", ifPartId); persistentState.put("timeStamp", timeStamp); return persistentState; } @Override public String getCaseDefinitionId() { return caseDefinitionId; } @Override public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @Override public String getCaseInstanceId() { return caseInstanceId; } @Override public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @Override public String getPlanItemInstanceId() { return planItemInstanceId;
} @Override public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } @Override public String getOnPartId() { return onPartId; } @Override public void setOnPartId(String onPartId) { this.onPartId = onPartId; } @Override public String getIfPartId() { return ifPartId; } @Override public void setIfPartId(String ifPartId) { this.ifPartId = ifPartId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\SentryPartInstanceEntityImpl.java
1
请完成以下Java代码
public String getResetPasswordUrl(final String token) { Check.assumeNotEmpty(token, "token is not empty"); return getFrontendURL(SYSCONFIG_RESET_PASSWORD_PATH, ImmutableMap.<String, Object>builder() .put(PARAM_ResetPasswordToken, token) .build()); } public boolean isCrossSiteUsageAllowed() { return sysConfigBL.getBooleanValue(SYSCONFIG_IsCrossSiteUsageAllowed, false); } public String getAppApiUrl() {
final String url = StringUtils.trimBlankToNull(sysConfigBL.getValue(SYSCONFIG_APP_API_URL)); if (url != null && !url.equals("-")) { return url; } final String frontendUrl = getFrontendURL(); if (frontendUrl != null) { return frontendUrl + "/app"; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui\web\WebuiURLs.java
1
请在Spring Boot框架中完成以下Java代码
public int getFactor() { return factor; } /** * Sets the value of the factor property. * */ public void setFactor(int value) { this.factor = value; } /** * Gets the value of the notOtherwiseSpecified property. * * @return * possible object is * {@link String } * */ public String getNotOtherwiseSpecified() { return notOtherwiseSpecified;
} /** * Sets the value of the notOtherwiseSpecified property. * * @param value * allowed object is * {@link String } * */ public void setNotOtherwiseSpecified(String value) { this.notOtherwiseSpecified = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Hazardous.java
2
请完成以下Java代码
public void setTypeName(String typeName) { this.typeName = typeName; } public VariableType getType() { return type; } public void setType(VariableType type) { this.type = type; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getExecutionId() { return executionId; } public Long getLongValue() { return longValue; } public void setLongValue(Long longValue) { this.longValue = longValue; } public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } public String getTextValue() { return textValue; } public void setTextValue(String textValue) { this.textValue = textValue; }
public String getTextValue2() { return textValue2; } public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } public Object getCachedValue() { return cachedValue; } public void setCachedValue(Object cachedValue) { this.cachedValue = cachedValue; } // misc methods /////////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("VariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(type != null ? type.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableInstanceEntityImpl.java
1
请完成以下Java代码
private String filterUrl(String requestPath){ String url = ""; if(oConvertUtils.isNotEmpty(requestPath)){ url = requestPath.replace("\\", "/"); url = url.replace("//", "/"); if(url.indexOf(SymbolConstant.DOUBLE_SLASH)>=0){ url = filterUrl(url); } /*if(url.startsWith("/")){ url=url.substring(1); }*/ } return url; } /** * 获取请求地址 * @param request * @return */ @Deprecated private String getJgAuthRequsetPath(HttpServletRequest request) { String queryString = request.getQueryString(); String requestPath = request.getRequestURI(); if(oConvertUtils.isNotEmpty(queryString)){ requestPath += "?" + queryString; } // 去掉其他参数(保留一个参数) 例如:loginController.do?login if (requestPath.indexOf(SymbolConstant.AND) > -1) { requestPath = requestPath.substring(0, requestPath.indexOf("&")); } if(requestPath.indexOf(QueryRuleEnum.EQ.getValue())!=-1){ if(requestPath.indexOf(SPOT_DO)!=-1){ requestPath = requestPath.substring(0,requestPath.indexOf(".do")+3);
}else{ requestPath = requestPath.substring(0,requestPath.indexOf("?")); } } // 去掉项目路径 requestPath = requestPath.substring(request.getContextPath().length() + 1); return filterUrl(requestPath); } @Deprecated private boolean moHuContain(List<String> list,String key){ for(String str : list){ if(key.contains(str)){ return true; } } return false; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\aspect\PermissionDataAspect.java
1
请完成以下Java代码
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * Role AD_Reference_ID=541254 * Reference name: Role */ public static final int ROLE_AD_Reference_ID=541254; /** Main Producer = MP */ public static final String ROLE_MainProducer = "MP"; /** Hostpital = HO */ public static final String ROLE_Hostpital = "HO"; /** Physician Doctor = PD */ public static final String ROLE_PhysicianDoctor = "PD"; /** General Practitioner = GP */ public static final String ROLE_GeneralPractitioner = "GP"; /** Health Insurance = HI */ public static final String ROLE_HealthInsurance = "HI"; /** Nursing Home = NH */ public static final String ROLE_NursingHome = "NH"; /** Caregiver = CG */ public static final String ROLE_Caregiver = "CG"; /** Preferred Pharmacy = PP */ public static final String ROLE_PreferredPharmacy = "PP"; /** Nursing Service = NS */ public static final String ROLE_NursingService = "NS"; /** Payer = PA */
public static final String ROLE_Payer = "PA"; /** Payer = PA */ public static final String ROLE_Pharmacy = "PH"; @Override public void setRole (final @Nullable java.lang.String Role) { set_Value (COLUMNNAME_Role, Role); } @Override public java.lang.String getRole() { return get_ValueAsString(COLUMNNAME_Role); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java
1
请完成以下Java代码
public class SaveUserCmd extends AbstractWritableIdentityServiceCmd<Void> implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected User user; protected boolean skipPasswordPolicy; public SaveUserCmd(User user) { this(user, false); } public SaveUserCmd(User user, boolean skipPasswordPolicy) { this.user = user; this.skipPasswordPolicy = skipPasswordPolicy; } protected Void executeCmd(CommandContext commandContext) { ensureNotNull("user", user); ensureWhitelistedResourceId(commandContext, "User", user.getId()); if (user instanceof UserEntity) { validateUserEntity(commandContext); } IdentityOperationResult operationResult = commandContext .getWritableIdentityProvider()
.saveUser(user); commandContext.getOperationLogManager().logUserOperation(operationResult, user.getId()); return null; } private void validateUserEntity(CommandContext commandContext) { if(shouldCheckPasswordPolicy(commandContext)) { if(!((UserEntity) user).checkPasswordAgainstPolicy()) { throw new ProcessEngineException("Password does not match policy"); } } } protected boolean shouldCheckPasswordPolicy(CommandContext commandContext) { return ((UserEntity) user).hasNewPassword() && !skipPasswordPolicy && commandContext.getProcessEngineConfiguration().isEnablePasswordPolicy(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SaveUserCmd.java
1
请完成以下Java代码
public static void printStack (boolean adempiereOnly, boolean first9only) { Throwable t = new Throwable(); // t.printStackTrace(); int counter = 0; StackTraceElement[] elements = t.getStackTrace(); for (int i = 1; i < elements.length; i++) { if (elements[i].getClassName().indexOf("util.Trace") != -1) { continue; } if (!adempiereOnly || (adempiereOnly && elements[i].getClassName().startsWith("org.compiere")) ) { if (first9only && ++counter > 8) { break; } } } } // printStack public static final String toOneLineStackTraceString() { return toOneLineStackTraceString(new Exception().getStackTrace()); } public static final String toOneLineStackTraceString(@NonNull final Throwable throwable) { return toOneLineStackTraceString(throwable.getStackTrace()); } public static final String toOneLineStackTraceString(@NonNull final StackTraceElement[] stacktrace) { final StringBuilder stackTraceStr = new StringBuilder(); int ste_Considered = 0; boolean ste_lastSkipped = false; for (final StackTraceElement ste : stacktrace) { if (ste_Considered >= 100) { stackTraceStr.append("..."); break; } String classname = ste.getClassName(); final String methodName = ste.getMethodName(); // Skip some irrelevant stack trace elements if (classname.startsWith("java.") || classname.startsWith("javax.") || classname.startsWith("sun.") || classname.startsWith("com.google.") || classname.startsWith("org.springframework.") || classname.startsWith("org.apache.") || classname.startsWith(QueryStatisticsLogger.class.getPackage().getName()) || classname.startsWith(Trace.class.getName()) // || classname.startsWith(StatementsFactory.class.getPackage().getName()) || classname.startsWith(AbstractResultSetBlindIterator.class.getPackage().getName()) || classname.startsWith(ITrxManager.class.getPackage().getName()) || classname.startsWith(org.adempiere.ad.persistence.TableModelLoader.class.getPackage().getName()) // || classname.startsWith(JavaAssistInterceptor.class.getPackage().getName()) || classname.indexOf("_$$_jvstdca_") >= 0 // javassist proxy || methodName.startsWith("access$")
// ) { ste_lastSkipped = true; continue; } final int lastDot = classname.lastIndexOf("."); if (lastDot >= 0) { classname = classname.substring(lastDot + 1); } if (ste_lastSkipped || stackTraceStr.length() > 0) { stackTraceStr.append(ste_lastSkipped ? " <~~~ " : " <- "); } stackTraceStr.append(classname).append(".").append(methodName); final int lineNumber = ste.getLineNumber(); if (lineNumber > 0) { stackTraceStr.append(":").append(lineNumber); } ste_lastSkipped = false; ste_Considered++; } return stackTraceStr.toString(); } } // Trace
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Trace.java
1
请完成以下Java代码
public Optional<DeviceAccessor> getDeviceAccessorById(@NonNull DeviceId deviceId) { return getDefaultDeviceAccessorsHub().getDeviceAccessorById(deviceId); } public DeviceAccessorsHub getDefaultDeviceAccessorsHub() { final IHostIdentifier clientHost = NetUtils.getLocalHost(); final Properties ctx = Env.getCtx(); final ClientId adClientId = Env.getClientId(ctx); final OrgId adOrgId = Env.getOrgId(ctx); return getDeviceAccessorsHub(clientHost, adClientId, adOrgId); } public DeviceAccessorsHub getDeviceAccessorsHub( @NonNull final IHostIdentifier clientHost, @NonNull final ClientId adClientId, @NonNull final OrgId adOrgId) { return hubsByKey.computeIfAbsent( DeviceAccessorsHubKey.of(clientHost, adClientId, adOrgId), this::createDeviceAccessorsHub); } private DeviceAccessorsHub createDeviceAccessorsHub(final DeviceAccessorsHubKey key) { final IDeviceConfigPool deviceConfigPool = configPoolFactory.createDeviceConfigPool( key.getClientHost(), key.getAdClientId(), key.getAdOrgId());
return new DeviceAccessorsHub(deviceConfigPool); } public void cacheReset() { hubsByKey.clear(); } @Value(staticConstructor = "of") private static class DeviceAccessorsHubKey { @NonNull IHostIdentifier clientHost; @NonNull ClientId adClientId; @NonNull OrgId adOrgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessorsHubFactory.java
1
请完成以下Java代码
public final void addHUAssignmentListener(final IHUAssignmentListener listener) { Check.assumeNotNull(listener, "listener not null"); listeners.addIfAbsent(listener); } /** * Invokes {@link #assertAssignable(I_M_HU, Object, String)} on all included listeners. */ @Override public void assertAssignable(final I_M_HU hu, final Object model, final String trxName) throws HUNotAssignableException { for (final IHUAssignmentListener listener : listeners) { listener.assertAssignable(hu, model, trxName); } }
@Override public final void onHUAssigned(final I_M_HU hu, final Object model, final String trxName) { for (final IHUAssignmentListener listener : listeners) { listener.onHUAssigned(hu, model, trxName); } } @Override public final void onHUUnassigned(final IReference<I_M_HU> huRef, final IReference<Object> modelRef, final String trxName) { for (final IHUAssignmentListener listener : listeners) { listener.onHUUnassigned(huRef, modelRef, trxName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUAssignmentListener.java
1