instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public StandardDocumentReportType getStandardDocumentReportType() { return StandardDocumentReportType.SHIPMENT; } @Override public @NonNull DocumentReportInfo getDocumentReportInfo( @NonNull final TableRecordReference recordRef, @Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse) { final InOutId inoutId = recordRef.getIdAssumingTableName(I_M_InOut.Table_Name, InOutId::ofRepoId); final I_M_InOut inout = inoutBL.getById(inoutId); final BPartnerId bpartnerId = BPartnerId.ofRepoId(inout.getC_BPartner_ID()); final I_C_BPartner bpartner = util.getBPartnerById(bpartnerId); final DocTypeId docTypeId = extractDocTypeId(inout); final I_C_DocType docType = util.getDocTypeById(docTypeId); final ClientId clientId = ClientId.ofRepoId(inout.getAD_Client_ID()); final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers( () -> adPrintFormatToUseId, () -> util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null), () -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()), () -> util.getDefaultPrintFormats(clientId).getShipmentPrintFormatId()); if (printFormatId == null) { throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@"); } final Language language = util.getBPartnerLanguage(bpartner).orElse(null); final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder() .adTableId(recordRef.getAdTableId()) .bpartnerId(bpartnerId) .bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, inout.getC_BPartner_Location_ID())) .docTypeId(docTypeId) .onlyCopiesGreaterZero(true) .build();
return DocumentReportInfo.builder() .recordRef(TableRecordReference.of(I_M_InOut.Table_Name, inoutId)) .reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId)) .copies(util.getDocumentCopies(docType, bpPrintFormatQuery)) .documentNo(inout.getDocumentNo()) .bpartnerId(bpartnerId) .docTypeId(docTypeId) .language(language) .poReference(inout.getPOReference()) .build(); } private DocTypeId extractDocTypeId(@NonNull final I_M_InOut inout) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(inout.getC_DocType_ID()); if (docTypeId != null) { return docTypeId; } else { throw new AdempiereException("No document type set"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\InOutDocumentReportAdvisor.java
1
请在Spring Boot框架中完成以下Java代码
private ClassPathResource asClassPathResource(LocatedResource locatedResource) { Location location = locatedResource.location(); String fileNameWithAbsolutePath = location.getRootPath() + "/" + locatedResource.resource().getFilename(); return new ClassPathResource(location, fileNameWithAbsolutePath, this.classLoader, this.encoding); } private void ensureInitialized() { this.lock.lock(); try { if (!this.initialized) { initialize(); this.initialized = true; } } finally { this.lock.unlock(); } } @SuppressWarnings("deprecation") private void initialize() { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); for (Location location : this.locations) { if (!location.isClassPath()) { continue; } Resource root = resolver.getResource(location.getDescriptor()); if (!root.exists()) {
if (this.failOnMissingLocations) { throw new FlywayException("Location " + location.getDescriptor() + " doesn't exist"); } continue; } Resource[] resources = getResources(resolver, location, root); for (Resource resource : resources) { this.locatedResources.add(new LocatedResource(resource, location)); } } } private Resource[] getResources(PathMatchingResourcePatternResolver resolver, Location location, Resource root) { try { return resolver.getResources(root.getURI() + "/*"); } catch (IOException ex) { throw new UncheckedIOException("Failed to list resources for " + location.getDescriptor(), ex); } } private record LocatedResource(Resource resource, Location location) { } }
repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\NativeImageResourceProvider.java
2
请完成以下Java代码
public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @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(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", level=").append(level); sb.append(", productCount=").append(productCount); sb.append(", productUnit=").append(productUnit); sb.append(", navStatus=").append(navStatus); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", icon=").append(icon); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java
1
请完成以下Java代码
public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setM_CostElement_Acct_ID (final int M_CostElement_Acct_ID) { if (M_CostElement_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_Acct_ID, M_CostElement_Acct_ID); } @Override public int getM_CostElement_Acct_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_Acct_ID); } @Override public org.compiere.model.I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class); } @Override public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
} @Override public org.compiere.model.I_C_ValidCombination getP_CostClearing_A() { return get_ValueAsPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_CostClearing_A(final org.compiere.model.I_C_ValidCombination P_CostClearing_A) { set_ValueFromPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class, P_CostClearing_A); } @Override public void setP_CostClearing_Acct (final int P_CostClearing_Acct) { set_Value (COLUMNNAME_P_CostClearing_Acct, P_CostClearing_Acct); } @Override public int getP_CostClearing_Acct() { return get_ValueAsInt(COLUMNNAME_P_CostClearing_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostElement_Acct.java
1
请完成以下Java代码
public static String getSplitText(List<String> list, String separator) { if (null != list && list.size() > 0) { return StringUtils.join(list, separator); } return ""; } /** * 通过table的条件SQL * * @param tableSql sys_user where name = '1212' * @return name = '1212' */ public static String getFilterSqlByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); if (arr != null && oConvertUtils.isNotEmpty(arr[1])) { return arr[1]; } } return ""; } /** * 通过table获取表名 * * @param tableSql sys_user where name = '1212' * @return sys_user */ public static String getTableNameByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); return arr[0].trim(); } else { return tableSql;
} } /** * 判断两个数组是否存在交集 * @param set1 * @param arr2 * @return */ public static boolean hasIntersection(Set<String> set1, String[] arr2) { if (set1 == null) { return false; } if(set1.size()>0){ for (String str : arr2) { if (set1.contains(str)) { return true; } } } return false; } /** * 输出info日志,会捕获异常,防止因为日志问题导致程序异常 * * @param msg * @param objects */ public static void logInfo(String msg, Object... objects) { try { log.info(msg, objects); } catch (Exception e) { log.warn("{} —— {}", msg, e.getMessage()); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\CommonUtils.java
1
请完成以下Java代码
public AWindow find(final AdWindowId adWindowId) { for (Window w : windows) { if (w instanceof AWindow) { AWindow a = (AWindow)w; if (AdWindowId.equals(a.getAdWindowId(), adWindowId)) { return a; } } } return null; } public FormFrame findForm(int AD_FORM_ID) { for (Window w : windows) { if (w instanceof FormFrame) { FormFrame ff = (FormFrame)w; if (ff.getAD_Form_ID() == AD_FORM_ID) { return ff; } } } return null; } } class WindowEventListener implements ComponentListener, WindowListener { WindowManager windowManager; protected WindowEventListener(WindowManager windowManager) { this.windowManager = windowManager; } @Override public void componentHidden(ComponentEvent e) { Component c = e.getComponent(); if (c instanceof Window) { c.removeComponentListener(this); ((Window)c).removeWindowListener(this); windowManager.remove((Window)c); } } @Override public void componentMoved(ComponentEvent e) { } @Override
public void componentResized(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { Window w = e.getWindow(); if (w instanceof Window) { w.removeComponentListener(this); w.removeWindowListener(this); windowManager.remove(w); } } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java
1
请完成以下Java代码
public void updateActivity(final I_C_InvoiceLine invoiceLine) { if (invoiceLine.getC_Activity_ID() > 0) { return; // was already set, so don't try to auto-fill it } final ProductId productId = ProductId.ofRepoIdOrNull(invoiceLine.getM_Product_ID()); if (productId == null) { return; } final ActivityId productActivityId = productAcctDAO.retrieveActivityForAcct( ClientId.ofRepoId(invoiceLine.getAD_Client_ID()),
OrgId.ofRepoId(invoiceLine.getAD_Org_ID()), productId); if (productActivityId == null) { return; } final Dimension orderLineDimension = dimensionService.getFromRecord(invoiceLine); if (orderLineDimension == null) { //nothing to do return; } dimensionService.updateRecord(invoiceLine, orderLineDimension.withActivityId(productActivityId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\activity\model\validator\C_InvoiceLine.java
1
请完成以下Java代码
public static byte[] decompress(byte[] input) throws DataFormatException { Inflater inflater = new Inflater(); inflater.setInput(input); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (!inflater.finished()) { int decompressedSize = inflater.inflate(buffer); outputStream.write(buffer, 0, decompressedSize); } return outputStream.toByteArray(); } public static void main(String[] args) throws Exception { String inputString = "Baeldung helps developers explore the Java ecosystem and simply be better engineers. " + "We publish to-the-point guides and courses, with a strong focus on building web applications, Spring, " +
"Spring Security, and RESTful APIs"; byte[] input = inputString.getBytes(); // Compression byte[] compressedData = compress(input); // Decompression byte[] decompressedData = decompress(compressedData); System.out.println("Original: " + input.length + " bytes"); System.out.println("Compressed: " + compressedData.length + " bytes"); System.out.println("Decompressed: " + decompressedData.length + " bytes"); } }
repos\tutorials-master\core-java-modules\core-java-lang-7\src\main\java\com\baeldung\compressbytes\CompressByteArrayUtil.java
1
请完成以下Java代码
public String getProcessDefinitionName() { return processDefinitionName; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public String getActivityId() { return activityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public boolean isIncludeChildExecutionsWithBusinessKeyQuery() { return includeChildExecutionsWithBusinessKeyQuery; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public boolean isActive() { return isActive; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser; } public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public void deployProcesses() { // build a single deployment containing all discovered processes Set<String> resourceNames = getResourceNames(); if (resourceNames.isEmpty()) { LOGGER.debug("Not creating a deployment"); return; } LOGGER.debug("Start deploying processes."); DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService().createDeployment(); for (String string : resourceNames) { LOGGER.info("Adding '{}' to deployment.", string); deploymentBuilder.addClasspathResource(string); } // deploy the processes deploymentBuilder.deploy(); LOGGER.debug("Done deploying processes."); } public Set<String> getResourceNames() { Set<String> result = new HashSet<>(); URL processFileUrl = getClass().getClassLoader().getResource(PROCESSES_FILE_NAME); if (processFileUrl == null) { LOGGER.debug("No '{}'-file provided.", PROCESSES_FILE_NAME); // return empty set return result; } try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(processFileUrl.openStream()); NodeList nodeList = document.getElementsByTagName(PROCESS_ELEMENT_NAME); for (int i = 0; i < nodeList.getLength(); i++) { Node cn = nodeList.item(i); if (!(cn instanceof Element)) { continue; } Element ce = (Element) cn; String resourceName = ce.getAttribute(PROCESS_ATTR_RESOURCE); if (resourceName == null || resourceName.length() == 0) { continue; } result.add(resourceName); } } catch (Exception e) { LOGGER.error("could not parse file '{}'. {}", PROCESSES_FILE_NAME, e.getMessage(), e); } return result; } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessDeployer.java
1
请完成以下Java代码
public void onException(Exception e) { e.printStackTrace(); } @Override public void onDeletionNotice(StatusDeletionNotice arg) { System.out.println("Got a status deletion notice id:" + arg.getStatusId()); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); }
@Override public void onStatus(Status status) { System.out.println(status.getUser().getName() + " : " + status.getText()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
1
请在Spring Boot框架中完成以下Java代码
public void sendMessage(Object o) { Message message = new Message(aLiMqConfig.getStockTopic(), "test", JSON.toJSON(o).toString().getBytes(StandardCharsets.UTF_8)); //向mq发送消息 sendAsync(ProducerBean::isStarted, producer, message); } /** * 向阿里云rocket mq发送消息。 * * @param predicate 断言 * @param bean 发送消息bean * @param message 需要发送的消息 */ private static void sendAsync(Predicate<ProducerBean> predicate, ProducerBean bean, Message message) { if (predicate.test(bean)) { bean.sendAsync(message, new SendCallback() {
@Override public void onSuccess(SendResult sendResult) { logger.info("向mq推送库存消息成功,消息是:{}", sendResult.toString()); } @Override public void onException(OnExceptionContext e) { logger.error("向mq推送库存消息失败,消息id 为 {} 错误是:{}", e.getMessageId(), e.getException().getMessage()); } }); } else { logger.error("mq库存生产端启动失败!!!消息是:{}", message.toString()); } } }
repos\springBoot-master\springboot-rocketmq-ali\src\main\java\cn\abel\queue\service\ProducerService.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { // ------------------------ // PUBLIC METHODS // ------------------------ /** * /create --> Create a new user and save it in the database. * * @param email User's email * @param name User's name * @return A string describing if the user is successfully created or not. */ @RequestMapping("/create") @ResponseBody public String create(String email, String name) { User user = null; try { user = new User(email, name); userDao.save(user); } catch (Exception ex) { return "Error creating the user: " + ex.toString(); } return "User succesfully created! (id = " + user.getId() + ")"; } /** * /delete --> Delete the user having the passed id. * * @param id The id of the user to delete * @return A string describing if the user is successfully deleted or not. */ @RequestMapping("/delete") @ResponseBody public String delete(long id) { try { User user = new User(id); userDao.delete(user); } catch (Exception ex) { return "Error deleting the user: " + ex.toString(); } return "User successfully deleted!"; } /** * /get-by-email --> Return the id for the user having the passed email. * * @param email The email to search in the database. * @return The user id or a message error if the user is not found. */ @RequestMapping("/get-by-email") @ResponseBody public String getByEmail(String email) { String userId; try { User user = userDao.findByEmail(email); userId = String.valueOf(user.getId()); } catch (Exception ex) { return "User not found";
} return "The user id is: " + userId; } /** * /update --> Update the email and the name for the user in the database * having the passed id. * * @param id The id for the user to update. * @param email The new email. * @param name The new name. * @return A string describing if the user is successfully updated or not. */ @RequestMapping("/update") @ResponseBody public String updateUser(long id, String email, String name) { try { User user = userDao.findOne(id); user.setEmail(email); user.setName(name); userDao.save(user); } catch (Exception ex) { return "Error updating the user: " + ex.toString(); } return "User successfully updated!"; } // ------------------------ // PRIVATE FIELDS // ------------------------ @Autowired private UserDao userDao; } // class UserController
repos\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate\src\main\java\netgloo\controllers\UserController.java
2
请完成以下Java代码
public int getM_DistributionList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_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()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing ()
{ Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Total Ratio. @param RatioTotal Total of relative weight in a distribution */ public void setRatioTotal (BigDecimal RatioTotal) { set_Value (COLUMNNAME_RatioTotal, RatioTotal); } /** Get Total Ratio. @return Total of relative weight in a distribution */ public BigDecimal getRatioTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionList.java
1
请完成以下Java代码
public class WEBUI_C_Flatrate_DataEntry_CompleteIt extends JavaProcess implements IProcessPrecondition { private final IDocumentBL documentBL = Services.get(IDocumentBL.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { final I_C_Flatrate_DataEntry entryRecord = ProcessUtil.extractEntryOrNull(context); if (entryRecord == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (entryRecord.isProcessed()) { return ProcessPreconditionsResolution.rejectWithInternalReason("C_Flatrate_DataEntry is already processed"); } final FlatrateDataEntryRepo flatrateDataEntryRepo = SpringContextHolder.instance.getBean(FlatrateDataEntryRepo.class); final FlatrateDataEntryId flatrateDataEntryId = FlatrateDataEntryId.ofRepoId(FlatrateTermId.ofRepoId(entryRecord.getC_Flatrate_Term_ID()), entryRecord.getC_Flatrate_DataEntry_ID()); final FlatrateDataEntry entry = flatrateDataEntryRepo.getById(flatrateDataEntryId); if (entry.getDetails().isEmpty()) {
return ProcessPreconditionsResolution.rejectWithInternalReason("C_Flatrate_DataEntry has no details"); } return ProcessPreconditionsResolution.accept(); } @Override protected final String doIt() { final I_C_Flatrate_DataEntry entryRecord = ProcessUtil.extractEntry(getProcessInfo()); documentBL.processEx(entryRecord, X_C_Flatrate_DataEntry.DOCACTION_Complete, X_C_Flatrate_DataEntry.DOCSTATUS_Completed); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\process\WEBUI_C_Flatrate_DataEntry_CompleteIt.java
1
请完成以下Java代码
public String asString() { return "messaging.destination.kind"; } } } /** * Default {@link KafkaTemplateObservationConvention} for Kafka template key values. * * @author Gary Russell * @author Christian Mergenthaler * @author Wang Zhiyang * * @since 3.0 * */ public static class DefaultKafkaTemplateObservationConvention implements KafkaTemplateObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultKafkaTemplateObservationConvention INSTANCE = new DefaultKafkaTemplateObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(KafkaRecordSenderContext context) { return KeyValues.of( TemplateLowCardinalityTags.BEAN_NAME.withValue(context.getBeanName()), TemplateLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"), TemplateLowCardinalityTags.MESSAGING_OPERATION.withValue("publish"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_KIND.withValue("topic"), TemplateLowCardinalityTags.MESSAGING_DESTINATION_NAME.withValue(context.getDestination())); } @Override public String getContextualName(KafkaRecordSenderContext context) { return context.getDestination() + " send"; } @Override @NonNull public String getName() { return "spring.kafka.template"; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaTemplateObservation.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 Fully Qualified Domain Name. @param FQDN Fully Qualified Domain Name i.e. www.comdivision.com */ public void setFQDN (String FQDN) { set_Value (COLUMNNAME_FQDN, FQDN); } /** Get Fully Qualified Domain Name. @return Fully Qualified Domain Name i.e. www.comdivision.com */ public String getFQDN () { return (String)get_Value(COLUMNNAME_FQDN); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help.
@return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject_Domain.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + intValue; result = (prime * result) + ((stringValue == null) ? 0 : stringValue.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Foo other = (Foo) obj; if (intValue != other.intValue) {
return false; } if (stringValue == null) { if (other.stringValue != null) { return false; } } else if (!stringValue.equals(other.stringValue)) { return false; } return true; } @Override public String toString() { return "TargetClass{" + "intValue= " + intValue + ", stringValue= " + stringValue + '}'; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\deserialization\Foo.java
1
请在Spring Boot框架中完成以下Java代码
public class Config { @Bean public MyRepoSpring repoSpring(BookRepository repository) { return new MyRepoSpring(repository); } private DataSource dataSource(boolean readOnly, boolean isAutoCommit) { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://localhost/baeldung?useUnicode=true&characterEncoding=UTF-8"); config.setUsername("baeldung"); config.setPassword("baeldung"); config.setReadOnly(readOnly); config.setAutoCommit(isAutoCommit); return new HikariDataSource(config); } @Bean public DataSource dataSource() { return new RoutingDS(dataSource(false, false), dataSource(true, true)); } @Bean public EntityManagerFactory entityManagerFactory(DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean(); managerFactoryBean.setJpaVendorAdapter(vendorAdapter); managerFactoryBean.setPackagesToScan(BookEntity.class.getPackage()
.getName()); managerFactoryBean.setDataSource(dataSource); Properties properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "validate"); managerFactoryBean.setJpaProperties(properties); managerFactoryBean.afterPropertiesSet(); return managerFactoryBean.getObject(); } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\mysql\spring\Config.java
2
请完成以下Java代码
protected Collection<String> getUrlPrefixes() { return Collections.singleton(name().toLowerCase(Locale.ENGLISH)); } protected boolean matchProductName(String productName) { return this.productName != null && this.productName.equalsIgnoreCase(productName); } /** * Return the driver class name. * @return the class name or {@code null} */ public @Nullable String getDriverClassName() { return this.driverClassName; } /** * Return the XA driver source class name. * @return the class name or {@code null} */ public @Nullable String getXaDataSourceClassName() { return this.xaDataSourceClassName; } /** * Return the validation query. * @return the validation query or {@code null} */ public @Nullable String getValidationQuery() { return this.validationQuery; } /** * Find a {@link DatabaseDriver} for the given URL. * @param url the JDBC URL * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromJdbcUrl(@Nullable String url) { if (StringUtils.hasLength(url)) { Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\""); String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH); for (DatabaseDriver driver : values()) { for (String urlPrefix : driver.getUrlPrefixes()) { String prefix = ":" + urlPrefix + ":";
if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) { return driver; } } } } return UNKNOWN; } /** * Find a {@link DatabaseDriver} for the given product name. * @param productName product name * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromProductName(@Nullable String productName) { if (StringUtils.hasLength(productName)) { for (DatabaseDriver candidate : values()) { if (candidate.matchProductName(productName)) { return candidate; } } } return UNKNOWN; } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java
1
请完成以下Java代码
public class ScriptCondition implements Condition { private static final long serialVersionUID = 1L; private final String expression; private final String language; public ScriptCondition(String expression, String language) { this.expression = expression; this.language = language; } @Override public boolean evaluate(String sequenceFlowId, DelegateExecution execution) { String conditionExpression = null; if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) { ObjectNode elementProperties = Context.getBpmnOverrideElementProperties(sequenceFlowId, execution.getProcessDefinitionId()); conditionExpression = getActiveValue(expression, DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties); } else { conditionExpression = expression; } ScriptingEngines scriptingEngines = Context .getProcessEngineConfiguration() .getScriptingEngines(); Object result = scriptingEngines.evaluate(conditionExpression, language, execution); if (result == null) { throw new ActivitiException("condition script returns null: " + expression); } if (!(result instanceof Boolean)) {
throw new ActivitiException("condition script returns non-Boolean: " + result + " (" + result.getClass().getName() + ")"); } return (Boolean) result; } protected String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) { String activeValue = originalValue; if (elementProperties != null) { JsonNode overrideValueNode = elementProperties.get(propertyName); if (overrideValueNode != null) { if (overrideValueNode.isNull()) { activeValue = null; } else { activeValue = overrideValueNode.asString(); } } } return activeValue; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptCondition.java
1
请完成以下Java代码
public Money convertToBase(@NonNull final CurrencyConversionContext conversionCtx, @NonNull final Money amt) { final CurrencyId currencyToId = getBaseCurrencyId(conversionCtx.getClientId(), conversionCtx.getOrgId()); final CurrencyConversionResult currencyConversionResult = convert(conversionCtx, amt, currencyToId); return Money.of(currencyConversionResult.getAmount(), currencyToId); } private static CurrencyConversionResult.CurrencyConversionResultBuilder prepareCurrencyConversionResult(@NonNull final CurrencyConversionContext conversionCtx) { return CurrencyConversionResult.builder() .clientId(conversionCtx.getClientId()) .orgId(conversionCtx.getOrgId()) .conversionDate(conversionCtx.getConversionDate()) .conversionTypeId(conversionCtx.getConversionTypeId()); } @Override public Money convert( @NonNull final Money amount, @NonNull final CurrencyId toCurrencyId, @NonNull final LocalDate conversionDate, @NonNull final ClientAndOrgId clientAndOrgId) { if (CurrencyId.equals(amount.getCurrencyId(), toCurrencyId)) { return amount; } else if(amount.isZero()) { return Money.zero(toCurrencyId); }
final CurrencyConversionContext conversionCtx = createCurrencyConversionContext( LocalDateAndOrgId.ofLocalDate(conversionDate, clientAndOrgId.getOrgId()), (CurrencyConversionTypeId)null, clientAndOrgId.getClientId()); final CurrencyConversionResult conversionResult = convert( conversionCtx, amount.toBigDecimal(), amount.getCurrencyId(), toCurrencyId); return Money.of(conversionResult.getAmount(), toCurrencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyBL.java
1
请完成以下Java代码
public I_I_Pharma_BPartner getPreviousImportRecord() { return previousImportRecord; } public void setPreviousImportRecord(@NonNull final I_I_Pharma_BPartner previousImportRecord) { this.previousImportRecord = previousImportRecord; } public int getPreviousC_BPartner_ID() { return previousImportRecord == null ? -1 : previousImportRecord.getC_BPartner_ID(); } public String getPreviousBPValue() { return previousImportRecord == null ? null : previousImportRecord.getb00adrnr(); }
public List<I_I_Pharma_BPartner> getPreviousImportRecordsForSameBP() { return previousImportRecordsForSameBP; } public void clearPreviousRecordsForSameBP() { previousImportRecordsForSameBP = new ArrayList<>(); } public void collectImportRecordForSameBP(@NonNull final I_I_Pharma_BPartner importRecord) { previousImportRecordsForSameBP.add(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerContext.java
1
请在Spring Boot框架中完成以下Java代码
public static SettDailyCollectTypeEnum getEnum(String enumName) { SettDailyCollectTypeEnum resultEnum = null; SettDailyCollectTypeEnum[] enumAry = SettDailyCollectTypeEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(enumName)) { resultEnum = enumAry[i]; break; } } return resultEnum; } public static Map<String, Map<String, Object>> toMap() { SettDailyCollectTypeEnum[] ary = SettDailyCollectTypeEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc());
enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { SettDailyCollectTypeEnum[] ary = SettDailyCollectTypeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettDailyCollectTypeEnum.java
2
请在Spring Boot框架中完成以下Java代码
public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; }
public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthParamVo.java
2
请在Spring Boot框架中完成以下Java代码
private void loadSql(Path sqlFile) { String sql; try { sql = Files.readString(sqlFile); } catch (IOException e) { throw new UncheckedIOException(e); } jdbcTemplate.execute((StatementCallback<Object>) stmt -> { stmt.execute(sql); printWarnings(stmt.getWarnings()); return null; }); } private void execute(@Language("sql") String... statements) { for (String statement : statements) { execute(statement, true); } } private void execute(@Language("sql") String statement, boolean ignoreErrors) { try {
jdbcTemplate.execute(statement); } catch (Exception e) { if (!ignoreErrors) { throw e; } } } private void printWarnings(SQLWarning warnings) { if (warnings != null) { log.info("{}", warnings.getMessage()); SQLWarning nextWarning = warnings.getNextWarning(); while (nextWarning != null) { log.info("{}", nextWarning.getMessage()); nextWarning = nextWarning.getNextWarning(); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\SqlDatabaseUpgradeService.java
2
请完成以下Java代码
private Optional<ScaleDevice> getCurrentScaleDevice(final @NonNull WFProcess wfProcess) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); return manufacturingJobService.getCurrentScaleDevice(job); } private Stream<ScaleDevice> streamAvailableScaleDevices(final @NonNull WFProcess wfProcess) { final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); return manufacturingJobService.streamAvailableScaleDevices(job); } private static JsonQRCode toJsonQRCode(final ScaleDevice scaleDevice, final String adLanguage) { final DeviceQRCode qrCode = DeviceQRCode.builder() .deviceId(scaleDevice.getDeviceId()) .caption(scaleDevice.getCaption().translate(adLanguage)) .build(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeJsonString()) .caption(qrCode.getCaption()) .build();
} @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return getCurrentScaleDevice(wfProcess).isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(final @NonNull SetScannedBarcodeRequest request) { final DeviceId newScaleDeviceId = DeviceQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode()).getDeviceId(); return ManufacturingMobileApplication.mapDocument( request.getWfProcess(), job -> manufacturingJobService.withCurrentScaleDevice(job, newScaleDeviceId) ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\scanScaleDevice\ScanScaleDeviceActivityHandler.java
1
请完成以下Java代码
public Builder setC_Flatrate_DataEntry_ID(int C_Flatrate_DataEntry_ID) { this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID; return this; } public Builder setDate(final Date date) { this.date = date; return this; } public Builder setQtyPromised(final BigDecimal qtyPromised, final BigDecimal qtyPromised_TU) { this.qtyPromised = qtyPromised; this.qtyPromised_TU = qtyPromised_TU; return this; }
public Builder setQtyOrdered(final BigDecimal qtyOrdered, final BigDecimal qtyOrdered_TU) { this.qtyOrdered = qtyOrdered; this.qtyOrdered_TU = qtyOrdered_TU; return this; } public Builder setQtyDelivered(BigDecimal qtyDelivered) { this.qtyDelivered = qtyDelivered; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceChangeEvent.java
1
请在Spring Boot框架中完成以下Java代码
private static BooleanWithReason checkCanEdit(@NonNull final Document document, @NonNull final IUserRolePermissions permissions) { // In case document type is not Window, return OK because we cannot validate final DocumentPath documentPath = document.getDocumentPath(); if (documentPath.getDocumentType() != DocumentType.Window) { return BooleanWithReason.TRUE; // OK } // Check if we have window write permission final AdWindowId adWindowId = documentPath.getWindowId().toAdWindowIdOrNull(); if (adWindowId != null && !permissions.checkWindowPermission(adWindowId).hasWriteAccess()) { return BooleanWithReason.falseBecause("no window edit permission"); } final int adTableId = getAdTableId(document); if (adTableId <= 0) { return BooleanWithReason.TRUE; // not table based => OK } final int recordId = getRecordId(document); final ClientId adClientId = document.getClientId(); final OrgId adOrgId = document.getOrgId(); if (adOrgId == null) { return BooleanWithReason.TRUE; // the user cleared the field; field is flagged as mandatory; until user set the field, don't make a fuss. } return permissions.checkCanUpdate(adClientId, adOrgId, adTableId, recordId); } private static int getAdTableId(final Document document) { final String tableName = document.getEntityDescriptor().getTableNameOrNull(); if (tableName == null)
{ // cannot apply security because this is not table based return -1; // OK } return Services.get(IADTableDAO.class).retrieveTableId(tableName); } private static int getRecordId(final Document document) { if (document.isNew()) { return -1; } else { return document.getDocumentId().toIntOr(-1); } } public static boolean isNewDocumentAllowed(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final UserSession userSession) { final AdWindowId adWindowId = entityDescriptor.getWindowId().toAdWindowIdOrNull(); if (adWindowId == null) {return true;} final IUserRolePermissions permissions = userSession.getUserRolePermissions(); final ElementPermission windowPermission = permissions.checkWindowPermission(adWindowId); if (!windowPermission.hasWriteAccess()) {return false;} final ILogicExpression allowExpr = entityDescriptor.getAllowCreateNewLogic(); final LogicExpressionResult allow = allowExpr.evaluateToResult(userSession.toEvaluatee(), IExpressionEvaluator.OnVariableNotFound.ReturnNoResult); return allow.isTrue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\DocumentPermissionsHelper.java
2
请完成以下Java代码
public void setFixedQtyAvailableToPromise (int FixedQtyAvailableToPromise) { set_Value (COLUMNNAME_FixedQtyAvailableToPromise, Integer.valueOf(FixedQtyAvailableToPromise)); } /** Get Konst. Zusagbar (ATP) Wert. @return Konst. Zusagbar (ATP) Wert */ @Override public int getFixedQtyAvailableToPromise () { Integer ii = (Integer)get_Value(COLUMNNAME_FixedQtyAvailableToPromise); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3 Server. @param MSV3_Server_ID MSV3 Server */ @Override public void setMSV3_Server_ID (int MSV3_Server_ID) { if (MSV3_Server_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, Integer.valueOf(MSV3_Server_ID)); } /** Get MSV3 Server. @return MSV3 Server */ @Override public int getMSV3_Server_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Server_ID); if (ii == null) return 0; return ii.intValue(); }
@Override public org.compiere.model.I_M_Warehouse_PickingGroup getM_Warehouse_PickingGroup() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class); } @Override public void setM_Warehouse_PickingGroup(org.compiere.model.I_M_Warehouse_PickingGroup M_Warehouse_PickingGroup) { set_ValueFromPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class, M_Warehouse_PickingGroup); } /** Set Kommissionier-Lagergruppe . @param M_Warehouse_PickingGroup_ID Kommissionier-Lagergruppe */ @Override public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID) { if (M_Warehouse_PickingGroup_ID < 1) set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, null); else set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID)); } /** Get Kommissionier-Lagergruppe . @return Kommissionier-Lagergruppe */ @Override public int getM_Warehouse_PickingGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Server.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter { // 查询用户使用 @Autowired AccountRepository accountRepository; @Autowired public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication() // .withUser("user").password("password").roles("USER") // .and() // .withUser("app_client").password("nopass").roles("USER") // .and() // .withUser("admin").password("password").roles("ADMIN"); //配置用户来源于数据库 auth.userDetailsService(userDetailsService()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and() .httpBasic().and().csrf().disable(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override @Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { // 通过用户名获取用户信息 Account account = accountRepository.findByName(name); if (account != null) { // 创建spring security安全用户 User user = new User(account.getName(), account.getPassword(), AuthorityUtils.createAuthorityList(account.getRoles())); return user; } else { throw new UsernameNotFoundException("用户[" + name + "]不存在"); } } }; } }
repos\spring-boot-quick-master\quick-oauth2\quick-oauth2-server\src\main\java\com\quick\auth\server\security\OAuth2SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void createAuthors() throws IOException { Author mt = new Author(); mt.setId(1L); mt.setName("Martin Ticher"); mt.setAge(43); mt.setGenre("Horror"); mt.setAvatar(Files.readAllBytes(new File("avatars/mt.png").toPath())); Author cd = new Author(); cd.setId(2L); cd.setName("Carla Donnoti"); cd.setAge(31); cd.setGenre("Science Fiction"); cd.setAvatar(Files.readAllBytes(new File("avatars/cd.png").toPath())); Author re = new Author(); re.setId(3L); re.setName("Rennata Elibol"); re.setAge(46); re.setGenre("Fantasy"); re.setAvatar(Files.readAllBytes(new File("avatars/re.png").toPath())); authorRepository.save(mt); authorRepository.save(cd); authorRepository.save(re); } public List<Author> fetchAuthorsByAgeGreaterThanEqual(int age) { List<Author> authors = authorRepository.findByAgeGreaterThanEqual(age); return authors; } @Transactional(readOnly = true) public byte[] fetchAuthorAvatarViaId(long id) { Author author = authorRepository.findById(id).orElseThrow(); return author.getAvatar(); }
@Transactional(readOnly = true) public List<Author> fetchAuthorsDetailsByAgeGreaterThanEqual(int age) { List<Author> authors = authorRepository.findByAgeGreaterThanEqual(40); // don't do this since this is a N+1 case authors.forEach(a -> { a.getAvatar(); }); return authors; } @Transactional(readOnly = true) public List<AuthorDto> fetchAuthorsWithAvatarsByAgeGreaterThanEqual(int age) { List<AuthorDto> authors = authorRepository.findDtoByAgeGreaterThanEqual(40); return authors; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingBasic\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getMobilephone() { return mobilephone; } public void setMobilephone(String mobilephone) { this.mobilephone = mobilephone; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Integer getUserType() { return userType; } public void setUserType(Integer userType) { this.userType = userType; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; }
public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getDisabled() { return disabled; } public void setDisabled(Integer disabled) { this.disabled = disabled; } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public Integer getIsLdap() { return isLdap; } public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
public java.lang.String getPMM_Trend () { return (java.lang.String)get_Value(COLUMNNAME_PMM_Trend); } /** Set Procurement Week. @param PMM_Week_ID Procurement Week */ @Override public void setPMM_Week_ID (int PMM_Week_ID) { if (PMM_Week_ID < 1) set_ValueNoCheck (COLUMNNAME_PMM_Week_ID, null); else set_ValueNoCheck (COLUMNNAME_PMM_Week_ID, Integer.valueOf(PMM_Week_ID)); } /** Get Procurement Week. @return Procurement Week */ @Override public int getPMM_Week_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Week_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Wochenerster. @param WeekDate Wochenerster */ @Override public void setWeekDate (java.sql.Timestamp WeekDate) { set_ValueNoCheck (COLUMNNAME_WeekDate, WeekDate); } /** Get Wochenerster. @return Wochenerster */ @Override public java.sql.Timestamp getWeekDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_WeekDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Week.java
1
请在Spring Boot框架中完成以下Java代码
public void setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose) { this.acceptTasksAfterContextClose = acceptTasksAfterContextClose; } } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination; /** * Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; }
public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } /** * Determine when the task executor is to be created. * * @since 3.5.0 */ public enum Mode { /** * Create the task executor if no user-defined executor is present. */ AUTO, /** * Create the task executor even if a user-defined executor is present. */ FORCE } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskExecutionProperties.java
2
请完成以下Java代码
public I_C_Flatrate_Term getC_Flatrate_Term() { final I_M_HU_PI_Item_Product hupip = getM_HU_PI_Item_Product(); if (hupip == null) { // the procurement product must have an M_HU_PI_Item_Product set return null; } // the product and M_HU_PI_Item_Product must belong to a PMM_ProductEntry that is currently valid final I_PMM_Product pmmProduct = Services.get(IPMMProductBL.class).getPMMProductForDateProductAndASI( getDate(), ProductId.ofRepoId(getM_Product().getM_Product_ID()), BPartnerId.ofRepoIdOrNull(getC_BPartner().getC_BPartner_ID()), hupip.getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance()); if (pmmProduct == null) { return null; } // retrieve the freshest, currently valid term for the partner and pmm product. return Services.get(IPMMContractsDAO.class).retrieveTermForPartnerAndProduct( getDate(), getC_BPartner().getC_BPartner_ID(), pmmProduct.getPMM_Product_ID()); } /** * @return the M_HU_PI_ItemProduct if set in the orderline. Null othersiwe. */ private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product() { final de.metas.handlingunits.model.I_C_OrderLine huOrderLine = InterfaceWrapperHelper.create(orderLine, de.metas.handlingunits.model.I_C_OrderLine.class); return huOrderLine.getM_HU_PI_Item_Product(); } @Override public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry() { return Services.get(IPMMContractsDAO.class).retrieveFlatrateDataEntry( getC_Flatrate_Term(), getDate()); } @Override public Object getWrappedModel() { return orderLine; } @Override public Timestamp getDate() { return CoalesceUtil.coalesceSuppliers( () -> orderLine.getDatePromised(), () -> orderLine.getC_Order().getDatePromised()); }
@Override public BigDecimal getQty() { return orderLine.getQtyOrdered(); } @Override public void setM_PricingSystem_ID(int M_PricingSystem_ID) { throw new NotImplementedException(); } @Override public void setM_PriceList_ID(int M_PriceList_ID) { throw new NotImplementedException(); } /** * Sets a private member variable to the given {@code price}. */ @Override public void setPrice(BigDecimal price) { this.price = price; } /** * * @return the value that was set via {@link #setPrice(BigDecimal)}. */ public BigDecimal getPrice() { return price; } public I_M_AttributeSetInstance getM_AttributeSetInstance() { return orderLine.getM_AttributeSetInstance(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_C_OrderLine.java
1
请完成以下Java代码
public void onParentTermination(CmmnActivityExecution execution) { if (execution.isCompleted()) { String id = execution.getId(); throw LOG.executionAlreadyCompletedException("parentTerminate", id); } performParentTerminate(execution); } public void onExit(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("exit", execution); } // occur ///////////////////////////////////////////////////////////////// public void onOccur(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, AVAILABLE, COMPLETED, "occur"); } // suspension //////////////////////////////////////////////////////////// public void onSuspension(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, AVAILABLE, SUSPENDED, "suspend"); performSuspension(execution); } public void onParentSuspension(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("parentSuspend", execution); } // resume //////////////////////////////////////////////////////////////// public void onResume(CmmnActivityExecution execution) { ensureTransitionAllowed(execution, SUSPENDED, AVAILABLE, "resume"); CmmnActivityExecution parent = execution.getParent(); if (parent != null) { if (!parent.isActive()) { String id = execution.getId(); throw LOG.resumeInactiveCaseException("resume", id); } } resuming(execution); } public void onParentResume(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("parentResume", execution); } // re-activation ////////////////////////////////////////////////////////
public void onReactivation(CmmnActivityExecution execution) { throw createIllegalStateTransitionException("reactivate", execution); } // sentry /////////////////////////////////////////////////////////////// protected boolean isAtLeastOneExitCriterionSatisfied(CmmnActivityExecution execution) { return false; } public void fireExitCriteria(CmmnActivityExecution execution) { throw LOG.criteriaNotAllowedForEventListenerOrMilestonesException("exit", execution.getId()); } // helper //////////////////////////////////////////////////////////////// protected CaseIllegalStateTransitionException createIllegalStateTransitionException(String transition, CmmnActivityExecution execution) { String id = execution.getId(); return LOG.illegalStateTransitionException(transition, id, getTypeName()); } protected abstract String getTypeName(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerOrMilestoneActivityBehavior.java
1
请完成以下Java代码
public void save(final BOM bom) { final Set<CurrentCostId> costIds = bom.getCostIds(CurrentCostId.class); final Map<CurrentCostId, CurrentCost> existingCostsById = currentCostsRepo.getByIds(costIds) .stream() .collect(GuavaCollectors.toImmutableMapByKey(CurrentCost::getId)); bom.streamCostPrices() .forEach(bomCostPrice -> save(bomCostPrice, existingCostsById)); } private void save( @NonNull final BOMCostPrice bomCostPrice, final Map<CurrentCostId, CurrentCost> existingCostsByRepoId) { final ProductId productId = bomCostPrice.getProductId(); for (final BOMCostElementPrice elementPrice : bomCostPrice.getElementPrices()) { final CurrentCostId currentCostId = elementPrice.getId(CurrentCostId.class); CurrentCost existingCost = existingCostsByRepoId.get(currentCostId); if (existingCost == null) { final CostSegmentAndElement costSegmentAndElement = createCostSegment(productId) .withCostElementId(elementPrice.getCostElementId()); existingCost = currentCostsRepo.create(costSegmentAndElement); } existingCost.setCostPrice(elementPrice.getCostPrice()); currentCostsRepo.save(existingCost);
elementPrice.setId(existingCost.getId()); } } private static BOMCostElementPrice toBOMCostElementPrice(@NonNull final CurrentCost currentCost) { return BOMCostElementPrice.builder() .id(currentCost.getId()) .costElementId(currentCost.getCostElementId()) .costPrice(currentCost.getCostPrice()) .build(); } @Override public void resetComponentsCostPrices(final ProductId productId) { final CostSegment costSegment = createCostSegment(productId); for (final CurrentCost cost : currentCostsRepo.getByCostSegmentAndCostingMethod(costSegment, costingMethod)) { cost.clearComponentsCostPrice(); currentCostsRepo.save(cost); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BatchProcessBOMCostCalculatorRepository.java
1
请在Spring Boot框架中完成以下Java代码
private static Map<Integer, DesadvLineWithPacks> getLinesWithPacks(@NonNull final List<EDIExpDesadvPackType> packs) { final Map<Integer, List<SinglePack>> lineIdToPacksCollector = new HashMap<>(); final Map<Integer, EDIExpDesadvLineType> lineIdToLine = new HashMap<>(); packs.forEach(pack -> { final SinglePack singlePack = SinglePack.of(pack); final List<SinglePack> packsForLine = new ArrayList<>(); packsForLine.add(singlePack); lineIdToPacksCollector.merge(singlePack.getDesadvLineID(), packsForLine, (old, newList) -> { old.addAll(newList); return old; }); lineIdToLine.put(singlePack.getDesadvLineID(), singlePack.getDesadvLine()); }); final ImmutableMap.Builder<Integer, DesadvLineWithPacks> lineWithPacksCollector = ImmutableMap.builder(); lineIdToLine.forEach((desadvLineID, desadvLine) -> { final DesadvLineWithPacks lineWithPacks = DesadvLineWithPacks.builder()
.desadvLine(desadvLine) .singlePacks(lineIdToPacksCollector.get(desadvLineID)) .build(); lineWithPacksCollector.put(desadvLineID, lineWithPacks); }); return lineWithPacksCollector.build(); } @NonNull private static Map<Integer, EDIExpDesadvLineType> getLinesWithNoPacks(@NonNull final List<EDIExpDesadvLineWithNoPackType> lineWithNoPacks) { return lineWithNoPacks.stream() .map(EDIExpDesadvLineWithNoPackType::getEDIDesadvLineID) .collect(ImmutableMap.toImmutableMap(desadvLine -> desadvLine.getEDIDesadvLineID().intValue(), Function.identity())); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\helper\DesadvParser.java
2
请完成以下Java代码
public class User { private final Logger logger = LoggerFactory.getLogger(User.class); private long id; private String name; private String email; public User(long id, String name, String email) { this.id = id; this.name = name; this.email = email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (this.getClass() != o.getClass()) return false; User user = (User) o;
return id == user.id && (name.equals(user.name) && email.equals(user.email)); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } // getters and setters here }
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods\src\main\java\com\baeldung\hashcode\eclipse\User.java
1
请在Spring Boot框架中完成以下Java代码
class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String title; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id", nullable = false) private Author author; public Long getId() { return id; } public String getTitle() { return title;
} public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\statelesssession\Article.java
2
请在Spring Boot框架中完成以下Java代码
public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public boolean isSslVerify() { return sslVerify; } public void setSslVerify(boolean sslVerify) { this.sslVerify = sslVerify; } public int getMaxResultSize() { return maxResultSize; } public void setMaxResultSize(int maxResultSize) { this.maxResultSize = maxResultSize; } public Map getHeaders() { return headers; } public void addHeader(String key, String value){ this.headers.put(key, value); } public void addHeaders(String key, Collection<String> values){ this.headers.put(key, values); } public void setHeaders(Map _headers) { this.headers.putAll(_headers); } public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public boolean isIgnoreContentIfUnsuccess() { return ignoreContentIfUnsuccess; } public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) { this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess; } public String getPostData() { return postData;
} public void setPostData(String postData) { this.postData = postData; } public ClientKeyStore getClientKeyStore() { return clientKeyStore; } public void setClientKeyStore(ClientKeyStore clientKeyStore) { this.clientKeyStore = clientKeyStore; } public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() { return TrustKeyStore; } public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) { TrustKeyStore = trustKeyStore; } public boolean isHostnameVerify() { return hostnameVerify; } public void setHostnameVerify(boolean hostnameVerify) { this.hostnameVerify = hostnameVerify; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
2
请完成以下Java代码
public void setES_CreateIndexCommand (final java.lang.String ES_CreateIndexCommand) { set_Value (COLUMNNAME_ES_CreateIndexCommand, ES_CreateIndexCommand); } @Override public java.lang.String getES_CreateIndexCommand() { return get_ValueAsString(COLUMNNAME_ES_CreateIndexCommand); } @Override public void setES_DocumentToIndexTemplate (final java.lang.String ES_DocumentToIndexTemplate) { set_Value (COLUMNNAME_ES_DocumentToIndexTemplate, ES_DocumentToIndexTemplate); } @Override public java.lang.String getES_DocumentToIndexTemplate() { return get_ValueAsString(COLUMNNAME_ES_DocumentToIndexTemplate); } @Override public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override
public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_Index (final java.lang.String ES_Index) { set_Value (COLUMNNAME_ES_Index, ES_Index); } @Override public java.lang.String getES_Index() { return get_ValueAsString(COLUMNNAME_ES_Index); } @Override public void setES_QueryCommand (final java.lang.String ES_QueryCommand) { set_Value (COLUMNNAME_ES_QueryCommand, ES_QueryCommand); } @Override public java.lang.String getES_QueryCommand() { return get_ValueAsString(COLUMNNAME_ES_QueryCommand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config.java
1
请完成以下Java代码
public void setMaxLaunchers (final int MaxLaunchers) { set_Value (COLUMNNAME_MaxLaunchers, MaxLaunchers); } @Override public int getMaxLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxLaunchers); } @Override public void setMaxStartedLaunchers (final int MaxStartedLaunchers) { set_Value (COLUMNNAME_MaxStartedLaunchers, MaxStartedLaunchers); } @Override public int getMaxStartedLaunchers() {
return get_ValueAsInt(COLUMNNAME_MaxStartedLaunchers); } @Override public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID) { if (MobileUI_UserProfile_DD_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID); } @Override public int getMobileUI_UserProfile_DD_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPriceList (final @Nullable BigDecimal PriceList) { set_Value (COLUMNNAME_PriceList, PriceList); } @Override public BigDecimal getPriceList() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriceStd (final BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } @Override public BigDecimal getPriceStd() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign_Price.java
1
请完成以下Java代码
public int getExternalSystem_Outbound_Endpoint_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID); } @Override public void setLoginUsername (final @Nullable String LoginUsername) { set_Value (COLUMNNAME_LoginUsername, LoginUsername); } @Override public String getLoginUsername() { return get_ValueAsString(COLUMNNAME_LoginUsername); } @Override public void setOutboundHttpEP (final String OutboundHttpEP) { set_Value (COLUMNNAME_OutboundHttpEP, OutboundHttpEP); } @Override public String getOutboundHttpEP() { return get_ValueAsString(COLUMNNAME_OutboundHttpEP); } @Override public void setOutboundHttpMethod (final String OutboundHttpMethod) { set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod); } @Override public String getOutboundHttpMethod() { return get_ValueAsString(COLUMNNAME_OutboundHttpMethod); } @Override public void setPassword (final @Nullable String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSasSignature (final @Nullable String SasSignature)
{ set_Value (COLUMNNAME_SasSignature, SasSignature); } @Override public String getSasSignature() { return get_ValueAsString(COLUMNNAME_SasSignature); } /** * Type AD_Reference_ID=542016 * Reference name: ExternalSystem_Outbound_Endpoint_EndpointType */ public static final int TYPE_AD_Reference_ID=542016; /** HTTP = HTTP */ public static final String TYPE_HTTP = "HTTP"; /** SFTP = SFTP */ public static final String TYPE_SFTP = "SFTP"; /** FILE = FILE */ public static final String TYPE_FILE = "FILE"; /** EMAIL = EMAIL */ public static final String TYPE_EMAIL = "EMAIL"; /** TCP = TCP */ public static final String TYPE_TCP = "TCP"; @Override public void setType (final String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java
1
请完成以下Java代码
protected void createDefaultAuthorizations(ProcessDefinition processDefinition) { if(isAuthorizationEnabled()) { ResourceAuthorizationProvider provider = getResourceAuthorizationProvider(); AuthorizationEntity[] authorizations = provider.newProcessDefinition(processDefinition); saveDefaultAuthorizations(authorizations); } } protected void configureProcessDefinitionQuery(ProcessDefinitionQueryImpl query) { getAuthorizationManager().configureProcessDefinitionQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public ProcessDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestProcessDefinitionByKey(key); } @Override public ProcessDefinitionEntity findLatestDefinitionById(String id) { return findLatestProcessDefinitionById(id); } @Override public ProcessDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(ProcessDefinitionEntity.class, definitionId); }
@Override public ProcessDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestProcessDefinitionByKeyAndTenantId(definitionKey, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findProcessDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { return findProcessDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findProcessDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionManager.java
1
请在Spring Boot框架中完成以下Java代码
public class InventoryId implements RepoIdAware { @JsonCreator public static InventoryId ofRepoId(final int repoId) { return new InventoryId(repoId); } public static InventoryId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final InventoryId id) { return id != null ? id.getRepoId() : -1; }
int repoId; private InventoryId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_Inventory_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\InventoryId.java
2
请完成以下Java代码
public Void call() throws Exception { ScriptInvocation invocation = new ScriptInvocation(script, execution); Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(invocation); Object result = invocation.getInvocationResult(); if (result != null && resultVariable != null) { execution.setVariable(resultVariable, result); } leave(execution); return null; } }); } /** * Searches recursively through the exception to see if the exception itself * or one of its causes is a {@link BpmnError}. * * @param e * the exception to check * @return the BpmnError that was the cause of this exception or null if no
* BpmnError was found */ protected BpmnError checkIfCauseOfExceptionIsBpmnError(Throwable e) { if (e instanceof BpmnError) { return (BpmnError) e; } else if (e.getCause() == null) { return null; } return checkIfCauseOfExceptionIsBpmnError(e.getCause()); } public ExecutableScript getScript() { return script; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ScriptTaskActivityBehavior.java
1
请完成以下Java代码
public BootstrapConfig get(String endpoint) { return bootstrapByEndpoint.get(endpoint); } @Override public Map<String, BootstrapConfig> getAll() { readLock.lock(); try { return super.getAll(); } finally { readLock.unlock(); } } @Override public void add(String endpoint, BootstrapConfig config) throws InvalidConfigurationException { writeLock.lock(); try { addToStore(endpoint, config); } finally { writeLock.unlock(); } } @Override public BootstrapConfig remove(String endpoint) { writeLock.lock(); try { return super.remove(endpoint); } finally { writeLock.unlock(); } }
public void addToStore(String endpoint, BootstrapConfig config) throws InvalidConfigurationException { configChecker.verify(config); // Check PSK identity uniqueness for bootstrap server: PskByServer pskToAdd = getBootstrapPskIdentity(config); if (pskToAdd != null) { BootstrapConfig existingConfig = bootstrapByPskId.get(pskToAdd); if (existingConfig != null) { // check if this config will be replace by the new one. BootstrapConfig previousConfig = bootstrapByEndpoint.get(endpoint); if (previousConfig != existingConfig) { throw new InvalidConfigurationException( "Psk identity [%s] already used for this bootstrap server [%s]", pskToAdd.identity, pskToAdd.serverUrl); } } } bootstrapByEndpoint.put(endpoint, config); if (pskToAdd != null) { bootstrapByPskId.put(pskToAdd, config); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MInMemoryBootstrapConfigStore.java
1
请完成以下Java代码
public Pipe<M, M> get(int index) { return pipeList.get(index); } @Override public Pipe<M, M> set(int index, Pipe<M, M> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<M, M> element) { pipeList.add(index, element); } /** * 以最高优先级加入管道 * * @param pipe */ public void addFirst(Pipe<M, M> pipe) { pipeList.addFirst(pipe); } /** * 以最低优先级加入管道 * * @param pipe */ public void addLast(Pipe<M, M> pipe) { pipeList.addLast(pipe); }
@Override public Pipe<M, M> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<M, M>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<M, M>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<M, M>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java
1
请完成以下Java代码
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] params) { Method method = getMethod(bindings, context, returnType, paramTypes); try { return method.invoke(null, params); } catch (IllegalAccessException e) { throw new ELException(LocalMessages.get("error.identifier.method.access", name)); } catch (IllegalArgumentException e) { throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e)); } catch (InvocationTargetException e) { throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e.getCause())); } } @Override public String toString() { return name; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name); } public int getIndex() {
return index; } public String getName() { return name; } public int getCardinality() { return 0; } public AstNode getChild(int i) { return null; } }
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstIdentifier.java
1
请完成以下Java代码
public @Nullable Http2 getHttp2() { return this.http2; } @Override public void setHttp2(@Nullable Http2 http2) { this.http2 = http2; } public @Nullable Compression getCompression() { return this.compression; } @Override public void setCompression(@Nullable Compression compression) { this.compression = compression; } public @Nullable String getServerHeader() { return this.serverHeader; } @Override public void setServerHeader(@Nullable String serverHeader) { this.serverHeader = serverHeader; } @Override public void setShutdown(Shutdown shutdown) { this.shutdown = shutdown; } /** * Returns the shutdown configuration that will be applied to the server. * @return the shutdown configuration * @since 2.3.0 */ public Shutdown getShutdown() { return this.shutdown;
} /** * Return the {@link SslBundle} that should be used with this server. * @return the SSL bundle */ protected final SslBundle getSslBundle() { return WebServerSslBundle.get(this.ssl, this.sslBundles); } protected final Map<String, SslBundle> getServerNameSslBundles() { Assert.state(this.ssl != null, "'ssl' must not be null"); return this.ssl.getServerNameBundles() .stream() .collect(Collectors.toMap(ServerNameSslBundle::serverName, (serverNameSslBundle) -> { Assert.state(this.sslBundles != null, "'sslBundles' must not be null"); return this.sslBundles.getBundle(serverNameSslBundle.bundle()); })); } /** * Return the absolute temp dir for given web server. * @param prefix server name * @return the temp dir for given server. */ protected final File createTempDir(String prefix) { try { File tempDir = Files.createTempDirectory(prefix + "." + getPort() + ".").toFile(); tempDir.deleteOnExit(); return tempDir; } catch (IOException ex) { throw new WebServerException( "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\AbstractConfigurableWebServerFactory.java
1
请完成以下Java代码
protected void publishFailureEvent(UsernamePasswordAuthenticationToken token, AuthenticationException ase) { // exists for passivity (the superclass does a null check before publishing) getApplicationEventPublisher().publishEvent(new JaasAuthenticationFailedEvent(token, ase)); } public Resource getLoginConfig() { return this.loginConfig; } /** * Set the JAAS login configuration file. * @param loginConfig * * @see <a href= * "https://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/JAASRefGuide.html">JAAS * Reference</a>
*/ public void setLoginConfig(Resource loginConfig) { this.loginConfig = loginConfig; } /** * If set, a call to {@code Configuration#refresh()} will be made by * {@code #configureJaas(Resource) } method. Defaults to {@code true}. * @param refresh set to {@code false} to disable reloading of the configuration. May * be useful in some environments. * @see <a href="https://jira.springsource.org/browse/SEC-1320">SEC-1320</a> */ public void setRefreshConfigurationOnStartup(boolean refresh) { this.refreshConfigurationOnStartup = refresh; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\JaasAuthenticationProvider.java
1
请完成以下Java代码
public String getId() { return id; } public String getName() { return name; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseDefinitionId() { return caseDefinitionId; } public Date getReachedBefore() { return reachedBefore; }
public Date getReachedAfter() { return reachedAfter; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java
1
请完成以下Java代码
public static DelegateExecution getParentInstanceExecutionInMultiInstance(ExecutionEntity execution) { ExecutionEntity instanceExecution = null; ExecutionEntity currentExecution = execution; while (currentExecution != null && instanceExecution == null && currentExecution.getParentId() != null) { if (currentExecution.getParent().isMultiInstanceRoot()) { instanceExecution = currentExecution; } else { currentExecution = currentExecution.getParent(); } } return instanceExecution; } /** * Returns the list of boundary event activity ids that are in the the process model, * associated with the current activity of the passed execution. * Note that no check if made here whether this an active child execution for those boundary events. */ public static List<String> getBoundaryEventActivityIds(DelegateExecution execution) { Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
String activityId = execution.getCurrentActivityId(); if (StringUtils.isNotEmpty(activityId)) { List<String> boundaryEventActivityIds = new ArrayList<>(); List<BoundaryEvent> boundaryEvents = process.findFlowElementsOfType(BoundaryEvent.class, true); for (BoundaryEvent boundaryEvent : boundaryEvents) { if (activityId.equals(boundaryEvent.getAttachedToRefId())) { boundaryEventActivityIds.add(boundaryEvent.getId()); } } return boundaryEventActivityIds; } else { return Collections.emptyList(); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\ExecutionGraphUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class ProxyExchangeWebMvcProperties { /** * Properties prefix. */ public static final String PREFIX = "spring.cloud.gateway.proxy-exchange.webmvc"; /** * Contains headers that are considered sensitive by default. */ public static Set<String> DEFAULT_SENSITIVE = Set.of("cookie", "authorization"); /** * Contains headers that are skipped by default. */ public static Set<String> DEFAULT_SKIPPED = Set.of("content-length", "host"); /** * Fixed header values that will be added to all downstream requests. */ private Map<String, String> headers = new LinkedHashMap<>(); /** * A set of header names that should be sent downstream by default. */ private Set<String> autoForward = new HashSet<>(); /** * A set of sensitive header names that will not be sent downstream by default. */ private Set<String> sensitive = DEFAULT_SENSITIVE; /** * A set of header names that will not be sent downstream because they could be * problematic. */ private Set<String> skipped = DEFAULT_SKIPPED; public Map<String, String> getHeaders() { return headers; }
public void setHeaders(Map<String, String> headers) { this.headers = headers; } public Set<String> getAutoForward() { return autoForward; } public void setAutoForward(Set<String> autoForward) { this.autoForward = autoForward; } public Set<String> getSensitive() { return sensitive; } public void setSensitive(Set<String> sensitive) { this.sensitive = sensitive; } public Set<String> getSkipped() { return skipped; } public void setSkipped(Set<String> skipped) { this.skipped = skipped; } public HttpHeaders convertHeaders() { HttpHeaders headers = new HttpHeaders(); for (String key : this.headers.keySet()) { headers.set(key, this.headers.get(key)); } return headers; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\config\ProxyExchangeWebMvcProperties.java
2
请在Spring Boot框架中完成以下Java代码
void setSecurityWebFilterChains(List<SecurityWebFilterChain> securityWebFilterChains) { this.securityWebFilterChains = securityWebFilterChains; } @Autowired(required = false) void setFilterChainPostProcessor(ObjectPostProcessor<WebFilterChainDecorator> postProcessor) { this.postProcessor = postProcessor; } @Bean(SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME) @Order(WEB_FILTER_CHAIN_FILTER_ORDER) WebFilterChainProxy springSecurityWebFilterChainFilter(ObjectProvider<ServerWebExchangeFirewall> firewall, ObjectProvider<ServerExchangeRejectedHandler> rejectedHandler) { WebFilterChainProxy proxy = new WebFilterChainProxy(getSecurityWebFilterChains()); WebFilterChainDecorator decorator = this.postProcessor.postProcess(new DefaultWebFilterChainDecorator()); proxy.setFilterChainDecorator(decorator); firewall.ifUnique(proxy::setFirewall); rejectedHandler.ifUnique(proxy::setExchangeRejectedHandler); return proxy; } @Bean(name = AbstractView.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME) CsrfRequestDataValueProcessor requestDataValueProcessor() { return new CsrfRequestDataValueProcessor(); } @Bean static RsaKeyConversionServicePostProcessor conversionServicePostProcessor() { return new RsaKeyConversionServicePostProcessor(); } private List<SecurityWebFilterChain> getSecurityWebFilterChains() { List<SecurityWebFilterChain> result = this.securityWebFilterChains; if (ObjectUtils.isEmpty(result)) { return Arrays.asList(springSecurityFilterChain()); } return result; } private SecurityWebFilterChain springSecurityFilterChain() { ServerHttpSecurity http = this.context.getBean(ServerHttpSecurity.class); return springSecurityFilterChain(http); } /** * The default {@link ServerHttpSecurity} configuration. * @param http * @return */
private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults()); http.formLogin(withDefaults()); } SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard { static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请完成以下Java代码
public boolean isZeroTax() { return getRate().signum() == 0; } // isZeroTax @Override public String toString() { StringBuffer sb = new StringBuffer("MTax[") .append(get_ID()) .append(", Name = ").append(getName()) .append(", SO/PO=").append(getSOPOType()) .append(", Rate=").append(getRate()) .append(", C_TaxCategory_ID=").append(getC_TaxCategory_ID()) .append(", Summary=").append(isSummary()) .append(", Parent=").append(getParent_Tax_ID()) .append(", Country=").append(getC_Country_ID()).append("|").append(getTo_Country_ID()) .append(", Region=").append(getC_Region_ID()).append("|").append(getTo_Region_ID()) .append("]"); return sb.toString(); } // toString /**
* After Save * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave (boolean newRecord, boolean success) { if (newRecord && success) insert_Accounting("C_Tax_Acct", "C_AcctSchema_Default", null); return success; } // afterSave /** * Before Delete * @return true */ @Override protected boolean beforeDelete () { return delete_Accounting("C_Tax_Acct"); } // beforeDelete } // MTax
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTax.java
1
请完成以下Java代码
public static String key(String name) { return PREFIX + "." + name; } private final String version; private final boolean isEnterprise; private final String formattedVersion; public CamundaBpmVersion() { this(ProcessEngine.class.getPackage()); } CamundaBpmVersion(final Package pkg) { this.version = Optional.ofNullable(pkg.getImplementationVersion()) .map(String::trim) .orElse(""); this.isEnterprise = version.endsWith("-ee"); this.formattedVersion = String.format(VERSION_FORMAT, version); } @Override public String get() {
return version; } public boolean isEnterprise() { return isEnterprise; } public PropertiesPropertySource getPropertiesPropertySource() { final Properties props = new Properties(); props.put(key(VERSION), version); props.put(key(IS_ENTERPRISE), isEnterprise); props.put(key(FORMATTED_VERSION), formattedVersion); return new PropertiesPropertySource(this.getClass().getSimpleName(), props); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\CamundaBpmVersion.java
1
请完成以下Java代码
public int getValue() { return value; } public static boolean equals(@Nullable final JsonMetasfreshId id1, @Nullable final JsonMetasfreshId id2) { return Objects.equals(id1, id2); } @Nullable public static Integer toValue(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return null; } return externalId.getValue(); } public static int toValueInt(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return -1; } return externalId.getValue(); } public static String toValueStr(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return "-1"; } return String.valueOf(externalId.getValue()); }
@NonNull public static Optional<Integer> toValueOptional(@Nullable final JsonMetasfreshId externalId) { return Optional.ofNullable(toValue(externalId)); } @Nullable public static <T> T mapToOrNull(@Nullable final JsonMetasfreshId externalId, @NonNull final Function<Integer, T> mapper) { return toValueOptional(externalId).map(mapper).orElse(null); } @Nullable public static String toValueStrOrNull(@Nullable final JsonMetasfreshId externalId) { if (externalId == null) { return null; } return String.valueOf(externalId.getValue()); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\common\JsonMetasfreshId.java
1
请在Spring Boot框架中完成以下Java代码
public PlatformTransactionManager hibernateTransactionManager() { final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } @Bean public IFooDao fooHibernateDao() { return new FooHibernateDao(); }
private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "false"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\spring\PersistenceConfig.java
2
请完成以下Java代码
private void publishInvitations(final I_C_RfQResponse rfqResponse) { final List<SyncRfQ> syncRfqs = SyncObjectsFactory.newFactory() .createSyncRfQs(rfqResponse); if (syncRfqs.isEmpty()) { logger.debug("Skip publishing the invitations because there are none for {}", rfqResponse); return; } this.syncRfQs.addAll(syncRfqs); } private void publishRfqClose(final I_C_RfQResponse rfqResponse) { for (final I_C_RfQResponseLine rfqResponseLine : pmmRfqDAO.retrieveResponseLines(rfqResponse)) { publishRfQClose(rfqResponseLine); } } private void publishRfQClose(final I_C_RfQResponseLine rfqResponseLine) { // Create and collect the RfQ close event final boolean winnerKnown = true; final SyncRfQCloseEvent syncRfQCloseEvent = syncObjectsFactory.createSyncRfQCloseEvent(rfqResponseLine, winnerKnown); if (syncRfQCloseEvent != null) { syncRfQCloseEvents.add(syncRfQCloseEvent); syncProductSupplies.addAll(syncRfQCloseEvent.getPlannedSupplies()); } } private void pushToWebUI() { trxManager.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> pushToWebUINow()); } private void pushToWebUINow() { // // Push new RfQs final List<SyncRfQ> syncRfQsCopy = copyAndClear(this.syncRfQs);
if (!syncRfQsCopy.isEmpty()) { webuiPush.pushRfQs(syncRfQsCopy); } // Push close events { final List<SyncRfQCloseEvent> syncRfQCloseEventsCopy = copyAndClear(this.syncRfQCloseEvents); if (!syncRfQCloseEventsCopy.isEmpty()) { webuiPush.pushRfQCloseEvents(syncRfQCloseEventsCopy); } // Internally push the planned product supplies, to create the PMM_PurchaseCandidates serverSyncBL.reportProductSupplies(PutProductSuppliesRequest.of(syncProductSupplies)); } } private static <T> List<T> copyAndClear(final List<T> list) { if (list == null || list.isEmpty()) { return ImmutableList.of(); } final List<T> listCopy = ImmutableList.copyOf(list); list.clear(); return listCopy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\PMMWebuiRfQResponsePublisherInstance.java
1
请在Spring Boot框架中完成以下Java代码
public List<T> findJobsToExecute(List<String> enabledCategories, Page page) { return dataManager.findJobsToExecute(enabledCategories, page); } @Override public List<T> findJobsByExecutionId(String executionId) { return dataManager.findJobsByExecutionId(executionId); } @Override public List<T> findJobsByProcessInstanceId(String processInstanceId) { return dataManager.findJobsByProcessInstanceId(processInstanceId); } @Override public List<T> findExpiredJobs(List<String> enabledCategories, Page page) { return dataManager.findExpiredJobs(enabledCategories, page); } @Override
public void resetExpiredJob(String jobId) { dataManager.resetExpiredJob(jobId); } @Override public void bulkUpdateJobLockWithoutRevisionCheck(List<T> jobEntities, String lockOwner, Date lockExpirationTime) { dataManager.bulkUpdateJobLockWithoutRevisionCheck(jobEntities, lockOwner, lockExpirationTime); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateJobTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobInfoEntityManagerImpl.java
2
请完成以下Java代码
public void triggerSyncAvailableForSales(@NonNull final I_C_OrderLine orderLineRecord) { syncOrderLineWithAvailableForSales(orderLineRecord); if (!InterfaceWrapperHelper.isNew(orderLineRecord)) { final I_C_OrderLine orderLineOld = InterfaceWrapperHelper.createOld(orderLineRecord, I_C_OrderLine.class); syncOrderLineWithAvailableForSales(orderLineOld); } } private void syncOrderLineWithAvailableForSales(@NonNull final I_C_OrderLine orderLineRecord) { if (!availableForSalesUtil.isOrderLineEligibleForFeature(orderLineRecord)) { return; } final boolean isOrderEligibleForFeature = availableForSalesUtil.isOrderEligibleForFeature(OrderId.ofRepoId(orderLineRecord.getC_Order_ID())); if (!isOrderEligibleForFeature) { return; } final AvailableForSalesConfig config = getAvailableForSalesConfig(orderLineRecord);
if (!config.isFeatureEnabled()) { return; // nothing to do } availableForSalesUtil.syncAvailableForSalesForOrderLine(orderLineRecord, config); } @NonNull private AvailableForSalesConfig getAvailableForSalesConfig(@NonNull final I_C_OrderLine orderLineRecord) { return availableForSalesConfigRepo.getConfig( AvailableForSalesConfigRepo.ConfigQuery.builder() .clientId(ClientId.ofRepoId(orderLineRecord.getAD_Client_ID())) .orgId(OrgId.ofRepoId(orderLineRecord.getAD_Org_ID())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\interceptor\C_OrderLine.java
1
请完成以下Java代码
public void setRecordKey(RecordKey recordKey) { this.recordKey = recordKey; } public KafkaPartition getPartition() { return partition; } public void setPartition(KafkaPartition partition) { this.partition = partition; } @JsonInclude(Include.NON_NULL) public static class KafkaPartition { protected String eventField; protected String roundRobin; protected String delegateExpression; public String getEventField() { return eventField; } public void setEventField(String eventField) { this.eventField = eventField; } public String getRoundRobin() { return roundRobin; } public void setRoundRobin(String roundRobin) { this.roundRobin = roundRobin; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } }
@JsonInclude(Include.NON_NULL) public static class RecordKey { protected String fixedValue; protected String eventField; protected String delegateExpression; public String getFixedValue() { return fixedValue; } public void setFixedValue(String fixedValue) { this.fixedValue = fixedValue; } public String getEventField() { return eventField; } public void setEventField(String eventField) { this.eventField = eventField; } public String getDelegateExpression() { return delegateExpression; } public void setDelegateExpression(String delegateExpression) { this.delegateExpression = delegateExpression; } // backward compatibility @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static RecordKey fromFixedValue(String fixedValue) { RecordKey recordKey = new RecordKey(); recordKey.setFixedValue(fixedValue); return recordKey; } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaOutboundChannelModel.java
1
请完成以下Java代码
public class GenericIdentification32 { @XmlElement(name = "Id", required = true) protected String id; @XmlElement(name = "Tp") @XmlSchemaType(name = "string") protected PartyType3Code tp; @XmlElement(name = "Issr") @XmlSchemaType(name = "string") protected PartyType4Code issr; @XmlElement(name = "ShrtNm") protected String shrtNm; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link PartyType3Code } * */ public PartyType3Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link PartyType3Code } * */ public void setTp(PartyType3Code value) { this.tp = value; } /** * Gets the value of the issr property. * * @return
* possible object is * {@link PartyType4Code } * */ public PartyType4Code getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link PartyType4Code } * */ public void setIssr(PartyType4Code value) { this.issr = value; } /** * Gets the value of the shrtNm property. * * @return * possible object is * {@link String } * */ public String getShrtNm() { return shrtNm; } /** * Sets the value of the shrtNm property. * * @param value * allowed object is * {@link String } * */ public void setShrtNm(String value) { this.shrtNm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\GenericIdentification32.java
1
请在Spring Boot框架中完成以下Java代码
public MedicineProcessor medicineProcessor(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineProcessor medicineProcessor = new MedicineProcessor(); enrichWithJobParameters(jobParameters, medicineProcessor); return medicineProcessor; } @Bean @StepScope public MedicineWriter medicineWriter(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineWriter medicineWriter = new MedicineWriter(); enrichWithJobParameters(jobParameters, medicineWriter); return medicineWriter; } @Bean public Job medExpirationJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, MedicineWriter medicineWriter, MedicineProcessor medicineProcessor, ExpiresSoonMedicineReader expiresSoonMedicineReader) { Step notifyAboutExpiringMedicine = new StepBuilder("notifyAboutExpiringMedicine", jobRepository).<Medicine, Medicine>chunk(10) .reader(expiresSoonMedicineReader) .processor(medicineProcessor) .writer(medicineWriter) .faultTolerant() .transactionManager(transactionManager) .build();
return new JobBuilder("medExpirationJob", jobRepository).incrementer(new RunIdIncrementer()) .start(notifyAboutExpiringMedicine) .build(); } private void enrichWithJobParameters(Map<String, Object> jobParameters, ContainsJobParameters container) { if (jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) != null) { container.setTriggeredDateTime(ZonedDateTime.parse(jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) .toString())); } if (jobParameters.get(BatchConstants.TRACE_ID) != null) { container.setTraceId(jobParameters.get(BatchConstants.TRACE_ID) .toString()); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\BatchConfiguration.java
2
请完成以下Java代码
public class DocumentsType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice", required = true) protected List<DocumentType> document; @XmlAttribute(name = "number", required = true) @XmlSchemaType(name = "unsignedLong") protected BigInteger number; /** * Gets the value of the document property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the document property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDocument().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentType } * * */ public List<DocumentType> getDocument() { if (document == null) {
document = new ArrayList<DocumentType>(); } return this.document; } /** * Gets the value of the number property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNumber() { return number; } /** * Sets the value of the number property. * * @param value * allowed object is * {@link BigInteger } * */ public void setNumber(BigInteger value) { this.number = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DocumentsType.java
1
请在Spring Boot框架中完成以下Java代码
public String auditUI(Model model, @RequestParam("id") String id) { RpSettRecord settRecord = rpSettQueryService.getDataById(id); model.addAttribute("settRecord", settRecord); return "sett/audit"; } /** * 函数功能说明 : 发起结算 * * @参数: @return * @return String * @throws */ @RequiresPermissions("sett:record:edit") @RequestMapping(value = "/audit", method = RequestMethod.POST) public String audit(HttpServletRequest request, Model model, DwzAjax dwz) { String settId = request.getParameter("settId"); String settStatus = request.getParameter("settStatus"); String remark = request.getParameter("remark"); rpSettHandleService.audit(settId, settStatus, remark); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 :跳转打款 * * @参数: @return * @return String * @throws */ @RequiresPermissions("sett:record:edit") @RequestMapping(value = "/remitUI", method = RequestMethod.GET) public String remitUI(Model model, @RequestParam("id") String id) { RpSettRecord settRecord = rpSettQueryService.getDataById(id); model.addAttribute("settRecord", settRecord); return "sett/remit"; } /** * 函数功能说明 : 发起打款 * * @参数: @return * @return String * @throws */ @RequiresPermissions("sett:record:edit") @RequestMapping(value = "/remit", method = RequestMethod.POST) public String remit(HttpServletRequest request, Model model, DwzAjax dwz) { String settId = request.getParameter("settId"); String settStatus = request.getParameter("settStatus");
String remark = request.getParameter("remark"); rpSettHandleService.remit(settId, settStatus, remark); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 :查看 * * @参数: @return * @return String * @throws */ @RequestMapping(value = "/view", method = RequestMethod.GET) public String view(Model model, @RequestParam("id") String id) { RpSettRecord settRecord = rpSettQueryService.getDataById(id); model.addAttribute("settRecord", settRecord); return "sett/view"; } /** * 函数功能说明 :根据支付产品获取支付方式 * * @参数: @return * @return String * @throws */ @RequestMapping(value = "/getSettAmount", method = RequestMethod.GET) @ResponseBody public RpAccount getSettAmount(@RequestParam("userNo") String userNo) { RpAccount rpAccount = rpAccountService.getDataByUserNo(userNo); return rpAccount; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\sett\SettController.java
2
请在Spring Boot框架中完成以下Java代码
public class BaseRestApiConfiguration implements ApplicationContextAware { protected ApplicationContext applicationContext; protected MultipartConfigElement multipartConfigElement; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } protected ServletRegistrationBean registerServlet(FlowableServlet servletProperties, Class<?> baseConfig) { AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext(); dispatcherServletConfiguration.setParent(applicationContext); dispatcherServletConfiguration.register(baseConfig); DispatcherServlet servlet = new DispatcherServlet(dispatcherServletConfiguration); String path = servletProperties.getPath();
String urlMapping = (path.endsWith("/") ? path + "*" : path + "/*"); ServletRegistrationBean registrationBean = new ServletRegistrationBean(servlet, urlMapping); registrationBean.setName(servletProperties.getName()); registrationBean.setLoadOnStartup(servletProperties.getLoadOnStartup()); registrationBean.setAsyncSupported(true); if (multipartConfigElement != null) { registrationBean.setMultipartConfig(multipartConfigElement); } return registrationBean; } @Autowired(required = false) public void setMultipartConfigElement(MultipartConfigElement multipartConfigElement) { this.multipartConfigElement = multipartConfigElement; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\rest\BaseRestApiConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public static PickingLineSortBy ofCode(@NonNull final String code) { return index.ofCode(code); } @Nullable public static PickingLineSortBy ofNullableCode(@Nullable final String code) { return index.ofNullableCode(code); } private final String code; @NonNull public List<PickingJobLine> sort(@NonNull final List<PickingJobLine> lines) { return lines.stream() .sorted(getComparator()) .collect(ImmutableList.toImmutableList()); }
@NonNull private Comparator<PickingJobLine> getComparator() { switch (this) { case ORDER_LINE_SEQ_NO: return Comparator.comparing(PickingJobLine::getOrderLineSeqNo); case QTY_TO_PICK_ASC: return Comparator.comparing(PickingJobLine::getQtyToPick); case QTY_TO_PICK_DESC: return Comparator.comparing(PickingJobLine::getQtyToPick).reversed(); default: throw new AdempiereException("Unsupported value! this =" + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\PickingLineSortBy.java
2
请完成以下Java代码
default List<String> getGrantTypes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.GRANT_TYPES); } /** * Returns the OAuth 2.0 {@code response_type} values that the Client will restrict * itself to using {@code (response_types)}. * @return the OAuth 2.0 {@code response_type} values that the Client will restrict * itself to using */ default List<String> getResponseTypes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.RESPONSE_TYPES); } /** * Returns the OAuth 2.0 {@code scope} values that the Client will restrict itself to * using {@code (scope)}.
* @return the OAuth 2.0 {@code scope} values that the Client will restrict itself to * using */ default List<String> getScopes() { return getClaimAsStringList(OAuth2ClientMetadataClaimNames.SCOPE); } /** * Returns the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}. * @return the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)} */ default URL getJwkSetUrl() { return getClaimAsURL(OAuth2ClientMetadataClaimNames.JWKS_URI); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2ClientMetadataClaimAccessor.java
1
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); int i = 1; for (Word word : innerList) { sb.append(word.getValue()); String label = word.getLabel(); if (label != null) { sb.append('/').append(label); } if (i != innerList.size()) { sb.append(' '); } ++i; } sb.append("]/"); sb.append(label); return sb.toString(); } /** * 转换为一个简单词 * @return */ public Word toWord() { return new Word(getValue(), getLabel()); } public CompoundWord(List<Word> innerList, String label) { this.innerList = innerList; this.label = label; } public static CompoundWord create(String param) { if (param == null) return null; int cutIndex = param.lastIndexOf(']');
if (cutIndex <= 2 || cutIndex == param.length() - 1) return null; String wordParam = param.substring(1, cutIndex); List<Word> wordList = new LinkedList<Word>(); for (String single : wordParam.split("\\s+")) { if (single.length() == 0) continue; Word word = Word.create(single); if (word == null) { Predefine.logger.warning("使用参数" + single + "构造单词时发生错误"); return null; } wordList.add(word); } String labelParam = param.substring(cutIndex + 1); if (labelParam.startsWith("/")) { labelParam = labelParam.substring(1); } return new CompoundWord(wordList, labelParam); } @Override public Iterator<Word> iterator() { return innerList.iterator(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\CompoundWord.java
1
请完成以下Java代码
public class Serie { private String name; private String type; private List<Double> data; private Label label; 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 List<Double> getData() {
return data; } public void setData(List<Double> data) { this.data = data; } public Label getLabel() { return label; } public void setLabel(Label label) { this.label = label; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\Serie.java
1
请完成以下Java代码
protected TableRecordReference extractModelToEnqueueFromItem(final Collector collector, final Object model) { return TableRecordReference.of(model); } @Nullable @Override protected UserId extractUserInChargeOrNull(final Object model) { final Properties ctx = extractCtxFromItem(model); return Env.getLoggedUserIdIfExists(ctx).orElse(null); } @Override public Optional<AsyncBatchId> extractAsyncBatchFromItem(final WorkpackagesOnCommitSchedulerTemplate<Object>.Collector collector, final Object item) { return asyncBatchBL.getAsyncBatchId(item); } }; static { SCHEDULER.setCreateOneWorkpackagePerAsyncBatch(true); } // services private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class); private final transient IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private final transient IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class);
@Override public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName) { try (final IAutoCloseable ignored = invoiceCandBL.setUpdateProcessInProgress()) { final List<Object> models = queueDAO.retrieveAllItemsSkipMissing(workpackage, Object.class); for (final Object model : models) { try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(model)) { final List<I_C_Invoice_Candidate> invoiceCandidates = invoiceCandidateHandlerBL.createMissingCandidatesFor(model); Loggables.addLog("Created {} invoice candidate for {}", invoiceCandidates.size(), model); } } } catch (final LockFailedException e) { // One of the models could not be locked => postpone processing this workpackage throw WorkpackageSkipRequestException.createWithThrowable("Skip processing because: " + e.getLocalizedMessage(), e); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\CreateMissingInvoiceCandidatesWorkpackageProcessor.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); }
/** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } @Override public String getBeforeChangeWarning() { return (String)get_Value(COLUMNNAME_BeforeChangeWarning); } @Override public void setBeforeChangeWarning(String BeforeChangeWarning) { set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public String getProcessDefinitionTenantId() { return processDefinitionTenantId; } public boolean isProcessDefinitionTenantIdSet() { return isProcessDefinitionTenantIdSet; } public void setModificationBuilder(ProcessInstanceModificationBuilderImpl modificationBuilder) { this.modificationBuilder = modificationBuilder; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId){ this.restartedProcessInstanceId = restartedProcessInstanceId; } public String getRestartedProcessInstanceId(){ return restartedProcessInstanceId;
} public static ProcessInstantiationBuilder createProcessInstanceById(CommandExecutor commandExecutor, String processDefinitionId) { ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor); builder.processDefinitionId = processDefinitionId; return builder; } public static ProcessInstantiationBuilder createProcessInstanceByKey(CommandExecutor commandExecutor, String processDefinitionKey) { ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor); builder.processDefinitionKey = processDefinitionKey; return builder; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstantiationBuilderImpl.java
1
请完成以下Java代码
public class ExchangeRateInformation1 { @XmlElement(name = "XchgRate") protected BigDecimal xchgRate; @XmlElement(name = "RateTp") @XmlSchemaType(name = "string") protected ExchangeRateType1Code rateTp; @XmlElement(name = "CtrctId") protected String ctrctId; /** * Gets the value of the xchgRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getXchgRate() { return xchgRate; } /** * Sets the value of the xchgRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setXchgRate(BigDecimal value) { this.xchgRate = value; } /** * Gets the value of the rateTp property. * * @return * possible object is * {@link ExchangeRateType1Code } * */ public ExchangeRateType1Code getRateTp() { return rateTp; } /** * Sets the value of the rateTp property. * * @param value * allowed object is * {@link ExchangeRateType1Code } * */
public void setRateTp(ExchangeRateType1Code value) { this.rateTp = value; } /** * Gets the value of the ctrctId property. * * @return * possible object is * {@link String } * */ public String getCtrctId() { return ctrctId; } /** * Sets the value of the ctrctId property. * * @param value * allowed object is * {@link String } * */ public void setCtrctId(String value) { this.ctrctId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ExchangeRateInformation1.java
1
请完成以下Java代码
public org.compiere.model.I_M_InventoryLine getM_InventoryLine() { return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class); } @Override public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } @Override public void setM_InventoryLine_ID (final int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null); else set_Value (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID); } @Override public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); } @Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override 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_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID) { if (MD_Candidate_StockChange_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID); } @Override public int getMD_Candidate_StockChange_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public ServletContextInitializer servletContextInitializer() { return (servletContext) -> { ServletRegistration initServlet = servletContext.addServlet("initServlet", InitServlet.class); initServlet.addMapping("/initServlet"); initServlet.setInitParameter("name", "initServlet"); initServlet.setInitParameter("sex", "man"); }; } @Bean public RestTemplate defaultRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(5)) .basicAuthentication("test", "test") .build(); }
@Bean public RestClient defaultRestClient(RestClient.Builder restClientBuilder) { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS .withConnectTimeout(Duration.ofSeconds(3)) .withReadTimeout(Duration.ofSeconds(3)); ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories.get(settings); return restClientBuilder .baseUrl("http://localhost:8080") .defaultHeader("Authorization", "Bearer test") .requestFactory(requestFactory) .build(); } }
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\config\WebConfig.java
2
请完成以下Java代码
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { final Object id = evalCtx.getSingleIdToFilterAsObject(); if (id == null) { throw new IllegalStateException("No ID provided in " + evalCtx); } return getLookupValueById(id); } public LookupValue getLookupValueById(final Object idObj) { final LookupValue country = getAllCountriesById().getById(idObj); return CoalesceUtil.coalesce(country, LOOKUPVALUE_NULL); } @Override public Builder newContextForFetchingList() { return LookupDataSourceContext.builder(CONTEXT_LookupTableName) .requiresFilterAndLimit() .requiresAD_Language(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { // // Determine what we will filter final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate(); final int offset = evalCtx.getOffset(0); final int limit = evalCtx.getLimit(filter.isMatchAll() ? Integer.MAX_VALUE : 100); // // Get, filter, return return getAllCountriesById() .getValues() .stream() .filter(filter) .collect(LookupValuesList.collect()) .pageByOffsetAndLimit(offset, limit); }
private LookupValuesList getAllCountriesById() { final Object cacheKey = "ALL"; return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById); } private LookupValuesList retriveAllCountriesById() { return Services.get(ICountryDAO.class) .getCountries(Env.getCtx()) .stream() .map(this::createLookupValue) .collect(LookupValuesList.collect()); } private IntegerLookupValue createLookupValue(final I_C_Country countryRecord) { final int countryId = countryRecord.getC_Country_ID(); final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord); final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName()); final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName()); return IntegerLookupValue.of(countryId, countryName, countryDescription); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java
1
请完成以下Java代码
public void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<V> processor) { int length = text.length; int begin = 0; BaseNode<V> state = this; for (int i = begin; i < length; ++i) { state = state.transition(text[i]); if (state != null) { V value = state.getValue(); if (value != null) { processor.hit(begin, i + 1, value); } /*如果是最后一位,这里不能直接跳出循环, 要继续从下一个字符开始判断*/
if (i == length - 1) { i = begin; ++begin; state = this; } } else { i = begin; ++begin; state = this; } } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\BinTrie.java
1
请在Spring Boot框架中完成以下Java代码
private void deleteDefaultPackPermission(String packCode, String permissionId) { if (oConvertUtils.isEmpty(packCode)) { return; } //查询当前匹配非默认套餐包的其他默认套餐包 LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>(); query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT); query.eq(SysTenantPack::getPackCode, packCode); List<SysTenantPack> defaultPacks = sysTenantPackMapper.selectList(query); for (SysTenantPack pack : defaultPacks) { //删除套餐权限 deletePackPermission(pack.getId(), permissionId); } } /** * 同步同 packCode 下的相关套餐包数据 * * @param sysTenantPack */ private void syncRelatedPackDataByDefaultPack(SysTenantPack sysTenantPack) { //查询与默认套餐相同code的套餐 LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>();
query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT); query.eq(SysTenantPack::getPackCode, sysTenantPack.getPackCode()); List<SysTenantPack> relatedPacks = sysTenantPackMapper.selectList(query); for (SysTenantPack pack : relatedPacks) { //更新自定义套餐 pack.setPackName(sysTenantPack.getPackName()); pack.setStatus(sysTenantPack.getStatus()); pack.setRemarks(sysTenantPack.getRemarks()); pack.setIzSysn(sysTenantPack.getIzSysn()); sysTenantPackMapper.updateById(pack); //同步默认套餐报下的所有用户已 if (oConvertUtils.isNotEmpty(sysTenantPack.getIzSysn()) && CommonConstant.STATUS_1.equals(sysTenantPack.getIzSysn())) { this.addPackUserByPackTenantId(pack.getTenantId(), pack.getId()); } } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTenantPackServiceImpl.java
2
请完成以下Java代码
public int length() { return this.value.length(); } @Override public char charAt(int index) { return this.value.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end); } public String[] split(String regex) {
return this.value.split(regex); } /** * @return 原始字符串 */ public String get() { return this.value; } @Override public String toString() { return this.value; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
1
请完成以下Java代码
public BaseResponse report(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody ReportParam param) { _logger.info("定时报告接口 start...."); BaseResponse result = new BaseResponse(); result.setSuccess(true); result.setMsg("心跳报告成功"); return result; } /** * 版本检查接口 * * @return 版本检查结果 */ @ApiOperation(value = "APP版本更新检查", notes = "APP版本更新检查", produces = "application/json")
@RequestMapping(value = "/version", method = RequestMethod.POST) public VersionResult version(@RequestHeader(name="Content-Type", defaultValue = "application/json") String contentType, @RequestHeader(name="Authorization", defaultValue="token") String token, @RequestBody VersionParam param) { _logger.info("版本检查接口 start...."); VersionResult result = new VersionResult(); result.setAppName("AppName"); result.setDownloadUrl("http://www.baidu.com/"); result.setFindNew(true); result.setPublishtime(new Date()); result.setTips("tips"); result.setVersion("v1.2"); return result; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\PublicController.java
1
请完成以下Java代码
public class MLanguage extends X_AD_Language { /** * */ private static final long serialVersionUID = 6415602943484245447L; private static final Logger s_log = LogManager.getLogger(MLanguage.class); // metas: begin: base language /** * Load the BaseLanguage from AD_Language table and set it to {@link Language} class using {@link Language#setBaseLanguage(Language)} method. If Env.getCtx() has no <code>#AD_Language</code> set, * then this method also sets this context property. */ public static void setBaseLanguage() { Language.setBaseLanguage(() -> Services.get(ILanguageDAO.class).retrieveBaseLanguage()); // // Try to initialize the base language, if possible. try { Language.getBaseLanguage(); } catch (Exception e) { s_log.warn("Cannot initialize base language. Skip.", e); } } // metas: end public MLanguage(final Properties ctx, final int AD_Language_ID, final String trxName) { super(ctx, AD_Language_ID, trxName); } public MLanguage(final Properties ctx, final ResultSet rs, final String trxName) { super(ctx, rs, trxName); } @Override public String toString() { return "MLanguage[" + getAD_Language() + "-" + getName() + ",Language=" + getLanguageISO() + ",Country=" + getCountryCode() + "]"; } @Override protected boolean beforeSave(final boolean newRecord) { if (is_ValueChanged(COLUMNNAME_DatePattern)) { assertValidDatePattern(this); } return true; } private static final void assertValidDatePattern(I_AD_Language language) { final String datePattern = language.getDatePattern();
if (Check.isEmpty(datePattern)) { return; // OK } if (datePattern.indexOf("MM") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Month (MM)"); } if (datePattern.indexOf("dd") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Day (dd)"); } if (datePattern.indexOf("yy") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Year (yy)"); } final Locale locale = new Locale(language.getLanguageISO(), language.getCountryCode()); final SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale); try { dateFormat.applyPattern(datePattern); } catch (final Exception e) { throw new AdempiereException("@Error@ @DatePattern@ - " + e.getMessage(), e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLanguage.java
1
请完成以下Java代码
private AbstractReceiptScheduleEvent createDeletedEvent(@NonNull final I_M_ReceiptSchedule receiptSchedule) { final MaterialDescriptor orderedMaterial = createOrderMaterialDescriptor(receiptSchedule); final MinMaxDescriptor minMaxDescriptor = replenishInfoRepository.getBy(orderedMaterial).toMinMaxDescriptor(); return ReceiptScheduleDeletedEvent.builder() .eventDescriptor(EventDescriptor.ofClientAndOrg(receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID())) .materialDescriptor(orderedMaterial) .reservedQuantity(extractQtyReserved(receiptSchedule)) .receiptScheduleId(receiptSchedule.getM_ReceiptSchedule_ID()) .minMaxDescriptor(minMaxDescriptor) .build(); } private MaterialDescriptor createOrderMaterialDescriptor(@NonNull final I_M_ReceiptSchedule receiptSchedule) { final IReceiptScheduleQtysBL receiptScheduleQtysBL = Services.get(IReceiptScheduleQtysBL.class); final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
final BigDecimal orderedQuantity = receiptScheduleQtysBL.getQtyOrdered(receiptSchedule); final Timestamp preparationDate = receiptSchedule.getMovementDate(); final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(receiptSchedule); return MaterialDescriptor.builder() .date(TimeUtil.asInstant(preparationDate)) .productDescriptor(productDescriptor) .warehouseId(receiptScheduleBL.getWarehouseEffectiveId(receiptSchedule)) // .customerId() we don't have the *customer* ID .quantity(orderedQuantity) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\material\interceptor\M_ReceiptSchedule_PostMaterialEvent.java
1
请完成以下Java代码
private static void parseField(final PO po, final String columnName, final Collection<MADBoilerPlateVar> vars) { final String text = po.get_ValueAsString(columnName); if (text == null || Check.isBlank(text)) return; // final BoilerPlateContext attributes = BoilerPlateContext.builder() .setSourceDocumentFromObject(po) .build(); // final Matcher m = MADBoilerPlate.NameTagPattern.matcher(text); final StringBuffer sb = new StringBuffer(); while (m.find()) { final String refName = MADBoilerPlate.getTagName(m); // MADBoilerPlateVar var = null; for (final MADBoilerPlateVar v : vars) { if (refName.equals(v.getValue().trim())) { var = v; break; } } // final String replacement; if (var != null) { replacement = MADBoilerPlate.getPlainText(var.evaluate(attributes)); } else { replacement = m.group(); } if (replacement == null) { continue; } m.appendReplacement(sb, replacement); }
m.appendTail(sb); final String textParsed = sb.toString(); po.set_ValueOfColumn(columnName, textParsed); } private static void setDunningRunEntryNote(final I_C_DunningRunEntry dre) { final Properties ctx = InterfaceWrapperHelper.getCtx(dre); final String trxName = InterfaceWrapperHelper.getTrxName(dre); final I_C_DunningLevel dl = dre.getC_DunningLevel(); final I_C_BPartner bp = Services.get(IBPartnerDAO.class).getById(dre.getC_BPartner_ID()); final String adLanguage = bp.getAD_Language(); final String text; if (adLanguage != null) { text = InterfaceWrapperHelper.getPO(dl).get_Translation(I_C_DunningLevel.COLUMNNAME_Note, adLanguage); } else { text = dl.getNote(); } final boolean isEmbeded = true; final BoilerPlateContext attributes = BoilerPlateContext.builder() .setSourceDocumentFromObject(dre) .build(); final String textParsed = MADBoilerPlate.parseText(ctx, text, isEmbeded, attributes, trxName); dre.setNote(textParsed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\model\LettersValidator.java
1
请完成以下Java代码
public String getValue() { return this.value; } /** * Gets an instance of {@link AuthenticatorTransport}. * @param value the value of the {@link AuthenticatorTransport} * @return the {@link AuthenticatorTransport} */ public static AuthenticatorTransport valueOf(String value) { switch (value) { case "usb": return USB; case "nfc": return NFC; case "ble": return BLE;
case "smart-card": return SMART_CARD; case "hybrid": return HYBRID; case "internal": return INTERNAL; default: return new AuthenticatorTransport(value); } } public static AuthenticatorTransport[] values() { return new AuthenticatorTransport[] { USB, NFC, BLE, HYBRID, INTERNAL }; } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorTransport.java
1
请完成以下Java代码
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } /** Set Ressource. @param S_Resource_ID Resource */ @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Ressource. @return Resource */ @Override public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** * TypeMRP AD_Reference_ID=53230 * Reference name: _MRP Type */ public static final int TYPEMRP_AD_Reference_ID=53230; /** Demand = D */ public static final String TYPEMRP_Demand = "D"; /** Supply = S */ public static final String TYPEMRP_Supply = "S"; /** Set TypeMRP. @param TypeMRP TypeMRP */ @Override public void setTypeMRP (java.lang.String TypeMRP) { set_Value (COLUMNNAME_TypeMRP, TypeMRP); } /** Get TypeMRP. @return TypeMRP */ @Override public java.lang.String getTypeMRP () { return (java.lang.String)get_Value(COLUMNNAME_TypeMRP); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique
*/ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.math.BigDecimal Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.math.BigDecimal getVersion () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
1
请完成以下Java代码
public DocumentValidStatus getValidStatus() { return _validStatus; } @Override public DocumentValidStatus updateStatusIfInitialInvalidAndGet(final IDocumentChangesCollector changesCollector) { if (_validStatus.isInitialInvalid()) { updateValid(changesCollector); } return _validStatus; } @Override public boolean hasChangesToSave() { if (isReadonlyVirtualField()) { return false; }
return !isInitialValue(); } private boolean isInitialValue() { return DataTypes.equals(_value, _initialValue); } @Override public Optional<WindowId> getZoomIntoWindowId() { final LookupDataSource lookupDataSource = getLookupDataSourceOrNull(); if (lookupDataSource == null) { return Optional.empty(); } return lookupDataSource.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentField.java
1
请完成以下Java代码
public WebServer getWebServer(HttpHandler httpHandler) { ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); Server server = createJettyServer(servlet); return new JettyWebServer(server, getPort() >= 0); } /** * Set the {@link JettyResourceFactory} to get the shared resources from. * @param resourceFactory the server resources */ public void setResourceFactory(@Nullable JettyResourceFactory resourceFactory) { this.resourceFactory = resourceFactory; } protected @Nullable JettyResourceFactory getResourceFactory() { return this.resourceFactory; } protected Server createJettyServer(ServletHttpHandlerAdapter servlet) { int port = Math.max(getPort(), 0); InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = new Server(getThreadPool()); if (this.resourceFactory == null) { server.addConnector(createConnector(address, server)); } else { server.addConnector(createConnector(address, server, this.resourceFactory.getExecutor(), this.resourceFactory.getScheduler(), this.resourceFactory.getByteBufferPool())); } server.setStopTimeout(0); ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setAsyncSupported(true); ServletContextHandler contextHandler = new ServletContextHandler("/", false, false); contextHandler.addServlet(servletHolder, "/"); server.setHandler(addHandlerWrappers(contextHandler));
logger.info("Server initialized with port: " + port); if (this.getMaxConnections() > -1) { server.addBean(new NetworkConnectionLimit(this.getMaxConnections(), server)); } if (Ssl.isEnabled(getSsl())) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.isUseForwardHeaders()) { new ForwardHeadersCustomizer().customize(server); } if (getShutdown() == Shutdown.GRACEFUL) { StatisticsHandler statisticsHandler = new StatisticsHandler(); statisticsHandler.setHandler(server.getHandler()); server.setHandler(statisticsHandler); } return server; } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\reactive\JettyReactiveWebServerFactory.java
1
请完成以下Java代码
public boolean configureMessageConverters(final List<MessageConverter> messageConverters) { messageConverters.add(new MappingJackson2MessageConverter()); return true; } private static class LoggingChannelInterceptor implements ChannelInterceptor { private static final Logger logger = LogManager.getLogger(LoggingChannelInterceptor.class); @Override public void afterSendCompletion(final @NonNull Message<?> message, final @NonNull MessageChannel channel, final boolean sent, final Exception ex) { if (!sent) { logger.warn("Failed sending: message={}, channel={}, sent={}", message, channel, sent, ex); } } @Override public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex) { if (ex != null) { logger.warn("Failed receiving: message={}, channel={}", message, channel, ex); } } } private static class AuthorizationHandshakeInterceptor implements HandshakeInterceptor { private static final Logger logger = LogManager.getLogger(AuthorizationHandshakeInterceptor.class); @Override public boolean beforeHandshake(@NonNull final ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final @NonNull Map<String, Object> attributes) {
final UserSession userSession = UserSession.getCurrentOrNull(); if (userSession == null) { logger.warn("Websocket connection not allowed (missing userSession)"); response.setStatusCode(HttpStatus.UNAUTHORIZED); return false; } if (!userSession.isLoggedIn()) { logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession); response.setStatusCode(HttpStatus.UNAUTHORIZED); return false; } return true; } @Override public void afterHandshake(final @NonNull ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final Exception exception) { // nothing } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\websocket\WebsocketConfig.java
1
请完成以下Java代码
public String getMethodAsString(Object payload) { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getMethod().toGenericString(); } else { Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required"); return this.delegatingHandler.getMethodNameFor(payload); } } /** * Get the method for the payload type. * @param payload the payload. * @return the method. * @since 2.2.3 */ public Method getMethodFor(Object payload) { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getMethod(); } else { Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required"); return this.delegatingHandler.getMethodFor(payload); } } /** * Return the return type for the method that will be chosen for this payload. * @param payload the payload. * @return the return type, or null if no handler found. * @since 2.2.3 */ public Type getReturnTypeFor(Object payload) { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getMethod().getReturnType(); } else { Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required"); return this.delegatingHandler.getMethodFor(payload).getReturnType(); } } /** * Get the bean from the handler method. * @return the bean. */ public Object getBean() { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getBean(); } else { Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getBean(); } } /** * Return true if any handler method has an async reply type. * @return the asyncReply. * @since 2.2.21 */ public boolean isAsyncReplies() { return this.asyncReplies; } /** * Build an {@link InvocationResult} for the result and inbound payload. * @param result the result. * @param inboundPayload the payload. * @return the invocation result. * @since 2.1.7 */ public @Nullable InvocationResult getInvocationResultFor(Object result, Object inboundPayload) { if (this.invokerHandlerMethod != null) { return new InvocationResult(result, null, this.invokerHandlerMethod.getMethod().getGenericReturnType(), this.invokerHandlerMethod.getBean(), this.invokerHandlerMethod.getMethod()); } else { Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required"); return this.delegatingHandler.getInvocationResultFor(result, inboundPayload); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\HandlerAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public class StubProcessDefinitionDto extends ProcessDefinitionDto { public void setId(String id) { this.id = id; } public void setKey(String key) { this.key = key; } public void setCategory(String category) { this.category = category; } public void setDescription(String description) { this.description = description; } public void setName(String name) { this.name = name; } public void setVersion(int version) {
this.version = version; } public void setResource(String resource) { this.resource = resource; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setDiagram(String diagram) { this.diagram = diagram; } public void setSuspended(boolean suspended) { this.suspended = suspended; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\StubProcessDefinitionDto.java
2
请完成以下Java代码
public void close() { ProcessEngines.unregister(this); if (asyncExecutor != null && asyncExecutor.isActive()) { asyncExecutor.shutdown(); } if (asyncHistoryExecutor != null && asyncHistoryExecutor.isActive()) { asyncHistoryExecutor.shutdown(); } Runnable closeRunnable = processEngineConfiguration.getProcessEngineCloseRunnable(); if (closeRunnable != null) { closeRunnable.run(); } processEngineConfiguration.close(); if (processEngineConfiguration.getEngineLifecycleListeners() != null) { for (EngineLifecycleListener engineLifecycleListener : processEngineConfiguration.getEngineLifecycleListeners()) { engineLifecycleListener.onEngineClosed(this); } } processEngineConfiguration.getEventDispatcher().dispatchEvent(FlowableEventBuilder.createGlobalEvent(FlowableEngineEventType.ENGINE_CLOSED), processEngineConfiguration.getEngineCfgKey()); } // getters and setters // ////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public IdentityService getIdentityService() { return identityService; } @Override public ManagementService getManagementService() { return managementService;
} @Override public TaskService getTaskService() { return taskService; } @Override public HistoryService getHistoryService() { return historicDataService; } @Override public RuntimeService getRuntimeService() { return runtimeService; } @Override public RepositoryService getRepositoryService() { return repositoryService; } @Override public FormService getFormService() { return formService; } @Override public DynamicBpmnService getDynamicBpmnService() { return dynamicBpmnService; } @Override public ProcessMigrationService getProcessMigrationService() { return processInstanceMigrationService; } @Override public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessEngineImpl.java
1
请完成以下Java代码
public static boolean isInvalidIdentifierError(final Exception e) { return isErrorCode(e, 904); } /** * Check if "invalid username/password" exception (aka ORA-01017) * * @param e exception */ public static boolean isInvalidUserPassError(final Exception e) { return isErrorCode(e, 1017); } /** * Check if "time out" exception (aka ORA-01013) */ public static boolean isTimeout(final Exception e) { if (DB.isPostgreSQL()) {
return isSQLState(e, PG_SQLSTATE_query_canceled); } return isErrorCode(e, 1013); } /** * Task 08353 */ public static boolean isDeadLockDetected(final Throwable e) { if (DB.isPostgreSQL()) { return isSQLState(e, PG_SQLSTATE_deadlock_detected); } return isErrorCode(e, 40001); // not tested for oracle, just did a brief googling } } // DBException
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DBException.java
1
请完成以下Java代码
static class SuspensionStateImpl implements SuspensionState { public final int stateCode; protected final String name; public SuspensionStateImpl(int suspensionCode, String string) { this.stateCode = suspensionCode; this.name = string; } public int getStateCode() { return stateCode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + stateCode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true;
if (obj == null) return false; if (getClass() != obj.getClass()) return false; SuspensionStateImpl other = (SuspensionStateImpl) obj; if (stateCode != other.stateCode) return false; return true; } @Override public String toString() { return name; } @Override public String getName() { return name; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\SuspensionState.java
1
请在Spring Boot框架中完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Binder binder = Binder.get(this.applicationContext.getEnvironment()); List<String> wsdlLocations = binder.bind("spring.webservices.wsdl-locations", Bindable.listOf(String.class)) .orElse(Collections.emptyList()); for (String wsdlLocation : wsdlLocations) { registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, SimpleWsdl11Definition::new, registry); registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, SimpleXsdSchema::new, registry); } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } private <T> void registerBeans(String location, String pattern, Class<T> type, Function<Resource, T> beanSupplier, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { BeanDefinition beanDefinition = BeanDefinitionBuilder .rootBeanDefinition(type, () -> beanSupplier.apply(resource)) .getBeanDefinition(); String filename = resource.getFilename(); Assert.state(filename != null, "'filename' must not be null");
registry.registerBeanDefinition(StringUtils.stripFilenameExtension(filename), beanDefinition); } } private Resource[] getResources(String location, String pattern) { try { return this.applicationContext.getResources(ensureTrailingSlash(location) + pattern); } catch (IOException ex) { return new Resource[0]; } } private String ensureTrailingSlash(String path) { return path.endsWith("/") ? path : path + "/"; } } }
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\autoconfigure\WebServicesAutoConfiguration.java
2