instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class GetDeploymentProcessDiagramCmd implements Command<InputStream>, Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(GetDeploymentProcessDiagramCmd.class); protected String processDefinitionId; public GetDeploymentProcessDiagramCmd(String processDefinitionId) { if (processDefinitionId == null || processDefinitionId.length() < 1) { throw new ActivitiIllegalArgumentException("The process definition id is mandatory, but '" + processDefinitionId + "' has been provided."); } this.processDefinitionId = processDefinitionId; } @Override public InputStream execute(CommandContext commandContext) { ProcessDefinition processDefinition = commandContext
.getProcessEngineConfiguration() .getDeploymentManager() .findDeployedProcessDefinitionById(processDefinitionId); String deploymentId = processDefinition.getDeploymentId(); String resourceName = processDefinition.getDiagramResourceName(); if (resourceName == null) { LOGGER.info("Resource name is null! No process diagram stream exists."); return null; } else { InputStream processDiagramStream = new GetDeploymentResourceCmd(deploymentId, resourceName) .execute(commandContext); return processDiagramStream; } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetDeploymentProcessDiagramCmd.java
1
请完成以下Java代码
public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public void setMD_Candidate_QtyDetails_ID (final int MD_Candidate_QtyDetails_ID) { if (MD_Candidate_QtyDetails_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, MD_Candidate_QtyDetails_ID); } @Override public int getMD_Candidate_QtyDetails_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_ID); }
@Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID) { if (Stock_MD_Candidate_ID < 1) set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null); else set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID); } @Override public int getStock_MD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
1
请完成以下Java代码
public DmnEngineException invalidValueForTypeDefinition(String typeName, Object value) { return new DmnEngineException(exceptionMessage( "005", "Invalid value '{}' for clause with type '{}'.", value, typeName) ); } public void unsupportedTypeDefinitionForClause(String typeName) { logWarn( "006", "Unsupported type '{}' for clause. Values of this clause will not transform into another type.", typeName ); } public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionRuleResult ruleResult) { return new DmnDecisionResultException(exceptionMessage( "007", "Unable to get single decision rule result entry as it has more than one entry '{}'", ruleResult) ); } public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionTableResult decisionResult) { return new DmnDecisionResultException(exceptionMessage( "008", "Unable to get single decision rule result as it has more than one rule result '{}'", decisionResult) ); } public DmnTransformException unableToFindAnyDecisionTable() { return new DmnTransformException(exceptionMessage( "009", "Unable to find any decision table in model.") ); } public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionResultEntries result) { return new DmnDecisionResultException(exceptionMessage( "010",
"Unable to get single decision result entry as it has more than one entry '{}'", result) ); } public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionResult decisionResult) { return new DmnDecisionResultException(exceptionMessage( "011", "Unable to get single decision result as it has more than one result '{}'", decisionResult) ); } public DmnEngineException decisionLogicTypeNotSupported(DmnDecisionLogic decisionLogic) { return new DmnEngineException(exceptionMessage( "012", "Decision logic type '{}' not supported by DMN engine.", decisionLogic.getClass()) ); } public DmnEngineException decisionIsNotADecisionTable(DmnDecision decision) { return new DmnEngineException(exceptionMessage( "013", "The decision '{}' is not implemented as decision table.", decision) ); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnEngineLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class ImportedInvoiceResponse { public enum Status { ACCEPTET, PENDING, REJECTED } @Nullable InvoiceId invoiceId; @NonNull String documentNumber; // invoiceNumber @NonNull Instant invoiceCreated; Status status; ImportInvoiceResponseRequest request; @Singular Map<String, String> additionalTags; String client; String invoiceRecipient; List<RejectedError> reason;
String explanation; String responsiblePerson; String phone; String email; String billerEan; int billerOrg; @Value public static class RejectedError { @NonNull String code; @NonNull String text; @Override public String toString() { return code + ": " + text + ";"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.invoice_gateway.spi\src\main\java\de\metas\invoice_gateway\spi\model\imp\ImportedInvoiceResponse.java
2
请完成以下Java代码
public String getDescription() { return activiti5ProcessInstance.getDescription(); } @Override public String getLocalizedName() { return activiti5ProcessInstance.getLocalizedName(); } @Override public String getLocalizedDescription() { return activiti5ProcessInstance.getLocalizedDescription(); } public org.activiti.engine.runtime.ProcessInstance getRawObject() { return activiti5ProcessInstance; } @Override public Date getStartTime() { return null; } @Override public String getStartUserId() { return null; }
@Override public String getCallbackId() { return null; } @Override public String getCallbackType() { return null; } @Override public String getReferenceId() { return null; } @Override public String getReferenceType() { return null; } @Override public String getPropagatedStageInstanceId() { return null; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5ProcessInstanceWrapper.java
1
请完成以下Java代码
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } @Override public I_C_Flatrate_Term getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public ContractBillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new ContractBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class));
} public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId, final @Nullable BPartnerContactId billToContactId) { setBill_BPartner_ID(billToLocationId.getBpartnerRepoId()); setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId()); setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId()); setBill_User_ID(billToContactId == null ? -1 : billToContactId.getRepoId()); } public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId) { setBill_BPartner_ID(billToLocationId.getBpartnerRepoId()); setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId()); setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractBillLocationAdapter.java
1
请完成以下Java代码
/* package */final class DocLineSortProductIdsComparator implements Comparator<Integer> { private final Map<Integer, Integer> productId2seqNo = new HashMap<>(); private final int notFoundSeqNo = Integer.MAX_VALUE; public DocLineSortProductIdsComparator(final I_C_DocLine_Sort docLineSort) { super(); Check.assumeNotNull(docLineSort, "docLineSort not null"); final List<I_C_DocLine_Sort_Item> items = Services.get(IDocLineSortDAO.class).retrieveItems(docLineSort); for (final I_C_DocLine_Sort_Item item : items) { final int productId = item.getM_Product_ID(); final int seqNo = item.getSeqNo(); productId2seqNo.put(productId, seqNo); } } @Override public int compare(final Integer productId1, final Integer productId2) { final int seqNo1 = getSeqNo(productId1); final int seqNo2 = getSeqNo(productId2);
return seqNo1 - seqNo2; } private int getSeqNo(final Integer productId) { if (productId == null || productId <= 0) { return notFoundSeqNo; } final Integer seqNo = productId2seqNo.get(productId); if (seqNo == null) { return notFoundSeqNo; } return seqNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\docline\sort\api\impl\DocLineSortProductIdsComparator.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteAuthorsViaDeleteInBatch() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteInBatch(authors); } // good if you want an alternative to deleteInBatch() @Transactional public void deleteAuthorsViaDeleteInBulk() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteInBulk(authors); } // good if you need to delete in a classical batch approach
@Transactional public void deleteAuthorsViaDeleteAll() { List<Author> authors = authorRepository.findByAgeLessThan(60); authorRepository.deleteAll(authors); // for deleting all Authors use deleteAll() with no arguments } // good if you need to delete in a classical batch approach @Transactional public void deleteAuthorsViaDelete() { List<Author> authors = authorRepository.findByAgeLessThan(60); authors.forEach(authorRepository::delete); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteSingleEntity\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void onClosedContext(ContextClosedEvent event) { if (event.getApplicationContext().getParent() == null || "bootstrap".equals(event.getApplicationContext().getParent().getId())) { stopRegisterTask(); if (autoDeregister) { registrator.deregister(); } } } public void startRegisterTask() { if (scheduledTask != null && !scheduledTask.isDone()) { return; } scheduledTask = taskScheduler.scheduleAtFixedRate(registrator::register, registerPeriod); LOGGER.debug("Scheduled registration task for every {}ms", registerPeriod.toMillis()); } public void stopRegisterTask() { if (scheduledTask != null && !scheduledTask.isDone()) { scheduledTask.cancel(true); LOGGER.debug("Canceled registration task"); }
} public void setAutoDeregister(boolean autoDeregister) { this.autoDeregister = autoDeregister; } public void setAutoRegister(boolean autoRegister) { this.autoRegister = autoRegister; } public void setRegisterPeriod(Duration registerPeriod) { this.registerPeriod = registerPeriod; } @Override public void afterPropertiesSet() { taskScheduler.afterPropertiesSet(); } @Override public void destroy() { taskScheduler.destroy(); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\RegistrationApplicationListener.java
1
请完成以下Java代码
public String getI18n() { if (!Arrays.asList("zh_CN", "zh_TC", "en").contains(i18n)) { return "zh_CN"; } return i18n; } public String getAccessToken() { return accessToken; } public String getEmailFrom() { return emailFrom; } public int getTriggerPoolFastMax() { if (triggerPoolFastMax < 200) { return 200; } return triggerPoolFastMax; } public int getTriggerPoolSlowMax() { if (triggerPoolSlowMax < 100) { return 100; } return triggerPoolSlowMax; } public int getLogretentiondays() { if (logretentiondays < 7) { return -1; // Limit greater than or equal to 7, otherwise close } return logretentiondays; } public XxlJobLogDao getXxlJobLogDao() { return xxlJobLogDao; }
public XxlJobInfoDao getXxlJobInfoDao() { return xxlJobInfoDao; } public XxlJobRegistryDao getXxlJobRegistryDao() { return xxlJobRegistryDao; } public XxlJobGroupDao getXxlJobGroupDao() { return xxlJobGroupDao; } public XxlJobLogReportDao getXxlJobLogReportDao() { return xxlJobLogReportDao; } public JavaMailSender getMailSender() { return mailSender; } public DataSource getDataSource() { return dataSource; } public JobAlarmer getJobAlarmer() { return jobAlarmer; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\conf\XxlJobAdminConfig.java
1
请在Spring Boot框架中完成以下Java代码
public class UserFilter implements Filter { private static final Log LOG = LogFactory.getLog(UserFilter.class); public void destroy() { // Do nothing because of X and Y. } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String uri = request.getServletPath(); // 请求路径 LOG.info("=== uri=" + uri); // 获取登录的用户
RpUserInfo rpUserInfo = (RpUserInfo) request.getSession().getAttribute(ConstantClass.USER); // 如果未登录,重定向到登录界面 if (uri.contains("merchant") && rpUserInfo == null) { HttpServletResponse response = (HttpServletResponse) res; response.sendRedirect(request.getContextPath() + "/login"); } else { chain.doFilter(req, res); } } public void init(FilterConfig arg0) throws ServletException { // Do nothing because of X and Y. } }
repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\filter\UserFilter.java
2
请完成以下Java代码
public class X_M_Allergen extends org.compiere.model.PO implements I_M_Allergen, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1730419304L; /** Standard Constructor */ public X_M_Allergen (final Properties ctx, final int M_Allergen_ID, @Nullable final String trxName) { super (ctx, M_Allergen_ID, trxName); } /** Load Constructor */ public X_M_Allergen (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setColor (final @Nullable java.lang.String Color) { set_Value (COLUMNNAME_Color, Color); } @Override public java.lang.String getColor() { return get_ValueAsString(COLUMNNAME_Color); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description);
} @Override public void setM_Allergen_ID (final int M_Allergen_ID) { if (M_Allergen_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, M_Allergen_ID); } @Override public int getM_Allergen_ID() { return get_ValueAsInt(COLUMNNAME_M_Allergen_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen.java
1
请完成以下Java代码
public class DeleteIdentityLinkForCaseInstanceCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String caseInstanceId; protected String userId; protected String groupId; protected String type; public DeleteIdentityLinkForCaseInstanceCmd(String caseInstanceId, String userId, String groupId, String type) { validateParams(userId, groupId, caseInstanceId, type); this.caseInstanceId = caseInstanceId; this.userId = userId; this.groupId = groupId; this.type = type; } protected void validateParams(String userId, String groupId, String caseInstanceId, String type) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null"); } if (type == null) { throw new FlowableIllegalArgumentException("type is required when deleting a process identity link");
} if (userId == null && groupId == null) { throw new FlowableIllegalArgumentException("userId and groupId cannot both be null"); } } @Override public Void execute(CommandContext commandContext) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); CaseInstance caseInstance = cmmnEngineConfiguration.getCaseInstanceEntityManager().findById(caseInstanceId); if (caseInstance == null) { throw new FlowableObjectNotFoundException("Cannot find case instance with id " + caseInstanceId, CaseInstanceEntity.class); } IdentityLinkUtil.deleteCaseInstanceIdentityLinks(caseInstance, userId, groupId, type, cmmnEngineConfiguration); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteIdentityLinkForCaseInstanceCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class GetUnitsRouteBuilder extends RouteBuilder { public static final String GET_UOM_MAPPINGS_ROUTE_ID = "Shopware6-getUOMMappings"; private final ProcessLogger processLogger; public GetUnitsRouteBuilder(@NonNull final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void configure() { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager cacheManager = cachingProvider.getCacheManager(); final MutableConfiguration<de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest, Object> config = new MutableConfiguration<>(); config.setTypes(de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest.class, Object.class); config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1))); final Cache<de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest, Object> cache = cacheManager.createCache("unit", config); final JCachePolicy jcachePolicy = new JCachePolicy(); jcachePolicy.setCache(cache); from(direct(GET_UOM_MAPPINGS_ROUTE_ID)) .id(GET_UOM_MAPPINGS_ROUTE_ID) .streamCache("true") .policy(jcachePolicy) .log("Route invoked. Results will be cached") .process(this::getUnits); } private void getUnits(final Exchange exchange) { final GetUnitsRequest getUnitsRequest = exchange.getIn().getBody(GetUnitsRequest.class);
if (getUnitsRequest == null) { throw new RuntimeException("No getUnitsRequest provided!"); } final ShopwareClient shopwareClient = ShopwareClient .of(getUnitsRequest.getClientId(), getUnitsRequest.getClientSecret(), getUnitsRequest.getBaseUrl(), PInstanceLogger.of(processLogger)); final JsonUnits units = shopwareClient.getUnits(); if (CollectionUtils.isEmpty(units.getUnitList())) { throw new RuntimeException("No units return from Shopware!"); } final ImmutableMap<String, String> unitId2Code = units.getUnitList() .stream() .collect(ImmutableMap.toImmutableMap(JsonUOM::getId, JsonUOM::getShortCode)); final UOMInfoProvider uomInfoProvider = UOMInfoProvider.builder() .unitId2Code(unitId2Code) .build(); exchange.getIn().setBody(uomInfoProvider); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\unit\GetUnitsRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public List<ForecastListLineItemType> getForecastListLineItem() { if (forecastListLineItem == null) { forecastListLineItem = new ArrayList<ForecastListLineItemType>(); } return this.forecastListLineItem; } /** * A free-text description suceeding a list line item group. * * @return * possible object is * {@link String } * */ public String getFooterDescription() { return footerDescription;
} /** * Sets the value of the footerDescription property. * * @param value * allowed object is * {@link String } * */ public void setFooterDescription(String value) { this.footerDescription = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemListType.java
2
请完成以下Java代码
public String getContentType() { return getHeader(HttpBaseRequest.HEADER_CONTENT_TYPE); } @SuppressWarnings("unchecked") public Q payload(String payload) { setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD, payload); return (Q) this; } public String getPayload() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD); } public Q get() { return method(HttpGet.METHOD_NAME); } public Q post() { return method(HttpPost.METHOD_NAME); } public Q put() { return method(HttpPut.METHOD_NAME); } public Q delete() { return method(HttpDelete.METHOD_NAME); } public Q patch() { return method(HttpPatch.METHOD_NAME); } public Q head() { return method(HttpHead.METHOD_NAME); } public Q options() { return method(HttpOptions.METHOD_NAME); } public Q trace() { return method(HttpTrace.METHOD_NAME); }
public Map<String, Object> getConfigOptions() { return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG); } public Object getConfigOption(String field) { Map<String, Object> config = getConfigOptions(); if (config != null) { return config.get(field); } return null; } @SuppressWarnings("unchecked") public Q configOption(String field, Object value) { if (field == null || field.isEmpty() || value == null) { LOG.ignoreConfig(field, value); } else { Map<String, Object> config = getConfigOptions(); if (config == null) { config = new HashMap<>(); setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config); } config.put(field, value); } return (Q) this; } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java
1
请完成以下Java代码
default void produceOperationLog(CommandContext commandContext, List<T> results) { if(results == null || results.isEmpty()) { return; } long logEntriesPerSyncOperationLimit = commandContext.getProcessEngineConfiguration() .getLogEntriesPerSyncOperationLimit(); if(logEntriesPerSyncOperationLimit == SUMMARY_LOG && results.size() > 1) { // create summary from multi-result operation List<PropertyChange> propChangesForOperation = getSummarizingPropChangesForOperation(results); if(propChangesForOperation == null) { // convert null return value to empty list propChangesForOperation = Collections.singletonList(PropertyChange.EMPTY_CHANGE); } // use first result as representative for summarized operation log entry createOperationLogEntry(commandContext, results.get(0), propChangesForOperation, true); } else { // create detailed log for each operation result
Map<T, List<PropertyChange>> propChangesForOperation = getPropChangesForOperation(results); if(propChangesForOperation == null ) { // create a map with empty result lists for each result item propChangesForOperation = results.stream().collect(Collectors.toMap(Function.identity(), (result) -> Collections.singletonList(PropertyChange.EMPTY_CHANGE))); } if (logEntriesPerSyncOperationLimit != UNLIMITED_LOG && logEntriesPerSyncOperationLimit < propChangesForOperation.size()) { throw new ProcessEngineException( "Maximum number of operation log entries for operation type synchronous APIs reached. Configured limit is " + logEntriesPerSyncOperationLimit + " but " + propChangesForOperation.size() + " entities were affected by API call."); } else { // produce one operation log per affected entity for (Entry<T, List<PropertyChange>> propChanges : propChangesForOperation.entrySet()) { createOperationLogEntry(commandContext, propChanges.getKey(), propChanges.getValue(), false); } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SynchronousOperationLogProducer.java
1
请完成以下Java代码
public static int[] mergeAndRemoveDuplicatesUsingSet(int[] arr1, int[] arr2) { int[] mergedArr = mergeArrays(arr1, arr2); Set<Integer> uniqueInts = new HashSet<>(); for (int el : mergedArr) { uniqueInts.add(el); } return getArrayFromSet(uniqueInts); } private static int[] getArrayFromSet(Set<Integer> set) { int[] mergedArrWithoutDuplicated = new int[set.size()]; int i = 0; for (Integer el: set) { mergedArrWithoutDuplicated[i] = el; i++; } return mergedArrWithoutDuplicated; } public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) { return removeDuplicate(mergeArrays(arr1, arr2)); } public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) { return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2)); } private static int[] mergeArrays(int[] arr1, int[] arr2) { int[] mergedArrays = new int[arr1.length + arr2.length]; System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length); System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length); return mergedArrays;
} private static int[] removeDuplicate(int[] arr) { int[] withoutDuplicates = new int[arr.length]; int i = 0; for(int element : arr) { if(!isElementPresent(withoutDuplicates, element)) { withoutDuplicates[i] = element; i++; } } int[] truncatedArray = new int[i]; System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i); return truncatedArray; } private static boolean isElementPresent(int[] arr, int element) { for(int el : arr) { if(el == element) { return true; } } return false; } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\mergeandremoveduplicate\MergeArraysAndRemoveDuplicate.java
1
请在Spring Boot框架中完成以下Java代码
public class MessageSourceProperties { /** * List of basenames (essentially a fully-qualified classpath location), each * following the ResourceBundle convention with relaxed support for slash based * locations. If it doesn't contain a package qualifier (such as "org.mypackage"), it * will be resolved from the classpath root. */ private List<String> basename = new ArrayList<>(List.of("messages")); /** * List of locale-independent property file resources containing common messages. */ private @Nullable List<Resource> commonMessages; /** * Message bundles encoding. */ private Charset encoding = StandardCharsets.UTF_8; /** * Loaded resource bundle files cache duration. When not set, bundles are cached * forever. If a duration suffix is not specified, seconds will be used. */ @DurationUnit(ChronoUnit.SECONDS) private @Nullable Duration cacheDuration; /** * Whether to fall back to the system Locale if no files for a specific Locale have * been found. if this is turned off, the only fallback will be the default file (e.g. * "messages.properties" for basename "messages"). */ private boolean fallbackToSystemLocale = true; /** * Whether to always apply the MessageFormat rules, parsing even messages without * arguments. */ private boolean alwaysUseMessageFormat; /** * Whether to use the message code as the default message instead of throwing a * "NoSuchMessageException". Recommended during development only. */ private boolean useCodeAsDefaultMessage; public List<String> getBasename() { return this.basename; } public void setBasename(List<String> basename) { this.basename = basename; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } public @Nullable Duration getCacheDuration() { return this.cacheDuration; }
public void setCacheDuration(@Nullable Duration cacheDuration) { this.cacheDuration = cacheDuration; } public boolean isFallbackToSystemLocale() { return this.fallbackToSystemLocale; } public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) { this.fallbackToSystemLocale = fallbackToSystemLocale; } public boolean isAlwaysUseMessageFormat() { return this.alwaysUseMessageFormat; } public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) { this.alwaysUseMessageFormat = alwaysUseMessageFormat; } public boolean isUseCodeAsDefaultMessage() { return this.useCodeAsDefaultMessage; } public void setUseCodeAsDefaultMessage(boolean useCodeAsDefaultMessage) { this.useCodeAsDefaultMessage = useCodeAsDefaultMessage; } public @Nullable List<Resource> getCommonMessages() { return this.commonMessages; } public void setCommonMessages(@Nullable List<Resource> commonMessages) { this.commonMessages = commonMessages; } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceProperties.java
2
请完成以下Java代码
public class BroadcastingClient { private DatagramSocket socket; private InetAddress address; private int expectedServerCount; private byte[] buf; public BroadcastingClient(int expectedServerCount) throws Exception { this.expectedServerCount = expectedServerCount; this.address = InetAddress.getByName("255.255.255.255"); } public int discoverServers(String msg) throws IOException { initializeSocketForBroadcasting(); copyMessageOnBuffer(msg); // When we want to broadcast not just to local network, call listAllBroadcastAddresses() and execute broadcastPacket for each value. broadcastPacket(address); return receivePackets(); } List<InetAddress> listAllBroadcastAddresses() throws SocketException { List<InetAddress> broadcastList = new ArrayList<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } broadcastList.addAll(networkInterface.getInterfaceAddresses() .stream() .filter(address -> address.getBroadcast() != null) .map(address -> address.getBroadcast()) .collect(Collectors.toList())); } return broadcastList; } private void initializeSocketForBroadcasting() throws SocketException { socket = new DatagramSocket();
socket.setBroadcast(true); } private void copyMessageOnBuffer(String msg) { buf = msg.getBytes(); } private void broadcastPacket(InetAddress address) throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); } private int receivePackets() throws IOException { int serversDiscovered = 0; while (serversDiscovered != expectedServerCount) { receivePacket(); serversDiscovered++; } return serversDiscovered; } private void receivePacket() throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); } public void close() { socket.close(); } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\broadcast\BroadcastingClient.java
1
请在Spring Boot框架中完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public String getPlanItemInstanceId() { return planItemInstanceId; } public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } public String getPlanItemInstanceUrl() { return planItemInstanceUrl; } public void setPlanItemInstanceUrl(String planItemInstanceUrl) { this.planItemInstanceUrl = planItemInstanceUrl; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; }
public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResponse.java
2
请完成以下Java代码
public abstract class DeleteIdentityLinkCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected String groupId; protected String type; protected String taskId; protected TaskEntity task; public DeleteIdentityLinkCmd(String taskId, String userId, String groupId, String type) { validateParams(userId, groupId, type, taskId); this.taskId = taskId; this.userId = userId; this.groupId = groupId; this.type = type; } protected void validateParams(String userId, String groupId, String type, String taskId) { ensureNotNull("taskId", taskId); ensureNotNull("type is required when adding a new task identity link", "type", type); // Special treatment for assignee and owner: group cannot be used and userId may be null if (IdentityLinkType.ASSIGNEE.equals(type) || IdentityLinkType.OWNER.equals(type)) { if (groupId != null) { throw new ProcessEngineException("Incompatible usage: cannot use type '" + type + "' together with a groupId"); } } else { if (userId == null && groupId == null) { throw new ProcessEngineException("userId and groupId cannot both be null"); } } } public Void execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task);
checkDeleteIdentityLink(task, commandContext); if (IdentityLinkType.ASSIGNEE.equals(type)) { task.setAssignee(null); } else if (IdentityLinkType.OWNER.equals(type)) { task.setOwner(null); } else { task.deleteIdentityLink(userId, groupId, type); } task.triggerUpdateEvent(); return null; } protected void checkDeleteIdentityLink(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskAssign(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteIdentityLinkCmd.java
1
请完成以下Java代码
public class TermOccurrence { /** * 词频统计用的储存结构 */ BinTrie<TermFrequency> trieSingle; int totalTerm; public TermOccurrence() { trieSingle = new BinTrie<TermFrequency>(); } public void add(String term) { TermFrequency value = trieSingle.get(term); if (value == null) { value = new TermFrequency(term); trieSingle.put(term, value); } else
{ value.increase(); } ++totalTerm; } public void addAll(List<String> termList) { for (String s : termList) { add(s); } } public java.util.Set<java.util.Map.Entry<String, TermFrequency>> getEntrySet() { return trieSingle.entrySet(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\occurrence\TermOccurrence.java
1
请完成以下Java代码
public int getAD_Workflow_Access_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_Access_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Workflow getAD_Workflow() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class); } @Override public void setAD_Workflow(org.compiere.model.I_AD_Workflow AD_Workflow) { set_ValueFromPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class, AD_Workflow); } /** Set Workflow. @param AD_Workflow_ID Workflow or combination of tasks */ @Override public void setAD_Workflow_ID (int AD_Workflow_ID) { if (AD_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, Integer.valueOf(AD_Workflow_ID)); } /** Get Workflow. @return Workflow or combination of tasks */ @Override
public int getAD_Workflow_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lesen und Schreiben. @param IsReadWrite Field is read / write */ @Override public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Lesen und Schreiben. @return Field is read / write */ @Override public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow_Access.java
1
请完成以下Java代码
public void updateFruit(@SerialNumber @FormParam("serial") String serial) { Fruit fruit = new Fruit(); fruit.setSerial(serial); SimpleStorageService.storeFruit(fruit); } @POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) public void createFruit(@Valid Fruit fruit) { SimpleStorageService.storeFruit(fruit); } @POST @Path("/created") @Consumes(MediaType.APPLICATION_JSON) public Response createNewFruit(@Valid Fruit fruit) { String result = "Fruit saved : " + fruit; return Response.status(Response.Status.CREATED.getStatusCode()) .entity(result) .build(); } @GET @Valid @Produces(MediaType.APPLICATION_JSON)
@Path("/search/{name}") public Fruit findFruitByName(@PathParam("name") String name) { return SimpleStorageService.findByName(name); } @GET @Produces(MediaType.TEXT_HTML) @Path("/exception") @Valid public Fruit exception() { Fruit fruit = new Fruit(); fruit.setName("a"); fruit.setColour("b"); return fruit; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\rest\FruitResource.java
1
请完成以下Java代码
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationReadyEvent) { this.handleApplicationReadyEvent((ApplicationReadyEvent) event); } else if (event instanceof ApplicationFailedEvent) { this.handleApplicationFailedEvent((ApplicationFailedEvent) event); } else if (event instanceof ContextClosedEvent) { this.handleContextClosedEvent((ContextClosedEvent) event); } } @SuppressWarnings("unused") private void handleApplicationReadyEvent(ApplicationReadyEvent event) { this.inService = true; } @SuppressWarnings("unused") private void handleApplicationFailedEvent(ApplicationFailedEvent event) { this.inService = false;
} @SuppressWarnings("unused") private void handleContextClosedEvent(ContextClosedEvent event) { // 标记不提供服务 this.inService = false; // sleep 等待负载均衡完成健康检查 for (int i = 0; i < 20; i++) { // TODO 20 需要配置 logger.info("[handleContextClosedEvent][优雅关闭,第 {} sleep 等待负载均衡完成健康检查]", i); try { Thread.sleep(1000L); } catch (InterruptedException ignore) { } } } }
repos\SpringBoot-Labs-master\lab-41\lab-41-demo02\src\main\java\cn\iocoder\springboot\lab40\jenkinsdemo\actuate\ServerHealthIndicator.java
1
请在Spring Boot框架中完成以下Java代码
public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public long getLogNumber() { return logNumber; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override public String getData() { return data; } @Override public String getExecutionId() { return executionId; }
@Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请完成以下Java代码
public class X_M_HU_PI extends org.compiere.model.PO implements I_M_HU_PI, org.compiere.model.I_Persistent { private static final long serialVersionUID = 979131992L; /** Standard Constructor */ public X_M_HU_PI (final Properties ctx, final int M_HU_PI_ID, @Nullable final String trxName) { super (ctx, M_HU_PI_ID, trxName); } /** Load Constructor */ public X_M_HU_PI (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsDefaultForPicking (final boolean IsDefaultForPicking) { set_Value (COLUMNNAME_IsDefaultForPicking, IsDefaultForPicking); } @Override
public boolean isDefaultForPicking() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultForPicking); } @Override public void setIsDefaultLU (final boolean IsDefaultLU) { set_Value (COLUMNNAME_IsDefaultLU, IsDefaultLU); } @Override public boolean isDefaultLU() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java
1
请完成以下Java代码
public FileValue convertToTypedValue(UntypedValueImpl untypedValue) { throw new UnsupportedOperationException("Currently no automatic conversation from UntypedValue to FileValue"); } @Override public FileValue readValue(ValueFields valueFields, boolean deserializeValue, boolean asTransientValue) { String fileName = valueFields.getTextValue(); if (fileName == null) { // ensure file name is not null fileName = ""; } FileValueBuilder builder = Variables.fileValue(fileName); if (valueFields.getByteArrayValue() != null) { builder.file(valueFields.getByteArrayValue()); } // to ensure the same array size all the time if (valueFields.getTextValue2() != null) { String[] split = Arrays.copyOf(valueFields.getTextValue2().split(MIMETYPE_ENCODING_SEPARATOR, NR_OF_VALUES_IN_TEXTFIELD2), NR_OF_VALUES_IN_TEXTFIELD2); String mimeType = returnNullIfEmptyString(split[0]); String encoding = returnNullIfEmptyString(split[1]); builder.mimeType(mimeType); builder.encoding(encoding); } builder.setTransient(asTransientValue); return builder.create(); }
protected String returnNullIfEmptyString(String s) { if (s.isEmpty()) { return null; } return s; } @Override public String getName() { return valueType.getName(); } @Override protected boolean canWriteValue(TypedValue value) { if (value == null || value.getType() == null) { // untyped value return false; } return value.getType().getName().equals(getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\FileValueSerializer.java
1
请完成以下Java代码
public void assertQualityInspectionOrder(@NonNull final I_PP_Order ppOrder) { Check.assume(isQualityInspection(ppOrder), "Order shall be Quality Inspection Order: {}", ppOrder); } @Override public IQueryFilter<I_PP_Order> getQualityInspectionFilter() { return qualityInspectionFilter; } @Override public Timestamp getDateOfProduction(final I_PP_Order ppOrder) { final Timestamp dateOfProduction; if (ppOrder.getDateDelivered() != null) { dateOfProduction = ppOrder.getDateDelivered(); } else { dateOfProduction = ppOrder.getDateFinishSchedule(); } Check.assumeNotNull(dateOfProduction, "dateOfProduction not null for PP_Order {}", ppOrder); return dateOfProduction; }
@Override public List<I_M_InOutLine> retrieveIssuedInOutLines(final I_PP_Order ppOrder) { // services final IPPOrderMInOutLineRetrievalService ppOrderMInOutLineRetrievalService = Services.get(IPPOrderMInOutLineRetrievalService.class); final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class); final List<I_M_InOutLine> allIssuedInOutLines = new ArrayList<>(); final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getByOrderId(ppOrderId)) { if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc)) { continue; } final List<I_M_InOutLine> issuedInOutLinesForCC = ppOrderMInOutLineRetrievalService.provideIssuedInOutLines(cc); allIssuedInOutLines.addAll(issuedInOutLinesForCC); } return allIssuedInOutLines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderBL.java
1
请完成以下Java代码
SparseVector feature() { return feature_; } /** * Add a feature. * * @param key the key of a feature * @param value the value of a feature */ void add_feature(int key, double value) { feature_.put(key, value); } /** * Set features. * * @param feature a feature vector */ void set_features(SparseVector feature) { feature_ = feature; } /** * Clear features. */ void clear() { feature_.clear(); } /** * Apply IDF(inverse document frequency) weighting. * * @param df document frequencies * @param ndocs the number of documents */ void idf(HashMap<Integer, Integer> df, int ndocs)
{ for (Map.Entry<Integer, Double> entry : feature_.entrySet()) { Integer denom = df.get(entry.getKey()); if (denom == null) denom = 1; entry.setValue((double) (entry.getValue() * Math.log(ndocs / denom))); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document<?> document = (Document<?>) o; return id_ != null ? id_.equals(document.id_) : document.id_ == null; } @Override public int hashCode() { return id_ != null ? id_.hashCode() : 0; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\Document.java
1
请完成以下Java代码
public static MRegion getDefault (Properties ctx) { if (s_regions == null || s_regions.size() == 0) loadAllRegions(ctx); return s_default; } // get /** * Return Array of Regions of Country * @param ctx context * @param C_Country_ID country * @return MRegion Array */ public static MRegion[] getRegions (Properties ctx, int C_Country_ID) { if (s_regions == null || s_regions.size() == 0) loadAllRegions(ctx); ArrayList<MRegion> list = new ArrayList<MRegion>(); Iterator<MRegion> it = s_regions.values().iterator(); while (it.hasNext()) { MRegion r = it.next(); if (r.getC_Country_ID() == C_Country_ID) list.add(r); } // Sort it MRegion[] retValue = new MRegion[list.size()]; list.toArray(retValue); Arrays.sort(retValue, new MRegion(ctx, 0, null)); return retValue; } // getRegions /** Region Cache */ private static CCache<String,MRegion> s_regions = null; /** Default Region */ private static MRegion s_default = null; /** Static Logger */ private static Logger s_log = LogManager.getLogger(MRegion.class); /************************************************************************** * Create empty Region * @param ctx context * @param C_Region_ID id * @param trxName transaction */ public MRegion (Properties ctx, int C_Region_ID, String trxName) { super (ctx, C_Region_ID, trxName); if (C_Region_ID == 0) { } } // MRegion /**
* Create Region from current row in ResultSet * @param ctx context * @param rs result set * @param trxName transaction */ public MRegion (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MRegion /** * Parent Constructor * @param country country * @param regionName Region Name */ public MRegion (MCountry country, String regionName) { super (country.getCtx(), 0, country.get_TrxName()); setC_Country_ID(country.getC_Country_ID()); setName(regionName); } // MRegion /** * Return Name * @return Name */ @Override public String toString() { return getName(); } // toString /** * Compare * @param o1 object 1 * @param o2 object 2 * @return -1,0, 1 */ @Override public int compare(Object o1, Object o2) { String s1 = o1.toString(); if (s1 == null) s1 = ""; String s2 = o2.toString(); if (s2 == null) s2 = ""; return s1.compareTo(s2); } // compare } // MRegion
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegion.java
1
请完成以下Java代码
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Supplier<SecurityContext> deferredContext = this.securityContextHolderStrategy.getDeferredContext(); this.securityContextHolderStrategy .setDeferredContext(defaultWithAnonymous((HttpServletRequest) req, deferredContext)); chain.doFilter(req, res); } private Supplier<SecurityContext> defaultWithAnonymous(HttpServletRequest request, Supplier<SecurityContext> currentDeferredContext) { return SingletonSupplier.of(() -> { SecurityContext currentContext = currentDeferredContext.get(); return defaultWithAnonymous(request, currentContext); }); } private SecurityContext defaultWithAnonymous(HttpServletRequest request, SecurityContext currentContext) { Authentication currentAuthentication = currentContext.getAuthentication(); if (currentAuthentication == null) { Authentication anonymous = createAuthentication(request); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Set SecurityContextHolder to " + anonymous)); } else { this.logger.debug("Set SecurityContextHolder to anonymous SecurityContext"); } SecurityContext anonymousContext = this.securityContextHolderStrategy.createEmptyContext(); anonymousContext.setAuthentication(anonymous); return anonymousContext; } else { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.of(() -> "Did not set SecurityContextHolder since already authenticated " + currentAuthentication)); } } return currentContext; } protected Authentication createAuthentication(HttpServletRequest request) { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(this.key, this.principal, this.authorities); token.setDetails(this.authenticationDetailsSource.buildDetails(request)); return token; }
public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } public Object getPrincipal() { return this.principal; } public List<GrantedAuthority> getAuthorities() { return this.authorities; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AnonymousAuthenticationFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class Cocktail { @Id @Column(name = "cocktail_name") private String name; @Column private double price; @Column(name = "category") private String category; @OneToOne @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "cocktail_name", referencedColumnName = "cocktail", insertable = false, updatable = false, foreignKey = @jakarta.persistence .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) private Recipe recipe; @OneToMany(fetch = FetchType.LAZY) @JoinColumn( name = "cocktail", referencedColumnName = "cocktail_name", insertable = false, updatable = false, foreignKey = @jakarta.persistence .ForeignKey(value = ConstraintMode.NO_CONSTRAINT)) private List<MultipleRecipe> recipeList; public Cocktail() { } public Cocktail(String name, double price, String baseIngredient) { this.name = name; this.price = price; this.category = baseIngredient; } public String getName() { return name; } public double getPrice() {
return price; } public String getCategory() { return category; } public Recipe getRecipe() { return recipe; } public List<MultipleRecipe> getRecipeList() { return recipeList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cocktail cocktail = (Cocktail) o; return Double.compare(cocktail.price, price) == 0 && Objects.equals(name, cocktail.name) && Objects.equals(category, cocktail.category); } @Override public int hashCode() { return Objects.hash(name, price, category); } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\unrelated\entities\Cocktail.java
2
请完成以下Java代码
protected ActivitiElContext createElContext(VariableScope variableScope) { ELResolver elResolver = createElResolver(variableScope); return new ActivitiElContext(elResolver); } protected ELResolver createElResolver(VariableScope variableScope) { CompositeELResolver elResolver = new CompositeELResolver(); elResolver.add(new VariableScopeElResolver(variableScope)); if (beans != null) { // ACT-1102: Also expose all beans in configuration when using standalone activiti, not // in spring-context elResolver.add(new ReadOnlyMapELResolver(beans)); } elResolver.add(new ArrayELResolver()); elResolver.add(new ListELResolver()); elResolver.add(new MapELResolver());
elResolver.add(new JsonNodeELResolver()); elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification elResolver.add(new BeanELResolver()); return elResolver; } public Map<Object, Object> getBeans() { return beans; } public void setBeans(Map<Object, Object> beans) { this.beans = beans; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getTaskId() { return taskId; } public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public String getAssignee() { return assignee; } public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getCanceled() { return canceled; } public Boolean getCompleteScope() {
return completeScope; } public String getTenantId() { return tenantId; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto, HistoricActivityInstance historicActivityInstance) { dto.id = historicActivityInstance.getId(); dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId(); dto.activityId = historicActivityInstance.getActivityId(); dto.activityName = historicActivityInstance.getActivityName(); dto.activityType = historicActivityInstance.getActivityType(); dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId(); dto.processInstanceId = historicActivityInstance.getProcessInstanceId(); dto.executionId = historicActivityInstance.getExecutionId(); dto.taskId = historicActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId(); dto.assignee = historicActivityInstance.getAssignee(); dto.startTime = historicActivityInstance.getStartTime(); dto.endTime = historicActivityInstance.getEndTime(); dto.durationInMillis = historicActivityInstance.getDurationInMillis(); dto.canceled = historicActivityInstance.isCanceled(); dto.completeScope = historicActivityInstance.isCompleteScope(); dto.tenantId = historicActivityInstance.getTenantId(); dto.removalTime = historicActivityInstance.getRemovalTime(); dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityInstanceDto.java
1
请完成以下Java代码
public int getC_Currency_ID() { return 0; // N/A } @Override public BigDecimal getApprovalAmt() { return BigDecimal.ZERO; // N/A } @Override public File createPDF() { throw new UnsupportedOperationException(); // N/A } @Override public String getDocumentInfo() { final I_C_DocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); }
private PPOrderRouting getOrderRouting() { final IPPOrderRoutingRepository orderRoutingsRepo = Services.get(IPPOrderRoutingRepository.class); final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return orderRoutingsRepo.getByOrderId(orderId); } private PPOrderRoutingActivityId getActivityId() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return PPOrderRoutingActivityId.ofRepoId(orderId, getPP_Order_Node_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPCostCollector.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price;
} public void setPrice(double price) { this.price = price; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\query\ProductItem.java
1
请完成以下Java代码
private ClassPathBeanDefinitionScanner configure(ClassPathBeanDefinitionScanner scanner) { Set<String> basePackages = this.basePackages; if (!basePackages.isEmpty()) { getLogger().debug("Scanning base packages: {}", basePackages); scanner.scan(StringUtils.toStringArray(basePackages)); } return scanner; } protected AnnotatedBeanDefinitionReader newAnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) { return new AnnotatedBeanDefinitionReader(registry, getEnvironment()); } protected ClassPathBeanDefinitionScanner newClassBeanDefinitionScanner(BeanDefinitionRegistry registry) { return new ClassPathBeanDefinitionScanner(registry, isUsingDefaultFilters(), getEnvironment()); } /** * Re-registers Singleton beans registered with the previous {@link ConfigurableListableBeanFactory BeanFactory} * (prior to refresh) with this {@link ApplicationContext}, iff this context was previously active * and subsequently refreshed. * * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#copyConfigurationFrom(ConfigurableBeanFactory) * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerSingleton(String, Object) * @see #getBeanFactory() */ @Override protected void onRefresh() { super.onRefresh(); ConfigurableListableBeanFactory currentBeanFactory = getBeanFactory(); if (this.beanFactory != null) { Arrays.stream(ArrayUtils.nullSafeArray(this.beanFactory.getSingletonNames(), String.class)) .filter(singletonBeanName -> !currentBeanFactory.containsSingleton(singletonBeanName)) .forEach(singletonBeanName -> currentBeanFactory .registerSingleton(singletonBeanName, this.beanFactory.getSingleton(singletonBeanName))); if (isCopyConfigurationEnabled()) { currentBeanFactory.copyConfigurationFrom(this.beanFactory); } } } /**
* Stores a reference to the previous {@link ConfigurableListableBeanFactory} in order to copy its configuration * and state on {@link ApplicationContext} refresh invocations. * * @see #getBeanFactory() */ @Override protected void prepareRefresh() { this.beanFactory = (DefaultListableBeanFactory) SpringExtensions.safeGetValue(this::getBeanFactory); super.prepareRefresh(); } /** * @inheritDoc */ @Override public void register(Class<?>... componentClasses) { Arrays.stream(ArrayUtils.nullSafeArray(componentClasses, Class.class)) .filter(Objects::nonNull) .forEach(this.componentClasses::add); } /** * @inheritDoc */ @Override public void scan(String... basePackages) { Arrays.stream(ArrayUtils.nullSafeArray(basePackages, String.class)) .filter(StringUtils::hasText) .forEach(this.basePackages::add); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\annotation\RefreshableAnnotationConfigApplicationContext.java
1
请完成以下Java代码
public class BookByIdGraphQLQuery extends GraphQLQuery { public BookByIdGraphQLQuery(String id, String queryName, Set<String> fieldsSet) { super("query", queryName); if (id != null || fieldsSet.contains("id")) { getInput().put("id", id); } } public BookByIdGraphQLQuery(String id, String queryName, Set<String> fieldsSet, Map<String, String> variableReferences, List<VariableDefinition> variableDefinitions) { super("query", queryName); if (id != null || fieldsSet.contains("id")) { getInput().put("id", id); } if (variableDefinitions != null) { getVariableDefinitions().addAll(variableDefinitions); } if (variableReferences != null) { getVariableReferences().putAll(variableReferences); } } public BookByIdGraphQLQuery() { super("query"); } @Override public String getOperationName() { return "bookById"; } public static Builder newRequest() { return new Builder(); } public static class Builder { private Set<String> fieldsSet = new HashSet<>(); private final Map<String, String> variableReferences = new HashMap<>(); private final List<VariableDefinition> variableDefinitions = new ArrayList<>(); private String id; private String queryName; public BookByIdGraphQLQuery build() { return new BookByIdGraphQLQuery(this.id, this.queryName, this.fieldsSet, this.variableReferences, this.variableDefinitions);
} public Builder id(String id) { this.id = id; this.fieldsSet.add("id"); return this; } public Builder idReference(String variableRef) { this.variableReferences.put("id", variableRef); this.variableDefinitions.add(VariableDefinition.newVariableDefinition(variableRef, new graphql.language.TypeName("ID")).build()); this.fieldsSet.add("id"); return this; } public Builder queryName(String queryName) { this.queryName = queryName; return this; } } }
repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\dgsgraphqlclient\BookByIdGraphQLQuery.java
1
请完成以下Java代码
static TrustedProxies from(String trustedProxies) { Assert.hasText(trustedProxies, "trustedProxies must not be empty"); Pattern pattern = Pattern.compile(trustedProxies); return value -> pattern.matcher(value).matches(); } class ForwardedTrustedProxiesCondition extends AllNestedConditions { public ForwardedTrustedProxiesCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".forwarded.enabled", matchIfMissing = true) static class OnPropertyEnabled { } @ConditionalOnPropertyExists static class OnTrustedProxiesNotEmpty { } } class XForwardedTrustedProxiesCondition extends AllNestedConditions { public XForwardedTrustedProxiesCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".x-forwarded.enabled", matchIfMissing = true) static class OnPropertyEnabled { } @ConditionalOnPropertyExists static class OnTrustedProxiesNotEmpty { } } class OnPropertyExistsCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
try { String property = context.getEnvironment().getProperty(PROPERTY); if (!StringUtils.hasText(property)) { return ConditionOutcome.noMatch(PROPERTY + " property is not set or is empty."); } return ConditionOutcome.match(PROPERTY + " property is not empty."); } catch (NoSuchElementException e) { return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists"); } } } @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnPropertyExistsCondition.class) @interface ConditionalOnPropertyExists { } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\TrustedProxies.java
1
请完成以下Java代码
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 Attribute Search. @param M_AttributeSearch_ID Common Search Attribute */ public void setM_AttributeSearch_ID (int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSearch_ID, Integer.valueOf(M_AttributeSearch_ID)); } /** Get Attribute Search. @return Common Search Attribute */ public int getM_AttributeSearch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSearch_ID); if (ii == null) return 0; return ii.intValue(); } /** 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSearch.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractMaxPermanentPrescriptionPeriod insuranceContractMaxPermanentPrescriptionPeriod = (InsuranceContractMaxPermanentPrescriptionPeriod) o; return Objects.equals(this.amount, insuranceContractMaxPermanentPrescriptionPeriod.amount) && Objects.equals(this.timePeriod, insuranceContractMaxPermanentPrescriptionPeriod.timePeriod); } @Override public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractMaxPermanentPrescriptionPeriod {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaxPermanentPrescriptionPeriod.java
2
请完成以下Java代码
JarFile get(URL jarFileUrl) { JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); synchronized (this) { return this.jarFileUrlToJarFile.get(urlKey); } } /** * Get a jar file URL from the cache given a jar file. * @param jarFile the jar file * @return the cached {@link URL} or {@code null} */ URL get(JarFile jarFile) { synchronized (this) { return this.jarFileToJarFileUrl.get(jarFile); } } /** * Put the given jar file URL and jar file into the cache if they aren't already * there. * @param jarFileUrl the jar file URL * @param jarFile the jar file * @return {@code true} if the items were added to the cache or {@code false} if * they were already there */ boolean putIfAbsent(URL jarFileUrl, JarFile jarFile) { JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); synchronized (this) { JarFile cached = this.jarFileUrlToJarFile.get(urlKey); if (cached == null) { this.jarFileUrlToJarFile.put(urlKey, jarFile); this.jarFileToJarFileUrl.put(jarFile, jarFileUrl); return true; } return false; } } /** * Remove the given jar and any related URL file from the cache. * @param jarFile the jar file to remove */
void remove(JarFile jarFile) { synchronized (this) { URL removedUrl = this.jarFileToJarFileUrl.remove(jarFile); if (removedUrl != null) { this.jarFileUrlToJarFile.remove(new JarFileUrlKey(removedUrl)); } } } void clear() { synchronized (this) { this.jarFileToJarFileUrl.clear(); this.jarFileUrlToJarFile.clear(); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarFiles.java
1
请完成以下Java代码
public List<PvmTransition> getOutgoingTransitions() { return (List) outgoingTransitions; } public ActivityBehavior getActivityBehavior() { return activityBehavior; } public void setActivityBehavior(ActivityBehavior activityBehavior) { this.activityBehavior = activityBehavior; } @Override public ScopeImpl getParent() { return parent; } @Override @SuppressWarnings("unchecked") public List<PvmTransition> getIncomingTransitions() { return (List) incomingTransitions; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; }
@Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; } @Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } @Override public boolean isAsync() { return isAsync; } public void setAsync(boolean isAsync) { this.isAsync = isAsync; } @Override public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); Assert.state(annotationAttributes != null, "'annotationAttributes' must not be null"); String endpointName = annotationAttributes.getString("value"); ConditionOutcome outcome = getEndpointOutcome(context, endpointName); if (outcome != null) { return outcome; } return getDefaultOutcome(context, annotationAttributes); } protected @Nullable ConditionOutcome getEndpointOutcome(ConditionContext context, String endpointName) { Environment environment = context.getEnvironment(); String enabledProperty = this.prefix + endpointName + ".enabled"; if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) .because(this.prefix + endpointName + ".enabled is " + match)); } return null; } /** * Return the default outcome that should be used if property is not set. By default
* this method will use the {@code <prefix>.defaults.enabled} property, matching if it * is {@code true} or if it is not configured. * @param context the condition context * @param annotationAttributes the annotation attributes * @return the default outcome * @since 2.6.0 */ protected ConditionOutcome getDefaultOutcome(ConditionContext context, AnnotationAttributes annotationAttributes) { boolean match = Boolean .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) .because(this.prefix + "defaults.enabled is considered " + match)); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\OnEndpointElementCondition.java
2
请在Spring Boot框架中完成以下Java代码
public static class PathMatcherConfig { protected String path; protected String methods; protected String authorizer; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getMethods() { return methods; } public void setMethods(String methods) { this.methods = methods; } public String getAuthorizer() {
return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } public String[] getParsedMethods() { if(methods == null || methods.isEmpty() || methods.equals("*") || methods.toUpperCase().equals("ALL")) { return new String[0]; } else { return methods.split(","); } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SecurityFilterConfig.java
2
请完成以下Java代码
public String getId() { return activiti5Attachment.getId(); } @Override public String getName() { return activiti5Attachment.getName(); } @Override public void setName(String name) { activiti5Attachment.setName(name); } @Override public String getDescription() { return activiti5Attachment.getDescription(); } @Override public void setDescription(String description) { activiti5Attachment.setDescription(description); } @Override public String getType() { return activiti5Attachment.getType(); } @Override public String getTaskId() { return activiti5Attachment.getTaskId(); } @Override public String getProcessInstanceId() { return activiti5Attachment.getProcessInstanceId(); } @Override public String getUrl() { return activiti5Attachment.getUrl(); } @Override
public String getUserId() { return activiti5Attachment.getUserId(); } @Override public Date getTime() { return activiti5Attachment.getTime(); } @Override public void setTime(Date time) { activiti5Attachment.setTime(time); } @Override public String getContentId() { return ((AttachmentEntity) activiti5Attachment).getContentId(); } public org.activiti.engine.task.Attachment getRawObject() { return activiti5Attachment; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5AttachmentWrapper.java
1
请完成以下Java代码
public void onComplete() { ctx.getResponse().status(202); } }); }); } @Bean public Action<Chain> download() { return chain -> chain.get("download", ctx -> { ctx.getResponse().sendStream(new RandomBytesPublisher(1024,512)); }); } @Bean public Action<Chain> downloadChunks() { return chain -> chain.get("downloadChunks", ctx -> { ctx.render(ResponseChunks.bufferChunks("application/octetstream", new RandomBytesPublisher(1024,512))); }); } @Bean public ServerConfig ratpackServerConfig() { return ServerConfig .builder() .findBaseDir("public") .build(); } public static void main(String[] args) { SpringApplication.run(EmbedRatpackStreamsApp.class, args); } public static class RandomBytesPublisher implements Publisher<ByteBuf> { private int bufCount; private int bufSize; private Random rnd = new Random(); RandomBytesPublisher(int bufCount, int bufSize) { this.bufCount = bufCount; this.bufSize = bufSize; } @Override public void subscribe(Subscriber<? super ByteBuf> s) { s.onSubscribe(new Subscription() { private boolean cancelled = false; private boolean recurse; private long requested = 0;
@Override public void request(long n) { if ( bufCount == 0 ) { s.onComplete(); return; } requested += n; if ( recurse ) { return; } recurse = true; try { while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) { byte[] data = new byte[bufSize]; rnd.nextBytes(data); ByteBuf buf = Unpooled.wrappedBuffer(data); s.onNext(buf); } } finally { recurse = false; } } @Override public void cancel() { cancelled = true; } }); } } }
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java
1
请完成以下Spring Boot application配置
app.datasource.url=jdbc:mysql://localhost:3306/numberdb?createDatabaseIfNotExist=true app.datasource.username=root app.datasource.password=root app.datasource.initialization-mode=always app.datasource.platform=mysql app.datasource.connection-timeout=50000 app.datasource.idle-timeout=300000 app.datasource.max-lifetime=900000 app.datasource.maximum-pool-size=8 app.datasource.minimum-idle=8 app.datasource.pool-name=MyPool app.datasource.connection-test-query=select 1 from dual # disable auto-commit app.datasource.auto-commit=false # more settings can be added as app.da
tasource.* spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect logging.level.com.zaxxer.hikari.HikariConfig=DEBUG logging.level.com.zaxxer.hikari=TRACE spring.jpa.open-in-view=false spring.jpa.hibernate.ddl-auto=create
repos\Hibernate-SpringBoot-master\HibernateSpringBootDataSourceBuilderHikariCPKickoff\src\main\resources\application.properties
2
请完成以下Java代码
public class SrcDialog extends JDialog { JPanel panel1 = new JPanel(); BorderLayout borderLayout1 = new BorderLayout(); JScrollPane jScrollPane1 = new JScrollPane(); JTextArea jTextArea1 = new JTextArea(); public SrcDialog(Frame frame, String text) { super(frame, "Source text", true); try { setText(text); jbInit(); pack(); } catch (Exception ex) { ex.printStackTrace(); } } public SrcDialog() {
this(null, ""); } void jbInit() throws Exception { panel1.setLayout(borderLayout1); jTextArea1.setEditable(false); getContentPane().add(panel1); panel1.add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextArea1, null); } public void setText(String txt) { jTextArea1.setText(txt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\SrcDialog.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isActive() { return active;
} public void setActive(boolean active) { this.active = active; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicinsert\model\Account.java
1
请完成以下Java代码
public class PlainPaymentDAO extends AbstractPaymentDAO { public PlainPaymentDAO() { Adempiere.assertUnitTestMode(); } @Override public BigDecimal getAvailableAmount(final PaymentId paymentId) { Adempiere.assertUnitTestMode(); final I_C_Payment payment = getById(paymentId); return payment.getPayAmt(); } @Override public BigDecimal getAllocatedAmt(final PaymentId paymentId) { final I_C_Payment payment = getById(paymentId); return getAllocatedAmt(payment); } @Override public BigDecimal getAllocatedAmt(final I_C_Payment payment) { Adempiere.assertUnitTestMode(); BigDecimal sum = BigDecimal.ZERO; for (final I_C_AllocationLine line : retrieveAllocationLines(payment)) { final I_C_AllocationHdr ah = line.getC_AllocationHdr(); final BigDecimal lineAmt = line.getAmount(); if (null != ah && ah.getC_Currency_ID() != payment.getC_Currency_ID()) { final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert( lineAmt, // Amt CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID CurrencyId.ofRepoId(payment.getC_Currency_ID()), // CurTo_ID ah.getDateTrx().toInstant(), // ConvDate CurrencyConversionTypeId.ofRepoIdOrNull(payment.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()), OrgId.ofRepoId(line.getAD_Org_ID())); sum = sum.add(lineAmtConv); } else { sum = sum.add(lineAmt); } } return sum; } @Override public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType) { Adempiere.assertUnitTestMode(); throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PlainPaymentDAO.java
1
请在Spring Boot框架中完成以下Java代码
protected static class PoolConnectionEndpoint extends ConnectionEndpoint { protected static PoolConnectionEndpoint from(@NonNull ConnectionEndpoint connectionEndpoint) { return new PoolConnectionEndpoint(connectionEndpoint.getHost(), connectionEndpoint.getPort()); } private Pool pool; PoolConnectionEndpoint(@NonNull String host, int port) { super(host, port); } public Optional<Pool> getPool() { return Optional.ofNullable(this.pool); } public @NonNull PoolConnectionEndpoint with(@Nullable Pool pool) { this.pool = pool; return this; } /** * @inheritDoc */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PoolConnectionEndpoint)) { return false; } PoolConnectionEndpoint that = (PoolConnectionEndpoint) obj; return super.equals(that) && this.getPool().equals(that.getPool()); } /** * @inheritDoc */ @Override public int hashCode() { int hashValue = super.hashCode(); hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool());
return hashValue; } /** * @inheritDoc */ @Override public String toString() { return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]", super.toString(), getPool().map(Pool::getName).orElse("")); } } @SuppressWarnings("unused") protected static class SocketCreationException extends RuntimeException { protected SocketCreationException() { } protected SocketCreationException(String message) { super(message); } protected SocketCreationException(Throwable cause) { super(cause); } protected SocketCreationException(String message, Throwable cause) { super(message, cause); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<?> repeatOrder(@CurrentUser UserPrincipal currentUser, @RequestBody List<GoodOrderDetailsResponse> detailsResponseList) { boolean isGoodExists = true; User user = userRepository.findById(currentUser.getId()).orElse(null); if(user != null) { Orders bucket = orderRepository.findFirstByStatusAndUser(OrderStatus.NEW, user).orElse(null); if(bucket == null) { bucket = new Orders(); bucket.setUser(user); bucket.setStatus(OrderStatus.NEW); orderRepository.save(bucket); } //TODO: если уже есть товары в корзине, то спрашивать перед тем как чистить корзину List<OrderDetails> bucketGoods = orderDetailsRepository.findAllByOrder(bucket); for(OrderDetails orderDetails : bucketGoods) { orderDetailsRepository.delete(orderDetails); } for(GoodOrderDetailsResponse goodOrderDetailsResponse : detailsResponseList) {
List<Good> goodList = goodsRepository.findAllByInternalCodeAndIsOutdated(goodOrderDetailsResponse.getInternalCode(), false); if(!goodList.isEmpty()) { Good good = goodsRepository.findAllByInternalCodeAndIsOutdated(goodOrderDetailsResponse.getInternalCode(), false).get(0); OrderDetails orderDetails = new OrderDetails(); orderDetails.setOrder(bucket); orderDetails.setGood(good); orderDetails.setQuantity(goodOrderDetailsResponse.getQuantity()); orderDetailsRepository.save(orderDetails); } else isGoodExists = false; } } if(!isGoodExists) return new ResponseEntity(new ApiResponse(false, "Извините, некоторых товаров уже нет в магазине!"), HttpStatus.INTERNAL_SERVER_ERROR); else return new ResponseEntity(new ApiResponse(true, "Запрос на повторное создание заказа успешно создан!"), HttpStatus.OK); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\OrderController.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserService userService; /** * 查询用户列表 */ @RequiresPermissions("user:list") @GetMapping("/list") public JSONObject listUser(HttpServletRequest request) { return userService.listUser(CommonUtil.request2Json(request)); } @RequiresPermissions("user:add") @PostMapping("/addUser") public JSONObject addUser(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "username, password, nickname, roleIds"); return userService.addUser(requestJson); } @RequiresPermissions("user:update") @PostMapping("/updateUser") public JSONObject updateUser(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, " nickname, roleIds, deleteStatus, userId"); return userService.updateUser(requestJson); } @RequiresPermissions(value = {"user:add", "user:update"}, logical = Logical.OR) @GetMapping("/getAllRoles") public JSONObject getAllRoles() { return userService.getAllRoles(); } /** * 角色列表 */ @RequiresPermissions("role:list") @GetMapping("/listRole") public JSONObject listRole() { return userService.listRole(); } /** * 查询所有权限, 给角色分配权限时调用 */ @RequiresPermissions("role:list") @GetMapping("/listAllPermission") public JSONObject listAllPermission() { return userService.listAllPermission(); } /** * 新增角色 */ @RequiresPermissions("role:add") @PostMapping("/addRole")
public JSONObject addRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleName,permissions"); return userService.addRole(requestJson); } /** * 修改角色 */ @RequiresPermissions("role:update") @PostMapping("/updateRole") public JSONObject updateRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId,roleName,permissions"); return userService.updateRole(requestJson); } /** * 删除角色 */ @RequiresPermissions("role:delete") @PostMapping("/deleteRole") public JSONObject deleteRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId"); return userService.deleteRole(requestJson); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\controller\UserController.java
2
请完成以下Java代码
private final boolean checkValid(final DocumentLayoutElementDescriptor element) { if (element.isEmpty()) { logger.trace("Skip adding {} to {} because it does not have fields", element, this); return false; } return true; } public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) {
elementsBuilders.add(elementBuilder); return this; } public boolean hasElements() { return !elementsBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementsBuilders.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementLineDescriptor.java
1
请完成以下Java代码
final class SyncConfirmationsSender { public static SyncConfirmationsSender forCurrentTransaction(@NonNull final SenderToProcurementWeb senderToProcurementWebUI) { final ITrxManager trxManager = Services.get(ITrxManager.class); final ITrx trx = trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (trxManager.isNull(trx)) { final SyncConfirmationsSender sender = new SyncConfirmationsSender(senderToProcurementWebUI); sender.setAutoSendAfterEachConfirm(true); return sender; } return trx.getProperty( TRXPROPERTY, () -> { final SyncConfirmationsSender sender = new SyncConfirmationsSender(senderToProcurementWebUI); sender.setAutoSendAfterEachConfirm(false); trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(innerTrx -> sender.send()); return sender; }); } private static final String TRXPROPERTY = SyncConfirmationsSender.class.getName(); private final List<SyncConfirmation> syncConfirmations = new ArrayList<>(); private boolean autoSendAfterEachConfirm = false; private final SenderToProcurementWeb senderToProcurementWebUI; private SyncConfirmationsSender(@NonNull final SenderToProcurementWeb senderToProcurementWebUI) { this.senderToProcurementWebUI = senderToProcurementWebUI; } private void setAutoSendAfterEachConfirm(final boolean autoSendAfterEachConfirm) { this.autoSendAfterEachConfirm = autoSendAfterEachConfirm; } public synchronized void send() { // Do nothing if there is nothing to send if (syncConfirmations.isEmpty()) { return;
} final PutConfirmationToProcurementWebRequest syncConfirmationRequest = PutConfirmationToProcurementWebRequest.of(syncConfirmations); senderToProcurementWebUI.send(syncConfirmationRequest); syncConfirmations.clear(); } /** * Generates a {@link SyncConfirmation} instance to be send either directly after the next commit. */ public void confirm(final IConfirmableDTO syncModel, final String serverEventId) { if (syncModel.getSyncConfirmationId() <= 0) { return; // nothing to do } final SyncConfirmation syncConfirmation = SyncConfirmation.forConfirmId(syncModel.getSyncConfirmationId()); syncConfirmation.setDateConfirmed(SystemTime.asDate()); syncConfirmation.setServerEventId(serverEventId); syncConfirmations.add(syncConfirmation); if (autoSendAfterEachConfirm) { send(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncConfirmationsSender.java
1
请在Spring Boot框架中完成以下Java代码
public class BookManager { private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM"); private AtomicInteger bookIdGenerator = new AtomicInteger(0); private ConcurrentMap<String, Book> inMemoryStore = new ConcurrentHashMap<>(); public BookManager() { Book book = new Book(); book.setId(getNextId()); book.setName("Building Microservice With Eclipse MicroProfile"); book.setIsbn("1"); book.setAuthor("baeldung"); book.setPages(420); inMemoryStore.put(book.getId(), book); } private String getNextId() { String date = LocalDate.now().format(formatter); return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date); }
public String add(Book book) { String id = getNextId(); book.setId(id); inMemoryStore.put(id, book); return id; } public Book get(String id) { return inMemoryStore.get(id); } public List<Book> getAll() { List<Book> books = new ArrayList<>(); books.addAll(inMemoryStore.values()); return books; } }
repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\repo\BookManager.java
2
请完成以下Java代码
public int getAD_Form_ID () { return p_AD_Form_ID; } // getAD_Window_ID public int getWindowNo() { return m_WindowNo; } /** * @return Returns the manuBar */ public JMenuBar getMenu() {
return menuBar; } public void showFormWindow() { if (m_panel instanceof FormPanel2) { ((FormPanel2)m_panel).showFormWindow(m_WindowNo, this); } else { AEnv.showCenterScreenOrMaximized(this); } } } // FormFrame
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java
1
请完成以下Java代码
public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set AD_Role_OrgAccess. @param AD_Role_OrgAccess_ID AD_Role_OrgAccess */ @Override public void setAD_Role_OrgAccess_ID (int AD_Role_OrgAccess_ID) { if (AD_Role_OrgAccess_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, Integer.valueOf(AD_Role_OrgAccess_ID)); } /** Get AD_Role_OrgAccess. @return AD_Role_OrgAccess */ @Override public int getAD_Role_OrgAccess_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_OrgAccess_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Schreibgeschützt. @param IsReadOnly
Field is read only */ @Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt. @return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_OrgAccess.java
1
请完成以下Java代码
public void setDK_Sender_ZipCode (java.lang.String DK_Sender_ZipCode) { set_Value (COLUMNNAME_DK_Sender_ZipCode, DK_Sender_ZipCode); } /** Get Absender PLZ. @return Postleitzahl */ @Override public java.lang.String getDK_Sender_ZipCode () { return (java.lang.String)get_Value(COLUMNNAME_DK_Sender_ZipCode); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override
public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Transport Auftrag. @param M_ShipperTransportation_ID Transport Auftrag */ @Override public void setM_ShipperTransportation_ID (int M_ShipperTransportation_ID) { if (M_ShipperTransportation_ID < 1) set_Value (COLUMNNAME_M_ShipperTransportation_ID, null); else set_Value (COLUMNNAME_M_ShipperTransportation_ID, Integer.valueOf(M_ShipperTransportation_ID)); } /** Get Transport Auftrag. @return Transport Auftrag */ @Override public int getM_ShipperTransportation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipperTransportation_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrder.java
1
请完成以下Java代码
public class ModifyCaseInstanceStartEventSubscriptionCmd extends AbstractCaseStartEventSubscriptionCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected final CaseInstanceStartEventSubscriptionModificationBuilderImpl builder; public ModifyCaseInstanceStartEventSubscriptionCmd(CaseInstanceStartEventSubscriptionModificationBuilderImpl builder) { this.builder = builder; } @Override public Void execute(CommandContext commandContext) { CaseDefinition newCaseDefinition; if (builder.hasNewCaseDefinitionId()) { newCaseDefinition = getCaseDefinitionById(builder.getNewCaseDefinitionId(), commandContext); } else { // no explicit case definition provided, so use latest one CaseDefinition caseDefinition = getCaseDefinitionById(builder.getCaseDefinitionId(), commandContext); newCaseDefinition = getLatestCaseDefinitionByKey(caseDefinition.getKey(), caseDefinition.getTenantId(), commandContext); } if (newCaseDefinition == null) { throw new FlowableIllegalArgumentException("Cannot find case definition with id " + (builder.hasNewCaseDefinitionId() ? builder.getNewCaseDefinitionId() : builder.getCaseDefinitionId())); } Case caze = getCase(newCaseDefinition.getId(), commandContext);
String eventDefinitionKey = caze.getStartEventType(); String startCorrelationConfiguration = getStartCorrelationConfiguration(newCaseDefinition.getId(), commandContext); if (eventDefinitionKey != null && Objects.equals(startCorrelationConfiguration, CmmnXmlConstants.START_EVENT_CORRELATION_MANUAL)) { String correlationKey = null; if (builder.hasCorrelationParameterValues()) { correlationKey = generateCorrelationConfiguration(eventDefinitionKey, builder.getTenantId(), builder.getCorrelationParameterValues(), commandContext); } getEventSubscriptionService(commandContext).updateEventSubscriptionScopeDefinitionId(builder.getCaseDefinitionId(), newCaseDefinition.getId(), eventDefinitionKey, null, correlationKey); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ModifyCaseInstanceStartEventSubscriptionCmd.java
1
请完成以下Java代码
public static class BaeldungHandler extends DefaultHandler { private static final String ARTICLES = "articles"; private static final String ARTICLE = "article"; private static final String TITLE = "title"; private static final String CONTENT = "content"; private Baeldung website; private StringBuilder elementValue; @Override public void characters(char[] ch, int start, int length) throws SAXException { if (elementValue == null) { elementValue = new StringBuilder(); } else { elementValue.append(ch, start, length); } } @Override public void startDocument() throws SAXException { website = new Baeldung(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch (qName) { case ARTICLES: website.setArticleList(new ArrayList<>()); break; case ARTICLE: website.getArticleList().add(new BaeldungArticle()); break; case TITLE: elementValue = new StringBuilder(); break; case CONTENT: elementValue = new StringBuilder(); break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { switch (qName) { case TITLE: latestArticle().setTitle(elementValue.toString()); break; case CONTENT: latestArticle().setContent(elementValue.toString()); break; } } private BaeldungArticle latestArticle() { List<BaeldungArticle> articleList = website.getArticleList(); int latestArticleIndex = articleList.size() - 1; return articleList.get(latestArticleIndex); }
public Baeldung getWebsite() { return website; } } public static class Baeldung { private List<BaeldungArticle> articleList; public void setArticleList(List<BaeldungArticle> articleList) { this.articleList = articleList; } public List<BaeldungArticle> getArticleList() { return this.articleList; } } public static class BaeldungArticle { private String title; private String content; public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\sax\SaxParserMain.java
1
请完成以下Java代码
public PageData<DeviceIdInfo> findDeviceIdInfos(PageLink pageLink) { log.debug("Try to find tenant device id infos by pageLink [{}]", pageLink); return nativeDeviceRepository.findDeviceIdInfos(DaoUtil.toPageable(pageLink)); } @Override public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(PageLink pageLink) { log.debug("Find profile device id infos by pageLink [{}]", pageLink); return nativeDeviceRepository.findProfileEntityIdInfos(DaoUtil.toPageable(pageLink)); } @Override public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, PageLink pageLink) { log.debug("Find profile device id infos by tenantId[{}], pageLink [{}]", tenantId, pageLink); return nativeDeviceRepository.findProfileEntityIdInfosByTenantId(tenantId, DaoUtil.toPageable(pageLink)); } @Override public Device findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(deviceRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public Device findByTenantIdAndName(UUID tenantId, String name) { return findDeviceByTenantIdAndName(tenantId, name).orElse(null); } @Override public PageData<Device> findByTenantId(UUID tenantId, PageLink pageLink) { return findDevicesByTenantId(tenantId, pageLink); } @Override public DeviceId getExternalIdByInternal(DeviceId internalId) { return Optional.ofNullable(deviceRepository.getExternalIdById(internalId.getId())) .map(DeviceId::new).orElse(null); }
@Override public PageData<Device> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<DeviceFields> findNextBatch(UUID id, int batchSize) { return deviceRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.DEVICE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceDao.java
1
请完成以下Java代码
public class ReactivatePlanItemInstanceOperation extends AbstractChangePlanItemInstanceStateOperation { public ReactivatePlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { super(commandContext, planItemInstanceEntity); } @Override protected void internalExecute() { CmmnHistoryManager cmmnHistoryManager = CommandContextUtil.getCmmnHistoryManager(commandContext); cmmnHistoryManager.recordPlanItemInstanceReactivated(planItemInstanceEntity); // Extending classes might override getNewState, so need to check the available state again if (getNewState().equals(PlanItemInstanceState.AVAILABLE)) { planItemInstanceEntity.setLastAvailableTime(getCurrentTime(commandContext)); cmmnHistoryManager.recordPlanItemInstanceAvailable(planItemInstanceEntity); } } @Override public String getNewState() { if (isEventListenerWithAvailableCondition(planItemInstanceEntity.getPlanItem())) { // We need a specific treatment of the reactivation event listener as it also has a condition to avoid being available at active state of the case, // but when reactivating its plan item to actually trigger a case reactivation, we need to ignore that condition and directly go to available state
// to trigger the case reactivation if (planItemInstanceEntity.getPlanItemDefinition() != null && planItemInstanceEntity.getPlanItemDefinition() instanceof ReactivateEventListener) { return PlanItemInstanceState.AVAILABLE; } return PlanItemInstanceState.UNAVAILABLE; } else { return PlanItemInstanceState.AVAILABLE; } } @Override public String getLifeCycleTransition() { return PlanItemTransition.REACTIVATE; } @Override public String getOperationName() { return "[Reactivate plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ReactivatePlanItemInstanceOperation.java
1
请完成以下Java代码
public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 为每个请求设置唯一标示到MDC容器中 setMdc(request); try { // 执行后续操作 chain.doFilter(request, response); } finally { try { MDC.remove(MdcConstant.SESSION_KEY); MDC.remove(MdcConstant.REQUEST_KEY); } catch (Exception e) { logger.warn(e.getMessage(), e); } } }
@Override public void init(FilterConfig arg0) throws ServletException { } /** * 为每个请求设置唯一标示到MDC容器中 */ private void setMdc(ServletRequest request) { try { // 设置SessionId String requestId = UUID.randomUUID().toString().replace("-", ""); MDC.put(MdcConstant.SESSION_KEY, "userId"); MDC.put(MdcConstant.REQUEST_KEY, requestId); } catch (Exception e) { logger.warn(e.getMessage(), e); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\interceptors\TrackFilter.java
1
请在Spring Boot框架中完成以下Java代码
public List<Map<String, VariableValueDto>> evaluateDecision(UriInfo context, EvaluateDecisionDto parameters) { DecisionService decisionService = engine.getDecisionService(); Map<String, Object> variables = VariableValueDto.toMap(parameters.getVariables(), engine, objectMapper); try { DmnDecisionResult decisionResult = decisionService .evaluateDecisionById(decisionDefinitionId) .variables(variables) .evaluate(); return createDecisionResultDto(decisionResult); } catch (AuthorizationException e) { throw e; } catch (NotFoundException e) { String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); throw new InvalidRequestException(Status.NOT_FOUND, e, errorMessage); } catch (NotValidException e) { String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); throw new InvalidRequestException(Status.BAD_REQUEST, e, errorMessage); } catch (ProcessEngineException e) { String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); } catch (DmnEngineException e) { String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); } }
@Override public void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto) { engine.getRepositoryService().updateDecisionDefinitionHistoryTimeToLive(decisionDefinitionId, historyTimeToLiveDto.getHistoryTimeToLive()); } protected List<Map<String, VariableValueDto>> createDecisionResultDto(DmnDecisionResult decisionResult) { List<Map<String, VariableValueDto>> dto = new ArrayList<>(); for (DmnDecisionResultEntries entries : decisionResult) { Map<String, VariableValueDto> resultEntriesDto = createResultEntriesDto(entries); dto.add(resultEntriesDto); } return dto; } protected Map<String, VariableValueDto> createResultEntriesDto(DmnDecisionResultEntries entries) { VariableMap variableMap = Variables.createVariables(); for(String key : entries.keySet()) { TypedValue typedValue = entries.getEntryTyped(key); variableMap.putValueTyped(key, typedValue); } return VariableValueDto.fromMap(variableMap); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DecisionDefinitionResourceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public ApplicationRunner runRequestResponseModel(MessageClient client) { return args -> { client.sendMessage(Mono.just("Request-Response test ")) .doOnNext(message -> { System.out.println("Response is :" + message); }) .subscribe(); }; } @Bean public ApplicationRunner runStreamModel(MessageClient client) { return args -> { client.Counter() .doOnNext(t -> { System.out.println("message is :" + t); }) .subscribe(); }; }
@Bean public ApplicationRunner runFireAndForget(MessageClient client) { return args -> { client.Warning(Mono.just("Important Warning")) .subscribe(); }; } @Bean public ApplicationRunner runChannel(MessageClient client) { return args -> { client.channel(Flux.just("a", "b", "c", "d", "e")) .doOnNext(i -> { System.out.println(i); }) .subscribe(); }; } }
repos\tutorials-master\spring-reactive-modules\spring-6-rsocket\src\main\java\com\baeldung\rsocket\responder\RSocketApplication.java
2
请在Spring Boot框架中完成以下Java代码
public Collection<Class<? extends ShipmentScheduleCreatedEvent>> getHandledEventType() { return ImmutableList.of(ShipmentScheduleCreatedEvent.class); } /** * Checks for an existing candidate that might have been left over after a shipment schedule deletion, and creates/updates the dispo. */ @Override public void handleEvent(@NonNull final ShipmentScheduleCreatedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.forDocumentLine(event.getDocumentLineDescriptor()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final DemandDetail demandDetail = DemandDetail.forDocumentLine( event.getShipmentScheduleId(), event.getDocumentLineDescriptor(), event.getMaterialDescriptor().getQuantity()); final CandidateBuilder candidateBuilder = Candidate
.builderForEventDescriptor(event.getEventDescriptor()) .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .businessCaseDetail(demandDetail); final Candidate existingCandidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); if (existingCandidate != null) { candidateBuilder.id(existingCandidate.getId()); } final Candidate candidate = candidateBuilder.build(); candidateChangeHandler.onCandidateNewOrChange(candidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleCreatedHandler.java
2
请完成以下Java代码
class RockPaperScissorsGame { enum Move { ROCK("rock"), PAPER("paper"), SCISSORS("scissors"); private String value; Move(String value) { this.value = value; } public String getValue() { return value; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int wins = 0; int losses = 0; System.out.println("Welcome to Rock-Paper-Scissors! Please enter \"rock\", \"paper\", \"scissors\", or \"quit\" to exit."); while (true) { System.out.println("-------------------------"); System.out.print("Enter your move: "); String playerMove = scanner.nextLine(); if (playerMove.equals("quit")) { System.out.println("You won " + wins + " times and lost " + losses + " times."); System.out.println("Thanks for playing! See you again."); break; }
if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) { System.out.println("Your move isn't valid!"); continue; } String computerMove = getComputerMove(); if (playerMove.equals(computerMove)) { System.out.println("It's a tie!"); } else if (isPlayerWin(playerMove, computerMove)) { System.out.println("You won!"); wins++; } else { System.out.println("You lost!"); losses++; } } } private static boolean isPlayerWin(String playerMove, String computerMove) { return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value) || (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value)) || (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value)); } private static String getComputerMove() { Random random = new Random(); int randomNumber = random.nextInt(3); String computerMove = Move.values()[randomNumber].getValue(); System.out.println("Computer move: " + computerMove); return computerMove; } }
repos\tutorials-master\core-java-modules\core-java-8-2\src\main\java\com\baeldung\game\RockPaperScissorsGame.java
1
请完成以下Java代码
public void processShipperTransportation(@NonNull final ShipperTransportationId shipperTransportationId) { final I_M_ShipperTransportation shipperTransportation = getById(shipperTransportationId); docActionBL.processEx(shipperTransportation, IDocument.ACTION_Complete); } private BPartnerLocationAndCaptureId getShipFromBPartnerAndLocation(final I_M_InOut shipment) { final WarehouseId warehouseId = WarehouseId.ofRepoId(shipment.getM_Warehouse_ID()); return warehouseDAO.getWarehouseLocationById(warehouseId); } @NonNull private List<CreatePackagesRequest> buildCreatePackageRequest( @NonNull final ShipperId shipperId, @NonNull final CreatePackagesForInOutRequest request, @NonNull final ShippingWeightCalculator weightCalculator) { if (Check.isEmpty(request.getPackageInfos())) { return huInOutDAO.retrieveShippedHandlingUnits(request.getShipment()) .stream() .map(hu -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) .weightInKg(weightCalculator.calculateWeightInKg(hu) .map(weight -> weight.toBigDecimal()) .orElse(null)) .packageDimensions(extractPackageDimensions(hu)) .build()) .collect(Collectors.toList()); } else { return request.getPackageInfos() .stream() .map(packageInfo -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) // .trackingCode(packageInfo.getTrackingNumber()) .trackingURL(packageInfo.getTrackingUrl()) .weightInKg(packageInfo.getWeight()) .packageDimensions(packageInfo.getPackageDimensions()) .build() ) .collect(ImmutableList.toImmutableList()); } } private PackageDimensions extractPackageDimensions(final I_M_HU hu) { final PackageDimensions packageDimensions = huPackageBL.getPackageDimensions(hu);
if (packageDimensions.isUnspecified()) { throw new AdempiereException(MSG_CANNOT_DETERMINE_HU_PACKAGE_DIMENSIONS, hu.getM_HU_ID()); } return packageDimensions; } private void linkTransportationToShipment(@NonNull final I_M_InOut shipment, @NonNull final ShipperTransportationId shipperTransportationId) { final de.metas.inout.model.I_M_InOut inOutShipment = InterfaceWrapperHelper.create(shipment, de.metas.inout.model.I_M_InOut.class); inOutShipment.setM_ShipperTransportation_ID(shipperTransportationId.getRepoId()); inOutDAO.save(inOutShipment); } private ShippingWeightCalculator newWeightCalculator() { return ShippingWeightCalculator.builder() .weightSourceTypes(getWeightsSourceTypes()) .build(); } private ShippingWeightSourceTypes getWeightsSourceTypes() { return ShippingWeightSourceTypes.ofCommaSeparatedString(sysConfigBL.getValue(SYSCONFIG_WeightSourceTypes)).orElse(ShippingWeightSourceTypes.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\impl\HUShipperTransportationBL.java
1
请完成以下Java代码
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } /** Set Nutzer 1. @param User1_ID User defined list element #1 */ @Override public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get Nutzer 1. @return User defined list element #1 */ @Override public int getUser1_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } /** Set Nutzer 2. @param User2_ID User defined list element #2 */ @Override public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get Nutzer 2. @return User defined list element #2 */ @Override public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_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_M_Movement.java
1
请在Spring Boot框架中完成以下Java代码
private void importBPartner(@NonNull final Exchange exchange) { final JsonRequestBPartnerUpsertItem upsertItem = exchange.getIn().getBody(JsonRequestBPartnerUpsertItem.class); if (upsertItem == null) { throw new RuntimeCamelException("Missing exchange body! No JsonRequestBPartnerUpsertItem found!"); } final String orgCode = ProcessorHelper.getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_ORG_CODE, String.class); final JsonRequestBPartnerUpsert bPartnerUpsert = JsonRequestBPartnerUpsert.builder() .requestItem(upsertItem) .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .build(); final BPUpsertCamelRequest bpUpsertCamelRequest = BPUpsertCamelRequest.builder() .jsonRequestBPartnerUpsert(bPartnerUpsert) .orgCode(orgCode) .build(); exchange.getIn().setBody(bpUpsertCamelRequest); } private void gatherBPartnerResponseItems(@NonNull final Exchange exchange) { final JsonResponseBPartnerCompositeUpsert bPartnerUpsertResult = exchange.getIn().getBody(JsonResponseBPartnerCompositeUpsert.class);
if (bPartnerUpsertResult == null) { throw new RuntimeCamelException("Missing exchange body! No JsonResponseBPartnerCompositeUpsert found!"); } final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); routeContext.addResponseItems(bPartnerUpsertResult.getResponseItems()); } private void cleanupResponseItems(@NonNull final Exchange exchange) { final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); routeContext.removeAllResponseItems(); } private void resetBodyToJsonExternalRequest(@NonNull final Exchange exchange) { final GetPatientsRouteContext routeContext = ProcessorHelper .getPropertyOrThrowError(exchange, GetPatientsRouteConstants.ROUTE_PROPERTY_GET_PATIENTS_CONTEXT, GetPatientsRouteContext.class); exchange.getIn().setBody(routeContext.getRequest()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\GetAlbertaPatientsRoute.java
2
请完成以下Java代码
public class X_M_CostType extends org.compiere.model.PO implements I_M_CostType, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 738739634L; /** Standard Constructor */ public X_M_CostType (Properties ctx, int M_CostType_ID, String trxName) { super (ctx, M_CostType_ID, trxName); /** if (M_CostType_ID == 0) { setM_CostType_ID (0); setName (null); } */ } /** Load Constructor */ public X_M_CostType (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Kommentar/Hilfe. @param Help Comment or Hint */ @Override public void setHelp (java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Kommentar/Hilfe. @return Comment or Hint */ @Override public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Kostenkategorie.
@param M_CostType_ID Type of Cost (e.g. Current, Plan, Future) */ @Override public void setM_CostType_ID (int M_CostType_ID) { if (M_CostType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID)); } /** Get Kostenkategorie. @return Type of Cost (e.g. Current, Plan, Future) */ @Override public int getM_CostType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostType.java
1
请完成以下Java代码
public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { throw new IllegalArgumentException ("M_Product_ID is virtual column"); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSerialNo (final @Nullable java.lang.String SerialNo) { throw new IllegalArgumentException ("SerialNo is virtual column"); } @Override public java.lang.String getSerialNo() { return get_ValueAsString(COLUMNNAME_SerialNo); } @Override public void setServiceContract (final @Nullable java.lang.String ServiceContract) {
throw new IllegalArgumentException ("ServiceContract is virtual column"); } @Override public java.lang.String getServiceContract() { return get_ValueAsString(COLUMNNAME_ServiceContract); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getLockDuration() { return lockDuration; } public void setLockDuration(Duration lockDuration) { this.lockDuration = lockDuration; } public int getNumberOfTasks() { return numberOfTasks; } public void setNumberOfTasks(int numberOfTasks) { this.numberOfTasks = numberOfTasks; } public int getNumberOfRetries() { return numberOfRetries; } public void setNumberOfRetries(int numberOfRetries) { this.numberOfRetries = numberOfRetries; }
public String getWorkerId() { return workerId; } public void setWorkerId(String workerId) { this.workerId = workerId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\AcquireExternalWorkerJobRequest.java
2
请完成以下Java代码
public Class<? extends IdentityInfoEntity> getManagedEntityClass() { return IdentityInfoEntityImpl.class; } @Override public IdentityInfoEntity create() { return new IdentityInfoEntityImpl(); } @Override public List<IdentityInfoEntity> findIdentityInfoDetails(String identityInfoId) { return getDbSqlSession().getSqlSession().selectList("selectIdentityInfoDetails", identityInfoId); } @Override @SuppressWarnings("unchecked") public List<IdentityInfoEntity> findIdentityInfoByUserId(String userId) { return getDbSqlSession().selectList("selectIdentityInfoByUserId", userId); }
@Override public IdentityInfoEntity findUserInfoByUserIdAndKey(String userId, String key) { Map<String, String> parameters = new HashMap<>(); parameters.put("userId", userId); parameters.put("key", key); return (IdentityInfoEntity) getDbSqlSession().selectOne("selectIdentityInfoByUserIdAndKey", parameters); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public List<String> findUserInfoKeysByUserIdAndType(String userId, String type) { Map<String, String> parameters = new HashMap<>(); parameters.put("userId", userId); parameters.put("type", type); return (List) getDbSqlSession().getSqlSession().selectList("selectIdentityInfoKeysByUserIdAndType", parameters); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\data\impl\MybatisIdentityInfoDataManager.java
1
请完成以下Java代码
public class Article extends PanacheMongoEntityBase { @BsonId private ObjectId id; private String author; private String title; private String description; // Getters and setters public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\quarkus-modules\mongo-db\src\main\java\com\baeldung\panache\Article.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentServiceConfiguration { private final ShippingHeaderTypesProperties typesProperties; private final SqsAsyncClient sqsAsyncClient; public ShipmentServiceConfiguration(ShippingHeaderTypesProperties typesProperties, SqsAsyncClient sqsAsyncClient) { this.typesProperties = typesProperties; this.sqsAsyncClient = sqsAsyncClient; } @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); JavaTimeModule module = new JavaTimeModule(); LocalDateDeserializer customDeserializer = new LocalDateDeserializer(DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.getDefault())); module.addDeserializer(LocalDate.class, customDeserializer); mapper.registerModule(module); return mapper; } @Bean public SqsMessageListenerContainerFactory<?> defaultSqsListenerContainerFactory(ObjectMapper objectMapper) { SqsMessagingMessageConverter converter = new SqsMessagingMessageConverter(); converter.setPayloadTypeMapper(message -> { if (!message.getHeaders() .containsKey(typesProperties.getHeaderName())) { return Object.class; }
String eventTypeHeader = MessageHeaderUtils.getHeaderAsString(message, typesProperties.getHeaderName()); if (eventTypeHeader.equals(typesProperties.getDomestic())) { return DomesticShipmentRequestedEvent.class; } else if (eventTypeHeader.equals(typesProperties.getInternational())) { return InternationalShipmentRequestedEvent.class; } throw new RuntimeException("Invalid shipping type"); }); converter.setObjectMapper(objectMapper); return SqsMessageListenerContainerFactory.builder() .sqsAsyncClient(sqsAsyncClient) .configure(configure -> configure.messageConverter(converter)) .build(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\conversion\configuration\ShipmentServiceConfiguration.java
2
请完成以下Java代码
static boolean isOdd(int x) { return x % 2 != 0; } static boolean isOrEven(int x) { return (x | 1) > x; } static boolean isOrOdd(int x) { return (x | 1) == x; } static boolean isAndEven(int x) { return (x & 1) == 0; } static boolean isAndOdd(int x) { return (x & 1) == 1; }
static boolean isXorEven(int x) { return (x ^ 1) > x; } static boolean isXorOdd(int x) { return (x ^ 1) < x; } static boolean isLsbEven(int x) { return Integer.toBinaryString(x) .endsWith("0"); } static boolean isLsbOdd(int x) { return Integer.toBinaryString(x) .endsWith("1"); } }
repos\tutorials-master\core-java-modules\core-java-numbers-5\src\main\java\com\baeldung\evenodd\EvenOdd.java
1
请完成以下Java代码
public long findIncidentCountByQueryCriteria(IncidentQueryImpl incidentQuery) { configureQuery(incidentQuery); return (Long) getDbEntityManager().selectOne("selectIncidentCountByQueryCriteria", incidentQuery); } public Incident findIncidentById(String id) { return (Incident) getDbEntityManager().selectById(IncidentEntity.class, id); } public List<Incident> findIncidentByConfiguration(String configuration) { return findIncidentByConfigurationAndIncidentType(configuration, null); } @SuppressWarnings("unchecked") public List<Incident> findIncidentByConfigurationAndIncidentType(String configuration, String incidentType) { Map<String,Object> params = new HashMap<String, Object>();
params.put("configuration", configuration); params.put("incidentType", incidentType); return getDbEntityManager().selectList("selectIncidentsByConfiguration", params); } @SuppressWarnings("unchecked") public List<Incident> findIncidentByQueryCriteria(IncidentQueryImpl incidentQuery, Page page) { configureQuery(incidentQuery); return getDbEntityManager().selectList("selectIncidentByQueryCriteria", incidentQuery, page); } protected void configureQuery(IncidentQueryImpl query) { getAuthorizationManager().configureIncidentQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentManager.java
1
请完成以下Java代码
public IAttributeValueGenerator getAttributeValueGeneratorOrNull() { return null; } @Override public void removeAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public boolean isReadonlyUI() { return true; } @Override public boolean isDisplayedUI() { return false; } @Override public boolean isMandatory() { return false; } @Override public int getDisplaySeqNo() { return 0;
} @Override public NamePair getNullAttributeValue() { return null; } /** * @return true; we consider Null attributes as always generated */ @Override public boolean isNew() { return true; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
static class JmxJacksonEndpointConfiguration { @Bean @ConditionalOnSingleCandidate(MBeanServer.class) JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<JsonMapper> jsonMapper, JmxEndpointsSupplier jmxEndpointsSupplier) { JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper( jsonMapper.getIfAvailable()); return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper, jmxEndpointsSupplier.getEndpoints()); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ObjectMapper.class) @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") @Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal") static class JmxJackson2EndpointConfiguration { @Bean @ConditionalOnSingleCandidate(MBeanServer.class) JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer, EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<ObjectMapper> objectMapper, JmxEndpointsSupplier jmxEndpointsSupplier) { JmxOperationResponseMapper responseMapper = new org.springframework.boot.actuate.endpoint.jmx.Jackson2JmxOperationResponseMapper( objectMapper.getIfAvailable()); return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper, jmxEndpointsSupplier.getEndpoints()); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\JmxEndpointAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class RecordAccess { @JsonProperty("recordRef") TableRecordReference recordRef; @JsonProperty("principal") Principal principal; @JsonProperty("permission") Access permission; @JsonProperty("issuer") PermissionIssuer issuer; @JsonProperty("createdBy") UserId createdBy; @JsonProperty("description") String description; @JsonProperty("id") @NonFinal RecordAccessId id; @JsonProperty("parentId") RecordAccessId parentId; @JsonProperty("rootId") @NonFinal RecordAccessId rootId; @Builder(toBuilder = true) @JsonCreator private RecordAccess( @JsonProperty("recordRef") @NonNull final TableRecordReference recordRef, @JsonProperty("principal") @NonNull final Principal principal, @JsonProperty("permission") @NonNull final Access permission, @JsonProperty("issuer") @NonNull final PermissionIssuer issuer, @JsonProperty("createdBy") @NonNull final UserId createdBy, @JsonProperty("description") @Nullable final String description, // @JsonProperty("id") @Nullable final RecordAccessId id, @JsonProperty("parentId") @Nullable final RecordAccessId parentId, @JsonProperty("rootId") @Nullable final RecordAccessId rootId) {
this.recordRef = recordRef; this.principal = principal; this.permission = permission; this.issuer = issuer; this.createdBy = createdBy; this.description = description; this.id = id; this.parentId = parentId; this.rootId = rootId; } void setId(@NonNull final RecordAccessId id) { this.id = id; } void setRootId(final RecordAccessId rootId) { this.rootId = rootId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccess.java
2
请在Spring Boot框架中完成以下Java代码
public Payer getPayer(String albertaApiKey, String _id) throws ApiException { ApiResponse<Payer> resp = getPayerWithHttpInfo(albertaApiKey, _id); return resp.getData(); } /** * Daten eines einzelnen Kostenträgers abrufen * Szenario - das WaWi fragt bei Alberta nach, wie die Daten des Kostenträgers mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id des Kostenträgers - bei Selbstzahlern, die des Patienten (required) * @return ApiResponse&lt;Payer&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<Payer> getPayerWithHttpInfo(String albertaApiKey, String _id) throws ApiException { com.squareup.okhttp.Call call = getPayerValidateBeforeCall(albertaApiKey, _id, null, null); Type localVarReturnType = new TypeToken<Payer>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Daten eines einzelnen Kostenträgers abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, wie die Daten des Kostenträgers mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id des Kostenträgers - bei Selbstzahlern, die des Patienten (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getPayerAsync(String albertaApiKey, String _id, final ApiCallback<Payer> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() {
@Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getPayerValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<Payer>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\PayerApi.java
2
请在Spring Boot框架中完成以下Java代码
public Result<SysRoleIndex> queryDefIndex() { SysRoleIndex defIndexCfg = sysRoleIndexService.queryDefaultIndex(); return Result.OK(defIndexCfg); } /** * 更新默认首页配置 */ @RequiresPermissions("system:permission:setDefIndex") @PutMapping("/updateDefIndex") public Result<?> updateDefIndex( @RequestParam("url") String url, @RequestParam("component") String component, @RequestParam("isRoute") Boolean isRoute ) { boolean success = sysRoleIndexService.updateDefaultIndex(url, component, isRoute); if (success) { return Result.OK("设置成功"); } else { return Result.error("设置失败"); } } /** * 切换默认门户 * * @param sysRoleIndex * @return */ @PostMapping(value = "/changeDefHome") public Result<?> changeDefHome(@RequestBody SysRoleIndex sysRoleIndex,HttpServletRequest request) { String username = JwtUtil.getUserNameByToken(request); sysRoleIndex.setRoleCode(username); sysRoleIndexService.changeDefHome(sysRoleIndex); // 代码逻辑说明: 切换完成后的homePath获取 String version = request.getHeader(CommonConstant.VERSION); String homePath = null; SysRoleIndex defIndexCfg = sysUserService.getDynamicIndexByUserRole(username, version); if (defIndexCfg == null) { defIndexCfg = sysRoleIndexService.initDefaultIndex(); } if (oConvertUtils.isNotEmpty(version) && defIndexCfg != null && oConvertUtils.isNotEmpty(defIndexCfg.getUrl())) { homePath = defIndexCfg.getUrl(); if (!homePath.startsWith(SymbolConstant.SINGLE_SLASH)) { homePath = SymbolConstant.SINGLE_SLASH + homePath; }
} return Result.OK(homePath); } /** * 获取门户类型 * * @return */ @GetMapping(value = "/getCurrentHome") public Result<?> getCurrentHome(HttpServletRequest request) { String username = JwtUtil.getUserNameByToken(request); Object homeType = redisUtil.get(DefIndexConst.CACHE_TYPE + username); return Result.OK(oConvertUtils.getString(homeType,DefIndexConst.HOME_TYPE_MENU)); } /** * 清除缓存 * * @return */ @RequestMapping(value = "/cleanDefaultIndexCache") public Result<?> cleanDefaultIndexCache(HttpServletRequest request) { sysRoleIndexService.cleanDefaultIndexCache(); return Result.OK(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysRoleIndexController.java
2
请完成以下Spring Boot application配置
management: endpoints: web: exposure: include: 'hystrix.stream' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 spring: application: name: hystrix-demo # 应用名 eureka: cli
ent: service-url: defaultZone: http://127.0.0.1:8761/eureka/ # Eureka-Server 地址
repos\SpringBoot-Labs-master\labx-23\labx-23-scn-hystrix-demo01-cluster\src\main\resources\application.yml
2
请完成以下Java代码
public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getClickCount() { return clickCount; } public void setClickCount(Integer clickCount) { this.clickCount = clickCount; } public Integer getOrderCount() { return orderCount; } public void setOrderCount(Integer orderCount) { this.orderCount = orderCount; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getSort() {
return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(type); sb.append(", pic=").append(pic); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", status=").append(status); sb.append(", clickCount=").append(clickCount); sb.append(", orderCount=").append(orderCount); sb.append(", url=").append(url); sb.append(", note=").append(note); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java
1
请完成以下Java代码
public static void addToken(HttpServletResponse res, String username, String tenant) { String JwtToken = Jwts.builder() .subject(username) .audience().add(tenant).and() .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) .signWith(SIGNINGKEY) .compact(); res.addHeader("Authorization", PREFIX + " " + JwtToken); } public static Authentication getAuthentication(HttpServletRequest req) { String token = req.getHeader("Authorization"); if (token != null) { String user = Jwts.parser() .verifyWith(SIGNINGKEY) .build().parseClaimsJws(token.replace(PREFIX, "").trim()).getPayload() .getSubject(); if (user != null) { return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()); } } return null;
} public static String getTenant(HttpServletRequest req) { String token = req.getHeader("Authorization"); if (token == null) { return null; } String tenant = Jwts.parser() .setSigningKey(SIGNINGKEY) .build().parseClaimsJws(token.replace(PREFIX, "").trim()) .getBody() .getAudience() .iterator() .next(); return tenant; } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\security\AuthenticationService.java
1
请完成以下Java代码
private List<PrintingQueueQueryRequest> getPrintingQueueQueryBuilders() { final Map<String, String> filtersMap = sysConfigBL.getValuesForPrefix(QUERY_PREFIX, clientAndOrgId); final Collection<String> keys = filtersMap.keySet(); final ArrayList<PrintingQueueQueryRequest> queries = new ArrayList<>(); for (final String key : keys) { final String whereClause = filtersMap.get(key); final IQuery<I_C_Printing_Queue> query = createPrintingQueueQuery(whereClause); final PrintingQueueQueryRequest request = PrintingQueueQueryRequest.builder() .queryName(key) .query(query) .build(); queries.add(request); } return queries;
} private IQuery<I_C_Printing_Queue> createPrintingQueueQuery(@NonNull final String whereClause) { return queryBL .createQueryBuilder(I_C_Printing_Queue.class) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId()) .addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, printingQueueItemsGeneratedAsyncBatchId) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false) .filter(TypedSqlQueryFilter.of(whereClause)) .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\ConcatenatePDFsCommand.java
1
请完成以下Java代码
public class PackageDimensions { private static final int UNSPECIFIED_DIMENSION = -1; public static final PackageDimensions UNSPECIFIED = new PackageDimensions(UNSPECIFIED_DIMENSION, UNSPECIFIED_DIMENSION, UNSPECIFIED_DIMENSION); int lengthInCM; int widthInCM; int heightInCM; /** * Note: dimensionsInCM may be <= 0 which can stand for "not specified". */ @Builder @Jacksonized private PackageDimensions(final int lengthInCM, final int widthInCM, final int heightInCM) { this.lengthInCM = lengthInCM; this.widthInCM = widthInCM; this.heightInCM = heightInCM; } @JsonIgnore public boolean isUnspecified() { return UNSPECIFIED.equals(this);
} public static PackageDimensions ofProductDimensionsAndQty(@NonNull final PackageDimensions packageDimensions, @NonNull final Quantity qtyInStockingUOM) { final List<Integer> dimensions = new ArrayList<>(); dimensions.add(packageDimensions.getHeightInCM()); dimensions.add(packageDimensions.getWidthInCM()); dimensions.add(packageDimensions.getLengthInCM()); dimensions.sort(null); final int qtyRoundedUpInStockUOM = qtyInStockingUOM.toBigDecimal().setScale(0, RoundingMode.CEILING).intValue(); return PackageDimensions.builder() .lengthInCM(dimensions.get(0) * qtyRoundedUpInStockUOM) .heightInCM(dimensions.get(1)) .widthInCM(dimensions.get(2)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\PackageDimensions.java
1
请完成以下Java代码
private boolean hasOperations(ExposableJmxEndpoint endpoint) { return !CollectionUtils.isEmpty(endpoint.getOperations()); } private ObjectName register(ExposableJmxEndpoint endpoint) { Assert.notNull(endpoint, "'endpoint' must not be null"); try { ObjectName name = this.objectNameFactory.getObjectName(endpoint); EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, endpoint); this.mBeanServer.registerMBean(mbean, name); return name; } catch (MalformedObjectNameException ex) { throw new IllegalStateException("Invalid ObjectName for " + getEndpointDescription(endpoint), ex); } catch (Exception ex) { throw new MBeanExportException("Failed to register MBean for " + getEndpointDescription(endpoint), ex); } } private void unregister(Collection<ObjectName> objectNames) { objectNames.forEach(this::unregister); }
private void unregister(ObjectName objectName) { try { if (logger.isDebugEnabled()) { logger.debug("Unregister endpoint with ObjectName '" + objectName + "' from the JMX domain"); } this.mBeanServer.unregisterMBean(objectName); } catch (InstanceNotFoundException ex) { // Ignore and continue } catch (MBeanRegistrationException ex) { throw new JmxException("Failed to unregister MBean with ObjectName '" + objectName + "'", ex); } } private String getEndpointDescription(ExposableJmxEndpoint endpoint) { return "endpoint '" + endpoint.getEndpointId() + "'"; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\JmxEndpointExporter.java
1
请完成以下Java代码
private int getAD_Column_ID() { // not set is allowed return AD_Column_ID; } /** * @param AD_Column_ID Column for lookups. */ public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener) { this.editorListener = listener;
return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请完成以下Java代码
public class AuthorDto implements Serializable { private static final long serialVersionUID = 1L; private String nickname; private int age; public AuthorDto() { } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname;
} public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "AuthorDto{" + "nickname=" + nickname + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCallStoredProcedureJdbcTemplateBeanPropertyRowMapper\src\main\java\com\bookstore\dto\AuthorDto.java
1
请完成以下Java代码
public SequenceType1Code getSeqTp() { return seqTp; } /** * Sets the value of the seqTp property. * * @param value * allowed object is * {@link SequenceType1Code } * */ public void setSeqTp(SequenceType1Code value) { this.seqTp = value; } /** * Gets the value of the ctgyPurp property. * * @return * possible object is * {@link CategoryPurposeSEPA } * */
public CategoryPurposeSEPA getCtgyPurp() { return ctgyPurp; } /** * Sets the value of the ctgyPurp property. * * @param value * allowed object is * {@link CategoryPurposeSEPA } * */ public void setCtgyPurp(CategoryPurposeSEPA value) { this.ctgyPurp = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentTypeInformationSDD.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getSequenceNoAttr() { return sequenceNoAttr; } /** * Sets the value of the sequenceNoAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setSequenceNoAttr(BigInteger value) { this.sequenceNoAttr = value; } /** * Gets the value of the trxNameAttr property. * * @return * possible object is * {@link String } * */ public String getTrxNameAttr() { return trxNameAttr; } /** * Sets the value of the trxNameAttr property. * * @param value
* allowed object is * {@link String } * */ public void setTrxNameAttr(String value) { this.trxNameAttr = value; } /** * Gets the value of the adSessionIDAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getADSessionIDAttr() { return adSessionIDAttr; } /** * Sets the value of the adSessionIDAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setADSessionIDAttr(BigInteger value) { this.adSessionIDAttr = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCBPartnerProductVType.java
2
请完成以下Java代码
public Object getPersistentState() { // membership is not updatable return MembershipEntityImpl.class; } @Override public String getId() { // membership doesn't have an id, returning a fake one to make the internals work return userId + groupId; } @Override public void setId(String id) { // membership doesn't have an id } @Override public String getUserId() { return userId; }
@Override public void setUserId(String userId) { this.userId = userId; } @Override public String getGroupId() { return groupId; } @Override public void setGroupId(String groupId) { this.groupId = groupId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\MembershipEntityImpl.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_CCM_Bundle_Result[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Bundle Result. @param CCM_Bundle_Result_ID Bundle Result */ public void setCCM_Bundle_Result_ID (int CCM_Bundle_Result_ID) { if (CCM_Bundle_Result_ID < 1) set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, null); else set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, Integer.valueOf(CCM_Bundle_Result_ID)); } /** Get Bundle Result. @return Bundle Result */ public int getCCM_Bundle_Result_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CCM_Bundle_Result_ID); if (ii == null) return 0; return ii.intValue(); } /** CCM_Success AD_Reference_ID=319 */ public static final int CCM_SUCCESS_AD_Reference_ID=319; /** Yes = Y */ public static final String CCM_SUCCESS_Yes = "Y"; /** No = N */ public static final String CCM_SUCCESS_No = "N"; /** Set Is Success. @param CCM_Success Is Success */ public void setCCM_Success (String CCM_Success) { set_Value (COLUMNNAME_CCM_Success, CCM_Success); } /** Get Is Success. @return Is Success */ public String getCCM_Success () { return (String)get_Value(COLUMNNAME_CCM_Success); } /** 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 Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_CCM_Bundle_Result.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(itemId, lineItemId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderLineItems {\n"); sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n"); sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n"); sb.append("}"); return sb.toString(); }
/** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderLineItems.java
2