instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public List<I_AD_User_SortPref_Line_Product> retrieveSortPreferenceLineProducts(final I_AD_User_SortPref_Line sortPreferenceLine) { // // Services final IQueryBL queryBL = Services.get(IQueryBL.class); final Object contextProvider = sortPreferenceLine; final IQueryBuilder<I_AD_User_SortPref_Line_Product> queryBuilder = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, contextProvider) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, sortPreferenceLine.getAD_User_SortPref_Line_ID()); final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_AD_User_SortPref_Line_Product.class) .addColumn(I_AD_User_SortPref_Line_Product.COLUMN_SeqNo) .createQueryOrderBy(); return queryBuilder.create() .setOrderBy(orderBy) .list(I_AD_User_SortPref_Line_Product.class); } @Override public int clearSortPreferenceLines(final I_AD_User_SortPref_Hdr hdr)
{ final IQueryBL queryBL = Services.get(IQueryBL.class); int count = 0; final List<I_AD_User_SortPref_Line> linesToDelete = retrieveSortPreferenceLines(hdr); for (final I_AD_User_SortPref_Line line : linesToDelete) { final int countProductLinesDeleted = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, hdr) .addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, line.getAD_User_SortPref_Line_ID()) .create() .deleteDirectly(); count += countProductLinesDeleted; InterfaceWrapperHelper.delete(line); count++; } logger.info("Deleted {} records in sum", count); return count; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserSortPrefDAO.java
1
请完成以下Java代码
public boolean hasNext() { if (finished) { return false; } if (currentPageIterator == null || !currentPageIterator.hasNext()) { final Collection<E> currentPage = getAndIncrementPage(); if (currentPage == null) { currentPageIterator = null; finished = true; return false; } else { currentPageIterator = currentPage.iterator(); return true; } } else { return currentPageIterator.hasNext(); } } private final Collection<E> getAndIncrementPage() { final int pageFirstRow = nextPageFirstRow; final int pageSize = computePageSize(pageFirstRow); if (pageSize <= 0) { return null; } final Page<E> currentPage = pageFetcher.getPage(pageFirstRow, pageSize); if (currentPage == null) { return null; } if (currentPage.getLastRowZeroBased() != null) { nextPageFirstRow = currentPage.getLastRowZeroBased() + 1; } else { nextPageFirstRow = computeNextPageFirstRow(pageFirstRow, pageSize); } return currentPage.getRows(); } private int computePageSize(final int firstRow) { final int remainingRows = lastRow - firstRow; if (remainingRows <= 0) { return 0; } return Math.min(pageSize, remainingRows); } private int computeNextPageFirstRow(final int firstRow, final int pageSize) { return firstRow + pageSize; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } return currentPageIterator.next(); } public Stream<E> stream() { return IteratorUtils.stream(this); }
@lombok.Value public static final class Page<E> { public static <E> Page<E> ofRows(final List<E> rows) { final Integer lastRow = null; return new Page<>(rows, lastRow); } public static <E> Page<E> ofRowsOrNull(final List<E> rows) { return rows != null && !rows.isEmpty() ? ofRows(rows) : null; } public static <E> Page<E> ofRowsAndLastRowIndex(final List<E> rows, final int lastRowZeroBased) { return new Page<>(rows, lastRowZeroBased); } private final List<E> rows; private final Integer lastRowZeroBased; private Page(final List<E> rows, final Integer lastRowZeroBased) { Check.assumeNotEmpty(rows, "rows is not empty"); Check.assume(lastRowZeroBased == null || lastRowZeroBased >= 0, "lastRow shall be null, positive or zero"); this.rows = rows; this.lastRowZeroBased = lastRowZeroBased; } } /** Loads and provides the requested page */ @FunctionalInterface public interface PageFetcher<E> { /** * @param firstRow (first page is ZERO) * @param pageSize max rows to return * @return page or null in case there is no page */ Page<E> getPage(int firstRow, int pageSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\PagedIterator.java
1
请完成以下Java代码
private void exportCollectedHUsIfRequired(@NonNull final Collection<ExportHUCandidate> huCandidates) { if (huCandidates.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("HuId list to sync empty! No action is performed!"); return; } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { Loggables.withLogger(logger, Level.DEBUG).addLog("No active config found for external system type: {}! No action is performed!", getExternalSystemType()); return; // nothing to do } for (final ExportHUCandidate exportHUCandidate : huCandidates)
{ final I_M_HU topLevelParent = handlingUnitsBL.getTopLevelParent(exportHUCandidate.getHuId()); final TableRecordReference topLevelRef = TableRecordReference.of(I_M_HU.Table_Name, topLevelParent.getM_HU_ID()); exportToExternalSystemIfRequired(topLevelRef, () -> getAdditionalExternalSystemConfigIds(exportHUCandidate)); } } protected abstract Map<String, String> buildParameters(@NonNull final IExternalSystemChildConfig childConfig, @NonNull final HuId huId); protected abstract String getExternalCommand(); protected abstract Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final ExportHUCandidate exportHUCandidate); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\hu\ExportHUToExternalSystemService.java
1
请完成以下Java代码
public final class ExchangeTypes { /** * Direct exchange. */ public static final String DIRECT = "direct"; /** * Topic exchange. */ public static final String TOPIC = "topic"; /** * Fanout exchange. */ public static final String FANOUT = "fanout"; /** * Headers exchange. */ public static final String HEADERS = "headers"; /**
* Consistent Hash exchange. * @since 3.2 */ public static final String CONSISTENT_HASH = "x-consistent-hash"; /** * System exchange. * @deprecated with no replacement (for removal): there is no such an exchange type in AMQP. */ @Deprecated(since = "3.2", forRemoval = true) public static final String SYSTEM = "system"; private ExchangeTypes() { } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\ExchangeTypes.java
1
请完成以下Java代码
private Stream<POInfoColumn> streamCustomRestAPIColumns(final POInfo poInfo) { final RESTApiTableInfo tableInfo = repository.getByTableNameOrNull(poInfo.getTableName()); if (tableInfo == null) { return Stream.empty(); } else { return poInfo.streamColumns(tableInfo::isCustomRestAPIColumn); } } private void assertRestAPIColumnNames(final String tableName, final Collection<String> columnNames) { if (columnNames.isEmpty()) { return; } final RESTApiTableInfo tableInfo = repository.getByTableNameOrNull(tableName); final Collection<String> notValidColumnNames; if (tableInfo == null) { notValidColumnNames = columnNames; } else { notValidColumnNames = columnNames.stream() .filter(columnName -> !tableInfo.isCustomRestAPIColumn(columnName)) .collect(Collectors.toList()); } if (!notValidColumnNames.isEmpty()) { final String notValidColumnNamesStr = notValidColumnNames.stream() .map(columnName -> tableName + "." + columnName) .collect(Collectors.joining(", ")); throw new AdempiereException(MSG_CUSTOM_REST_API_COLUMN, notValidColumnNamesStr) .markAsUserValidationError(); } } @NonNull public CustomColumnsJsonValues getCustomColumnsJsonValues(@NonNull final PO record) { final ZoneId zoneId = extractZoneId(record); return convertToJsonValues(record, zoneId); }
@NonNull private CustomColumnsJsonValues convertToJsonValues(final @NonNull PO record, final ZoneId zoneId) { final POInfo poInfo = record.getPOInfo(); final ImmutableMap.Builder<String, Object> map = ImmutableMap.builder(); streamCustomRestAPIColumns(poInfo) .forEach(customColumn -> { final String columnName = customColumn.getColumnName(); final Object poValue = record.get_Value(columnName); final Object jsonValue = CustomColumnsConverters.convertToJsonValue(poValue, customColumn.getDisplayType(), zoneId); if (jsonValue != null) { map.put(columnName, jsonValue); } }); return CustomColumnsJsonValues.ofJsonValuesMap(map.build()); } private ZoneId extractZoneId(final @NonNull PO record) {return orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID()));} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnService.java
1
请完成以下Java代码
public class DataImporter { private final ActorSystem actorSystem; private final AverageRepository averageRepository = new AverageRepository(); public DataImporter(ActorSystem actorSystem) { this.actorSystem = actorSystem; } private List<Integer> parseLine(String line) { String[] fields = line.split(";"); return Arrays.stream(fields) .map(Integer::parseInt) .collect(Collectors.toList()); } private Flow<String, Integer, NotUsed> parseContent() { return Flow.of(String.class).mapConcat(this::parseLine); } private Flow<Integer, Double, NotUsed> computeAverage() { return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers -> CompletableFuture.supplyAsync(() -> integers .stream() .mapToDouble(v -> v) .average() .orElse(-1.0))); }
Flow<String, Double, NotUsed> calculateAverage() { return Flow.of(String.class) .via(parseContent()) .via(computeAverage()); } private Sink<Double, CompletionStage<Done>> storeAverages() { return Flow.of(Double.class) .mapAsyncUnordered(4, averageRepository::save) .toMat(Sink.ignore(), Keep.right()); } CompletionStage<Done> calculateAverageForContent(String content) { return Source.single(content) .via(calculateAverage()) .runWith(storeAverages(), ActorMaterializer.create(actorSystem)) .whenComplete((d, e) -> { if (d != null) { System.out.println("Import finished "); } else { e.printStackTrace(); } }); } }
repos\tutorials-master\akka-modules\akka-streams\src\main\java\com\baeldung\akkastreams\DataImporter.java
1
请在Spring Boot框架中完成以下Java代码
public class TellerService { private final BankAccountService bankAccountService; private final AuditService auditService; private final UserTransaction userTransaction; @Autowired public TellerService(BankAccountService bankAccountService, AuditService auditService, UserTransaction userTransaction) { this.bankAccountService = bankAccountService; this.auditService = auditService; this.userTransaction = userTransaction; } @Transactional public void executeTransfer(String fromAccontId, String toAccountId, BigDecimal amount) { bankAccountService.transfer(fromAccontId, toAccountId, amount); auditService.log(fromAccontId, toAccountId, amount); BigDecimal balance = bankAccountService.balanceOf(fromAccontId); if (balance.compareTo(BigDecimal.ZERO) < 0) { throw new RuntimeException("Insufficient fund."); }
} public void executeTransferProgrammaticTx(String fromAccontId, String toAccountId, BigDecimal amount) throws Exception { userTransaction.begin(); bankAccountService.transfer(fromAccontId, toAccountId, amount); auditService.log(fromAccontId, toAccountId, amount); BigDecimal balance = bankAccountService.balanceOf(fromAccontId); if (balance.compareTo(BigDecimal.ZERO) < 0) { userTransaction.rollback(); throw new RuntimeException("Insufficient fund."); } else { userTransaction.commit(); } } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\jtademo\services\TellerService.java
2
请完成以下Java代码
public void prepare() { int common = 1; elements = new float[s]; for (int i = 0; i < s - 1; i++) { elements[i] = common; } elements[s - 1] = pivot; } @TearDown @Override public void clean() { elements = null; }
@Benchmark @BenchmarkMode(Mode.AverageTime) public int findPosition() { int index = 0; while (pivot != elements[index]) { index++; } return index; } @Override public String getSimpleClassName() { return FloatPrimitiveLookup.class.getSimpleName(); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\FloatPrimitiveLookup.java
1
请完成以下Java代码
public static Integer toValue(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return null; } return externalId.getValue(); } public static int toValueInt(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return -1; } return externalId.getValue(); } public static String toValueStr(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return "-1"; } return String.valueOf(externalId.getValue()); } @NonNull public static Optional<Integer> toValueOptional(@Nullable final JsonMetasfreshId externalId) { return Optional.ofNullable(toValue(externalId)); } @Nullable
public static <T> T mapToOrNull(@Nullable final JsonMetasfreshId externalId, @NonNull final Function<Integer, T> mapper) { return toValueOptional(externalId).map(mapper).orElse(null); } @Nullable public static String toValueStrOrNull(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return null; } return String.valueOf(externalId.getValue()); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\common\JsonMetasfreshId.java
1
请完成以下Java代码
public String getTableName() { return InterfaceWrapperHelper.getModelTableName(model); } @Override public int getRecordId() { return InterfaceWrapperHelper.getId(model); } @Override public TableRecordReference getRootRecordReferenceOrNull() { return null;
} @Override public Integer getValueAsInt(final String columnName, final Integer defaultValue) { final Object valueObj = InterfaceWrapperHelper.getValueOrNull(model, columnName); return NumberUtils.asInteger(valueObj, defaultValue); } @Override public boolean isValueChanged(final String columnName) { return InterfaceWrapperHelper.isValueChanged(model, columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ModelCacheSourceModel.java
1
请在Spring Boot框架中完成以下Java代码
private void updateConfirmedByUser() { this.confirmedByUser = computeConfirmedByUser(); } private boolean computeConfirmedByUser() { if (pricePromised.compareTo(pricePromisedUserEntered) != 0) { return false; } for (final RfqQty rfqQty : quantities) { if (!rfqQty.isConfirmedByUser()) { return false;
} } return true; } public void closeIt() { this.closed = true; } public void confirmByUser() { this.pricePromised = getPricePromisedUserEntered(); quantities.forEach(RfqQty::confirmByUser); updateConfirmedByUser(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
2
请完成以下Java代码
public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getVariableName() { return name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public VariableType getVariableType() { return variableType; } public void setVariableType(VariableType variableType) { this.variableType = variableType; } 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; } // common methods /////////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricDetailVariableInstanceUpdateEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(variableType != null ? variableType.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\HistoricDetailVariableInstanceUpdateEntityImpl.java
1
请完成以下Java代码
public List<String> segment(String text) { List<String> wordList = new LinkedList<String>(); segment(text, CharTable.convert(text), wordList); return wordList; } @Override public void segment(String text, String normalized, List<String> wordList) { perceptronSegmenter.segment(text, createInstance(normalized), wordList); } private CWSInstance createInstance(String text) { final FeatureTemplate[] featureTemplateArray = model.getFeatureTemplateArray(); return new CWSInstance(text, model.featureMap) { @Override protected int[] extractFeature(String sentence, FeatureMap featureMap, int position) { StringBuilder sbFeature = new StringBuilder(); List<Integer> featureVec = new LinkedList<Integer>(); for (int i = 0; i < featureTemplateArray.length; i++) { Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator(); Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator(); delimiterIterator.next(); // ignore U0 之类的id while (offsetIterator.hasNext()) { int offset = offsetIterator.next()[0] + position; if (offset < 0) sbFeature.append(FeatureIndex.BOS[-(offset + 1)]); else if (offset >= sentence.length()) sbFeature.append(FeatureIndex.EOS[offset - sentence.length()]); else sbFeature.append(sentence.charAt(offset)); if (delimiterIterator.hasNext()) sbFeature.append(delimiterIterator.next()); else sbFeature.append(i); } addFeatureThenClear(sbFeature, featureVec, featureMap); } return toFeatureArray(featureVec);
} }; } @Override protected String getDefaultFeatureTemplate() { return "# Unigram\n" + "U0:%x[-1,0]\n" + "U1:%x[0,0]\n" + "U2:%x[1,0]\n" + "U3:%x[-2,0]%x[-1,0]\n" + "U4:%x[-1,0]%x[0,0]\n" + "U5:%x[0,0]%x[1,0]\n" + "U6:%x[1,0]%x[2,0]\n" + "\n" + "# Bigram\n" + "B"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFSegmenter.java
1
请完成以下Java代码
private String getTopicSuffix(int backOffIndex, long thisBackOffValue) { if (this.isSameIntervalReuse && this.retryTopicsAmount == 1) { return this.destinationTopicSuffixes.getRetrySuffix(); } else if (this.isFixedDelay) { return joinWithRetrySuffix(backOffIndex); } else { String retrySuffix = joinWithRetrySuffix(thisBackOffValue); if (!this.isSameIntervalReuse && hasDuplicates(thisBackOffValue)) { return retrySuffix.concat("-" + (backOffIndex - this.backOffValues.indexOf(thisBackOffValue))); } return retrySuffix; } } private DestinationTopic.Type getDestinationTopicType(Long backOffValue) { return this.isSameIntervalReuse && hasDuplicates(backOffValue) ? Type.REUSABLE_RETRY_TOPIC : Type.RETRY; } private int reusableTopicAttempts() { if (this.isSameIntervalReuse && this.backOffValues.size() > 1) { // Assuming that duplicates are always at the end of the list. return amountOfDuplicates(this.backOffValues.get(this.backOffValues.size() - 1)) - 1; } return 0; } private boolean hasDuplicates(Long thisBackOffValue) { return amountOfDuplicates(thisBackOffValue) > 1; } private int amountOfDuplicates(Long thisBackOffValue) { return Long.valueOf(this.backOffValues .stream() .filter(thisBackOffValue::equals) .count()) .intValue();
} private DestinationTopic.Properties createProperties(long delayMs, String suffix) { return new DestinationTopic.Properties(delayMs, suffix, getDestinationTopicType(delayMs), this.maxAttempts, this.numPartitions, this.dltStrategy, this.kafkaOperations, this.shouldRetryOn, this.timeout); } private String joinWithRetrySuffix(long parameter) { return String.join("-", this.destinationTopicSuffixes.getRetrySuffix(), String.valueOf(parameter)); } public static class DestinationTopicSuffixes { private final String retryTopicSuffix; private final String dltSuffix; public DestinationTopicSuffixes(@Nullable String retryTopicSuffix, @Nullable String dltSuffix) { this.retryTopicSuffix = StringUtils.hasText(retryTopicSuffix) ? retryTopicSuffix : RetryTopicConstants.DEFAULT_RETRY_SUFFIX; this.dltSuffix = StringUtils.hasText(dltSuffix) ? dltSuffix : RetryTopicConstants.DEFAULT_DLT_SUFFIX; } public String getRetrySuffix() { return this.retryTopicSuffix; } public String getDltSuffix() { return this.dltSuffix; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopicPropertiesFactory.java
1
请完成以下Java代码
public void setM_Package_ID (int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID)); } /** Get PackstĂĽck. @return Shipment Package */ public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Virtual Package. @param M_PackageTree_ID Virtual Package */ public void setM_PackageTree_ID (int M_PackageTree_ID) { if (M_PackageTree_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, Integer.valueOf(M_PackageTree_ID)); } /** Get Virtual Package. @return Virtual Package */ public int getM_PackageTree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageTree_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackageTree.java
1
请完成以下Java代码
public static DmnDecisionResult evaluateDecision(DecisionDefinition decisionDefinition, VariableMap variables) throws Exception { DecisionInvocation invocation = createInvocation(decisionDefinition, variables); invoke(invocation); return invocation.getInvocationResult(); } public static DmnDecisionTableResult evaluateDecisionTable(DecisionDefinition decisionDefinition, VariableMap variables) throws Exception { // doesn't throw an exception if the decision definition is not implemented as decision table DmnDecisionResult decisionResult = evaluateDecision(decisionDefinition, variables); return DmnDecisionTableResultImpl.wrap(decisionResult); } protected static void invoke(DecisionInvocation invocation) throws Exception { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(invocation); }
protected static DecisionInvocation createInvocation(DecisionDefinition decisionDefinition, VariableMap variables) { return createInvocation(decisionDefinition, variables.asVariableContext()); } protected static DecisionInvocation createInvocation(DecisionDefinition decisionDefinition, AbstractVariableScope variableScope) { return createInvocation(decisionDefinition, VariableScopeContext.wrap(variableScope)); } protected static DecisionInvocation createInvocation(DecisionDefinition decisionDefinition, VariableContext variableContext) { return new DecisionInvocation(decisionDefinition, variableContext); } protected static DecisionDefinition resolveDecisionDefinition(BaseCallableElement callableElement, AbstractVariableScope execution, String defaultTenantId) { return CallableElementUtil.getDecisionDefinitionToCall(execution, defaultTenantId, callableElement); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\DecisionEvaluationUtil.java
1
请完成以下Java代码
public class SpringUtil implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 实现ApplicationContextAware接口, 注入Context到静态变量中. */ @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringUtil.applicationContext = applicationContext; } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); } /** * 清除SpringContextHolder中的ApplicationContext为Null. */ public static void clearHolder() { if (log.isDebugEnabled()) { log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); }
applicationContext = null; } /** * 发布事件 * * @param event 事件 */ public static void publishEvent(ApplicationEvent event) { if (applicationContext == null) { return; } applicationContext.publishEvent(event); } /** * 实现DisposableBean接口, 在Context关闭时清理静态变量. */ @Override public void destroy() { SpringUtil.clearHolder(); } }
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\utils\SpringUtil.java
1
请完成以下Java代码
protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport(); } @Override protected void applyFilters(CleanableHistoricDecisionInstanceReport query) { if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) { query.decisionDefinitionIdIn(decisionDefinitionIdIn); } if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) { query.decisionDefinitionKeyIn(decisionDefinitionKeyIn); } if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId(); }
if (tenantIdIn != null && tenantIdIn.length > 0) { query.tenantIdIn(tenantIdIn); } if (Boolean.TRUE.equals(compact)) { query.compact(); } } @Override protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { query.orderByFinished(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportDto.java
1
请在Spring Boot框架中完成以下Java代码
public Long sAdd(String key, Object... values) { return redisTemplate.opsForSet().add(key, values); } @Override public Long sAdd(String key, long time, Object... values) { Long count = redisTemplate.opsForSet().add(key, values); expire(key, time); return count; } @Override public Boolean sIsMember(String key, Object value) { return redisTemplate.opsForSet().isMember(key, value); } @Override public Long sSize(String key) { return redisTemplate.opsForSet().size(key); } @Override public Long sRemove(String key, Object... values) { return redisTemplate.opsForSet().remove(key, values); } @Override public List<Object> lRange(String key, long start, long end) { return redisTemplate.opsForList().range(key, start, end); } @Override public Long lSize(String key) { return redisTemplate.opsForList().size(key); } @Override public Object lIndex(String key, long index) { return redisTemplate.opsForList().index(key, index); } @Override public Long lPush(String key, Object value) { return redisTemplate.opsForList().rightPush(key, value); }
@Override public Long lPush(String key, Object value, long time) { Long index = redisTemplate.opsForList().rightPush(key, value); expire(key, time); return index; } @Override public Long lPushAll(String key, Object... values) { return redisTemplate.opsForList().rightPushAll(key, values); } @Override public Long lPushAll(String key, Long time, Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); expire(key, time); return count; } @Override public Long lRemove(String key, long count, Object value) { return redisTemplate.opsForList().remove(key, count, value); } }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\service\impl\RedisServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class JobController { private final JobService jobService; private static final String ENTITY_NAME = "job"; @ApiOperation("导出岗位数据") @GetMapping(value = "/download") @PreAuthorize("@el.check('job:list')") public void exportJob(HttpServletResponse response, JobQueryCriteria criteria) throws IOException { jobService.download(jobService.queryAll(criteria), response); } @ApiOperation("查询岗位") @GetMapping @PreAuthorize("@el.check('job:list','user:list')") public ResponseEntity<PageResult<JobDto>> queryJob(JobQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK); } @Log("新增岗位") @ApiOperation("新增岗位") @PostMapping @PreAuthorize("@el.check('job:add')") public ResponseEntity<Object> createJob(@Validated @RequestBody Job resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } jobService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); }
@Log("修改岗位") @ApiOperation("修改岗位") @PutMapping @PreAuthorize("@el.check('job:edit')") public ResponseEntity<Object> updateJob(@Validated(Job.Update.class) @RequestBody Job resources){ jobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除岗位") @ApiOperation("删除岗位") @DeleteMapping @PreAuthorize("@el.check('job:del')") public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids){ // 验证是否被用户关联 jobService.verification(ids); jobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\JobController.java
2
请在Spring Boot框架中完成以下Java代码
public class PasswordStorageWebSecurityConfigurer { @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); authenticationManagerBuilder.eraseCredentials(false) .userDetailsService(getUserDefaultDetailsService()) .passwordEncoder(passwordEncoder()); return authenticationManagerBuilder.build(); } @Bean public UserDetailsService getUserDefaultDetailsService() { return new InMemoryUserDetailsManager(User .withUsername("baeldung") .password("{noop}SpringSecurity5") .authorities(Collections.emptyList()) .build()); } @Bean
public PasswordEncoder passwordEncoder() { // set up the list of supported encoders and their prefixes PasswordEncoder defaultEncoder = new StandardPasswordEncoder(); Map<String, PasswordEncoder> encoders = new HashMap<>(); encoders.put("bcrypt", new BCryptPasswordEncoder()); encoders.put("scrypt", new SCryptPasswordEncoder(1, 1, 1, 1, 10)); encoders.put("noop", NoOpPasswordEncoder.getInstance()); DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt", encoders); passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder); return passwordEncoder; } }
repos\tutorials-master\spring-security-modules\spring-security-web-rest-basic-auth\src\main\java\com\baeldung\passwordstorage\PasswordStorageWebSecurityConfigurer.java
2
请完成以下Java代码
public void setNamespaceUri(String namespaceUri) { this.namespaceUri = namespaceUri; } /** * @return the namespaceUri */ public String getNamespaceUri() { return namespaceUri; } public boolean isIdAttribute() { return isIdAttribute; } /** * Indicate whether this attribute is an Id attribute * */ public void setId() { this.isIdAttribute = true; } /** * @return the attributeName */ public String getAttributeName() { return attributeName; } /** * @param attributeName the attributeName to set */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } public void removeAttribute(ModelElementInstance modelElement) { if (namespaceUri == null) { modelElement.removeAttribute(attributeName); } else { modelElement.removeAttributeNs(namespaceUri, attributeName); } } public void unlinkReference(ModelElementInstance modelElement, Object referenceIdentifier) { if (!incomingReferences.isEmpty()) { for (Reference<?> incomingReference : incomingReferences) { ((ReferenceImpl<?>) incomingReference).referencedElementRemoved(modelElement, referenceIdentifier); }
} } /** * @return the incomingReferences */ public List<Reference<?>> getIncomingReferences() { return incomingReferences; } /** * @return the outgoingReferences */ public List<Reference<?>> getOutgoingReferences() { return outgoingReferences; } public void registerOutgoingReference(Reference<?> ref) { outgoingReferences.add(ref); } public void registerIncoming(Reference<?> ref) { incomingReferences.add(ref); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\AttributeImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { // Running the application should result in // org.springframework.orm.ObjectOptimisticLockingFailureException private final InventoryService inventoryService; public MainApplication(InventoryService inventoryService) { this.inventoryService = inventoryService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() {
return args -> { ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(inventoryService); // Thread.sleep(2000); -> adding a sleep here will break the transactions concurrency executor.execute(inventoryService); executor.shutdown(); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSimulateVersionedOptimisticLocking\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public int getDoc_User_ID(DocumentTableFields docFields) { return extractShipmentDeclaration(docFields).getCreatedBy(); } @Override public String completeIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(true); shipmentDeclaration.setDocAction(IDocument.ACTION_ReActivate); return IDocument.STATUS_Completed; }
@Override public void reactivateIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(false); shipmentDeclaration.setDocAction(IDocument.ACTION_Complete); } private static I_M_Shipment_Declaration extractShipmentDeclaration(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_M_Shipment_Declaration.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\document\ShipmentDeclarationDocumentHandler.java
1
请完成以下Java代码
public void setUrlMappings(Collection<String> urlMappings) { Assert.notNull(urlMappings, "'urlMappings' must not be null"); this.urlMappings = new LinkedHashSet<>(urlMappings); } /** * Return a mutable collection of the URL mappings, as defined in the Servlet * specification, for the servlet. * @return the urlMappings */ public Collection<String> getUrlMappings() { return this.urlMappings; } /** * Add URL mappings, as defined in the Servlet specification, for the servlet. * @param urlMappings the mappings to add * @see #setUrlMappings(Collection) */ public void addUrlMappings(String... urlMappings) { Assert.notNull(urlMappings, "'urlMappings' must not be null"); this.urlMappings.addAll(Arrays.asList(urlMappings)); } /** * Sets the {@code loadOnStartup} priority. See * {@link ServletRegistration.Dynamic#setLoadOnStartup} for details. * @param loadOnStartup if load on startup is enabled */ public void setLoadOnStartup(int loadOnStartup) { this.loadOnStartup = loadOnStartup; } /** * Set the {@link MultipartConfigElement multi-part configuration}. * @param multipartConfig the multipart configuration to set or {@code null} */ public void setMultipartConfig(@Nullable MultipartConfigElement multipartConfig) { this.multipartConfig = multipartConfig; } /** * Returns the {@link MultipartConfigElement multi-part configuration} to be applied * or {@code null}. * @return the multipart config */ public @Nullable MultipartConfigElement getMultipartConfig() { return this.multipartConfig; } @Override protected String getDescription() { Assert.state(this.servlet != null, "Unable to return description for null servlet");
return "servlet " + getServletName(); } @Override protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); return servletContext.addServlet(name, this.servlet); } /** * Configure registration settings. Subclasses can override this method to perform * additional configuration if required. * @param registration the registration */ @Override protected void configure(ServletRegistration.Dynamic registration) { super.configure(registration); String[] urlMapping = StringUtils.toStringArray(this.urlMappings); if (urlMapping.length == 0 && this.alwaysMapUrl) { urlMapping = DEFAULT_MAPPINGS; } if (!ObjectUtils.isEmpty(urlMapping)) { registration.addMapping(urlMapping); } registration.setLoadOnStartup(this.loadOnStartup); if (this.multipartConfig != null) { registration.setMultipartConfig(this.multipartConfig); } } /** * Returns the servlet name that will be registered. * @return the servlet name */ public String getServletName() { return getOrDeduceName(this.servlet); } @Override public String toString() { return getServletName() + " urls=" + getUrlMappings(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java
1
请完成以下Java代码
public void setBackupValue (java.lang.String BackupValue) { set_Value (COLUMNNAME_BackupValue, BackupValue); } /** Get Backup Value. @return The value of the column prior to migration. */ @Override public java.lang.String getBackupValue () { return (java.lang.String)get_Value(COLUMNNAME_BackupValue); } /** Set Spaltenname. @param ColumnName Name der Spalte in der Datenbank */ @Override public void setColumnName (java.lang.String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } /** Get Spaltenname. @return Name der Spalte in der Datenbank */ @Override public java.lang.String getColumnName () { return (java.lang.String)get_Value(COLUMNNAME_ColumnName); } /** Set Backup value null. @param IsBackupNull The backup value is null. */ @Override public void setIsBackupNull (boolean IsBackupNull) { set_Value (COLUMNNAME_IsBackupNull, Boolean.valueOf(IsBackupNull)); } /** Get Backup value null. @return The backup value is null. */ @Override public boolean isBackupNull () { Object oo = get_Value(COLUMNNAME_IsBackupNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set New value null. @param IsNewNull The new value is null. */ @Override public void setIsNewNull (boolean IsNewNull) { set_Value (COLUMNNAME_IsNewNull, Boolean.valueOf(IsNewNull)); } /** Get New value null. @return The new value is null. */ @Override public boolean isNewNull () { Object oo = get_Value(COLUMNNAME_IsNewNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Old value null. @param IsOldNull The old value was null. */ @Override public void setIsOldNull (boolean IsOldNull) { set_Value (COLUMNNAME_IsOldNull, Boolean.valueOf(IsOldNull)); } /** Get Old value null. @return The old value was null. */ @Override
public boolean isOldNull () { Object oo = get_Value(COLUMNNAME_IsOldNull); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set New Value. @param NewValue New field value */ @Override public void setNewValue (java.lang.String NewValue) { set_Value (COLUMNNAME_NewValue, NewValue); } /** Get New Value. @return New field value */ @Override public java.lang.String getNewValue () { return (java.lang.String)get_Value(COLUMNNAME_NewValue); } /** Set Old Value. @param OldValue The old file data */ @Override public void setOldValue (java.lang.String OldValue) { set_Value (COLUMNNAME_OldValue, OldValue); } /** Get Old Value. @return The old file data */ @Override public java.lang.String getOldValue () { return (java.lang.String)get_Value(COLUMNNAME_OldValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationData.java
1
请在Spring Boot框架中完成以下Java代码
protected Map<TopicPartitionInfo, List<ListenableFuture<?>>> onAddedPartitions(Set<TopicPartitionInfo> addedPartitions) { var result = new HashMap<TopicPartitionInfo, List<ListenableFuture<?>>>(); try { log.info("Initializing tenant states."); updateLock.lock(); try { PageDataIterable<Tenant> tenantIterator = new PageDataIterable<>(tenantService::findTenants, 1024); for (Tenant tenant : tenantIterator) { TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenant.getId(), tenant.getId()); if (addedPartitions.contains(tpi)) { if (!myUsageStates.containsKey(tenant.getId()) && tpi.isMyPartition()) { log.debug("[{}] Initializing tenant state.", tenant.getId()); result.computeIfAbsent(tpi, tmp -> new ArrayList<>()).add(dbExecutor.submit(() -> { try { updateTenantState((TenantApiUsageState) getOrFetchState(tenant.getId(), tenant.getId()), tenantProfileCache.get(tenant.getTenantProfileId())); log.debug("[{}] Initialized tenant state.", tenant.getId()); } catch (Exception e) { log.warn("[{}] Failed to initialize tenant API state", tenant.getId(), e); } return null; })); }
} else { log.debug("[{}][{}] Tenant doesn't belong to current partition. tpi [{}]", tenant.getName(), tenant.getId(), tpi); } } } finally { updateLock.unlock(); } } catch (Exception e) { log.warn("Unknown failure", e); } return result; } @PreDestroy private void destroy() { super.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\DefaultTbApiUsageStateService.java
2
请在Spring Boot框架中完成以下Java代码
public class MyProperties { /** * excel模板文件路径 */ private String excelPath = ""; /** * 文件保存路径 */ private String filesPath = ""; /** * 图片保存路径 */ private String picsPath = ""; /** * 图片访问URL前缀 */ private String picsUrlPrefix = ""; /** * 文件访问URL前缀 */ private String filesUrlPrefix = ""; /** * POS API接口前缀 */ private String posapiUrlPrefix = ""; /** * 是否验证码 */ private Boolean kaptchaOpen = false; /** * 是否开启Swaggr */ private Boolean swaggerOpen = false; /** * session 失效时间(默认为30分钟 单位:秒) */ private Integer sessionInvalidateTime = 30 * 60; /** * session 验证失效时间(默认为15分钟 单位:秒) */ private Integer sessionValidationInterval = 15 * 60; /** * 机具心跳报告超时时间 单位:分钟 */ private Integer heartbeatTimeout; public String getExcelPath() { return excelPath; } public void setExcelPath(String excelPath) { this.excelPath = excelPath; } public String getPicsUrlPrefix() { return picsUrlPrefix; } public void setPicsUrlPrefix(String picsUrlPrefix) { this.picsUrlPrefix = picsUrlPrefix; } public Boolean getKaptchaOpen() { return kaptchaOpen; } public void setKaptchaOpen(Boolean kaptchaOpen) { this.kaptchaOpen = kaptchaOpen; } public Boolean getSwaggerOpen() { return swaggerOpen; } public void setSwaggerOpen(Boolean swaggerOpen) { this.swaggerOpen = swaggerOpen; } public Integer getSessionInvalidateTime() { return sessionInvalidateTime; } public void setSessionInvalidateTime(Integer sessionInvalidateTime) { this.sessionInvalidateTime = sessionInvalidateTime;
} public Integer getSessionValidationInterval() { return sessionValidationInterval; } public void setSessionValidationInterval(Integer sessionValidationInterval) { this.sessionValidationInterval = sessionValidationInterval; } public String getFilesUrlPrefix() { return filesUrlPrefix; } public void setFilesUrlPrefix(String filesUrlPrefix) { this.filesUrlPrefix = filesUrlPrefix; } public String getFilesPath() { return filesPath; } public void setFilesPath(String filesPath) { this.filesPath = filesPath; } public Integer getHeartbeatTimeout() { return heartbeatTimeout; } public void setHeartbeatTimeout(Integer heartbeatTimeout) { this.heartbeatTimeout = heartbeatTimeout; } public String getPicsPath() { return picsPath; } public void setPicsPath(String picsPath) { this.picsPath = picsPath; } public String getPosapiUrlPrefix() { return posapiUrlPrefix; } public void setPosapiUrlPrefix(String posapiUrlPrefix) { this.posapiUrlPrefix = posapiUrlPrefix; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java
2
请完成以下Java代码
public boolean isRuecknahmeangebotVereinbart() { return ruecknahmeangebotVereinbart; } /** * Sets the value of the ruecknahmeangebotVereinbart property. * */ public void setRuecknahmeangebotVereinbart(boolean value) { this.ruecknahmeangebotVereinbart = value; } /** * Gets the value of the sondertag property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sondertag property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSondertag().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TypSondertag } * * */ public List<TypSondertag> getSondertag() { if (sondertag == null) { sondertag = new ArrayList<TypSondertag>(); } return this.sondertag; } /** * Gets the value of the automatischerAbruf property. * */ public boolean isAutomatischerAbruf() { return automatischerAbruf; } /** * Sets the value of the automatischerAbruf property. * */ public void setAutomatischerAbruf(boolean value) { this.automatischerAbruf = value; }
/** * Gets the value of the kundenKennung property. * * @return * possible object is * {@link String } * */ public String getKundenKennung() { return kundenKennung; } /** * Sets the value of the kundenKennung property. * * @param value * allowed object is * {@link String } * */ public void setKundenKennung(String value) { this.kundenKennung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAntwort.java
1
请完成以下Java代码
public Object getPersistentState() { return CommentEntityImpl.class; } public byte[] getFullMessageBytes() { return (fullMessage != null ? fullMessage.getBytes() : null); } public void setFullMessageBytes(byte[] fullMessageBytes) { fullMessage = (fullMessageBytes != null ? new String(fullMessageBytes) : null); } public static String MESSAGE_PARTS_MARKER = "_|_"; public static Pattern MESSAGE_PARTS_MARKER_REGEX = Pattern.compile("_\\|_"); public void setMessage(String[] messageParts) { StringBuilder stringBuilder = new StringBuilder(); for (String part : messageParts) { if (part != null) { stringBuilder.append(part.replace(MESSAGE_PARTS_MARKER, " | ")); stringBuilder.append(MESSAGE_PARTS_MARKER); } else { stringBuilder.append("null"); stringBuilder.append(MESSAGE_PARTS_MARKER); } } for (int i = 0; i < MESSAGE_PARTS_MARKER.length(); i++) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } message = stringBuilder.toString(); } public List<String> getMessageParts() { if (message == null) { return null; } List<String> messageParts = new ArrayList<String>(); String[] parts = MESSAGE_PARTS_MARKER_REGEX.split(message); for (String part : parts) { if ("null".equals(part)) { messageParts.add(null); } else { messageParts.add(part); } } return messageParts; } // getters and setters // ////////////////////////////////////////////////////// public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getMessage() { return message; } public void setMessage(String message) {
this.message = message; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getFullMessage() { return fullMessage; } public void setFullMessage(String fullMessage) { this.fullMessage = fullMessage; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java
1
请完成以下Java代码
public class GetIdentityLinksForTaskCmd implements Command<List<IdentityLink>>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; public GetIdentityLinksForTaskCmd(String taskId) { this.taskId = taskId; } public List<IdentityLink> execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task); checkGetIdentityLink(task, commandContext); List<IdentityLink> identityLinks = task.getIdentityLinks().stream().collect(Collectors.toList()); // assignee is not part of identity links in the db. // so if there is one, we add it here. // @Tom: we discussed this long on skype and you agreed ;-) // an assignee *is* an identityLink, and so must it be reflected in the API // // Note: we cant move this code to the TaskEntity (which would be cleaner), // since the task.delete cascased to all associated identityLinks // and of course this leads to exception while trying to delete a non-existing identityLink if (task.getAssignee() != null) {
IdentityLinkEntity identityLink = new IdentityLinkEntity(); identityLink.setUserId(task.getAssignee()); identityLink.setTask(task); identityLink.setType(IdentityLinkType.ASSIGNEE); identityLinks.add(identityLink); } if (task.getOwner() != null) { IdentityLinkEntity identityLink = new IdentityLinkEntity(); identityLink.setUserId(task.getOwner()); identityLink.setTask(task); identityLink.setType(IdentityLinkType.OWNER); identityLinks.add(identityLink); } return identityLinks; } protected void checkGetIdentityLink(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadTask(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetIdentityLinksForTaskCmd.java
1
请完成以下Java代码
public void setProperty(String name, Object value) { if (properties == null) { properties = new HashMap<>(); } properties.put(name, value); } @Override public Object getProperty(String name) { if (properties == null) { return null; } return properties.get(name); } @SuppressWarnings("unchecked") public Map<String, Object> getProperties() { if (properties == null) { return Collections.EMPTY_MAP; }
return properties; } // getters and setters ////////////////////////////////////////////////////// @Override public String getId() { return id; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } @Override public ProcessDefinitionImpl getProcessDefinition() { return processDefinition; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ProcessElementImpl.java
1
请完成以下Java代码
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 Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) {
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请在Spring Boot框架中完成以下Java代码
public class AppDefinitionQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, AppDefinitionQueryProperty> properties = new HashMap<>(); public static final AppDefinitionQueryProperty APP_DEFINITION_KEY = new AppDefinitionQueryProperty("RES.KEY_"); public static final AppDefinitionQueryProperty APP_DEFINITION_CATEGORY = new AppDefinitionQueryProperty("RES.CATEGORY_"); public static final AppDefinitionQueryProperty APP_DEFINITION_ID = new AppDefinitionQueryProperty("RES.ID_"); public static final AppDefinitionQueryProperty APP_DEFINITION_VERSION = new AppDefinitionQueryProperty("RES.VERSION_"); public static final AppDefinitionQueryProperty APP_DEFINITION_NAME = new AppDefinitionQueryProperty("RES.NAME_"); public static final AppDefinitionQueryProperty APP_DEFINITION_DEPLOYMENT_ID = new AppDefinitionQueryProperty("RES.DEPLOYMENT_ID_"); public static final AppDefinitionQueryProperty APP_DEFINITION_TENANT_ID = new AppDefinitionQueryProperty("RES.TENANT_ID_"); private String name;
public AppDefinitionQueryProperty(String name) { this.name = name; properties.put(name, this); } @Override public String getName() { return name; } public static AppDefinitionQueryProperty findByName(String propertyName) { return properties.get(propertyName); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryProperty.java
2
请完成以下Java代码
public int getAD_BoilerPlate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.letters.model.I_AD_BoilerPlate getRef_BoilerPlate() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class); } @Override public void setRef_BoilerPlate(de.metas.letters.model.I_AD_BoilerPlate Ref_BoilerPlate) { set_ValueFromPO(COLUMNNAME_Ref_BoilerPlate_ID, de.metas.letters.model.I_AD_BoilerPlate.class, Ref_BoilerPlate); } /** Set Referenced template. @param Ref_BoilerPlate_ID Referenced template */
@Override public void setRef_BoilerPlate_ID (int Ref_BoilerPlate_ID) { if (Ref_BoilerPlate_ID < 1) set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, null); else set_ValueNoCheck (COLUMNNAME_Ref_BoilerPlate_ID, Integer.valueOf(Ref_BoilerPlate_ID)); } /** Get Referenced template. @return Referenced template */ @Override public int getRef_BoilerPlate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_BoilerPlate_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Ref.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); final EnqueuePPOrderCandidateRequest enqueuePPOrderCandidateRequest = EnqueuePPOrderCandidateRequest.builder() .adPInstanceId(pinstanceId) .ctx(Env.getCtx()) .isCompleteDocOverride(isDocComplete) .autoProcessCandidatesAfterProduction(autoProcessCandidatesAfterProduction) .autoCloseCandidatesAfterProduction(autoCloseCandidatesAfterProduction) .build(); ppOrderCandidateEnqueuer.enqueueSelection(enqueuePPOrderCandidateRequest); return MSG_OK; } @Override @RunOutOfTrx protected void prepare() { if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } protected int createSelection() { final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
return queryBuilder .create() .setRequiredAccess(Access.READ) .createSelection(adPInstanceId); } protected IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder() { final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, false) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false) .addCompareFilter(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .orderBy(I_PP_Order_Candidate.COLUMNNAME_SeqNo) .orderBy(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_EnqueueSelectionForOrdering.java
1
请完成以下Java代码
public boolean isFailOnFirstError() { return failOnFirstError; } @Override public void setFailOnFirstError(final boolean failOnFirstError) { this.failOnFirstError = failOnFirstError; } @Override public IMigrationExecutorProvider getMigrationExecutorProvider() { return factory; } @Override public void setMigrationOperation(MigrationOperation operation) { Check.assumeNotNull(operation, "operation not null"); this.migrationOperation = operation; } @Override public boolean isApplyDML() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DML; } @Override public boolean isApplyDDL() { return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DDL; } @Override
public boolean isSkipMissingColumns() { // TODO configuration to be implemented return true; } @Override public boolean isSkipMissingTables() { // TODO configuration to be implemented return true; } @Override public void addPostponedExecutable(IPostponedExecutable executable) { Check.assumeNotNull(executable, "executable not null"); postponedExecutables.add(executable); } @Override public List<IPostponedExecutable> popPostponedExecutables() { final List<IPostponedExecutable> result = new ArrayList<IPostponedExecutable>(postponedExecutables); postponedExecutables.clear(); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorContext.java
1
请完成以下Java代码
public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) throws PrinterException { if (!havePage(pageIndex)) return Printable.NO_SUCH_PAGE; // Rectangle r = new Rectangle(0, 0, (int)getPaper().getWidth(true), (int)getPaper().getHeight(true)); Page page = getPage(pageIndex + 1); // // log.debug("#" + m_id, "PageIndex=" + pageIndex + ", Copy=" + m_isCopy); page.paint((Graphics2D)graphics, r, false, m_isCopy); // sets context getHeaderFooter().paint((Graphics2D)graphics, r, false); // return Printable.PAGE_EXISTS; } // print /** * Do we have the page * * @param pageIndex page index * @return true if page exists */ private boolean havePage(final int pageIndex) { if (pageIndex < 0 || pageIndex >= getNumberOfPages()) return false; return true; } // havePage /** * Print Copy * * @return true if copy */ public boolean isCopy() { return m_isCopy; } // isCopy /** * Set Copy * * @param isCopy if true document is a copy */ public void setCopy(final boolean isCopy) { m_isCopy = isCopy; } // setCopy /************************************************************************** * Get the doc flavor (Doc Interface) * * @return SERVICE_FORMATTED.PAGEABLE */ @Override public DocFlavor getDocFlavor() { return DocFlavor.SERVICE_FORMATTED.PAGEABLE; } // getDocFlavor /** * Get Print Data (Doc Interface) * * @return this * @throws IOException */ @Override public Object getPrintData() throws IOException { return this; } // getPrintData /** * Get Document Attributes (Doc Interface) * * @return null to obtain all attribute values from the
* job's attribute set. */ @Override public DocAttributeSet getAttributes() { return null; } // getAttributes /** * Obtains a reader for extracting character print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public Reader getReaderForText() throws IOException { return null; } // getReaderForText /** * Obtains an input stream for extracting byte print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public InputStream getStreamForBytes() throws IOException { return null; } // getStreamForBytes public void setPrintInfo(final ArchiveInfo info) { m_PrintInfo = info; } /** * @return PrintInfo */ public ArchiveInfo getPrintInfo() { return m_PrintInfo; } } // LayoutEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\LayoutEngine.java
1
请在Spring Boot框架中完成以下Java代码
private Options copy(Consumer<EnumSet<Option>> processor) { EnumSet<Option> options = (!this.options.isEmpty()) ? EnumSet.copyOf(this.options) : EnumSet.noneOf(Option.class); processor.accept(options); return new Options(options); } /** * Create a new instance with the given {@link Option} values. * @param options the options to include * @return a new {@link Options} instance */ public static Options of(Option... options) { Assert.notNull(options, "'options' must not be null"); if (options.length == 0) { return NONE; } return new Options(EnumSet.copyOf(Arrays.asList(options))); } } /** * Option flags that can be applied. */ public enum Option { /** * Ignore all imports properties from the source. */ IGNORE_IMPORTS,
/** * Ignore all profile activation and include properties. * @since 2.4.3 */ IGNORE_PROFILES, /** * Indicates that the source is "profile specific" and should be included after * profile specific sibling imports. * @since 2.4.5 */ PROFILE_SPECIFIC } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigData.java
2
请完成以下Java代码
public class ImportUtils { private static Logger log = LogManager.getLogger(ImportUtils.class); public static List<String> lines(String json) { if (json == null) return Collections.emptyList(); String[] split = json.split("[\\r\\n]+"); return Arrays.asList(split); } public static List<String> lines(MultipartFile file) { try { Path tmp = Files.write(File.createTempFile("mongo-upload", null) .toPath(), file.getBytes()); return Files.readAllLines(tmp); } catch (IOException e) { log.error("reading lines from " + file, e); return null; } } public static List<String> lines(File file) { try { return Files.readAllLines(file.toPath()); } catch (IOException e) { log.error("reading lines from " + file, e);
return null; } } public static List<String> linesFromResource(String resource) { Resource input = new ClassPathResource(resource); try { Path path = input.getFile() .toPath(); return Files.readAllLines(path); } catch (IOException e) { log.error("reading lines from classpath resource: " + resource, e); return null; } } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\json\convertfile\ImportUtils.java
1
请在Spring Boot框架中完成以下Java代码
public void setTaxBaseAmt(final BigDecimal taxBaseAmt) { this.taxBaseAmt = taxBaseAmt; } public BigDecimal getTotalAmt() { return totalAmt; } public void setTotalAmt(final BigDecimal totalAmt) { this.totalAmt = totalAmt; } public BigDecimal getTaxAmtSumTaxBaseAmt() { return taxAmtSumTaxBaseAmt; } public void setTaxAmtSumTaxBaseAmt(final BigDecimal taxAmtSumTaxBaseAmt) { this.taxAmtSumTaxBaseAmt = taxAmtSumTaxBaseAmt; } public String getESRNumber() { return ESRNumber; } public void setESRNumber(final String eSRNumber) { ESRNumber = eSRNumber; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (ESRNumber == null ? 0 : ESRNumber.hashCode()); result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (rate == null ? 0 : rate.hashCode()); result = prime * result + (taxAmt == null ? 0 : taxAmt.hashCode()); result = prime * result + (taxAmtSumTaxBaseAmt == null ? 0 : taxAmtSumTaxBaseAmt.hashCode()); result = prime * result + (taxBaseAmt == null ? 0 : taxBaseAmt.hashCode()); result = prime * result + (totalAmt == null ? 0 : totalAmt.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop901991V other = (Cctop901991V)obj; if (ESRNumber == null) { if (other.ESRNumber != null) { return false; } } else if (!ESRNumber.equals(other.ESRNumber)) { return false; } if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (rate == null) { if (other.rate != null) { return false;
} } else if (!rate.equals(other.rate)) { return false; } if (taxAmt == null) { if (other.taxAmt != null) { return false; } } else if (!taxAmt.equals(other.taxAmt)) { return false; } if (taxAmtSumTaxBaseAmt == null) { if (other.taxAmtSumTaxBaseAmt != null) { return false; } } else if (!taxAmtSumTaxBaseAmt.equals(other.taxAmtSumTaxBaseAmt)) { return false; } if (taxBaseAmt == null) { if (other.taxBaseAmt != null) { return false; } } else if (!taxBaseAmt.equals(other.taxBaseAmt)) { return false; } if (totalAmt == null) { if (other.totalAmt != null) { return false; } } else if (!totalAmt.equals(other.totalAmt)) { return false; } return true; } @Override public String toString() { return "Cctop901991V [cInvoiceID=" + cInvoiceID + ", rate=" + rate + ", taxAmt=" + taxAmt + ", taxBaseAmt=" + taxBaseAmt + ", totalAmt=" + totalAmt + ", ESRNumber=" + ESRNumber + ", taxAmtSumTaxBaseAmt=" + taxAmtSumTaxBaseAmt + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop901991V.java
2
请完成以下Java代码
public final <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider) { final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(modelClass); final String joinColumnNameFQ = InterfaceWrapperHelper.getTableName(modelClass) + "." + keyColumnName; final String lockedRecordsSQL = getLockedWhereClauseAllowNullLock(modelClass, joinColumnNameFQ, null); // note: don't specify a particular ordering; leave that freedom to the caller if this method return Services.get(IQueryBL.class).createQueryBuilder(modelClass, contextProvider) .addOnlyActiveRecordsFilter() // .addOnlyContextClientOrSystem() // avoid applying context client because in some cases context is not available .filter(TypedSqlQueryFilter.of(lockedRecordsSQL)); } @Override @NonNull public final <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz) { final ILockCommand lockCommand = new LockCommand(this) .setOwner(LockOwner.NONE); final ImmutableList.Builder<T> lockedModelsCollector = ImmutableList.builder(); final List<T> models = query.list(clazz); if (models == null || models.isEmpty()) { return ImmutableList.of(); } for (final T model : models) { final TableRecordReference record = TableRecordReference.of(model); if (lockRecord(lockCommand, record)) { lockedModelsCollector.add(model); } } final ImmutableList<T> lockedModels = lockedModelsCollector.build(); if (lockedModels.size() != models.size()) {
logger.warn("*** retrieveAndLockMultipleRecords: not all retrieved records could be locked! expectedLockedSize: {}, actualLockedSize: {}" , models.size(), lockedModels.size()); } return lockedModels; } public <T> IQuery<T> addNotLockedClause(final IQuery<T> query) { return retrieveNotLockedQuery(query); } /** * @return <code>true</code> if the given <code>allowAdditionalLocks</code> is <code>FOR_DIFFERENT_OWNERS</code>. */ protected static boolean isAllowMultipleOwners(final AllowAdditionalLocks allowAdditionalLocks) { return allowAdditionalLocks == AllowAdditionalLocks.FOR_DIFFERENT_OWNERS; } protected abstract <T> IQuery<T> retrieveNotLockedQuery(IQuery<T> query); protected abstract String getLockedWhereClauseAllowNullLock(@NonNull final Class<?> modelClass, @NonNull final String joinColumnNameFQ, @Nullable final LockOwner lockOwner); }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\AbstractLockDatabase.java
1
请在Spring Boot框架中完成以下Java代码
public class M_InOut_Receipt { /** * When a receipt is reversed we need to reverse the allocations too. * * Precisely, we create {@link I_M_ReceiptSchedule_Alloc} records to allocate reversal lines to initial {@link I_M_ReceiptSchedule} * * @param receipt */ @DocValidate(timings = { ModelValidator.TIMING_AFTER_REVERSECORRECT, ModelValidator.TIMING_AFTER_REVERSEACCRUAL }) public void reverseReceiptScheduleAllocs(final I_M_InOut receipt) { // Only if it's a receipt if (receipt.isSOTrx()) { return; } for (final I_M_InOutLine line : Services.get(IInOutDAO.class).retrieveLines(receipt)) { final List<I_M_ReceiptSchedule_Alloc> lineAllocs = Services.get(IReceiptScheduleDAO.class).retrieveRsaForInOutLine(line); if (lineAllocs.isEmpty()) { continue; } final I_M_InOutLine reversalLine = line.getReversalLine(); Check.assumeNotNull(reversalLine, "reversalLine not null (original line: {})", line); Check.assume(reversalLine.getM_InOutLine_ID() > 0, "reversalLine not null (original line: {})", line); reverseAllocations(lineAllocs, reversalLine); } } private void reverseAllocations(final List<I_M_ReceiptSchedule_Alloc> lineAllocs, final I_M_InOutLine reversalLine) { for (final I_M_ReceiptSchedule_Alloc lineAlloc : lineAllocs) { reverseAllocation(lineAlloc, reversalLine); } }
private void reverseAllocation(I_M_ReceiptSchedule_Alloc lineAlloc, I_M_InOutLine reversalLine) { final I_M_ReceiptSchedule_Alloc reversalLineAlloc = Services.get(IReceiptScheduleBL.class).reverseAllocation(lineAlloc); reversalLineAlloc.setM_InOutLine(reversalLine); InterfaceWrapperHelper.save(reversalLineAlloc); } @DocValidate(timings = { ModelValidator.TIMING_AFTER_VOID }) public void deleteReceiptScheduleAllocs(final I_M_InOut receipt) { // Only if it's a receipt if (receipt.isSOTrx()) { return; } Services.get(IReceiptScheduleDAO.class) .retrieveRsaForInOut(receipt) .forEach(rsa -> InterfaceWrapperHelper.delete(rsa)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_InOut_Receipt.java
2
请完成以下Java代码
public String getType() { if (type == null) { return "15"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the participantNumber property. * * @return * possible object is * {@link String } * */ public String getParticipantNumber() { return participantNumber; } /** * Sets the value of the participantNumber property. * * @param value * allowed object is * {@link String } * */ public void setParticipantNumber(String value) { this.participantNumber = value; } /** * Gets the value of the referenceNumber property. * * @return * possible object is * {@link String } * */ public String getReferenceNumber() { return referenceNumber; }
/** * Sets the value of the referenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNumber(String value) { this.referenceNumber = value; } /** * Gets the value of the codingLine property. * * @return * possible object is * {@link String } * */ public String getCodingLine() { return codingLine; } /** * Sets the value of the codingLine property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine(String value) { this.codingLine = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\Esr5Type.java
1
请完成以下Java代码
private void prepareAD_PInstance(final ProcessInfo pi) { // // Save process info to database, including parameters. adPInstanceDAO.saveProcessInfo(pi); } private ProcessInfo getProcessInfo() { return processInfo; } public Builder setListener(final IProcessExecutionListener listener) { this.listener = listener; return this; } private IProcessExecutionListener getListener() { return listener; } /** * Advice the executor to propagate the error in case the execution failed. */ public Builder onErrorThrowException() { this.onErrorThrowException = true; return this; } public Builder onErrorThrowException(final boolean onErrorThrowException) { this.onErrorThrowException = onErrorThrowException; return this; } /** * Advice the executor to switch current context with process info's context. * * @see ProcessInfo#getCtx() * @see Env#switchContext(Properties)
*/ public Builder switchContextWhenRunning() { this.switchContextWhenRunning = true; return this; } /** * Sets the callback to be executed after AD_PInstance is created but before the actual process is started. * If the callback fails, the exception is propagated, so the process will not be started. * <p> * A common use case of <code>beforeCallback</code> is to create to selections which are linked to this process instance. */ public Builder callBefore(final Consumer<ProcessInfo> beforeCallback) { this.beforeCallback = beforeCallback; return this; } } } // ProcessCtl
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutor.java
1
请完成以下Java代码
public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load document content from the specified file document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx"); // Create a fixed layout document object FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document); // Get the first page FixedLayoutPage page = layoutDoc.getPages().get(0); // Get the section where the page is located Section section = page.getSection(); // Get the first paragraph of the page Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph(); int startIndex = 0; if (paragraphStart != null) { // Get the index of the paragraph in the section startIndex = section.getBody().getChildObjects().indexOf(paragraphStart); } // Get the last paragraph of the page Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph(); int endIndex = 0; if (paragraphEnd != null) { // Get the index of the paragraph in the section endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd); } // Create a new document object Document newdoc = new Document(); // Add a new section Section newSection = newdoc.addSection(); // Clone the properties of the original section to the new section
section.cloneSectionPropertiesTo(newSection); // Copy the content of the original document's page to the new document for (int i = startIndex; i <=endIndex; i++) { newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone()); } // Save the new document to the specified file newdoc.saveToFile("/Users/liuhaihua/tmp/Content of One Page.docx", FileFormat.Docx); // Close and release the new document newdoc.close(); newdoc.dispose(); // Close and release the original document document.close(); document.dispose(); } }
repos\springboot-demo-master\spire-doc\src\main\java\com\et\spire\doc\ReadOnePage.java
1
请完成以下Java代码
public void setM_Product_Proxy_ID (final int M_Product_Proxy_ID) { if (M_Product_Proxy_ID < 1) set_Value (COLUMNNAME_M_Product_Proxy_ID, null); else set_Value (COLUMNNAME_M_Product_Proxy_ID, M_Product_Proxy_ID); } @Override public int getM_Product_Proxy_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Proxy_ID); } @Override public void setM_ProductGroup_ID (final int M_ProductGroup_ID) { if (M_ProductGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID); } @Override public int getM_ProductGroup_ID() { return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_M_ProductGroup.java
1
请完成以下Java代码
private static BPartnerVendorAccounts fromRecord(@NonNull final I_C_BP_Vendor_Acct record) { return BPartnerVendorAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .V_Liability_Acct(Account.of(AccountId.ofRepoId(record.getV_Liability_Acct()), BPartnerVendorAccountType.V_Liability)) .V_Liability_Services_Acct(Account.of(AccountId.ofRepoId(record.getV_Liability_Services_Acct()), BPartnerVendorAccountType.V_Liability_Services)) .V_Prepayment_Acct(Account.of(AccountId.ofRepoId(record.getV_Prepayment_Acct()), BPartnerVendorAccountType.V_Prepayment)) .build(); } public BPartnerCustomerAccounts getCustomerAccounts( @NonNull final BPartnerId bpartnerId, @NonNull final AcctSchemaId acctSchemaId) { final ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> map = customerAccountsCache.getOrLoad(bpartnerId, this::retrieveCustomerAccounts); final BPartnerCustomerAccounts accounts = map.get(acctSchemaId); if (accounts == null) { throw new AdempiereException("No customer accounts defined for " + bpartnerId + " and " + acctSchemaId); } return accounts; } private ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> retrieveCustomerAccounts(final BPartnerId bpartnerId) { return queryBL.createQueryBuilder(I_C_BP_Customer_Acct.class) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BP_Customer_Acct.COLUMNNAME_C_BPartner_ID, bpartnerId) .create() .stream() .map(BPartnerAccountsRepository::fromRecord) .collect(ImmutableMap.toImmutableMap(BPartnerCustomerAccounts::getAcctSchemaId, accts -> accts)); } @NonNull private static BPartnerCustomerAccounts fromRecord(@NonNull final I_C_BP_Customer_Acct record) { return BPartnerCustomerAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .C_Receivable_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Acct()), BPartnerCustomerAccountType.C_Receivable)) .C_Receivable_Services_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Services_Acct()), BPartnerCustomerAccountType.C_Receivable_Services)) .C_Prepayment_Acct(Account.of(AccountId.ofRepoId(record.getC_Prepayment_Acct()), BPartnerCustomerAccountType.C_Prepayment)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\BPartnerAccountsRepository.java
1
请完成以下Java代码
public void setVariables(Map<String, Object> variables) { this.variables = variables; } @Override public Map<String, Object> getVariables() { return this.variables; } public void setExtensions(Map<String, Object> extensions) { this.extensions = extensions; } @Override public Map<String, Object> getExtensions() { return this.extensions; }
@Override public String getDocument() { if (this.query == null) { if (this.extensions.get("persistedQuery") != null) { return PersistedQuerySupport.PERSISTED_QUERY_MARKER; } throw new ServerWebInputException("No 'query'"); } return this.query; } @Override public Map<String, Object> toMap() { throw new UnsupportedOperationException(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\SerializableGraphQlRequest.java
1
请完成以下Java代码
public JsonWorkplace assignWorkplace(@PathVariable("workplaceId") @NonNull final Integer workplaceIdInt) { final WorkplaceId workplaceId = WorkplaceId.ofRepoId(workplaceIdInt); workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder() .workplaceId(workplaceId) .userId(Env.getLoggedUserId()) .build()); return getWorkplaceById(workplaceId); } @PostMapping("/byQRCode") public JsonWorkplace getWorkplaceByQRCode(@RequestBody @NonNull final JsonGetWorkplaceByQRCodeRequest request) { final WorkplaceQRCode qrCode = WorkplaceQRCode.ofGlobalQRCodeJsonString(request.getQrCode()); return getWorkplaceById(qrCode.getWorkplaceId()); } private JsonWorkplace getWorkplaceById(@NonNull final WorkplaceId workplaceId)
{ final Workplace workplace = workplaceService.getById(workplaceId); return toJson(workplace); } private JsonWorkplace toJson(final Workplace workplace) { return JsonWorkplace.builder() .id(workplace.getId()) .name(workplace.getName()) .qrCode(WorkplaceQRCode.ofWorkplace(workplace).toGlobalQRCodeJsonString()) .warehouseName(workplace.getWarehouseId() != null ? warehouseService.getWarehouseName(workplace.getWarehouseId()) : null) .isUserAssigned(workplaceService.isUserAssigned(Env.getLoggedUserId(), workplace.getId())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\workplace\WorkplaceRestController.java
1
请完成以下Java代码
public Exception getException() { return exception; } public int incrementHitCount() { dateLastRequest = new Date(); return hitCount.incrementAndGet(); } } private final transient Logger logger = LogManager.getLogger(getClass()); private final Map<Integer, BlackListItem> blacklist = new ConcurrentHashMap<Integer, BlackListItem>(); public WorkpackageProcessorBlackList() { super(); } public boolean isBlacklisted(final int workpackageProcessorId) { return blacklist.containsKey(workpackageProcessorId); } public void addToBlacklist(final int packageProcessorId, String packageProcessorClassname, Exception e) { final ConfigurationException exception = ConfigurationException.wrapIfNeeded(e); final BlackListItem blacklistItemToAdd = new BlackListItem(packageProcessorId, packageProcessorClassname, exception); blacklist.put(packageProcessorId, blacklistItemToAdd); logger.warn("Processor blacklisted: " + blacklistItemToAdd, exception); } public void removeFromBlacklist(final int packageProcessorId) { final BlackListItem blacklistItem = blacklist.remove(packageProcessorId); if (blacklistItem != null) { logger.info("Processor removed from blacklist: " + blacklistItem); } }
public void assertNotBlacklisted(final int workpackageProcessorId) { final BlackListItem blacklistItem = blacklist.get(workpackageProcessorId); if (blacklistItem != null) { blacklistItem.incrementHitCount(); throw new ConfigurationException("Already blacklisted: " + blacklistItem, blacklistItem.getException()); } } public List<BlackListItem> getItems() { return new ArrayList<BlackListItem>(blacklist.values()); } public void clear() { blacklist.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorBlackList.java
1
请在Spring Boot框架中完成以下Java代码
public void loadPolicy(Model model) { if (classPath.equals("")) { // throw new Error("invalid file path, file path cannot be empty"); return; } loadPolicyClassPath(model, Helper::loadPolicyLine); } @Override public void savePolicy(Model model) { LOG.warn("savePolicy is not implemented !"); } @Override public void addPolicy(String sec, String ptype, List<String> rule) { throw new Error("not implemented"); } @Override public void removePolicy(String sec, String ptype, List<String> rule) { throw new Error("not implemented"); }
@Override public void removeFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) { throw new Error("not implemented"); } private void loadPolicyClassPath(Model model, Helper.loadPolicyLineHandler<String, Model> handler) { InputStream is = IsAdapter.class.getResourceAsStream(classPath); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; try { while((line = br.readLine()) != null) { handler.accept(line, model); } is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); throw new Error("IO error occurred"); } } }
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\config\IsAdapter.java
2
请完成以下Java代码
public class MovePlanItemDefinitionIdContainer { protected List<String> planItemDefinitionIds; protected List<String> moveToPlanItemDefinitionIds; protected String newAssigneeId; public MovePlanItemDefinitionIdContainer(String singlePlanItemDefinitionId, String moveToPlanItemDefinitionId) { this(singlePlanItemDefinitionId, moveToPlanItemDefinitionId, null); } public MovePlanItemDefinitionIdContainer(String singlePlanItemDefinitionId, String moveToPlanItemDefinitionId, String newAssigneeId) { this.planItemDefinitionIds = Collections.singletonList(singlePlanItemDefinitionId); this.moveToPlanItemDefinitionIds = Collections.singletonList(moveToPlanItemDefinitionId); this.newAssigneeId = newAssigneeId; } public MovePlanItemDefinitionIdContainer(List<String> planItemDefinitionIds, String moveToPlanItemDefinitionId) { this(planItemDefinitionIds, moveToPlanItemDefinitionId, null); } public MovePlanItemDefinitionIdContainer(List<String> planItemDefinitionIds, String moveToPlanItemDefinitionId, String newAssigneeId) { this.planItemDefinitionIds = planItemDefinitionIds; this.moveToPlanItemDefinitionIds = Collections.singletonList(moveToPlanItemDefinitionId); this.newAssigneeId = newAssigneeId; } public MovePlanItemDefinitionIdContainer(String singlePlanItemDefinitionId, List<String> moveToPlanItemDefinitionIds) { this(singlePlanItemDefinitionId, moveToPlanItemDefinitionIds, null); } public MovePlanItemDefinitionIdContainer(String singlePlanItemDefinitionId, List<String> moveToPlanItemDefinitionIds, String newAssigneeId) { this.planItemDefinitionIds = Collections.singletonList(singlePlanItemDefinitionId); this.moveToPlanItemDefinitionIds = moveToPlanItemDefinitionIds; this.newAssigneeId = newAssigneeId; } public List<String> getPlanItemDefinitionIds() { return planItemDefinitionIds; }
public void setPlanItemDefinitionIds(List<String> planItemDefinitionIds) { this.planItemDefinitionIds = planItemDefinitionIds; } public List<String> getMoveToPlanItemDefinitionIds() { return moveToPlanItemDefinitionIds; } public void setMoveToPlanItemDefinitionIds(List<String> moveToPlanItemDefinitionIds) { this.moveToPlanItemDefinitionIds = moveToPlanItemDefinitionIds; } public String getNewAssigneeId() { return newAssigneeId; } public void setNewAssigneeId(String newAssigneeId) { this.newAssigneeId = newAssigneeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemDefinitionIdContainer.java
1
请完成以下Java代码
public Resource concatenatePDF( @NonNull final Resource documentPdfData, @NonNull final List<PdfDataProvider> pdfDataToConcatenate) { if (pdfDataToConcatenate.isEmpty()) { return documentPdfData; } final PdfDataProvider pdfData = PdfDataProvider.forData(documentPdfData); final ImmutableList<PdfDataProvider> allPdfDataToConcatenate = ImmutableList.<PdfDataProvider>builder() .add(pdfData) .addAll(pdfDataToConcatenate) .build(); return concatenatePDFs(allPdfDataToConcatenate); } /** * The more sane version of {@link #concatenatePDF(Resource, List)}. */ @NonNull public Resource concatenatePDFs(@NonNull final ImmutableList<PdfDataProvider> pdfDataToConcatenate) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); concatenatePDFsToOutputStream(out, pdfDataToConcatenate); return new ByteArrayResource(out.toByteArray()); } private void concatenatePDFsToOutputStream( @NonNull final OutputStream outputStream, @NonNull final ImmutableList<PdfDataProvider> pdfDataToConcatenate) { final Document document = new Document(); try { final PdfCopy copyDestination = new PdfCopy(document, outputStream); document.open(); for (final PdfDataProvider pdfData : pdfDataToConcatenate) { appendPdfPages(copyDestination, pdfData); }
document.close(); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e); } } private static void appendPdfPages(@NonNull final PdfCopy copyDestination, @NonNull final PdfDataProvider pdfData) throws IOException, BadPdfFormatException { final Resource data = pdfData.getPdfData(); final PdfReader pdfReader = new PdfReader(data.getInputStream()); for (int page = 0; page < pdfReader.getNumberOfPages(); ) { copyDestination.addPage(copyDestination.getImportedPage(pdfReader, ++page)); } copyDestination.freeReader(pdfReader); pdfReader.close(); } @Value public static class PdfDataProvider { public static PdfDataProvider forData(@NonNull final Resource pdfData) { return new PdfDataProvider(pdfData); } Resource pdfData; private PdfDataProvider(@NonNull final Resource pdfData) { this.pdfData = pdfData; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ExecuteReportStrategyUtil.java
1
请完成以下Java代码
public void setQtyIssued (java.math.BigDecimal QtyIssued) { set_Value (COLUMNNAME_QtyIssued, QtyIssued); } /** Get Ausgelagerte Menge. @return Ausgelagerte Menge */ @Override public java.math.BigDecimal getQtyIssued () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Empfangene Menge. @param QtyReceived Empfangene Menge */ @Override public void setQtyReceived (java.math.BigDecimal QtyReceived) { throw new IllegalArgumentException ("QtyReceived is virtual column"); } /** Get Empfangene Menge. @return Empfangene Menge */ @Override public java.math.BigDecimal getQtyReceived () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived); if (bd == null)
return BigDecimal.ZERO; return bd; } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking_Ref.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("collectModels", collectModels) .add("workpackageProcessorClass", getWorkpackageProcessorClass()) .add("modelType", modelType) .toString(); } @Override protected Properties extractCtxFromItem(final ModelType item) { return InterfaceWrapperHelper.getCtx(item); } @Override protected String extractTrxNameFromItem(final ModelType item) {
return InterfaceWrapperHelper.getTrxName(item); } @Nullable @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final ModelType item) { return collectModels ? item : null; } @Override protected boolean isEnqueueWorkpackageWhenNoModelsEnqueued() { return !collectModels; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackagesOnCommitSchedulerTemplate.java
1
请完成以下Java代码
protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId); } @Override protected void applyFilters(HistoricActivityStatisticsQuery query) { if (includeCanceled != null && includeCanceled) { query.includeCanceled(); } if (includeFinished != null && includeFinished) { query.includeFinished(); } if (includeCompleteScope != null && includeCompleteScope) { query.includeCompleteScope(); } if (includeIncidents !=null && includeIncidents) { query.includeIncidents(); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (finishedAfter != null) { query.finishedAfter(finishedAfter); }
if (finishedBefore != null) { query.finishedBefore(finishedBefore); } if (processInstanceIdIn != null) { query.processInstanceIdIn(processInstanceIdIn); } } @Override protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) { query.orderByActivityId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java
1
请完成以下Java代码
public Date toDate(Object value) { if (value instanceof String) { return parse((String) value); } if (value instanceof Date) { return (Date) value; } if (value instanceof Long) { return new Date((long) value); } if (value instanceof LocalDate) { return Date.from(((LocalDate) value).atStartOfDay(getZoneId()).toInstant());
} if (value instanceof LocalDateTime) { return Date.from(((LocalDateTime) value).atZone(getZoneId()).toInstant()); } if (value instanceof ZonedDateTime) { return Date.from(((ZonedDateTime) value).toInstant()); } throw new DateTimeException( MessageFormat.format("Error while parsing date. Type: {0}, value: {1}", value.getClass().getName(), value) ); } }
repos\Activiti-develop\activiti-core-common\activiti-common-util\src\main\java\org\activiti\common\util\DateFormatterProvider.java
1
请完成以下Java代码
public WritablePdxInstance createWriter() { return getDelegate().createWriter(); } /** * @inheritDoc */ @Override public boolean hasField(String fieldName) { return getDelegate().hasField(fieldName); } /** * @inheritDoc */ @Override public void sendTo(DataOutput out) throws IOException { PdxInstance delegate = getDelegate(); if (delegate instanceof Sendable) { ((Sendable) delegate).sendTo(out); } } /** * Returns a {@link String} representation of this {@link PdxInstance}. * * @return a {@link String} representation of this {@link PdxInstance}. * @see java.lang.String */ @Override public String toString() { //return getDelegate().toString(); return toString(this); } private String toString(PdxInstance pdx) { return toString(pdx, ""); } private String toString(PdxInstance pdx, String indent) { if (Objects.nonNull(pdx)) { StringBuilder buffer = new StringBuilder(OBJECT_BEGIN).append(NEW_LINE); String fieldIndent = indent + INDENT_STRING; buffer.append(fieldIndent).append(formatFieldValue(CLASS_NAME_PROPERTY, pdx.getClassName())); for (String fieldName : nullSafeList(pdx.getFieldNames())) { Object fieldValue = pdx.getField(fieldName); String valueString = toStringObject(fieldValue, fieldIndent); buffer.append(COMMA_NEW_LINE); buffer.append(fieldIndent).append(formatFieldValue(fieldName, valueString)); } buffer.append(NEW_LINE).append(indent).append(OBJECT_END); return buffer.toString(); } else { return null; } }
private String toStringArray(Object value, String indent) { Object[] array = (Object[]) value; StringBuilder buffer = new StringBuilder(ARRAY_BEGIN); boolean addComma = false; for (Object element : array) { buffer.append(addComma ? COMMA_SPACE : EMPTY_STRING); buffer.append(toStringObject(element, indent)); addComma = true; } buffer.append(ARRAY_END); return buffer.toString(); } private String toStringObject(Object value, String indent) { return isPdxInstance(value) ? toString((PdxInstance) value, indent) : isArray(value) ? toStringArray(value, indent) : String.valueOf(value); } private String formatFieldValue(String fieldName, Object fieldValue) { return String.format(FIELD_TYPE_VALUE, fieldName, nullSafeType(fieldValue), fieldValue); } private boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } private boolean isArray(Object value) { return Objects.nonNull(value) && value.getClass().isArray(); } private boolean isPdxInstance(Object value) { return value instanceof PdxInstance; } private <T> List<T> nullSafeList(List<T> list) { return list != null ? list : Collections.emptyList(); } private Class<?> nullSafeType(Object value) { return value != null ? value.getClass() : Object.class; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\pdx\PdxInstanceWrapper.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final RuleCalloutInstance other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(id, other.id) .isEqual(); } @Override public void execute(final ICalloutExecutor executor, final ICalloutField field) { final Properties ctx = field.getCtx(); final int windowNo = field.getWindowNo(); final Object value = field.getValue();
final Object valueOld = field.getOldValue(); final GridField gridField = (field instanceof GridField ? (GridField)field : null); try { scriptExecutorSupplier.get() .putContext(ctx, windowNo) .putArgument("Value", value) .putArgument("OldValue", valueOld) .putArgument("Field", gridField) .putArgument("Tab", gridField == null ? null : gridField.getGridTab()) .setThrowExceptionIfResultNotEmpty() .execute(script); } catch (final Exception e) { throw CalloutExecutionException.wrapIfNeeded(e) .setCalloutInstance(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\RuleCalloutInstance.java
1
请在Spring Boot框架中完成以下Java代码
public class DubboServicesMetadata extends AbstractDubboMetadata { public Map<String, Map<String, Object>> services() { Map<String, ServiceBean> serviceBeansMap = getServiceBeansMap(); Map<String, Map<String, Object>> servicesMetadata = new LinkedHashMap<>(serviceBeansMap.size()); for (Map.Entry<String, ServiceBean> entry : serviceBeansMap.entrySet()) { String serviceBeanName = entry.getKey(); ServiceBean serviceBean = entry.getValue(); Map<String, Object> serviceBeanMetadata = resolveBeanMetadata(serviceBean); Object service = resolveServiceBean(serviceBeanName, serviceBean); if (service != null) { // Add Service implementation class serviceBeanMetadata.put("serviceClass", service.getClass().getName()); } servicesMetadata.put(serviceBeanName, serviceBeanMetadata); } return servicesMetadata; }
private Object resolveServiceBean(String serviceBeanName, ServiceBean serviceBean) { int index = serviceBeanName.indexOf("#"); if (index > -1) { Class<?> interfaceClass = serviceBean.getInterfaceClass(); String serviceName = serviceBeanName.substring(index + 1); if (applicationContext.containsBean(serviceName)) { return applicationContext.getBean(serviceName, interfaceClass); } } return null; } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\DubboServicesMetadata.java
2
请完成以下Java代码
public boolean isOneAssetPerUOM () { Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Owned. @param IsOwned The asset is owned by the organization */ public void setIsOwned (boolean IsOwned) { set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned)); } /** Get Owned. @return The asset is owned by the organization */ public boolean isOwned () { Object oo = get_Value(COLUMNNAME_IsOwned); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Track Issues. @param IsTrackIssues
Enable tracking issues for this asset */ public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); } /** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java
1
请完成以下Java代码
public URL lookupBpmPlatformXmlLocationFromJndi() { String jndi = "java:comp/env/" + BPM_PLATFORM_XML_LOCATION; try { String bpmPlatformXmlLocation = InitialContext.doLookup(jndi); URL fileLocation = checkValidBpmPlatformXmlResourceLocation(bpmPlatformXmlLocation); if (fileLocation != null) { LOG.foundConfigJndi(jndi, fileLocation.toString()); } return fileLocation; } catch (NamingException e) { LOG.debugExceptionWhileGettingConfigFromJndi(jndi, e); return null; } } public URL lookupBpmPlatformXmlLocationFromEnvironmentVariable() { String bpmPlatformXmlLocation = System.getenv(BPM_PLATFORM_XML_ENVIRONMENT_VARIABLE); String logStatement = "environment variable [" + BPM_PLATFORM_XML_ENVIRONMENT_VARIABLE + "]"; if (bpmPlatformXmlLocation == null) { bpmPlatformXmlLocation = System.getProperty(BPM_PLATFORM_XML_SYSTEM_PROPERTY); logStatement = "system property [" + BPM_PLATFORM_XML_SYSTEM_PROPERTY + "]"; } URL fileLocation = checkValidBpmPlatformXmlResourceLocation(bpmPlatformXmlLocation); if (fileLocation != null) { LOG.foundConfigAtLocation(logStatement, fileLocation.toString()); } return fileLocation; } public URL lookupBpmPlatformXmlFromClassPath(String resourceLocation) { URL fileLocation = ClassLoaderUtil.getClassloader(getClass()).getResource(resourceLocation); if (fileLocation != null) { LOG.foundConfigAtLocation(resourceLocation, fileLocation.toString()); } return fileLocation; }
public URL lookupBpmPlatformXmlFromClassPath() { return lookupBpmPlatformXmlFromClassPath(BPM_PLATFORM_XML_RESOURCE_LOCATION); } public URL lookupBpmPlatformXml() { URL fileLocation = lookupBpmPlatformXmlLocationFromJndi(); if (fileLocation == null) { fileLocation = lookupBpmPlatformXmlLocationFromEnvironmentVariable(); } if (fileLocation == null) { fileLocation = lookupBpmPlatformXmlFromClassPath(); } return fileLocation; } public abstract URL getBpmPlatformXmlStream(DeploymentOperation operationContext); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\AbstractParseBpmPlatformXmlStep.java
1
请完成以下Java代码
public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item huItem) { final IQueryBuilder<I_M_HU_Item_Storage> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item_Storage.class, huItem) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID())); queryBuilder.orderBy() .addColumn(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_Storage_ID); // predictive order final List<I_M_HU_Item_Storage> huItemStorages = queryBuilder .create() .setOnlyActiveRecords(true) .list(I_M_HU_Item_Storage.class); // Optimization: set parent link for (final I_M_HU_Item_Storage huItemStorage : huItemStorages) { huItemStorage.setM_HU_Item(huItem); }
return huItemStorages; } @Override public void save(final I_M_HU_Item_Storage storageLine) { InterfaceWrapperHelper.save(storageLine); } @Override public void save(final I_M_HU_Item item) { InterfaceWrapperHelper.save(item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorageDAO.java
1
请完成以下Java代码
public void loadImage() { if (file == null) { return; } ImageIcon tmpIcon = new ImageIcon(file.getPath()); if (tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon(tmpIcon.getImage(). getScaledInstance(90, -1, Image.SCALE_DEFAULT)); } else { thumbnail = tmpIcon; } } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { file = (File) e.getNewValue(); if (isShowing()) { loadImage(); repaint();
} } } public void paintComponent(Graphics g) { if (thumbnail == null) { loadImage(); } if (thumbnail != null) { int x = getWidth()/2 - thumbnail.getIconWidth()/2; int y = getHeight()/2 - thumbnail.getIconHeight()/2; if (y < 0) { y = 0; } if (x < 5) { x = 5; } thumbnail.paintIcon(this, g, x, y); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\filechooser\ImagePreview.java
1
请完成以下Java代码
public static List<Integer> findPairsWithForLoop(int[] input, int sum) { final List<Integer> allDifferentPairs = new ArrayList<>(); // Aux. hash map final Map<Integer, Integer> pairs = new HashMap<>(); for (int i : input) { if (pairs.containsKey(i)) { if (pairs.get(i) != null) { // Add pair to returned list allDifferentPairs.add(i); } // Mark pair as added to prevent duplicates pairs.put(sum - i, null); } else if (!pairs.containsValue(i)) { // Add pair to aux. hash map pairs.put(sum - i, i); } } return allDifferentPairs; } /** * Show all different pairs using Java 8 stream API * * @param input - number's array * @param sum - given sum * @return - number's array with all existing pairs. This list will contain just one pair's element because * the other one can be calculated with SUM - element_1 = element_2 */ public static List<Integer> findPairsWithStreamApi(int[] input, int sum) { final List<Integer> allDifferentPairs = new ArrayList<>(); // Aux. hash map
final Map<Integer, Integer> pairs = new HashMap<>(); IntStream.range(0, input.length).forEach(i -> { if (pairs.containsKey(input[i])) { if (pairs.get(input[i]) != null) { // Add pair to returned list allDifferentPairs.add(input[i]); } // Mark pair as added to prevent duplicates pairs.put(sum - input[i], null); } else if (!pairs.containsValue(input[i])) { // Add pair to aux. hash map pairs.put(sum - input[i], input[i]); } } ); return allDifferentPairs; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\pairsaddupnumber\DifferentPairs.java
1
请在Spring Boot框架中完成以下Java代码
public void updateOauth2Clients(@PathVariable UUID id, @RequestBody UUID[] clientIds) throws ThingsboardException { DomainId domainId = new DomainId(id); Domain domain = checkDomainId(domainId, Operation.WRITE); List<OAuth2ClientId> oAuth2ClientIds = getOAuth2ClientIds(clientIds); tbDomainService.updateOauth2Clients(domain, oAuth2ClientIds, getCurrentUser()); } @ApiOperation(value = "Get Domain infos (getTenantDomainInfos)", notes = SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @GetMapping(value = "/domain/infos") public PageData<DomainInfo> getTenantDomainInfos(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @Parameter(description = "Case-insensitive 'substring' filter based on domain's name") @RequestParam(required = false) String textSearch, @Parameter(description = SORT_PROPERTY_DESCRIPTION) @RequestParam(required = false) String sortProperty, @Parameter(description = SORT_ORDER_DESCRIPTION) @RequestParam(required = false) String sortOrder) throws ThingsboardException { accessControlService.checkPermission(getCurrentUser(), Resource.DOMAIN, Operation.READ); PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); return domainService.findDomainInfosByTenantId(getTenantId(), pageLink);
} @ApiOperation(value = "Get Domain info by Id (getDomainInfoById)", notes = SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @GetMapping(value = "/domain/info/{id}") public DomainInfo getDomainInfoById(@PathVariable UUID id) throws ThingsboardException { DomainId domainId = new DomainId(id); return checkEntityId(domainId, domainService::findDomainInfoById, Operation.READ); } @ApiOperation(value = "Delete Domain by ID (deleteDomain)", notes = "Deletes Domain by ID. Referencing non-existing domain Id will cause an error." + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('SYS_ADMIN')") @DeleteMapping(value = "/domain/{id}") public void deleteDomain(@PathVariable UUID id) throws Exception { DomainId domainId = new DomainId(id); Domain domain = checkDomainId(domainId, Operation.DELETE); tbDomainService.delete(domain, getCurrentUser()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\DomainController.java
2
请完成以下Java代码
public class ScalaFeelLogger extends BaseLogger { public static final String PROJECT_CODE = "FEEL/SCALA"; public static final String PROJECT_LOGGER = "org.camunda.bpm.dmn.feel.scala"; public static final ScalaFeelLogger LOGGER = createLogger(ScalaFeelLogger.class, PROJECT_CODE, PROJECT_LOGGER, "01"); protected void logError(String id, String messageTemplate, Throwable t) { super.logError(id, messageTemplate, t); } protected void logInfo(String id, String messageTemplate, Throwable t) { super.logInfo(id, messageTemplate, t); } public void logSpinValueMapperDetected() { logInfo("001", "Spin value mapper detected"); } public FeelException spinValueMapperInstantiationException(Throwable cause) { return new FeelException(exceptionMessage( "002", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + "on class path but cannot be instantiated."), cause); } public FeelException spinValueMapperAccessException(Throwable cause) { return new FeelException(exceptionMessage( "003", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + "on class path but cannot be accessed."), cause); } public FeelException spinValueMapperCastException(Throwable cause, String className) { return new FeelException(exceptionMessage( "004", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + "on class path but cannot be cast to " + className), cause); } public FeelException spinValueMapperException(Throwable cause) { return new FeelException(exceptionMessage(
"005", "Error while looking up or registering Spin value mapper", cause)); } public FeelException functionCountExceededException() { return new FeelException(exceptionMessage( "006", "Only set one return value or a function.")); } public FeelException customFunctionNotFoundException() { return new FeelException(exceptionMessage( "007", "Custom function not available.")); } public FeelException evaluationException(String message) { return new FeelException(exceptionMessage( "008", "Error while evaluating expression: {}", message)); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\ScalaFeelLogger.java
1
请完成以下Java代码
public void updateDropshipAddress(final I_C_Flatrate_Term term) { documentLocationBL.updateRenderedAddressAndCapturedLocation(ContractDocumentLocationAdapterFactory.dropShipLocationAdapter(term)); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, I_C_Flatrate_Term.COLUMNNAME_StartDate, I_C_Flatrate_Term.COLUMNNAME_EndDate, I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID }) public void ensureOneContract(@NonNull final I_C_Flatrate_Term term) { ensureOneContractOfGivenType(term); } @DocValidate(timings = ModelValidator.TIMING_BEFORE_COMPLETE) public void ensureOneContractBeforeComplete(@NonNull final I_C_Flatrate_Term term) { ensureOneContractOfGivenType(term); } private void ensureOneContractOfGivenType(@NonNull final I_C_Flatrate_Term term) {
flatrateBL.ensureOneContractOfGivenType(term, TypeConditions.MARGIN_COMMISSION); final TypeConditions contractType = TypeConditions.ofCode(term.getType_Conditions()); switch (contractType) { case MEDIATED_COMMISSION: case MARGIN_COMMISSION: case LICENSE_FEE: flatrateBL.ensureOneContractOfGivenType(term, contractType); default: logger.debug("Skipping ensureOneContractOfGivenType check for 'Type_Conditions' =" + contractType); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE }) public void setC_Flatrate_Term_Master(@NonNull final I_C_Flatrate_Term term) { if (term.getC_Flatrate_Term_Master_ID() <= 0) { final I_C_Flatrate_Term ancestor = flatrateDAO.retrieveAncestorFlatrateTerm(term); if (ancestor == null) { term.setC_Flatrate_Term_Master_ID(term.getC_Flatrate_Term_ID()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Term.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** 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 Target URL. @param TargetURL URL for the Target */ public void setTargetURL (String TargetURL) { set_Value (COLUMNNAME_TargetURL, TargetURL); } /** Get Target URL. @return URL for the Target */ public String getTargetURL () { return (String)get_Value(COLUMNNAME_TargetURL); }
/** Set Click Count. @param W_ClickCount_ID Web Click Management */ public void setW_ClickCount_ID (int W_ClickCount_ID) { if (W_ClickCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID)); } /** Get Click Count. @return Web Click Management */ public int getW_ClickCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_ClickCount.java
1
请在Spring Boot框架中完成以下Java代码
public synchronized void delete(String id) { try { repository.delete(Mono.just(id)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); }catch (Exception e){ log.warn(e.getMessage(),e); } } /** * 更新路由 * * @param definition * @return */ public synchronized String update(RouteDefinition definition) { try { log.info("gateway update route {}", definition); } catch (Exception e) { return "update fail,not find route routeId: " + definition.getId(); } try { repository.save(Mono.just(definition)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); return "success"; } catch (Exception e) { return "update route fail";
} } /** * 增加路由 * * @param definition * @return */ public synchronized String add(RouteDefinition definition) { log.info("gateway add route {}", definition); try { repository.save(Mono.just(definition)).subscribe(); } catch (Exception e) { log.warn(e.getMessage(),e); } return "success"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\repository\DynamicRouteService.java
2
请完成以下Java代码
protected InternalsImpl resolveDynamicData() { InternalsImpl result = new InternalsImpl(); Map<String, Metric> metrics = calculateMetrics(); result.setMetrics(metrics); // command counts are modified after the metrics are retrieved, because // metric retrieval can fail and resetting the command count is a side effect // that we would otherwise have to undo Map<String, Command> commands = fetchAndResetCommandCounts(); result.setCommands(commands); return result; } protected Map<String, Command> fetchAndResetCommandCounts() { Map<String, Command> commandsToReport = new HashMap<>(); Map<String, CommandCounter> originalCounts = diagnosticsRegistry.getCommands(); synchronized (originalCounts) { for (Map.Entry<String, CommandCounter> counter : originalCounts.entrySet()) { long occurrences = counter.getValue().get(); commandsToReport.put(counter.getKey(), new CommandImpl(occurrences)); } } return commandsToReport; } protected Map<String, Metric> calculateMetrics() { Map<String, Metric> metrics = new HashMap<>();
if (metricsRegistry != null) { Map<String, Meter> telemetryMeters = metricsRegistry.getDiagnosticsMeters(); for (String metricToReport : METRICS_TO_REPORT) { long value = telemetryMeters.get(metricToReport).get(); // add public names metrics.put(MetricsUtil.resolvePublicName(metricToReport), new MetricImpl(value)); } } return metrics; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsCollector.java
1
请完成以下Java代码
public class MapConfigurationPropertySource implements IterableConfigurationPropertySource { private static final PropertyMapper[] DEFAULT_MAPPERS = { DefaultPropertyMapper.INSTANCE }; private final Map<String, Object> source; private final IterableConfigurationPropertySource delegate; /** * Create a new empty {@link MapConfigurationPropertySource} instance. */ public MapConfigurationPropertySource() { this(Collections.emptyMap()); } /** * Create a new {@link MapConfigurationPropertySource} instance with entries copies * from the specified map. * @param map the source map */ public MapConfigurationPropertySource(Map<?, ?> map) { this.source = new LinkedHashMap<>(); MapPropertySource mapPropertySource = new MapPropertySource("source", this.source); this.delegate = new SpringIterableConfigurationPropertySource(mapPropertySource, false, DEFAULT_MAPPERS); putAll(map); } /** * Add all entries from the specified map. * @param map the source map */ public void putAll(Map<?, ?> map) { Assert.notNull(map, "'map' must not be null"); assertNotReadOnlySystemAttributesMap(map); map.forEach(this::put); } /** * Add an individual entry. * @param name the name * @param value the value */ public void put(Object name, Object value) { Assert.notNull(name, "'name' must not be null"); this.source.put(name.toString(), value); } @Override
public Object getUnderlyingSource() { return this.source; } @Override public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) { return this.delegate.getConfigurationProperty(name); } @Override public Iterator<ConfigurationPropertyName> iterator() { return this.delegate.iterator(); } @Override public Stream<ConfigurationPropertyName> stream() { return this.delegate.stream(); } private void assertNotReadOnlySystemAttributesMap(Map<?, ?> map) { try { map.size(); } catch (UnsupportedOperationException ex) { throw new IllegalArgumentException("Security restricted maps are not supported", ex); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\MapConfigurationPropertySource.java
1
请完成以下Java代码
public class StringMinusOperations { public static String removeLastCharBySubstring(String sentence) { return sentence.substring(0, sentence.length() - 1); } public static String removeTrailingStringBySubstring(String sentence, String lastSequence) { var trailing = sentence.substring(sentence.length() - lastSequence.length()); if(trailing.equals(lastSequence)) { return sentence.substring(0, sentence.length() - lastSequence.length()); } else { return sentence; } }
public static String minusByReplace(String sentence, char removeMe) { return sentence.replace(String.valueOf(removeMe), ""); } public static String minusByReplace(String sentence, String removeMe) { return sentence.replace(removeMe, ""); } public static String minusByStream(String sentence, char removeMe) { return sentence.chars() .mapToObj(c -> (char) c) .filter(it -> !it.equals(removeMe)) .map(String::valueOf) .collect(Collectors.joining()); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-12\src\main\java\com\baeldung\minusoperation\StringMinusOperations.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_PA_SLA_Criteria[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Classname. @param Classname Java Classname */ public void setClassname (String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Classname. @return Java Classname */ public String getClassname () { return (String)get_Value(COLUMNNAME_Classname); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** 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 Manual. @param IsManual This is a manual process */ public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manual. @return This is a manual process */ public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set SLA Criteria. @param PA_SLA_Criteria_ID Service Level Agreement Criteria */ public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID) { if (PA_SLA_Criteria_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID)); } /** Get SLA Criteria. @return Service Level Agreement Criteria */ public int getPA_SLA_Criteria_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Criteria.java
1
请在Spring Boot框架中完成以下Java代码
public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised) { final RfqQty rfqQty = getOrCreateQty(date); rfqQty.setQtyPromisedUserEntered(qtyPromised); updateConfirmedByUser(); } private RfqQty getOrCreateQty(@NonNull final LocalDate date) { final RfqQty existingRfqQty = getRfqQtyByDate(date); if (existingRfqQty != null) { return existingRfqQty; } else { final RfqQty rfqQty = RfqQty.builder() .rfq(this) .datePromised(date) .build(); addRfqQty(rfqQty); return rfqQty; } } private void addRfqQty(final RfqQty rfqQty) { rfqQty.setRfq(this); quantities.add(rfqQty); } @Nullable public RfqQty getRfqQtyByDate(@NonNull final LocalDate date) { for (final RfqQty rfqQty : quantities) { if (date.equals(rfqQty.getDatePromised())) { return rfqQty; } } return null; } private void updateConfirmedByUser() { this.confirmedByUser = computeConfirmedByUser(); } private boolean computeConfirmedByUser() { if (pricePromised.compareTo(pricePromisedUserEntered) != 0)
{ return false; } for (final RfqQty rfqQty : quantities) { if (!rfqQty.isConfirmedByUser()) { return false; } } return true; } public void closeIt() { this.closed = true; } public void confirmByUser() { this.pricePromised = getPricePromisedUserEntered(); quantities.forEach(RfqQty::confirmByUser); updateConfirmedByUser(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
2
请完成以下Java代码
public class CmsHelp implements Serializable { private Long id; private Long categoryId; private String icon; private String title; private Integer showStatus; private Date createTime; private Integer readCount; private String content; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime;
} public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @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(", categoryId=").append(categoryId); sb.append(", icon=").append(icon); sb.append(", title=").append(title); sb.append(", showStatus=").append(showStatus); sb.append(", createTime=").append(createTime); sb.append(", readCount=").append(readCount); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelp.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof AnnotatedBean)) { return false; } AnnotatedBean other = (AnnotatedBean) obj; return Objects.equals(name, other.name) && Objects.equals(annotation, other.annotation); } @Override public String toString() { return "AnnotatedBean [name=" + name + ", annotation=" + annotation + "]"; } } /** * Finds all beans with annotation. * * @throws IllegalStateException if more than one bean is found */ public static Function<ApplicationContext, Optional<AnnotatedBean>> getAnnotatedBean = applicationContext -> { final Set<Entry<String, Object>> beans = Optional.ofNullable(applicationContext.getBeansWithAnnotation(EnableProcessApplication.class)) .map(Map::entrySet) .orElse(Collections.emptySet()); return beans.stream().filter(ANNOTATED_WITH_ENABLEPROCESSAPPLICATION) .map(e -> AnnotatedBean.of(e.getKey(), e.getValue())) .reduce( (u,v) -> { throw new IllegalStateException("requires exactly one bean to be annotated with @EnableProcessApplication, found: " + beans); }); };
public static Function<EnableProcessApplication, Optional<String>> getAnnotationValue = annotation -> Optional.of(annotation) .map(EnableProcessApplication::value) .filter(StringUtils::isNotBlank); public static Function<AnnotatedBean, String> getName = pair -> Optional.of(pair.getAnnotation()).flatMap(getAnnotationValue).orElse(pair.getName()); public static Function<ApplicationContext, Optional<String>> getProcessApplicationName = applicationContext -> getAnnotatedBean.apply(applicationContext).map(getName); @Override public Optional<String> get() { return getProcessApplicationName.apply(applicationContext); } @Override public Optional<String> apply(Optional<String> springApplicationName) { Optional<String> processApplicationName = GetProcessApplicationNameFromAnnotation.getProcessApplicationName.apply(applicationContext); if (processApplicationName.isPresent()) { return processApplicationName; } else if (springApplicationName.isPresent()) { return springApplicationName; } return Optional.empty(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\GetProcessApplicationNameFromAnnotation.java
1
请在Spring Boot框架中完成以下Java代码
protected void performUndeployment() { final ProcessEngine processEngine = processEngineSupplier.get(); try { if(deployment != null) { // always unregister Set<String> deploymentIds = deployment.getProcessApplicationRegistration().getDeploymentIds(); processEngine.getManagementService().unregisterProcessApplication(deploymentIds, true); } } catch(Exception e) { LOGGER.log(Level.SEVERE, "Exception while unregistering process application with the process engine."); } // delete the deployment only if requested in metadata if(deployment != null && PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) { try { LOGGER.info("Deleting cascade deployment with name '"+deployment.getName()+"/"+deployment.getId()+"'."); // always cascade & skip custom listeners processEngine.getRepositoryService().deleteDeployment(deployment.getId(), true, true); } catch (Exception e) { LOGGER.log(Level.WARNING, "Exception while deleting process engine deployment", e); } }
} @Override public ProcessApplicationDeploymentService getValue() throws IllegalStateException, IllegalArgumentException { return this; } public ProcessApplicationDeployment getDeployment() { return deployment; } public String getProcessEngineName() { return processEngineSupplier.get().getName(); } public Supplier<ProcessEngine> getProcessEngineSupplier() { return processEngineSupplier; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationDeploymentService.java
2
请完成以下Java代码
public String getType() { if (type == null) { return "invoice"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the storno property. * * @return * possible object is * {@link Boolean } * */ public boolean isStorno() { if (storno == null) { return false; } else { return storno; } } /** * Sets the value of the storno property. * * @param value * allowed object is * {@link Boolean } * */ public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } * */ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /** * Sets the value of the copy property. * * @param value * allowed object is * {@link Boolean }
* */ public void setCopy(Boolean value) { this.copy = value; } /** * Gets the value of the creditAdvice property. * * @return * possible object is * {@link Boolean } * */ public boolean isCreditAdvice() { if (creditAdvice == null) { return false; } else { return creditAdvice; } } /** * Sets the value of the creditAdvice property. * * @param value * allowed object is * {@link Boolean } * */ public void setCreditAdvice(Boolean value) { this.creditAdvice = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PayloadType.java
1
请完成以下Java代码
public static CostingDocumentRef ofProjectIssueId(final int projectIssueId) { return new CostingDocumentRef(TABLE_NAME_C_ProjectIssue, ProjectIssueId.ofRepoId(projectIssueId), I_M_CostDetail.COLUMNNAME_C_ProjectIssue_ID, null); } public static CostingDocumentRef ofCostCollectorId(final int ppCostCollectorId) { return ofCostCollectorId(PPCostCollectorId.ofRepoId(ppCostCollectorId)); } public static CostingDocumentRef ofCostCollectorId(final PPCostCollectorId ppCostCollectorId) { return new CostingDocumentRef(TABLE_NAME_PP_Cost_Collector, ppCostCollectorId, I_M_CostDetail.COLUMNNAME_PP_Cost_Collector_ID, null); } public static CostingDocumentRef ofCostRevaluationLineId(@NonNull final CostRevaluationLineId costRevaluationLineId) { return new CostingDocumentRef(TABLE_NAME_M_CostRevaluationLine, costRevaluationLineId, I_M_CostDetail.COLUMNNAME_M_CostRevaluationLine_ID, null); } String tableName; RepoIdAware id; String costDetailColumnName; Boolean outboundTrx; private CostingDocumentRef( @NonNull final String tableName, @NonNull final RepoIdAware id, @NonNull final String costDetailColumnName, @Nullable final Boolean outboundTrx) { this.tableName = tableName; this.id = id; this.costDetailColumnName = costDetailColumnName; this.outboundTrx = outboundTrx; } public boolean isTableName(final String expectedTableName) {return Objects.equals(tableName, expectedTableName);} public boolean isInventoryLine() {return isTableName(TABLE_NAME_M_InventoryLine);} public boolean isCostRevaluationLine() {return isTableName(TABLE_NAME_M_CostRevaluationLine);}
public boolean isMatchInv() { return isTableName(TABLE_NAME_M_MatchInv); } public PPCostCollectorId getCostCollectorId() { return getId(PPCostCollectorId.class); } public <T extends RepoIdAware> T getId(final Class<T> idClass) { if (idClass.isInstance(id)) { return idClass.cast(id); } else { throw new AdempiereException("Expected id to be of type " + idClass + " but it was " + id); } } public static boolean equals(CostingDocumentRef ref1, CostingDocumentRef ref2) {return Objects.equals(ref1, ref2);} public TableRecordReference toTableRecordReference() {return TableRecordReference.of(tableName, id);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostingDocumentRef.java
1
请完成以下Java代码
public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry_Detail.java
1
请完成以下Java代码
private ITranslatableString getOriginalProcessCaption() { final I_AD_Process adProcess = adProcessSupplier.get(); return InterfaceWrapperHelper.getModelTranslationMap(adProcess) .getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName()); } public String getDescription(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); String description = adProcessTrl.getDescription(); if (Services.get(IDeveloperModeBL.class).isEnabled()) { if (description == null) { description = ""; } else { description += "\n - "; } description += "Classname:" + adProcess.getClassname() + ", ID=" + adProcess.getAD_Process_ID(); } return description; } public String getHelp(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); return adProcessTrl.getHelp(); } public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get(); final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS);
} return Images.getImageIcon2(iconName); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get(); } public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请完成以下Java代码
public void setState(String state) { this.state = state; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; }
public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ContactBased.java
1
请完成以下Java代码
public int getK_IndexLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexLog_ID); if (ii == null) return 0; return ii.intValue(); } /** QuerySource AD_Reference_ID=391 */ public static final int QUERYSOURCE_AD_Reference_ID=391; /** Collaboration Management = C */ public static final String QUERYSOURCE_CollaborationManagement = "C"; /** Java Client = J */ public static final String QUERYSOURCE_JavaClient = "J"; /** HTML Client = H */ public static final String QUERYSOURCE_HTMLClient = "H"; /** Self Service = W */ public static final String QUERYSOURCE_SelfService = "W"; /** Set Query Source. @param QuerySource
Source of the Query */ public void setQuerySource (String QuerySource) { set_Value (COLUMNNAME_QuerySource, QuerySource); } /** Get Query Source. @return Source of the Query */ public String getQuerySource () { return (String)get_Value(COLUMNNAME_QuerySource); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexLog.java
1
请完成以下Java代码
public String getExporterVersion() { return exporterVersionAttribute.getValue(this); } public void setExporterVersion(String exporterVersion) { exporterVersionAttribute.setValue(this, exporterVersion); } public Collection<Import> getImports() { return importCollection.get(this); } public Collection<ItemDefinition> getItemDefinitions() { return itemDefinitionCollection.get(this); } public Collection<DrgElement> getDrgElements() { return drgElementCollection.get(this); } public Collection<Artifact> getArtifacts() { return artifactCollection.get(this); } public Collection<ElementCollection> getElementCollections() { return elementCollectionCollection.get(this); } public Collection<BusinessContextElement> getBusinessContextElements() { return businessContextElementCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, DMN_ELEMENT_DEFINITIONS) .namespaceUri(LATEST_DMN_NS) .extendsType(NamedElement.class) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() { public Definitions newInstance(ModelTypeInstanceContext instanceContext) { return new DefinitionsImpl(instanceContext); } }); expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE) .defaultValue("http://www.omg.org/spec/FEEL/20140401") .build();
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE) .defaultValue("http://www.omg.org/spec/FEEL/20140401") .build(); namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE) .required() .build(); exporterAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER) .build(); exporterVersionAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER_VERSION) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); importCollection = sequenceBuilder.elementCollection(Import.class) .build(); itemDefinitionCollection = sequenceBuilder.elementCollection(ItemDefinition.class) .build(); drgElementCollection = sequenceBuilder.elementCollection(DrgElement.class) .build(); artifactCollection = sequenceBuilder.elementCollection(Artifact.class) .build(); elementCollectionCollection = sequenceBuilder.elementCollection(ElementCollection.class) .build(); businessContextElementCollection = sequenceBuilder.elementCollection(BusinessContextElement.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DefinitionsImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class GetJobExceptionStacktraceCmd implements Command<String>, Serializable { private static final long serialVersionUID = 1L; protected JobServiceConfiguration jobServiceConfiguration; protected String jobId; protected JobType jobType; public GetJobExceptionStacktraceCmd(String jobId, JobType jobType, JobServiceConfiguration jobServiceConfiguration) { this.jobId = jobId; this.jobType = jobType; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public String execute(CommandContext commandContext) { if (jobId == null) { throw new FlowableIllegalArgumentException("jobId is null"); } AbstractRuntimeJobEntity job = null; switch (jobType) { case ASYNC: job = jobServiceConfiguration.getJobEntityManager().findById(jobId); break; case TIMER: job = jobServiceConfiguration.getTimerJobEntityManager().findById(jobId); break;
case SUSPENDED: job = jobServiceConfiguration.getSuspendedJobEntityManager().findById(jobId); break; case DEADLETTER: job = jobServiceConfiguration.getDeadLetterJobEntityManager().findById(jobId); break; case EXTERNAL_WORKER: job = jobServiceConfiguration.getExternalWorkerJobEntityManager().findById(jobId); break; default: break; } if (job == null) { throw new FlowableObjectNotFoundException("No job found with id " + jobId, Job.class); } return job.getExceptionStacktrace(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\GetJobExceptionStacktraceCmd.java
2
请完成以下Java代码
private Bucket getBucket(String bucketName) { bucket = storage.get(bucketName); if (bucket == null) { System.out.println("Creating new bucket."); bucket = storage.create(BucketInfo.of(bucketName)); } return bucket; } // Save a string to a blob private BlobId saveString(String blobName, String value, Bucket bucket) { byte[] bytes = value.getBytes(UTF_8); Blob blob = bucket.create(blobName, bytes); return blob.getBlobId(); } // get a blob by id private String getString(BlobId blobId) { Blob blob = storage.get(blobId); return new String(blob.getContent()); } // get a blob by name
private String getString(String name) { Page<Blob> blobs = bucket.list(); for (Blob blob: blobs.getValues()) { if (name.equals(blob.getName())) { return new String(blob.getContent()); } } return "Blob not found"; } // Update a blob private void updateString(BlobId blobId, String newString) throws IOException { Blob blob = storage.get(blobId); if (blob != null) { WritableByteChannel channel = blob.writer(); channel.write(ByteBuffer.wrap(newString.getBytes(UTF_8))); channel.close(); } } }
repos\tutorials-master\google-cloud\src\main\java\com\baeldung\google\cloud\storage\GoogleCloudStorage.java
1
请完成以下Java代码
public void setAD_UI_ElementGroup_ID (int AD_UI_ElementGroup_ID) { if (AD_UI_ElementGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_ElementGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_ElementGroup_ID, Integer.valueOf(AD_UI_ElementGroup_ID)); } /** Get UI Element Group. @return UI Element Group */ @Override public int getAD_UI_ElementGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_ElementGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set 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 UI Style. @param UIStyle UI Style */ @Override public void setUIStyle (java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } /** Get UI Style. @return UI Style */ @Override public java.lang.String getUIStyle () { return (java.lang.String)get_Value(COLUMNNAME_UIStyle); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementGroup.java
1
请在Spring Boot框架中完成以下Java代码
public class WeightingSpecificationsRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, WeightingSpecificationsMap> cache = CCache.<Integer, WeightingSpecificationsMap>builder() .tableName(I_PP_Weighting_Spec.Table_Name) .build(); public WeightingSpecifications getById(@NonNull final WeightingSpecificationsId id) { return getMap().getById(id); } public WeightingSpecificationsId getDefaultId() { return getMap().getDefaultId(); } public WeightingSpecifications getDefault() { return getMap().getDefault(); } public WeightingSpecificationsMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private WeightingSpecificationsMap retrieveMap() { final ImmutableList<WeightingSpecifications> list = queryBL .createQueryBuilder(I_PP_Weighting_Spec.class) .addEqualsFilter(I_PP_Weighting_Spec.COLUMNNAME_AD_Client_ID, ClientId.METASFRESH) .addOnlyActiveRecordsFilter() .create() .stream()
.map(WeightingSpecificationsRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new WeightingSpecificationsMap(list); } public static WeightingSpecifications fromRecord(I_PP_Weighting_Spec record) { return WeightingSpecifications.builder() .id(WeightingSpecificationsId.ofRepoId(record.getPP_Weighting_Spec_ID())) .weightChecksRequired(record.getWeightChecksRequired()) .tolerance(Percent.of(record.getTolerance_Perc())) .uomId(UomId.ofRepoId(record.getC_UOM_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\spec\WeightingSpecificationsRepository.java
2
请完成以下Java代码
public void setPosts(List<Post> posts) { this.posts = posts; } public void setGroups(List<Group> groups) { this.groups = groups; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
User user = (User) o; return Objects.equals(id, user.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", profile=" + this.getProfile() + ", posts=" + this.getPosts() + ", groups=" + this.getGroups() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\User.java
1
请在Spring Boot框架中完成以下Java代码
public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "http://localhost:8182/repository/deployments/2/resources/testProcess.xml", value = "Contains the actual deployed BPMN 2.0 xml.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a process for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setDiagramResource(String diagramResource) { this.diagramResource = diagramResource; } @ApiModelProperty(example = "http://localhost:8182/repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the process, null when no diagram is available.") public String getDiagramResource() {
return diagramResource; } public void setGraphicalNotationDefined(boolean graphicalNotationDefined) { this.graphicalNotationDefined = graphicalNotationDefined; } @ApiModelProperty(value = "Indicates the process definition contains graphical information (BPMN DI).") public boolean isGraphicalNotationDefined() { return graphicalNotationDefined; } public void setSuspended(boolean suspended) { this.suspended = suspended; } public boolean isSuspended() { return suspended; } public void setStartFormDefined(boolean startFormDefined) { this.startFormDefined = startFormDefined; } public boolean isStartFormDefined() { return startFormDefined; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionResponse.java
2
请完成以下Spring Boot application配置
server: context-path: /web spring: datasource: druid: # 数据库访问配置, 使用druid数据源 # 数据源1 mysql mysql: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull username: root password: 123456 # 数据源2 oracle oracle: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:ORCL username: test password: 123456 # 连接池配置 initial-size: 5 min-idle: 5 max-active: 20 # 连接等待超时时间 max-wait: 30000 # 配置检测可以关闭的空闲连接间隔时间 time-between-eviction-runs-millis: 60000 # 配置连接在池中的最小生存时间 min-evictable-idle-time-millis: 300000 validation-query: select '1' from dual test-while-idle: true test-on-borrow: false test-on-return: false # 打开PSCache,并且指定每个连接上PSCache的大小 pool-prepared-statements: true max-open-prepared-statements: 20 max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙 filters: stat,wall # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔 aop-patterns: com.springboot.servie.* # WebStatFilter配置 web-
stat-filter: enabled: true # 添加过滤规则 url-pattern: /* # 忽略过滤的格式 exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' # StatViewServlet配置 stat-view-servlet: enabled: true # 访问路径为/druid时,跳转到StatViewServlet url-pattern: /druid/* # 是否能够重置数据 reset-enable: false # 需要账号密码才能访问控制台 login-username: druid login-password: druid123 # IP白名单 # allow: 127.0.0.1 # IP黑名单(共同存在时,deny优先于allow) # deny: 192.168.1.218 # 配置StatFilter filter: stat: log-slow-sql: true
repos\SpringAll-master\05.Spring-Boot-MyBatis-MultiDataSource\src\main\resources\application.yml
2
请完成以下Java代码
public void mouseEntered(final MouseEvent me) { result.setBorderPainted(true); result.setIcon(icon); } @Override public void mouseExited(final MouseEvent me) { result.setBorderPainted(false); result.setIcon(darkerIcon); } }); result.setBorderPainted(false); result.setFocusPainted(false); return result; } public int getCurrentPage() { return currentPage; } public void clearDocument() { decoder.closePdfFile(); if (tmpFile != null) { tmpFile.delete(); tmpFile = null; } } public void setScaleStep(final int scaleStep) { if (scaleStep < 0 || zoomFactors.length <= scaleStep) { return; } this.scaleStep = scaleStep; zoomSelect.setSelectedIndex(scaleStep); updateZoomRotate(); } protected void updateZoomRotate() { final Cursor oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); decoder.setPageParameters(zoomFactors[scaleStep], currentPage, rotation); decoder.invalidate(); decoder.repaint(); zoomInAction.setEnabled(scaleStep < zoomFactors.length - 1); zoomOutAction.setEnabled(scaleStep > 0); } finally { setCursor(oldCursor); } } public void setScale(final int percent) { int step; for (step = 0; step < zoomFactors.length - 1; step++) { if (zoomFactors[step] * 100 >= percent) { break; } } setScaleStep(step); }
public boolean loadPDF(final byte[] data) { return loadPDF(new ByteArrayInputStream(data)); } public boolean loadPDF(final InputStream is) { if (tmpFile != null) { tmpFile.delete(); } try { tmpFile = File.createTempFile("adempiere", ".pdf"); tmpFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); return false; } try { final OutputStream os = new FileOutputStream(tmpFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { os.close(); } } catch (IOException e) { e.printStackTrace(); } return loadPDF(tmpFile.getAbsolutePath()); } @Override protected void finalize() throws Throwable { if (tmpFile != null) { tmpFile.delete(); } decoder.closePdfFile(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\viewer\PDFViewerBean.java
1
请完成以下Java代码
public static boolean notAllOf(Object collection, Object value) { if (collection == null) { throw new IllegalArgumentException("collection cannot be null"); } if (value == null) { throw new IllegalArgumentException("value cannot be null"); } // collection to check against Collection targetCollection = getTargetCollection(collection, value); // elements to check if (DMNParseUtil.isParseableCollection(value)) { Collection valueCollection = DMNParseUtil.parseCollection(value, targetCollection); return valueCollection == null || !targetCollection.containsAll(valueCollection); } else if (DMNParseUtil.isJavaCollection(value)) { return !targetCollection.containsAll((Collection) value); } else if (DMNParseUtil.isArrayNode(value)) { Collection valueCollection = DMNParseUtil.getCollectionFromArrayNode(JsonUtil.asFlowableArrayNode(value)); return valueCollection == null || !targetCollection.containsAll(valueCollection); } else { Object formattedValue = DMNParseUtil.getFormattedValue(value, targetCollection); return !targetCollection.contains(formattedValue); } } /** * @deprecated use {@link #notAllOf(Object, Object)} instead */ @Deprecated public static boolean notContainsAny(Object collection, Object value) { return notAllOf(collection, value); }
protected static Collection getTargetCollection(Object collection, Object value) { Collection targetCollection; if (!DMNParseUtil.isCollection(collection)) { if (DMNParseUtil.isParseableCollection(collection)) { targetCollection = DMNParseUtil.parseCollection(collection, value); } else { targetCollection = Arrays.asList(collection); } } else if (DMNParseUtil.isArrayNode(collection)) { targetCollection = DMNParseUtil.getCollectionFromArrayNode(JsonUtil.asFlowableArrayNode(collection)); } else { targetCollection = (Collection) collection; } return targetCollection; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\util\CollectionUtil.java
1
请完成以下Java代码
class RolloutMigrationConfig { public static final String DEFAULT_SETTINGS_FILENAME = "local_settings.properties"; @Default boolean canRun = false; @NonNull @Default String rolloutDirName = CommandlineParams.DEFAULT_RolloutDirectory; /** * If specified, the tools shall load the {@link #dbConnectionSettings} from this file. */ @Default String dataBaseSettingsFile = null; /** * If specified, the tool shall ignore all files and use these settings. */ @Default DBConnectionSettings dbConnectionSettings = null; @Default String scriptFileName = null; @Default IScriptsApplierListener scriptsApplierListener = NullScriptsApplierListener.instance; @Default boolean justMarkScriptAsExecuted = false; /** * By default we will check the versions. */ @Default boolean checkVersions = true; /** * By default we will store our won version in the DB after a successful update.
*/ @Default boolean storeVersion = true; /** * If the DB version is already ahead of our local rollout package usually means that something is wrong, so by default the rollout shall fail. */ @Default boolean failIfRolloutIsGreaterThanDB = true; @Default String templateDBName = null; @Default String newDBName = null; @Default @NonNull ImmutableSet<IFileRef> additionalSqlDirs = ImmutableSet.of(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\RolloutMigrationConfig.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(SequenceFlow.class, BPMN_ELEMENT_SEQUENCE_FLOW) .namespaceUri(BPMN20_NS) .extendsType(FlowElement.class) .instanceProvider(new ModelTypeInstanceProvider<SequenceFlow>() { public SequenceFlow newInstance(ModelTypeInstanceContext instanceContext) { return new SequenceFlowImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF) .required() .idAttributeReference(FlowNode.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF) .required() .idAttributeReference(FlowNode.class) .build(); isImmediateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_IMMEDIATE) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionExpressionCollection = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } public SequenceFlowImpl(ModelTypeInstanceContext context) { super(context); } @Override public SequenceFlowBuilder builder() { return new SequenceFlowBuilder((BpmnModelInstance) modelInstance, this); } public FlowNode getSource() { return sourceRefAttribute.getReferenceTargetElement(this); }
public void setSource(FlowNode source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public FlowNode getTarget() { return targetRefAttribute.getReferenceTargetElement(this); } public void setTarget(FlowNode target) { targetRefAttribute.setReferenceTargetElement(this, target); } public boolean isImmediate() { return isImmediateAttribute.getValue(this); } public void setImmediate(boolean isImmediate) { isImmediateAttribute.setValue(this, isImmediate); } public ConditionExpression getConditionExpression() { return conditionExpressionCollection.getChild(this); } public void setConditionExpression(ConditionExpression conditionExpression) { conditionExpressionCollection.setChild(this, conditionExpression); } public void removeConditionExpression() { conditionExpressionCollection.removeChild(this); } public BpmnEdge getDiagramElement() { return (BpmnEdge) super.getDiagramElement(); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SequenceFlowImpl.java
1
请完成以下Java代码
public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { throw new IllegalArgumentException ("Shipment_DocumentNo is virtual column"); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } @Override public void setSumDeliveredInStockingUOM (final BigDecimal SumDeliveredInStockingUOM) { set_Value (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final BigDecimal SumOrderedInStockingUOM)
{ set_Value (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM); } @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_Value (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv.java
1
请完成以下Java代码
public void setMKTG_Platform_ID (int MKTG_Platform_ID) { if (MKTG_Platform_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID)); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name
Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Platform.java
1
请完成以下Java代码
public boolean isInterrupting() { return interrupting; } public void setInterrupting(boolean interrupting) { this.interrupting = interrupting; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public Set<String> getVariableEvents() { return variableEvents; } public void setVariableEvents(Set<String> variableEvents) { this.variableEvents = variableEvents; } public String getConditionAsString() { return conditionAsString; } public void setConditionAsString(String conditionAsString) { this.conditionAsString = conditionAsString; } public boolean shouldEvaluateForVariableEvent(VariableEvent event) { return
((variableName == null || event.getVariableInstance().getName().equals(variableName)) && ((variableEvents == null || variableEvents.isEmpty()) || variableEvents.contains(event.getEventName()))); } public boolean evaluate(DelegateExecution execution) { if (condition != null) { return condition.evaluate(execution, execution); } throw new IllegalStateException("Conditional event must have a condition!"); } public boolean tryEvaluate(DelegateExecution execution) { if (condition != null) { return condition.tryEvaluate(execution, execution); } throw new IllegalStateException("Conditional event must have a condition!"); } public boolean tryEvaluate(VariableEvent variableEvent, DelegateExecution execution) { return (variableEvent == null || shouldEvaluateForVariableEvent(variableEvent)) && tryEvaluate(execution); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ConditionalEventDefinition.java
1