instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class ExceptionLogger extends BaseLogger { public static final String PROJECT_CODE = "ENGINE-REST"; public static final String REST_API = "org.camunda.bpm.engine.rest.exception"; public static final ExceptionLogger REST_LOGGER = BaseLogger.createLogger(ExceptionLogger.class, PROJECT_CODE, REST_API, "HTTP" ); public void log(Throwable throwable) { Response.Status status = ExceptionHandlerHelper.getInstance().getStatus(throwable); int statusCode = status.getStatusCode(); if (statusCode < 500) { logDebug(String.valueOf(statusCode), getExceptionStacktrace(throwable)); return; } logInternalServerAndOtherStatusCodes(throwable, statusCode); } protected void logInternalServerAndOtherStatusCodes(Throwable throwable, int statusCode) { if (isPersistenceConnectionError(throwable)) { logError(String.valueOf(statusCode), getExceptionStacktrace(throwable)); return; } logWarn(String.valueOf(statusCode), getExceptionStacktrace(throwable)); } protected boolean isPersistenceConnectionError(Throwable throwable) { boolean isPersistenceException = (throwable instanceof ProcessEnginePersistenceException); if (!isPersistenceException) { return false; }
SQLException sqlException = getSqlException((ProcessEnginePersistenceException) throwable); if (sqlException == null) { return false; } String sqlState = sqlException.getSQLState(); return sqlState != null && sqlState.startsWith(PERSISTENCE_CONNECTION_ERROR_CLASS); } protected SQLException getSqlException(ProcessEnginePersistenceException e) { boolean hasTwoCauses = e.getCause() != null && e.getCause().getCause() != null; if (!hasTwoCauses) { return null; } Throwable cause = e.getCause().getCause(); return cause instanceof SQLException ? (SQLException) cause : null; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\exception\ExceptionLogger.java
1
请完成以下Java代码
public TablePageQueryImpl tableName(String tableName) { this.tableName = tableName; return this; } public TablePageQueryImpl orderAsc(String column) { addOrder(column, AbstractQuery.SORTORDER_ASC); return this; } public TablePageQueryImpl orderDesc(String column) { addOrder(column, AbstractQuery.SORTORDER_DESC); return this; } public String getTableName() { return tableName; } protected void addOrder(String column, String sortOrder) { if (order == null) { order = "";
} else { order = order + ", "; } order = order + column + " " + sortOrder; } public TablePage listPage(int firstResult, int maxResults) { this.firstResult = firstResult; this.maxResults = maxResults; return commandExecutor.execute(this); } public TablePage execute(CommandContext commandContext) { return commandContext.getTableDataManager().getTablePage(this, firstResult, maxResults); } public String getOrder() { return order; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TablePageQueryImpl.java
1
请完成以下Java代码
public Resource newInstance(ModelTypeInstanceContext instanceContext) { return new ResourceImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .required() .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); resourceParameterCollection = sequenceBuilder.elementCollection(ResourceParameter.class) .build(); typeBuilder.build(); }
public ResourceImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<ResourceParameter> getResourceParameters() { return resourceParameterCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceImpl.java
1
请完成以下Java代码
private static void updateDescription(@NonNull final I_I_BankStatement importRecord) { final String lineDescription = Joiner.on(" / ") .skipNulls() .join(StringUtils.trimBlankToNull(importRecord.getLineDescription()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_1()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_2()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_3()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_4())); importRecord.setLineDescription(lineDescription); } /** * @return {@link I_I_BankStatement#getAmtFormat()} if exists. Try to autodetect if not exists. */ @NonNull @VisibleForTesting static String getAmtFormat(@NonNull final I_I_BankStatement importRecord) { if (Check.isNotBlank(importRecord.getAmtFormat()))
{ //noinspection ConstantConditions return importRecord.getAmtFormat(); } // try to autodetect the current format if (Check.isNotBlank(importRecord.getDebitOrCreditIndicator()) && importRecord.getDebitOrCreditAmt().signum() != 0) { return X_I_BankStatement.AMTFORMAT_AmountPlusIndicator; } else if (importRecord.getDebitStmtAmt().signum() != 0 || importRecord.getCreditStmtAmt().signum() != 0) { return X_I_BankStatement.AMTFORMAT_DebitPlusCredit; } else if (importRecord.getTrxAmt() != null) { return X_I_BankStatement.AMTFORMAT_Straight; } throw new AdempiereException("Invalid Amount format."); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\impexp\BankStatementImportProcess.java
1
请完成以下Java代码
private void sleep() throws InterruptedException { final Duration pollInterval = getPollInterval(); logger.debug("Sleeping {}", pollInterval); Thread.sleep(pollInterval.toMillis()); } private Duration getPollInterval() { final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1); return pollIntervalInSeconds > 0 ? Duration.ofSeconds(pollIntervalInSeconds) : DEFAULT_PollInterval; } private QueryLimit getRetrieveBatchSize() { final int retrieveBatchSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveBatchSize, -1); return retrieveBatchSize > 0 ? QueryLimit.ofInt(retrieveBatchSize) : DEFAULT_RetrieveBatchSize; } @VisibleForTesting FactAcctLogProcessResult processNow() { FactAcctLogProcessResult finalResult = FactAcctLogProcessResult.ZERO;
boolean mightHaveMore; do { final QueryLimit retrieveBatchSize = getRetrieveBatchSize(); final FactAcctLogProcessResult result = factAcctLogService.processAll(retrieveBatchSize); finalResult = finalResult.combineWith(result); mightHaveMore = retrieveBatchSize.isLessThanOrEqualTo(result.getProcessedLogRecordsCount()); logger.debug("processNow: retrieveBatchSize={}, result={}, mightHaveMore={}", retrieveBatchSize, result, mightHaveMore); } while (mightHaveMore); logger.debug("processNow: DONE. Processed {}", finalResult); return finalResult; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\FactAcctLogDBTableWatcher.java
1
请完成以下Java代码
public class Account { private Long id; private String iban; private BigDecimal balance; public Account() {} public Account(Long id, String iban, BigDecimal balance) { this.id = id; this.iban = iban; this.balance = balance; } public Account(Long id, String iban, Double balance) { this.id = id; this.iban = iban; this.balance = new BigDecimal(balance); } /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /**
* @return the iban */ public String getIban() { return iban; } /** * @param iban the iban to set */ public void setIban(String iban) { this.iban = iban; } /** * @return the balance */ public BigDecimal getBalance() { return balance; } /** * @param balance the balance to set */ public void setBalance(BigDecimal balance) { this.balance = balance; } }
repos\tutorials-master\persistence-modules\r2dbc\src\main\java\com\baeldung\examples\r2dbc\Account.java
1
请在Spring Boot框架中完成以下Java代码
public class AccountSetting { @Id @GeneratedValue private Long id; @Column(name = "name", nullable = false) private String settingName; @Column(name = "value", nullable = false) private String settingValue; @ManyToOne() @JoinColumn(name ="account_id", nullable = false) private Account account; public AccountSetting() { } public AccountSetting(String settingName, String settingValue) { this.settingName = settingName; this.settingValue = settingValue; } public Long getId() { return id; } public void setId(Long id) { this.id = id;
} public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; } public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\schemageneration\model\AccountSetting.java
2
请在Spring Boot框架中完成以下Java代码
public boolean matches(Class<?> clazz) { return this.expression.couldMatchJoinPointsInType(clazz); } @Override public boolean matches(Method method, Class<?> targetClass) { return this.expression.matchesMethodExecution(method).alwaysMatches(); } @Override public boolean isRuntime() { return false; } @Override
public boolean matches(Method method, Class<?> targetClass, Object... args) { return matches(method, targetClass); } @Override public ClassFilter getClassFilter() { return this; } @Override public MethodMatcher getMethodMatcher() { return this; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\AspectJMethodMatcher.java
2
请在Spring Boot框架中完成以下Java代码
private void prepareApiCredentials(@NonNull final Map<String, String> parameters, @NonNull final OAuth2Api oAuth2Api) throws IOException { final ApiMode apiMode = ApiMode.valueOf(parameters.get(ExternalSystemConstants.PARAM_API_MODE)); final Map<String, String> mapCredentialUtil = new HashMap<>(); mapCredentialUtil.put(CredentialParams.APP_ID.getValue(), parameters.get(ExternalSystemConstants.PARAM_APP_ID)); mapCredentialUtil.put(CredentialParams.CERT_ID.getValue(), parameters.get(ExternalSystemConstants.PARAM_CERT_ID)); mapCredentialUtil.put(CredentialParams.REDIRECT_URI.getValue(), parameters.get(ExternalSystemConstants.PARAM_REDIRECT_URL)); final Map<String, Map<String, String>> parentMap = new HashMap<>(); parentMap.put(apiMode.getValue(), mapCredentialUtil); final Yaml yaml = new Yaml(); final String output = yaml.dump(parentMap); CredentialUtil.load(output); } @NonNull private Optional<JsonExternalSystemEbayConfigMappings> getEbayOrderMappingRules(@NonNull final JsonExternalSystemRequest request)
{ final String ebayMappings = request.getParameters().get(ExternalSystemConstants.PARAM_CONFIG_MAPPINGS); if (Check.isBlank(ebayMappings)) { return Optional.empty(); } final ObjectMapper mapper = new ObjectMapper(); try { return Optional.of(mapper.readValue(ebayMappings, JsonExternalSystemEbayConfigMappings.class)); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\order\GetEbayOrdersProcessor.java
2
请完成以下Java代码
public void setLanguage(final String language) { this.language = language; this.languageSet = true; } public void setInvoiceRule(final JsonInvoiceRule invoiceRule) { this.invoiceRule = invoiceRule; this.invoiceRuleSet = true; } public void setUrl(final String url) { this.url = url; this.urlSet = true; } public void setUrl2(final String url2) { this.url2 = url2; this.url2Set = true; } public void setUrl3(final String url3) { this.url3 = url3; this.url3Set = true; } public void setGroup(final String group) {
this.group = group; this.groupSet = true; } public void setGlobalId(final String globalId) { this.globalId = globalId; this.globalIdset = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setVatId(final String vatId) { this.vatId = vatId; this.vatIdSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonPurchaseCandidate { @JsonProperty("externalSystemCode") String externalSystemCode; @JsonProperty("externalHeaderId") JsonExternalId externalHeaderId; @JsonProperty("externalLineId") JsonExternalId externalLineId; @Schema(description = "The date ordered of the purchase candidate") @JsonProperty("purchaseDateOrdered") @JsonFormat(shape = JsonFormat.Shape.STRING) ZonedDateTime purchaseDateOrdered; @Schema(description = "The promised date of the purchase candidate") @JsonProperty("purchaseDatePromised") @JsonFormat(shape = JsonFormat.Shape.STRING) ZonedDateTime purchaseDatePromised; @JsonProperty("externalPurchaseOrderUrl") String externalPurchaseOrderUrl; @JsonProperty("metasfreshId") JsonMetasfreshId metasfreshId; @JsonProperty("processed") boolean processed; @JsonProperty("purchaseOrders") List<JsonPurchaseOrder> purchaseOrders; @JsonProperty("workPackages") List<JsonWorkPackageStatus> workPackages; @Builder @JsonCreator private JsonPurchaseCandidate( @JsonProperty("externalSystemCode") @Nullable final String externalSystemCode, @JsonProperty("externalHeaderId") @Nullable final JsonExternalId externalHeaderId,
@JsonProperty("externalLineId") @Nullable final JsonExternalId externalLineId, @JsonProperty("purchaseDatePromised") @Nullable final ZonedDateTime purchaseDatePromised, @JsonProperty("purchaseDateOrdered") @Nullable final ZonedDateTime purchaseDateOrdered, @JsonProperty("externalPurchaseOrderUrl") @Nullable final String externalPurchaseOrderUrl, @JsonProperty("metasfreshId") @NonNull final JsonMetasfreshId metasfreshId, @JsonProperty("processed") final boolean processed, @JsonProperty("purchaseOrders") @Nullable @Singular final List<JsonPurchaseOrder> purchaseOrders, @JsonProperty("workPackages") @Nullable @Singular final List<JsonWorkPackageStatus> workPackages) { this.externalSystemCode = externalSystemCode; this.externalHeaderId = externalHeaderId; this.externalLineId = externalLineId; this.purchaseDatePromised = purchaseDatePromised; this.purchaseDateOrdered = purchaseDateOrdered; this.externalPurchaseOrderUrl = externalPurchaseOrderUrl; this.metasfreshId = metasfreshId; this.processed = processed; this.purchaseOrders = CoalesceUtil.coalesce(purchaseOrders, Collections.emptyList()); this.workPackages = CoalesceUtil.coalesce(workPackages, Collections.emptyList()); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\JsonPurchaseCandidate.java
2
请完成以下Java代码
public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID)); } /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity
*/ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroup.java
1
请完成以下Java代码
public List<ShipmentScheduleWithHU> retrieveShipmentSchedulesWithHUsFromHUs(@NonNull final List<I_M_HU> hus) { final IMutableHUContext huContext = huContextFactory.createMutableHUContext(); // // Iterate HUs and collect candidates from them final IHandlingUnitsBL handlingUnitsBL = handlingUnitsBL(); final ArrayList<ShipmentScheduleWithHU> result = new ArrayList<>(); for (final I_M_HU hu : hus) { // Make sure we are dealing with an top level HU if (!handlingUnitsBL.isTopLevel(hu)) { throw new HUException("HU " + hu + " shall be top level"); } // // Retrieve and create candidates from shipment schedule QtyPicked assignments final List<ShipmentScheduleWithHU> candidatesForHU = new ArrayList<>(); final List<I_M_ShipmentSchedule_QtyPicked> shipmentSchedulesQtyPicked = retrieveQtyPickedNotDeliveredForTopLevelHU(hu); for (final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked : shipmentSchedulesQtyPicked) { if (!shipmentScheduleQtyPicked.isActive()) { continue; } // NOTE: we allow negative Qtys too because they shall be part of a bigger transfer and overall qty can be positive // if (ssQtyPicked.getQtyPicked().signum() <= 0) // { // continue; // }
final ShipmentScheduleWithHU candidate = ShipmentScheduleWithHU.ofShipmentScheduleQtyPickedWithHuContext(shipmentScheduleQtyPicked, huContext); candidatesForHU.add(candidate); } // // Add the candidates for current HU to the list of all collected candidates result.addAll(candidatesForHU); // Log if there were no candidates created for current HU. if (candidatesForHU.isEmpty()) { Loggables.addLog("No eligible {} records found for hu {}", I_M_ShipmentSchedule_QtyPicked.Table_Name, handlingUnitsBL().getDisplayName(hu)); } } // // Sort result result.sort(new ShipmentScheduleWithHUComparator()); // TODO: make sure all shipment schedules are valid return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\HUShipmentScheduleDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class CommissionInstanceDAO { private final IQueryBL queryBL = Services.get(IQueryBL.class); /** * @return true if any of the {@code salesCandDocIds}'s {@link InvoiceCandidateId}s is referenced by a commission instance. */ public boolean isICsReferencedByCommissionInstances(@NonNull final Set<SalesInvoiceCandidateDocumentId> salesCandDocIds) { final ImmutableSet<InvoiceCandidateId> invoiceCandidateIds = salesCandDocIds.stream() .map(SalesInvoiceCandidateDocumentId::getInvoiceCandidateId) .collect(ImmutableSet.toImmutableSet()); return queryBL.createQueryBuilder(I_C_Commission_Instance.class) .addInArrayFilter(I_C_Commission_Instance.COLUMNNAME_C_Invoice_Candidate_ID, invoiceCandidateIds) .create() .anyMatch();
} /** * @return true if any of the {@code salesCandDocIds}'s {@link InvoiceLineId}s is referenced by a commission instance. */ public boolean isILsReferencedByCommissionInstances(@NonNull final Set<SalesInvoiceLineDocumentId> salesInvoiceLineDocumentIds) { final ImmutableSet<InvoiceAndLineId> invoiceLineIds = salesInvoiceLineDocumentIds.stream() .map(SalesInvoiceLineDocumentId::getInvoiceAndLineId) .collect(ImmutableSet.toImmutableSet()); return queryBL.createQueryBuilder(I_C_Commission_Instance.class) .addInArrayFilter(I_C_Commission_Instance.COLUMNNAME_C_InvoiceLine_ID, invoiceLineIds) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\dao\CommissionInstanceDAO.java
2
请在Spring Boot框架中完成以下Java代码
public void setDateConfirmed(Date dateConfirmed) { this.dateConfirmed = dateConfirmed; } /** * * @return the date when our local endpoint received the remote endpoint's confirmation. */ public Date getDateConfirmReceived() { return dateConfirmReceived; } public void setDateConfirmReceived(Date dateConfirmReceived)
{ this.dateConfirmReceived = dateConfirmReceived; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java
2
请完成以下Java代码
public Object getAggregatedValue(final RModelCalculationContext calculationCtx, final List<Object> groupRow) { if (!valid) { return null; } if (!isGroupBy(calculationCtx, COLUMNNAME_M_Product_ID)) { return null; } final IRModelMetadata metadata = calculationCtx.getMetadata(); final int groupProductId = getM_Product_ID(metadata, groupRow); if (groupProductId <= 0) { return null; } else if (product == null) { return BigDecimal.ZERO; } else if (product.getM_Product_ID() != groupProductId) { // shall not happen return null; } //
// Update UOM column // FIXME: dirty hack { final KeyNamePair uomKNP = new KeyNamePair(uom.getC_UOM_ID(), uom.getName()); setRowValueOrNull(metadata, groupRow, COLUMNNAME_C_UOM_ID, uomKNP); } return qty; } private final int getM_Product_ID(final IRModelMetadata metadata, final List<Object> row) { final KeyNamePair productKNP = getRowValueOrNull(metadata, row, COLUMNNAME_M_Product_ID, KeyNamePair.class); if (productKNP == null) { return -1; } return productKNP.getKey(); } private final int getC_UOM_ID(final IRModelMetadata metadata, final List<Object> row) { final KeyNamePair uomKNP = getRowValueOrNull(metadata, row, COLUMNNAME_C_UOM_ID, KeyNamePair.class); if (uomKNP == null) { return -1; } return uomKNP.getKey(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\ProductQtyRModelAggregatedValue.java
1
请在Spring Boot框架中完成以下Java代码
public Status getStatus() { return this.status; } public @Nullable Show getShowComponents() { return this.showComponents; } public void setShowComponents(@Nullable Show showComponents) { this.showComponents = showComponents; } public abstract @Nullable Show getShowDetails(); public Set<String> getRoles() { return this.roles; } public void setRoles(Set<String> roles) { this.roles = roles; } /** * Status properties for the group. */ public static class Status { /** * List of health statuses in order of severity. */
private List<String> order = new ArrayList<>(); /** * Mapping of health statuses to HTTP status codes. By default, registered health * statuses map to sensible defaults (for example, UP maps to 200). */ private final Map<String, Integer> httpMapping = new HashMap<>(); public List<String> getOrder() { return this.order; } public void setOrder(List<String> statusOrder) { if (!CollectionUtils.isEmpty(statusOrder)) { this.order = statusOrder; } } public Map<String, Integer> getHttpMapping() { return this.httpMapping; } } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthProperties.java
2
请完成以下Java代码
public class BaseResp<T> { private int status; private T data; private String message; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data;
} public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "BaseResp{" + "status=" + status + ", data=" + data + ", message='" + message + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-feign\src\main\java\com\quick\feign\entity\BaseResp.java
1
请在Spring Boot框架中完成以下Java代码
public String loginPage() { return "login.html"; } @ResponseBody @PostMapping("/login") public String login(HttpServletRequest request) { // 判断是否已经登陆 Subject subject = SecurityUtils.getSubject(); if (subject.getPrincipal() != null) { return "你已经登陆账号:" + subject.getPrincipal(); } // 获得登陆失败的原因 String shiroLoginFailure = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); // 翻译成人类看的懂的提示 String msg = ""; if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号不存在"; } else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "密码不正确"; } else if (LockedAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号被锁定"; } else if (ExpiredCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "账号已过期"; } else {
msg = "未知"; logger.error("[login][未知登陆错误:{}]", shiroLoginFailure); } return "登陆失败,原因:" + msg; } @ResponseBody @GetMapping("/login_success") public String loginSuccess() { return "登陆成功"; } @ResponseBody @GetMapping("/unauthorized") public String unauthorized() { return "你没有权限"; } }
repos\SpringBoot-Labs-master\lab-33\lab-33-shiro-demo\src\main\java\cn\iocoder\springboot\lab01\shirodemo\controller\SecurityController.java
2
请完成以下Java代码
protected boolean writeExtensionChildElements( BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw ) throws Exception { ValuedDataObject dataObject = (ValuedDataObject) element; if (StringUtils.isNotEmpty(dataObject.getId()) && dataObject.getValue() != null) { if (!didWriteExtensionStartElement) { xtw.writeStartElement(ELEMENT_EXTENSIONS); didWriteExtensionStartElement = true; } xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_DATA_VALUE, ACTIVITI_EXTENSIONS_NAMESPACE); if (dataObject.getValue() != null) { String value = null; if (dataObject instanceof DateDataObject) { value = sdf.format(dataObject.getValue()); } else { value = dataObject.getValue().toString();
} if (dataObject instanceof StringDataObject && xmlChars.matcher(value).find()) { xtw.writeCData(value); } else { xtw.writeCharacters(value); } } xtw.writeEndElement(); } return didWriteExtensionStartElement; } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {} }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\ValuedDataObjectXMLConverter.java
1
请完成以下Java代码
public class DiagnosisType { @XmlValue protected String value; @XmlAttribute(name = "type") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String type; @XmlAttribute(name = "code") protected String code; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) {
return "by_contract"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = 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\DiagnosisType.java
1
请完成以下Java代码
public FactLineBuilder toLocationOfBPartner(@Nullable final BPartnerLocationId bpartnerLocationId) { return toLocation(getServices().getLocationId(bpartnerLocationId)); } public FactLineBuilder toLocationOfLocator(final int locatorRepoId) { return toLocation(getServices().getLocationIdByLocatorRepoId(locatorRepoId)); } public FactLineBuilder costElement(@Nullable final CostElementId costElementId) { assertNotBuild(); this.costElementId = costElementId; return this; } public FactLineBuilder costElement(@Nullable final CostElement costElement) { return costElement(costElement != null ? costElement.getId() : null); } public FactLineBuilder description(@Nullable final String description) { assertNotBuild(); this.description = StringUtils.trimBlankToOptional(description); return this; } public FactLineBuilder additionalDescription(@Nullable final String additionalDescription) { assertNotBuild(); this.additionalDescription = StringUtils.trimBlankToNull(additionalDescription); return this; } public FactLineBuilder openItemKey(@Nullable FAOpenItemTrxInfo openItemTrxInfo) { assertNotBuild(); this.openItemTrxInfo = openItemTrxInfo; return this; } public FactLineBuilder productId(@Nullable ProductId productId)
{ assertNotBuild(); this.productId = Optional.ofNullable(productId); return this; } public FactLineBuilder userElementString1(@Nullable final String userElementString1) { assertNotBuild(); this.userElementString1 = StringUtils.trimBlankToOptional(userElementString1); return this; } public FactLineBuilder salesOrderId(@Nullable final OrderId salesOrderId) { assertNotBuild(); this.salesOrderId = Optional.ofNullable(salesOrderId); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLineBuilder.java
1
请完成以下Java代码
public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getTargetNamespace() { return targetNamespaceAttribute.getValue(this); } public void setTargetNamespace(String namespace) { targetNamespaceAttribute.setValue(this, namespace); } public String getExpressionLanguage() { return expressionLanguageAttribute.getValue(this); } public void setExpressionLanguage(String expressionLanguage) { expressionLanguageAttribute.setValue(this, expressionLanguage); } public String getTypeLanguage() { return typeLanguageAttribute.getValue(this); } public void setTypeLanguage(String typeLanguage) { typeLanguageAttribute.setValue(this, typeLanguage); } public String getExporter() { return exporterAttribute.getValue(this); } public void setExporter(String exporter) { exporterAttribute.setValue(this, exporter); } public String getExporterVersion() { return exporterVersionAttribute.getValue(this); } public void setExporterVersion(String exporterVersion) {
exporterVersionAttribute.setValue(this, exporterVersion); } public Collection<Import> getImports() { return importCollection.get(this); } public Collection<Extension> getExtensions() { return extensionCollection.get(this); } public Collection<RootElement> getRootElements() { return rootElementCollection.get(this); } public Collection<BpmnDiagram> getBpmDiagrams() { return bpmnDiagramCollection.get(this); } public Collection<Relationship> getRelationships() { return relationshipCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DefinitionsImpl.java
1
请完成以下Java代码
public PlanItem newInstance(ModelTypeInstanceContext instanceContext) { return new PlanItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); planItemDefinitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .idAttributeReference(PlanItemDefinition.class) .build(); entryCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ENTRY_CRITERIA_REFS) .namespace(CMMN10_NS) .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) .build(); exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS) .namespace(CMMN10_NS) .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); itemControlChild = sequenceBuilder.element(ItemControl.class) .build(); entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class) .build(); exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Rfq changeActiveRfq( @NonNull final JsonChangeRfqRequest request, @NonNull final User loggedUser) { final Rfq rfq = getUserActiveRfq( loggedUser, Long.parseLong(request.getRfqId())); for (final JsonChangeRfqQtyRequest qtyChangeRequest : request.getQuantities()) { rfq.setQtyPromised(qtyChangeRequest.getDate(), qtyChangeRequest.getQtyPromised()); } if (request.getPrice() != null) { rfq.setPricePromisedUserEntered(request.getPrice()); } saveRecursively(rfq); return rfq; } @Override public long getCountUnconfirmed(@NonNull final User user)
{ return rfqRepo.countUnconfirmed(user.getBpartner()); } @Override @Transactional public void confirmUserEntries(@NonNull final User user) { final BPartner bpartner = user.getBpartner(); final List<Rfq> rfqs = rfqRepo.findUnconfirmed(bpartner); for (final Rfq rfq : rfqs) { rfq.confirmByUser(); saveRecursivelyAndPush(rfq); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\RfQService.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult cancelTimeOutOrder() { portalOrderService.cancelTimeOutOrder(); return CommonResult.success(null); } @ApiOperation("取消单个超时订单") @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST) @ResponseBody public CommonResult cancelOrder(Long orderId) { portalOrderService.sendDelayMessageCancelOrder(orderId); return CommonResult.success(null); } @ApiOperation("按状态分页获取用户订单列表") @ApiImplicitParam(name = "status", value = "订单状态:-1->全部;0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭", defaultValue = "-1", allowableValues = "-1,0,1,2,3,4", paramType = "query", dataType = "int") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrderDetail>> list(@RequestParam Integer status, @RequestParam(required = false, defaultValue = "1") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize) { CommonPage<OmsOrderDetail> orderPage = portalOrderService.list(status,pageNum,pageSize); return CommonResult.success(orderPage); } @ApiOperation("根据ID获取订单详情") @RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET) @ResponseBody
public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) { OmsOrderDetail orderDetail = portalOrderService.detail(orderId); return CommonResult.success(orderDetail); } @ApiOperation("用户取消订单") @RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST) @ResponseBody public CommonResult cancelUserOrder(Long orderId) { portalOrderService.cancelOrder(orderId); return CommonResult.success(null); } @ApiOperation("用户确认收货") @RequestMapping(value = "/confirmReceiveOrder", method = RequestMethod.POST) @ResponseBody public CommonResult confirmReceiveOrder(Long orderId) { portalOrderService.confirmReceiveOrder(orderId); return CommonResult.success(null); } @ApiOperation("用户删除订单") @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST) @ResponseBody public CommonResult deleteOrder(Long orderId) { portalOrderService.deleteOrder(orderId); return CommonResult.success(null); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\OmsPortalOrderController.java
2
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public boolean isActive() { return isActive; }
public void setActive(boolean isActive) { this.isActive = isActive; } public List<String> getCourses() { return courses; } public void setCourses(List<String> courses) { this.courses = courses; } public String getAdditionalSkills() { return additionalSkills; } public void setAdditionalSkills(String additionalSkills) { this.additionalSkills = additionalSkills; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\model\Teacher.java
1
请完成以下Java代码
public UserCredentials findByUserId(TenantId tenantId, UUID userId) { return DaoUtil.getData(userCredentialsRepository.findByUserId(userId)); } @Override public UserCredentials findByActivateToken(TenantId tenantId, String activateToken) { return DaoUtil.getData(userCredentialsRepository.findByActivateToken(activateToken)); } @Override public UserCredentials findByResetToken(TenantId tenantId, String resetToken) { return DaoUtil.getData(userCredentialsRepository.findByResetToken(resetToken)); } @Override public void removeByUserId(TenantId tenantId, UserId userId) { userCredentialsRepository.removeByUserId(userId.getId()); } @Override public void setLastLoginTs(TenantId tenantId, UserId userId, long lastLoginTs) { userCredentialsRepository.updateLastLoginTsByUserId(userId.getId(), lastLoginTs); }
@Override public int incrementFailedLoginAttempts(TenantId tenantId, UserId userId) { return userCredentialsRepository.incrementFailedLoginAttemptsByUserId(userId.getId()); } @Override public void setFailedLoginAttempts(TenantId tenantId, UserId userId, int failedLoginAttempts) { userCredentialsRepository.updateFailedLoginAttemptsByUserId(userId.getId(), failedLoginAttempts); } @Override public PageData<UserCredentials> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(userCredentialsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserCredentialsDao.java
1
请完成以下Java代码
public class RoleAccessUpdate extends JavaProcess { private static final Logger logger = LogManager.getLogger(RoleAccessUpdate.class); /** Update Role */ private int p_AD_Role_ID = -1; /** Update Roles of Client */ private int p_AD_Client_ID = -1; /** * Prepare */ @Override protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("AD_Role_ID")) p_AD_Role_ID = para[i].getParameterAsInt(); else if (name.equals("AD_Client_ID")) p_AD_Client_ID = para[i].getParameterAsInt(); else log.error("Unknown Parameter: " + name); } } // prepare /** * Process * * @return info * @throws Exception */ @Override protected String doIt() throws Exception { if (p_AD_Role_ID > 0) { final RoleId roleId = RoleId.ofRepoId(p_AD_Role_ID); final Role role = Services.get(IRoleDAO.class).getById(roleId); updateRole(role); } else { final ClientId clientId = ClientId.ofRepoIdOrNull(p_AD_Client_ID); updateAllRoles(clientId); } // // Reset role related cache (i.e. UserRolePermissions) CacheMgt.get().reset(I_AD_Role.Table_Name); return MSG_OK; } // doIt public static void updateAllRoles() {
final ClientId clientId = null; // all updateAllRoles(clientId); } public static void updateAllRoles(final ClientId clientId) { Services.get(IRoleDAO.class).retrieveAllRolesWithAutoMaintenance() .stream() .filter(role -> isRoleMatchingClientId(role, clientId)) .forEach(role -> updateRole(role)); } private static boolean isRoleMatchingClientId(final Role role, final ClientId clientId) { if (clientId == null) { return true; } return ClientId.equals(role.getClientId(), clientId); } /** * Update Role */ private static void updateRole(final Role role) { final String result = Services.get(IUserRolePermissionsDAO.class).updateAccessRecords(role); Loggables.withLogger(logger, Level.DEBUG).addLog("Role access updated: {}: {}", role.getName(), result); } // updateRole }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\RoleAccessUpdate.java
1
请完成以下Java代码
public class Author { @Id private Long id; private String name; @Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.INCOMING) private List<Book> books; public Author(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
repos\tutorials-master\persistence-modules\spring-data-neo4j\src\main\java\com\baeldung\spring\data\neo4j\domain\Author.java
1
请完成以下Java代码
public boolean isRecordCopyingMode() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.isDataNewCopy(); } @Override public boolean isRecordCopyingModeIncludingDetails() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.getTableModel().isCopyWithDetails(); } @Override public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError); return; }
gridTab.fireDataStatusEEvent(AD_Message, info, isError); } @Override public void fireDataStatusEEvent(final ValueNamePair errorLog) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog); return; } gridTab.fireDataStatusEEvent(errorLog); } @Override public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { throw new UnsupportedOperationException(); } @Override public ICalloutRecord getCalloutRecord() { final GridTab gridTab = getGridTab(); Check.assumeNotNull(gridTab, "gridTab not null"); return gridTab; } @Override public int getContextAsInt(String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
1
请完成以下Java代码
public class JSONObjectMapper<T> { public static <T> JSONObjectMapper<T> forClass(@NonNull final Class<T> clazz) { return new JSONObjectMapper<>(clazz); } private final static ObjectMapper jsonObjectMapper= JsonObjectMapperHolder.sharedJsonObjectMapper(); private final Class<T> clazz; private JSONObjectMapper(@NonNull final Class<T> clazz) { this.clazz = clazz; } public String writeValueAsString(final T object) { try { return jsonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object); } catch (final JsonProcessingException ex) { throw new AdempiereException("Failed converting object to json: " + object, ex); } } public T readValue(final String objectString) { try {
return jsonObjectMapper.readValue(objectString, clazz); } catch (IOException ex) { throw new AdempiereException("Failed converting json to class= " + clazz + "; object=" + objectString, ex); } } public T readValue(final InputStream objectStream) { try { return jsonObjectMapper.readValue(objectStream, clazz); } catch (IOException ex) { throw new AdempiereException("Failed converting json to class= " + clazz + "; object=" + objectStream, ex); } } public T convertValue(final Object object) { return jsonObjectMapper.convertValue(object, clazz); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\JSONObjectMapper.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 Report Line Set Name. @param ReportLineSetName Name of the Report Line Set */ public void setReportLineSetName (String ReportLineSetName) { set_Value (COLUMNNAME_ReportLineSetName, ReportLineSetName); } /** Get Report Line Set Name. @return Name of the Report Line Set */ public String getReportLineSetName () { return (String)get_Value(COLUMNNAME_ReportLineSetName);
} /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_ReportLine.java
1
请完成以下Java代码
public BigDecimal getTotalNetAmt(final boolean isApprovedForInvoicing) { if (isApprovedForInvoicing) { return getTotalNetAmtApproved(); } else { return getTotalNetAmt(); } } public int getCountTotalToRecompute() { return countTotalToRecompute; } public Set<String> getCurrencySymbols() { return currencySymbols; } @Override public String toString() { return getSummaryMessage(); } /** * Keep in sync with {@link de.metas.ui.web.view.OrderCandidateViewHeaderPropertiesProvider#toViewHeaderProperties(de.metas.invoicecandidate.api.impl.InvoiceCandidatesAmtSelectionSummary)} */ public String getSummaryMessage() { final StringBuilder message = new StringBuilder(); message.append("@Netto@ (@ApprovalForInvoicing@): "); final BigDecimal totalNetAmtApproved = getTotalNetAmtApproved(); message.append(getAmountFormatted(totalNetAmtApproved)); final BigDecimal huNetAmtApproved = getHUNetAmtApproved(); message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtApproved)); final BigDecimal cuNetAmtApproved = getCUNetAmtApproved(); message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtApproved)); message.append(" | @Netto@ (@NotApprovedForInvoicing@): "); final BigDecimal totalNetAmtNotApproved = getTotalNetAmtNotApproved(); message.append(getAmountFormatted(totalNetAmtNotApproved)); final BigDecimal huNetAmtNotApproved = getHUNetAmtNotApproved(); message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtNotApproved)); final BigDecimal cuNetAmtNotApproved = getCUNetAmtNotApproved();
message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtNotApproved)); if (countTotalToRecompute > 0) { message.append(", @IsToRecompute@: "); message.append(countTotalToRecompute); } return message.toString(); } private String getAmountFormatted(final BigDecimal amt) { final DecimalFormat amountFormat = DisplayType.getNumberFormat(DisplayType.Amount); final StringBuilder amountFormatted = new StringBuilder(); amountFormatted.append(amountFormat.format(amt)); final boolean isSameCurrency = currencySymbols.size() == 1; String curSymbol = null; if (isSameCurrency) { curSymbol = currencySymbols.iterator().next(); amountFormatted.append(curSymbol); } return amountFormatted.toString(); } @Override public String getSummaryMessageTranslated(final Properties ctx) { final String message = getSummaryMessage(); final String messageTrl = Services.get(IMsgBL.class).parseTranslation(ctx, message); return messageTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\invoicecandidate\ui\spi\impl\HUInvoiceCandidatesSelectionSummaryInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class SumUpLogRepository { @NonNull private final Logger logger = LogManager.getLogger(SumUpLogRepository.class); @NonNull private final ObjectMapper jsonMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); public void createLog(final SumUpLogRequest request) { try { final I_SUMUP_API_Log record = InterfaceWrapperHelper.newInstanceOutOfTrx(I_SUMUP_API_Log.class); record.setSUMUP_Config_ID(request.getConfigId().getRepoId()); record.setSUMUP_merchant_code(request.getMerchantCode().getAsString()); record.setMethod(request.getMethod().name()); record.setRequestURI(request.getRequestURI()); record.setRequestBody(toJson(request.getRequestBody())); if (request.getResponseCode() != null) { record.setResponseCode(request.getResponseCode().value()); } record.setResponseBody(toJson(request.getResponseBody())); record.setAD_Issue_ID(AdIssueId.toRepoId(request.getAdIssueId())); record.setC_POS_Order_ID(request.getPosRef() != null ? request.getPosRef().getPosOrderId() : -1); record.setC_POS_Payment_ID(request.getPosRef() != null ? request.getPosRef().getPosPaymentId() : -1); InterfaceWrapperHelper.save(record); } catch (Exception ex) { logger.error("Failed saving log {}", request, ex); } } private String toJson(@Nullable final Object obj) { if (obj == null)
{ return null; } if (obj instanceof String) { return StringUtils.trimBlankToNull((String)obj); } try { return jsonMapper.writeValueAsString(obj); } catch (JsonProcessingException ex) { logger.error("Failed converting object to json: {}", obj, ex); return obj.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpLogRepository.java
2
请完成以下Spring Boot application配置
#basic auth creddentials spring.security.user.name=client spring.security.user.password=client #configs to connect to a secured server spring.boot.admin.client.url=http://localhost:8080 #spring.boot.admin.client.instance.service-base-url=http://localhost:8081 spring.boot.admin.client.username=admin spring.boot.admin.client.password=admin #configs to give secured server info spring.boot.admin.client.instance.metadata.user.name=${spring.security.user.name} spring.boot.admin.client.instance.metadata.
user.password=${spring.security.user.password} #app config spring.application.name=spring-boot-admin-client server.port=8081 management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always
repos\tutorials-master\spring-boot-modules\spring-boot-admin\spring-boot-admin-client\src\main\resources\application.properties
2
请完成以下Java代码
public String getSourceCaseDefinitionId() { return sourceProcessDefinitionId; } public void setSourceCaseDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetCaseDefinitionId() { return targetProcessDefinitionId; } public void setTargetCaseDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<CaseInstanceBatchMigrationPartResult> getAllMigrationParts() { return allMigrationParts; } public void addMigrationPart(CaseInstanceBatchMigrationPartResult migrationPart) { if (allMigrationParts == null) { allMigrationParts = new ArrayList<>(); } allMigrationParts.add(migrationPart); if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) { if (waitingMigrationParts == null) { waitingMigrationParts = new ArrayList<>(); } waitingMigrationParts.add(migrationPart); } else { if (RESULT_SUCCESS.equals(migrationPart.getResult())) { if (succesfulMigrationParts == null) { succesfulMigrationParts = new ArrayList<>();
} succesfulMigrationParts.add(migrationPart); } else { if (failedMigrationParts == null) { failedMigrationParts = new ArrayList<>(); } failedMigrationParts.add(migrationPart); } } } public List<CaseInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() { return succesfulMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getFailedMigrationParts() { return failedMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getWaitingMigrationParts() { return waitingMigrationParts; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationResult.java
1
请完成以下Java代码
private boolean isBlankColumn(final String columnName) { return rowsList.stream().allMatch(row -> row.isBlankColumn(columnName)); } public void moveColumnsToStart(final String... columnNamesToMove) { if (columnNamesToMove == null || columnNamesToMove.length == 0) { return; } for (int i = columnNamesToMove.length - 1; i >= 0; i--) { if (columnNamesToMove[i] == null) { continue; } final String columnNameToMove = columnNamesToMove[i]; if (header.remove(columnNameToMove)) { header.add(0, columnNameToMove); } } } public void moveColumnsToEnd(final String... columnNamesToMove) { if (columnNamesToMove == null) { return; } for (final String columnNameToMove : columnNamesToMove) { if (columnNameToMove == null) { continue; } if (header.remove(columnNameToMove)) { header.add(columnNameToMove); } } } public Optional<Table> removeColumnsWithSameValue() { if (rowsList.isEmpty()) { return Optional.empty(); } final Table removedTable = new Table(); for (final String columnName : new ArrayList<>(header)) { final Cell commonValue = getCommonValue(columnName).orElse(null); if (commonValue != null) { header.remove(columnName); removedTable.addHeader(columnName); removedTable.setCell(0, columnName, commonValue); } } if (removedTable.isEmpty()) { return Optional.empty(); } return Optional.of(removedTable); }
private Optional<Cell> getCommonValue(@NonNull final String columnName) { if (rowsList.isEmpty()) { return Optional.empty(); } final Cell firstValue = rowsList.get(0).getCell(columnName); for (int i = 1; i < rowsList.size(); i++) { final Cell value = rowsList.get(i).getCell(columnName); if (!Objects.equals(value, firstValue)) { return Optional.empty(); } } return Optional.of(firstValue); } public TablePrinter toPrint() { return new TablePrinter(this); } public String toTabularString() { return toPrint().toString(); } @Override @Deprecated public String toString() {return toTabularString();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Table.java
1
请在Spring Boot框架中完成以下Java代码
private String getLogoutSuccessUrl() { return this.logoutSuccessUrl; } /** * Gets the {@link LogoutHandler} instances that will be used. * @return the {@link LogoutHandler} instances. Cannot be null. */ public List<LogoutHandler> getLogoutHandlers() { return this.logoutHandlers; } /** * Creates the {@link LogoutFilter} using the {@link LogoutHandler} instances, the * {@link #logoutSuccessHandler(LogoutSuccessHandler)} and the * {@link #logoutUrl(String)}. * @param http the builder to use * @return the {@link LogoutFilter} to use. */ private LogoutFilter createLogoutFilter(H http) { this.contextLogoutHandler.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.contextLogoutHandler.setSecurityContextRepository(getSecurityContextRepository(http)); this.logoutHandlers.add(this.contextLogoutHandler); this.logoutHandlers.add(postProcess(new LogoutSuccessEventPublishingLogoutHandler())); LogoutHandler[] handlers = this.logoutHandlers.toArray(new LogoutHandler[0]); LogoutFilter result = new LogoutFilter(getLogoutSuccessHandler(), handlers); result.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); result.setLogoutRequestMatcher(getLogoutRequestMatcher(http)); result = postProcess(result); return result; } private SecurityContextRepository getSecurityContextRepository(H http) { SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class); if (securityContextRepository == null) { securityContextRepository = new HttpSessionSecurityContextRepository(); } return securityContextRepository; } private RequestMatcher getLogoutRequestMatcher(H http) { if (this.logoutRequestMatcher != null) { return this.logoutRequestMatcher; } this.logoutRequestMatcher = createLogoutRequestMatcher(http);
return this.logoutRequestMatcher; } @SuppressWarnings("unchecked") private RequestMatcher createLogoutRequestMatcher(H http) { RequestMatcher post = createLogoutRequestMatcher("POST"); if (http.getConfigurer(CsrfConfigurer.class) != null) { return post; } RequestMatcher get = createLogoutRequestMatcher("GET"); RequestMatcher put = createLogoutRequestMatcher("PUT"); RequestMatcher delete = createLogoutRequestMatcher("DELETE"); return new OrRequestMatcher(get, post, put, delete); } private RequestMatcher createLogoutRequestMatcher(String httpMethod) { return getRequestMatcherBuilder().matcher(HttpMethod.valueOf(httpMethod), this.logoutUrl); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\LogoutConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public List<HistoricTaskLogEntry> findHistoricTaskLogEntriesByQueryCriteria(HistoricTaskLogEntryQueryImpl taskLogEntryQuery) { return getDbSqlSession().selectList("selectHistoricTaskLogEntriesByQueryCriteria", taskLogEntryQuery); } @Override public void deleteHistoricTaskLogEntry(long logEntryNumber) { getDbSqlSession().delete("deleteHistoricTaskLogEntryByLogNumber", logEntryNumber, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByProcessDefinitionId(String processDefinitionId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByProcessDefinitionId", processDefinitionId, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByScopeDefinitionId(String scopeType, String scopeDefinitionId) { Map<String, String> params = new HashMap<>(2); params.put("scopeDefinitionId", scopeDefinitionId); params.put("scopeType", scopeType); getDbSqlSession().delete("deleteHistoricTaskLogEntriesByScopeDefinitionId", params, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByTaskId(String taskId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByTaskId", taskId, HistoricTaskLogEntryEntityImpl.class); } @Override public void bulkDeleteHistoricTaskLogEntriesForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForTaskIds", createSafeInValuesList(taskIds), HistoricTaskLogEntryEntityImpl.class); }
@Override public void deleteHistoricTaskLogEntriesForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances", null, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances", null, HistoricTaskLogEntryEntityImpl.class); } @Override public long findHistoricTaskLogEntriesCountByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricTaskLogEntriesCountByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override public List<HistoricTaskLogEntry> findHistoricTaskLogEntriesByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return getDbSqlSession().selectListWithRawParameter("selectHistoricTaskLogEntriesByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MyBatisHistoricTaskLogEntryDataManager.java
2
请完成以下Java代码
public void setAD_PrintFont_ID (int AD_PrintFont_ID) { if (AD_PrintFont_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, Integer.valueOf(AD_PrintFont_ID)); } /** Get Print Font. @return Maintain Print Font */ public int getAD_PrintFont_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintFont_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFont.java
1
请完成以下Java代码
public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public boolean isIgnoreDataAccessException() { return ignoreDataAccessException; } public void setIgnoreDataAccessException(boolean ignoreDataAccessException) { this.ignoreDataAccessException = ignoreDataAccessException; } public CamundaBpmProperties getCamundaBpmProperties() { return camundaBpmProperties; } public void setCamundaBpmProperties(CamundaBpmProperties camundaBpmProperties) { this.camundaBpmProperties = camundaBpmProperties; } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(jdbcTemplate, "a jdbc template must be set"); Assert.notNull(camundaBpmProperties, "Camunda Platform properties must be set"); String historyLevelDefault = camundaBpmProperties.getHistoryLevelDefault(); if (StringUtils.hasText(historyLevelDefault)) { defaultHistoryLevel = historyLevelDefault; } } @Override public String determineHistoryLevel() { Integer historyLevelFromDb = null; try { historyLevelFromDb = jdbcTemplate.queryForObject(getSql(), Integer.class); log.debug("found history '{}' in database", historyLevelFromDb); } catch (DataAccessException e) { if (ignoreDataAccessException) { log.warn("unable to fetch history level from database: {}", e.getMessage()); log.debug("unable to fetch history level from database", e); } else { throw e; } } return getHistoryLevelFrom(historyLevelFromDb); }
protected String getSql() { String tablePrefix = camundaBpmProperties.getDatabase().getTablePrefix(); if (tablePrefix == null) { tablePrefix = ""; } return SQL_TEMPLATE.replace(TABLE_PREFIX_PLACEHOLDER, tablePrefix); } protected String getHistoryLevelFrom(Integer historyLevelFromDb) { String result = defaultHistoryLevel; if (historyLevelFromDb != null) { for (HistoryLevel historyLevel : historyLevels) { if (historyLevel.getId() == historyLevelFromDb.intValue()) { result = historyLevel.getName(); log.debug("found matching history level '{}'", result); break; } } } return result; } public void addCustomHistoryLevels(Collection<HistoryLevel> customHistoryLevels) { historyLevels.addAll(customHistoryLevels); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\jdbc\HistoryLevelDeterminatorJdbcTemplateImpl.java
1
请完成以下Java代码
private static <T> T parse(Map<String, Object> body, ThrowingFunction<JSONObject, T, ParseException> parser) { try { return parser.apply(new JSONObject(body)); } catch (ParseException ex) { throw new RuntimeException(ex); } } private static ClientRegistration.Builder withProviderConfiguration(AuthorizationServerMetadata metadata, String issuer) { String metadataIssuer = metadata.getIssuer().getValue(); Assert.state(issuer.equals(metadataIssuer), () -> "The Issuer \"" + metadataIssuer + "\" provided in the configuration metadata did " + "not match the requested issuer \"" + issuer + "\""); String name = URI.create(issuer).getHost(); ClientAuthenticationMethod method = getClientAuthenticationMethod(metadata.getTokenEndpointAuthMethods()); Map<String, Object> configurationMetadata = new LinkedHashMap<>(metadata.toJSONObject()); // @formatter:off return ClientRegistration.withRegistrationId(name) .userNameAttributeName(IdTokenClaimNames.SUB) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(method) .redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}") .authorizationUri((metadata.getAuthorizationEndpointURI() != null) ? metadata.getAuthorizationEndpointURI().toASCIIString() : null) .providerConfigurationMetadata(configurationMetadata) .tokenUri(metadata.getTokenEndpointURI().toASCIIString()) .issuerUri(issuer) .clientName(issuer); // @formatter:on } private static ClientAuthenticationMethod getClientAuthenticationMethod(
List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) { if (metadataAuthMethods == null || metadataAuthMethods .contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) { // If null, the default includes client_secret_basic return ClientAuthenticationMethod.CLIENT_SECRET_BASIC; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) { return ClientAuthenticationMethod.CLIENT_SECRET_POST; } if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.NONE)) { return ClientAuthenticationMethod.NONE; } return null; } private interface ThrowingFunction<S, T, E extends Throwable> { T apply(S src) throws E; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\ClientRegistrations.java
1
请完成以下Java代码
public static boolean hasColumnName(final Object model, final String columnName) { final Document document = getDocument(model); if (document == null) { return false; } final IDocumentFieldView documentField = document.getFieldViewOrNull(columnName); return documentField != null; } @Override public final boolean hasColumnName(final String columnName) { return getDocument().hasField(columnName); } public static int getId(final Object model) { return getDocument(model).getDocumentIdAsInt(); } public static boolean isNew(final Object model) { return getDocument(model).isNew(); } public <T> T getDynAttribute(final String attributeName) { return getDocument().getDynAttribute(attributeName); } public Object setDynAttribute(final String attributeName, final Object value) { return getDocument().setDynAttribute(attributeName, value); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final DocumentInterfaceWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } @Override public Set<String> getColumnNames() { return document.getFieldNames(); } @Override public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey(); }
@Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Java代码
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getOccurCount() { return occurCount; } public void setOccurCount(Integer occurCount) { this.occurCount = occurCount; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public Date getResponsedTime() { return responsedTime; } public void setResponsedTime(Date responsedTime) { this.responsedTime = responsedTime; } public String getResponsedBy() { return responsedBy; } public void setResponsedBy(String responsedBy) { this.responsedBy = responsedBy; } public Date getResolvedTime() { return resolvedTime; } public void setResolvedTime(Date resolvedTime) { this.resolvedTime = resolvedTime; } public String getResolvedBy() { return resolvedBy; } public void setResolvedBy(String resolvedBy) { this.resolvedBy = resolvedBy; } public Date getClosedTime() { return closedTime; } public void setClosedTime(Date closedTime) { this.closedTime = closedTime; } public String getClosedBy() { return closedBy; } public void setClosedBy(String closedBy) { this.closedBy = closedBy;
} @Override public String toString() { return "Event{" + "id=" + id + ", rawEventId=" + rawEventId + ", host=" + host + ", ip=" + ip + ", source=" + source + ", type=" + type + ", startTime=" + startTime + ", endTime=" + endTime + ", content=" + content + ", dataType=" + dataType + ", suggest=" + suggest + ", businessSystemId=" + businessSystemId + ", departmentId=" + departmentId + ", status=" + status + ", occurCount=" + occurCount + ", owner=" + owner + ", responsedTime=" + responsedTime + ", responsedBy=" + responsedBy + ", resolvedTime=" + resolvedTime + ", resolvedBy=" + resolvedBy + ", closedTime=" + closedTime + ", closedBy=" + closedBy + '}'; } }
repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java
1
请完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public boolean isWarning() { return isWarning; } public void setWarning(boolean isWarning) { this.isWarning = isWarning; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Map<String, String> getParams() { return params; } public void setParams(Map<String, String> params) { this.params = params; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("[Validation set: '" + validatorSetName + "' | Problem: '" + problem + "'] : "); strb.append(defaultDescription); strb.append(" - [Extra info : "); boolean extraInfoAlreadyPresent = false; if (processDefinitionId != null) { strb.append("processDefinitionId = " + processDefinitionId); extraInfoAlreadyPresent = true; } if (processDefinitionName != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("processDefinitionName = " + processDefinitionName + " | "); extraInfoAlreadyPresent = true; } if (activityId != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("id = " + activityId + " | "); extraInfoAlreadyPresent = true; } if (activityName != null) { if (extraInfoAlreadyPresent) {
strb.append(" | "); } strb.append("activityName = " + activityName + " | "); extraInfoAlreadyPresent = true; } if (xmlLineNumber > 0 && xmlColumnNumber > 0) { strb.append(" ( line: " + xmlLineNumber + ", column: " + xmlColumnNumber + ")"); } if (key != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append(" ( key: " + key + " )"); extraInfoAlreadyPresent = true; } if (params != null && !params.isEmpty()) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append(" ( "); for (Map.Entry<String, String> param : params.entrySet()) { strb.append(param.getKey() + " = " + param.getValue() + " | "); } strb.append(")"); extraInfoAlreadyPresent = true; } strb.append("]"); return strb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\ValidationError.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client oAuth2Client) { OAuth2MapperConfig config = oAuth2Client.getMapperConfig(); Map<String, String> githubMapperConfig = oAuth2Configuration.getGithubMapper(); String email = getEmail(githubMapperConfig.get(EMAIL_URL_KEY), providerAccessToken); Map<String, Object> attributes = token.getPrincipal().getAttributes(); OAuth2User oAuth2User = BasicMapperUtils.getOAuth2User(email, attributes, config); return getOrCreateSecurityUserFromOAuth2User(oAuth2User, oAuth2Client); } private synchronized String getEmail(String emailUrl, String oauth2Token) { restTemplateBuilder = restTemplateBuilder.defaultHeader(AUTHORIZATION, "token " + oauth2Token); RestTemplate restTemplate = restTemplateBuilder.build(); GithubEmailsResponse githubEmailsResponse; try { githubEmailsResponse = restTemplate.getForEntity(emailUrl, GithubEmailsResponse.class).getBody(); if (githubEmailsResponse == null){ throw new RuntimeException("Empty Github response!"); } } catch (Exception e) { log.error("There was an error during connection to Github API", e); throw new RuntimeException("Unable to login. Please contact your Administrator!"); }
Optional<String> emailOpt = githubEmailsResponse.stream() .filter(GithubEmailResponse::isPrimary) .map(GithubEmailResponse::getEmail) .findAny(); if (emailOpt.isPresent()){ return emailOpt.get(); } else { log.error("Could not find primary email from {}.", githubEmailsResponse); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } } private static class GithubEmailsResponse extends ArrayList<GithubEmailResponse> {} @Data @ToString private static class GithubEmailResponse { private String email; private boolean verified; private boolean primary; private String visibility; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\GithubOAuth2ClientMapper.java
2
请完成以下Java代码
public void setPriceMatchDifference (java.math.BigDecimal PriceMatchDifference) { set_Value (COLUMNNAME_PriceMatchDifference, PriceMatchDifference); } /** Get Price Match Difference. @return Difference between Purchase and Invoice Price per matched line */ @Override public java.math.BigDecimal getPriceMatchDifference () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceMatchDifference); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (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 Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) {
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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 Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchPO.java
1
请完成以下Java代码
public class InventoryUserNotificationsProducer { public static InventoryUserNotificationsProducer newInstance() { return new InventoryUserNotificationsProducer(); } // services private final INotificationBL notificationBL = Services.get(INotificationBL.class); /** * Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously */ public static final Topic EVENTBUS_TOPIC = Topic.distributed("de.metas.inventory.UserNotifications"); /** * M_Inventory internal use */ private static final AdWindowId WINDOW_INTERNAL_INVENTORY = AdWindowId.ofRepoId(341); // FIXME: HARDCODED private static final AdMessageKey MSG_Event_InventoryGenerated = AdMessageKey.of("Event_InventoryGenerated"); private InventoryUserNotificationsProducer() { } public void notifyGenerated(@Nullable final Collection<? extends I_M_Inventory> inventories) { if (inventories == null || inventories.isEmpty()) { return; } notificationBL.sendAfterCommit(inventories.stream() .map(InventoryUserNotificationsProducer::toUserNotification) .collect(ImmutableList.toImmutableList())); } private static UserNotificationRequest toUserNotification(@NonNull final I_M_Inventory inventory) { final TableRecordReference inventoryRef = TableRecordReference.of(inventory); return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC) .recipientUserId(getNotificationRecipientUserId(inventory)) .contentADMessage(MSG_Event_InventoryGenerated)
.contentADMessageParam(inventoryRef) .targetAction(TargetRecordAction.ofRecordAndWindow(inventoryRef, WINDOW_INTERNAL_INVENTORY)) .build(); } private static UserId getNotificationRecipientUserId(final I_M_Inventory inventory) { // // In case of reversal i think we shall notify the current user too final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inventory.getDocStatus()); if (docStatus.isReversedOrVoided()) { final UserId loggedUserId = Env.getLoggedUserIdIfExists().orElse(null); if (loggedUserId != null) { return loggedUserId; } return UserId.ofRepoId(inventory.getUpdatedBy()); // last updated } // // Fallback: notify only the creator else { return UserId.ofRepoId(inventory.getCreatedBy()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\event\InventoryUserNotificationsProducer.java
1
请完成以下Java代码
public Object getValue() { return isSelected(); } // getValue /** * Return Display Value * @return value */ @Override public String getDisplay() { String value = isSelected() ? "Y" : "N"; return Msg.translate(Env.getCtx(), value); } // getDisplay /** * Set Background (nop) */ public void setBackground() { } // setBackground /** * Action Listener - data binding * @param e */ @Override public void actionPerformed(ActionEvent e) { try { fireVetoableChange(m_columnName, null, getValue()); } catch (PropertyVetoException pve) { } } // actionPerformed /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField
@Override public GridField getField() { return m_mField; } /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic @Override public boolean isAutoCommit() { return true; } } // VCheckBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCheckBox.java
1
请完成以下Java代码
public void setISO_Code (java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code); } /** Get ISO Währungscode. @return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Round Off Factor. @param RoundOffFactor Used to Round Off Payment Amount */ @Override public void setRoundOffFactor (java.math.BigDecimal RoundOffFactor) { set_Value (COLUMNNAME_RoundOffFactor, RoundOffFactor); } /** Get Round Off Factor. @return Used to Round Off Payment Amount */ @Override public java.math.BigDecimal getRoundOffFactor () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoundOffFactor); if (bd == null)
return Env.ZERO; return bd; } /** Set Standardgenauigkeit. @param StdPrecision Rule for rounding calculated amounts */ @Override public void setStdPrecision (int StdPrecision) { set_Value (COLUMNNAME_StdPrecision, Integer.valueOf(StdPrecision)); } /** Get Standardgenauigkeit. @return Rule for rounding calculated amounts */ @Override public int getStdPrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_StdPrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency.java
1
请完成以下Java代码
public class TreeSelectModel implements Serializable { private static final long serialVersionUID = 9016390975325574747L; private String key; private String title; /** * 是否叶子节点 */ private boolean isLeaf; private String icon; private String parentId; private String value; private String code; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public boolean isLeaf() { return isLeaf; } public void setLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } private List<TreeSelectModel> children; public List<TreeSelectModel> getChildren() { return children; } public void setChildren(List<TreeSelectModel> children) { this.children = children; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeSelectModel.java
1
请完成以下Java代码
public String getEventName() { return eventSubscriptionDeclaration.getUnresolvedEventName(); } public String getActivityId() { return eventSubscriptionDeclaration.getActivityId(); } protected ExecutionEntity resolveExecution(EventSubscriptionEntity context) { return context.getExecution(); } protected JobHandlerConfiguration resolveJobHandlerConfiguration(EventSubscriptionEntity context) { return new EventSubscriptionJobConfiguration(context.getId()); } @SuppressWarnings("unchecked") public static List<EventSubscriptionJobDeclaration> getDeclarationsForActivity(PvmActivity activity) { Object result = activity.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_JOB_DECLARATION); if (result != null) { return (List<EventSubscriptionJobDeclaration>) result; } else { return Collections.emptyList(); }
} /** * Assumes that an activity has at most one declaration of a certain eventType. */ public static EventSubscriptionJobDeclaration findDeclarationForSubscription(EventSubscriptionEntity eventSubscription) { List<EventSubscriptionJobDeclaration> declarations = getDeclarationsForActivity(eventSubscription.getActivity()); for (EventSubscriptionJobDeclaration declaration : declarations) { if (declaration.getEventType().equals(eventSubscription.getEventType())) { return declaration; } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\EventSubscriptionJobDeclaration.java
1
请完成以下Java代码
public long getId() { return id; } public int getIndex() { return index; } public String getName() { return name; } @Override public int hashCode() { return Objects.hash(index, name); } public void setId(final long id) { this.id = id; } public void setIndex(int index) {
this.index = index; } public void setName(final String name) { this.name = name; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Bar [name=") .append(name) .append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Bar.java
1
请完成以下Java代码
public static ResponseEntity ok(Object data) { ResponseEntity ResponseEntity = new ResponseEntity(); ResponseEntity.setData(data); return ResponseEntity; } public static ResponseEntity error(InfoCode infoCode) { ResponseEntity ResponseEntity = new ResponseEntity(); ResponseEntity.setStatus(infoCode.getStatus()); ResponseEntity.setMessage(infoCode.getMsg()); return ResponseEntity; } public static ResponseEntity ok() { ResponseEntity ResponseEntity = new ResponseEntity(); return ResponseEntity; } public static ResponseEntity error(int code, String msg) { ResponseEntity ResponseEntity = new ResponseEntity(); ResponseEntity.setStatus(code); ResponseEntity.setMessage(msg); return ResponseEntity; }
public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data == null ? new HashMap() : data; } public void setData(Object data) { this.data = data; } }
repos\springBoot-master\abel-util\src\main\java\cn\abel\response\ResponseEntity.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); if (taskId == null) { throw new FlowableIllegalArgumentException("taskId is null"); } TaskEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isDeleted()) { throw new FlowableException("Task " + taskId + " is already deleted"); } if (!task.isSuspended()) { throw new FlowableException("Task " + taskId + " is not suspended, so can't be activated"); } Clock clock = cmmnEngineConfiguration.getClock(); Date updateTime = clock.getCurrentTime(); task.setSuspendedTime(null);
task.setSuspendedBy(null); if (task.getInProgressStartTime() != null) { task.setState(Task.IN_PROGRESS); } else if (task.getClaimTime() != null) { task.setState(Task.CLAIMED); } else { task.setState(Task.CREATED); } task.setSuspensionState(SuspensionState.ACTIVE.getStateCode()); HistoricTaskService historicTaskService = cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskService(); historicTaskService.recordTaskInfoChange(task, updateTime, cmmnEngineConfiguration); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ActivateTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleUnLockRequest { public static ShipmentScheduleUnLockRequest of(final ShipmentScheduleLockRequest lockRequest) { return builder() .shipmentScheduleIds(lockRequest.getShipmentScheduleIds()) .lockType(lockRequest.getLockType()) .lockedBy(lockRequest.getLockedBy()) .build(); } ImmutableSet<ShipmentScheduleId> shipmentScheduleIds; UserId lockedBy; ShipmentScheduleLockType lockType; @Builder(toBuilder = true) private ShipmentScheduleUnLockRequest( @NonNull @Singular final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds, final UserId lockedBy, @NonNull final ShipmentScheduleLockType lockType) { Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds is not empty"); this.shipmentScheduleIds = shipmentScheduleIds; this.lockedBy = lockedBy; this.lockType = lockType; } public ShipmentScheduleUnLockRequest withShipmentScheduleIds(final Set<ShipmentScheduleId> shipmentScheduleIds) { if (Objects.equals(this.shipmentScheduleIds, shipmentScheduleIds))
{ return this; } return toBuilder().shipmentScheduleIds(shipmentScheduleIds).build(); } // // // // // public static class ShipmentScheduleUnLockRequestBuilder { public ShipmentScheduleUnLockRequestBuilder lockedByAnyUser() { return lockedBy(null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\lock\ShipmentScheduleUnLockRequest.java
2
请完成以下Java代码
public boolean isTexture() { return MFColorType.TEXTURE.equals(getType()); } public MFColor setGradientUpperColor(final Color color) { if (!isGradient() || color == null) { return this; } return toBuilder().gradientUpperColor(color).build(); } public MFColor setGradientLowerColor(final Color color) { if (!isGradient() || color == null) { return this; } return toBuilder().gradientLowerColor(color).build(); } public MFColor setGradientStartPoint(final int startPoint) { if (!isGradient()) { return this; } return toBuilder().gradientStartPoint(startPoint).build(); } public MFColor setGradientRepeatDistance(final int repeatDistance) { if (!isGradient()) { return this; } return toBuilder().gradientRepeatDistance(repeatDistance).build(); } public MFColor setTextureURL(final URL textureURL) { if (!isTexture() || textureURL == null) { return this; } return toBuilder().textureURL(textureURL).build(); } public MFColor setTextureTaintColor(final Color color) { if (!isTexture() || color == null) { return this; } return toBuilder().textureTaintColor(color).build(); } public MFColor setTextureCompositeAlpha(final float alpha) { if (!isTexture()) { return this; } return toBuilder().textureCompositeAlpha(alpha).build(); } public MFColor setLineColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineColor(color).build(); } public MFColor setLineBackColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineBackColor(color).build(); } public MFColor setLineWidth(final float width) { if (!isLine()) { return this; } return toBuilder().lineWidth(width).build();
} public MFColor setLineDistance(final int distance) { if (!isLine()) { return this; } return toBuilder().lineDistance(distance).build(); } public MFColor toFlatColor() { switch (getType()) { case FLAT: return this; case GRADIENT: return ofFlatColor(getGradientUpperColor()); case LINES: return ofFlatColor(getLineBackColor()); case TEXTURE: return ofFlatColor(getTextureTaintColor()); default: throw new IllegalStateException("Type not supported: " + getType()); } } public String toHexString() { final Color awtColor = toFlatColor().getFlatColor(); return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } public static String toHexString(final int red, final int green, final int blue) { Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red); Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green); Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue); return String.format("#%02x%02x%02x", red, green, blue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java
1
请完成以下Java代码
public org.compiere.util.KeyNamePair getKeyNamePair() { return new org.compiere.util.KeyNamePair(get_ID(), getName()); } /** Set Sql ORDER BY. @param OrderByClause Fully qualified ORDER BY clause */ @Override public void setOrderByClause (java.lang.String OrderByClause) { set_Value (COLUMNNAME_OrderByClause, OrderByClause); } /** Get Sql ORDER BY. @return Fully qualified ORDER BY clause */ @Override public java.lang.String getOrderByClause () { return (java.lang.String)get_Value(COLUMNNAME_OrderByClause); } /** Set Other SQL Clause. @param OtherClause Other SQL Clause */ @Override public void setOtherClause (java.lang.String OtherClause) { set_Value (COLUMNNAME_OtherClause, OtherClause); } /** Get Other SQL Clause. @return Other SQL Clause */ @Override public java.lang.String getOtherClause () { return (java.lang.String)get_Value(COLUMNNAME_OtherClause); } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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 ShowInMenu. @param ShowInMenu ShowInMenu */ @Override public void setShowInMenu (boolean ShowInMenu) { set_Value (COLUMNNAME_ShowInMenu, Boolean.valueOf(ShowInMenu)); } /** Get ShowInMenu. @return ShowInMenu */ @Override public boolean isShowInMenu () { Object oo = get_Value(COLUMNNAME_ShowInMenu); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow.java
1
请完成以下Java代码
public Artifact getArtifact(String id) { Artifact foundArtifact = null; for (Artifact artifact : artifactList) { if (id.equals(artifact.getId())) { foundArtifact = artifact; break; } } return foundArtifact; } public Collection<Artifact> getArtifacts() { return artifactList; } public void addArtifact(Artifact artifact) { artifactList.add(artifact); } public void removeArtifact(String artifactId) { Artifact artifact = getArtifact(artifactId); if (artifact != null) { artifactList.remove(artifact); } } public SubProcess clone() { SubProcess clone = new SubProcess(); clone.setValues(this); return clone; } public void setValues(SubProcess otherElement) { super.setValues(otherElement); /* * This is required because data objects in Designer have no DI info and are added as properties, not flow elements * * Determine the differences between the 2 elements' data object */ for (ValuedDataObject thisObject : getDataObjects()) { boolean exists = false; for (ValuedDataObject otherObject : otherElement.getDataObjects()) { if (thisObject.getId().equals(otherObject.getId())) { exists = true; } } if (!exists) { // missing object removeFlowElement(thisObject.getId()); } }
dataObjects = new ArrayList<ValuedDataObject>(); if (otherElement.getDataObjects() != null && !otherElement.getDataObjects().isEmpty()) { for (ValuedDataObject dataObject : otherElement.getDataObjects()) { ValuedDataObject clone = dataObject.clone(); dataObjects.add(clone); // add it to the list of FlowElements // if it is already there, remove it first so order is same as // data object list removeFlowElement(clone.getId()); addFlowElement(clone); } } flowElementList.clear(); for (FlowElement flowElement : otherElement.getFlowElements()) { addFlowElement(flowElement); } artifactList.clear(); for (Artifact artifact : otherElement.getArtifacts()) { addArtifact(artifact); } } public List<ValuedDataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<ValuedDataObject> dataObjects) { this.dataObjects = dataObjects; } @Override public void accept(ReferenceOverrider referenceOverrider) { getFlowElements().forEach(flowElement -> flowElement.accept(referenceOverrider)); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SubProcess.java
1
请完成以下Java代码
public static JsonDhlAddress getShipperAddress(@NonNull final Address address) { final JsonDhlAddress.JsonDhlAddressBuilder addressBuilder = JsonDhlAddress.builder(); mapCommonAddressFields(addressBuilder, address); return addressBuilder.build(); } @NonNull public static JsonDhlAddress getConsigneeAddress(@NonNull final Address address, @Nullable final ContactPerson deliveryContact) { final JsonDhlAddress.JsonDhlAddressBuilder addressBuilder = JsonDhlAddress.builder(); mapCommonAddressFields(addressBuilder, address); addressBuilder.additionalAddressInformation1(StringUtils.trunc(address.getStreet2(), 50, ON_TRUNC)); if (deliveryContact != null) { final String email = deliveryContact.getEmailAddress(); if (Check.isNotBlank(email)) { Check.assume(email.length() > 2, "email has minimum three characters"); addressBuilder.email(StringUtils.trunc(deliveryContact.getEmailAddress(), 80, ON_TRUNC)); } addressBuilder.phone(StringUtils.trunc(deliveryContact.getPhoneAsStringOrNull(), 20, ON_TRUNC)); } return addressBuilder.build(); } private static boolean isValidAlpha3CountryCode(@NonNull final String code) { if (code.length() != 3) { return false; }
for (final String iso : Locale.getISOCountries()) { final Locale locale = new Locale("", iso); if (locale.getISO3Country().equalsIgnoreCase(code)) { return true; } } return false; } private static void mapCommonAddressFields(@NonNull final JsonDhlAddress.JsonDhlAddressBuilder addressBuilder, @NonNull final Address address) { final String country = address.getCountry().getAlpha3(); final String postalCode = StringUtils.trunc(address.getZipCode(), 10, ON_TRUNC); // Validate ISO 3166-1 alpha-3 country code Check.assume(isValidAlpha3CountryCode(country), "Invalid ISO alpha-3 country code: " + country); if (!IRL_COUNTRY.equals(country)) { Check.assumeNotNull(postalCode, "postalCode is not NULL"); Check.assume(postalCode.length() > 2, "postalCode has minimum three characters"); } addressBuilder.name1(StringUtils.trunc(address.getCompanyName1(), 50, ON_TRUNC)) .name2(StringUtils.trunc(address.getCompanyName2(), 50, ON_TRUNC)) .addressStreet(StringUtils.trunc(address.getStreet1(), 50, ON_TRUNC)) .addressHouse(StringUtils.trunc(address.getHouseNo(), 10, ON_TRUNC)) .postalCode(StringUtils.trim(postalCode)) .city(StringUtils.trunc(address.getCity(), 40, ON_TRUNC)) .country(country); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlAddressMapper.java
1
请在Spring Boot框架中完成以下Java代码
public void checkQueryOk() { super.checkQueryOk(); // latest() makes only sense when used with key() or keyLike() if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){ throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)"); } } private boolean isCmmnEnabled(CommandContext commandContext) { return commandContext .getProcessEngineConfiguration() .isCmmnEnabled(); } // getters //////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; } public String getKey() { return key;
} public String getKeyLike() { return keyLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public Integer getVersion() { return version; } public boolean isLatest() { return latest; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class PropertyConfig { @Value("注入普通字符串") // 注入普通字符串 private String normal; @Value("#{systemProperties['os.name']}") // 注入操作系统属性 private String osName; @Value("#{T(java.lang.Math).random() * 100.0 }") // 注入表达式结果 private double randomNumber; @Value("#{person.name}") // 注入其他Bean属性 private String fromAnother; @Value("classpath:config/test.txt") // 注入文件资源 private Resource testFile; @Value("https://www.baidu.com") // 注入网址资源 private Resource testUrl; @Value("${book.name}") // 注入配置文件【注意是$符号】 private String bookName; @Autowired // Properties可以从Environment获得 private Environment environment; // @Bean
// public static PropertySourcesPlaceholderConfigurer propertyConfigure() { // return new PropertySourcesPlaceholderConfigurer(); // } @Override public String toString() { try { return "PropertyConfig [normal=" + normal + ", osName=" + osName + ", randomNumber=" + randomNumber + ", fromAnother=" + fromAnother + ", testFile=" + IOUtils.toString(testFile.getInputStream()) + ", testUrl=" + IOUtils.toString(testUrl.getInputStream()) + ", bookName=" + bookName + ", environment=" + environment + "]"; } catch (IOException e) { e.printStackTrace(); } return null; } }
repos\spring-boot-student-master\spring-boot-student-config\src\main\java\com\xiaolyuh\config\PropertyConfig.java
2
请完成以下Java代码
public static void defineDynamicPersistentUnit() { PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); pumd.addProperty("datanucleus.xml.indentSize", "4"); pmf = new JDOPersistenceManagerFactory(pumd, null); pm = pmf.getPersistenceManager(); } public static void defineNamedPersistenceManagerFactory(String pmfName) { pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); pm = pmf.getPersistenceManager(); } public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { pmf = JDOHelper.getPersistenceManagerFactory(filePath); pm = pmf.getPersistenceManager(); } public static void closePersistenceManager() { if (pm != null && !pm.isClosed()) { pm.close(); } } public static void persistObject(Object obj) { Transaction tx = pm.currentTransaction();
try { tx.begin(); pm.makePersistent(obj); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } } } public static void queryPersonsInXML() { Query<Person> query = pm.newQuery(Person.class); List<Person> result = query.executeList(); System.out.println("name: " + result.get(0).getFirstName()); } public static void queryAnnotatedPersonsInXML() { Query<AnnotadedPerson> query = pm.newQuery(AnnotadedPerson.class); List<AnnotadedPerson> result = query.executeList(); System.out.println("name: " + result.get(0).getFirstName()); } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\xml\MyApp.java
1
请完成以下Java代码
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (requiresLogout(request, response)) { Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication(); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Logging out [%s]", auth)); } this.handler.logout(request, response, auth); this.logoutSuccessHandler.onLogoutSuccess(request, response, auth); return; } chain.doFilter(request, response); } /** * Allow subclasses to modify when a logout should take place. * @param request the request * @param response the response * @return <code>true</code> if logout should occur, <code>false</code> otherwise */ protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) { if (this.logoutRequestMatcher.matches(request)) { return true; } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Did not match request to %s", this.logoutRequestMatcher)); } return false; }
/** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); this.logoutRequestMatcher = logoutRequestMatcher; } public void setFilterProcessesUrl(String filterProcessesUrl) { this.logoutRequestMatcher = pathPattern(filterProcessesUrl); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\logout\LogoutFilter.java
1
请完成以下Java代码
private boolean checkEligible(final I_C_Aggregation aggregationDef) { if (aggregationDef == null) { return false; // not eligible } final int aggregationId = aggregationDef.getC_Aggregation_ID(); if (aggregationId <= 0) { return false; // not eligible } // Avoid cycles (i.e. self including an aggregation, direct or indirect) if (!seenAggregationIds.add(aggregationId)) { throw new AdempiereException("Aggregation cycle detected: " + aggregationDef); // return false; // not eligible
} final String tableName = aggregationDef.getAD_Table().getTableName(); final String tableNameExpected = getTableName(); if (!Objects.equals(tableNameExpected, tableName)) { throw new AdempiereException("Aggregation's table name does not match" + "\n @C_Aggregation_ID@: " + aggregationDef + "\n @TableName@: " + tableName + "\n @TableName@ (expected): " + tableNameExpected); } return true; // eligible } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\C_Aggregation2AggregationBuilder.java
1
请完成以下Java代码
public abstract class AbstractAppRuntimeDelegate<T extends AppPlugin> implements AppRuntimeDelegate<T> { protected final AppPluginRegistry<T> pluginRegistry; protected final ProcessEngineProvider processEngineProvider; protected List<PluginResourceOverride> resourceOverrides; public AbstractAppRuntimeDelegate(Class<T> pluginType) { pluginRegistry = new DefaultAppPluginRegistry<T>(pluginType); processEngineProvider = loadProcessEngineProvider(); } public ProcessEngine getProcessEngine(String processEngineName) { try { return processEngineProvider.getProcessEngine(processEngineName); } catch (Exception e) { throw new ProcessEngineException("No process engine with name " + processEngineName + " found.", e); } } public Set<String> getProcessEngineNames() { return processEngineProvider.getProcessEngineNames(); } public ProcessEngine getDefaultProcessEngine() { return processEngineProvider.getDefaultProcessEngine(); } public AppPluginRegistry<T> getAppPluginRegistry() { return pluginRegistry; } /** * Load the {@link ProcessEngineProvider} spi implementation.
* * @return */ protected ProcessEngineProvider loadProcessEngineProvider() { ServiceLoader<ProcessEngineProvider> loader = ServiceLoader.load(ProcessEngineProvider.class); try { return loader.iterator().next(); } catch (NoSuchElementException e) { String message = String.format("No implementation for the %s spi found on classpath", ProcessEngineProvider.class.getName()); throw new IllegalStateException(message, e); } } public List<PluginResourceOverride> getResourceOverrides() { if(resourceOverrides == null) { initResourceOverrides(); } return resourceOverrides; } protected synchronized void initResourceOverrides() { if(resourceOverrides == null) { // double-checked sync, do not remove resourceOverrides = new ArrayList<PluginResourceOverride>(); List<T> plugins = pluginRegistry.getPlugins(); for (T p : plugins) { resourceOverrides.addAll(p.getResourceOverrides()); } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\AbstractAppRuntimeDelegate.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderPayScheduleCreateRequest { @NonNull OrderId orderId; @NonNull ImmutableList<Line> lines; @Builder private OrderPayScheduleCreateRequest( @NonNull final OrderId orderId, @NonNull final ImmutableList<Line> lines) { Check.assumeNotEmpty(lines, "lines shall not empty"); this.orderId = orderId; this.lines = lines; } // // // // //
@Value @Builder public static class Line { @NonNull PaymentTermBreakId paymentTermBreakId; @NonNull ReferenceDateType referenceDateType; @NonNull Percent percent; @NonNull OrderPayScheduleStatus orderPayScheduleStatus; @NonNull LocalDate dueDate; @NonNull Money dueAmount; int offsetDays; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleCreateRequest.java
2
请在Spring Boot框架中完成以下Java代码
public boolean enabled() { return obtain(AtlasProperties::isEnabled, AtlasConfig.super::enabled); } @Override public Duration connectTimeout() { return obtain(AtlasProperties::getConnectTimeout, AtlasConfig.super::connectTimeout); } @Override public Duration readTimeout() { return obtain(AtlasProperties::getReadTimeout, AtlasConfig.super::readTimeout); } @Override public int numThreads() { return obtain(AtlasProperties::getNumThreads, AtlasConfig.super::numThreads); } @Override public int batchSize() { return obtain(AtlasProperties::getBatchSize, AtlasConfig.super::batchSize); } @Override public String uri() { return obtain(AtlasProperties::getUri, AtlasConfig.super::uri); } @Override public Duration meterTTL() { return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL); } @Override public boolean lwcEnabled() { return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled); } @Override public Duration lwcStep() { return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep); }
@Override public boolean lwcIgnorePublishStep() { return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep); } @Override public Duration configRefreshFrequency() { return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency); } @Override public Duration configTTL() { return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL); } @Override public String configUri() { return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri); } @Override public String evalUri() { return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java
2
请完成以下Java代码
public BigDecimal getLatitude() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Latitude); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLongitude (final @Nullable BigDecimal Longitude) { set_Value (COLUMNNAME_Longitude, Longitude); } @Override public BigDecimal getLongitude() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Longitude); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOBox (final @Nullable java.lang.String POBox) { set_ValueNoCheck (COLUMNNAME_POBox, POBox); } @Override public java.lang.String getPOBox() { return get_ValueAsString(COLUMNNAME_POBox); } @Override public void setPostal (final @Nullable java.lang.String Postal) { set_ValueNoCheck (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } @Override public void setPostal_Add (final @Nullable java.lang.String Postal_Add) { set_ValueNoCheck (COLUMNNAME_Postal_Add, Postal_Add); } @Override public java.lang.String getPostal_Add() {
return get_ValueAsString(COLUMNNAME_Postal_Add); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) { set_ValueNoCheck (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setStreet (final @Nullable java.lang.String Street) { set_Value (COLUMNNAME_Street, Street); } @Override public java.lang.String getStreet() { return get_ValueAsString(COLUMNNAME_Street); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Location.java
1
请完成以下Java代码
public Tls hostnameVerification() { this.tls.hostnameVerification(); return this; } public Tls hostnameVerification(boolean hostnameVerification) { this.tls.hostnameVerification(hostnameVerification); return this; } public Tls sslContext(SSLContext sslContext) { this.tls.sslContext(sslContext); return this; } public Tls trustEverything() { this.tls.trustEverything(); return this; } } public static final class Affinity { private final ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity; private Affinity(ConnectionSettings.Affinity<? extends ConnectionBuilder> affinity) { this.affinity = affinity; } public Affinity queue(String queue) { this.affinity.queue(queue); return this; } public Affinity operation(ConnectionSettings.Affinity.Operation operation) { this.affinity.operation(operation); return this; } public Affinity reuse(boolean reuse) { this.affinity.reuse(reuse); return this; } public Affinity strategy(ConnectionSettings.AffinityStrategy strategy) { this.affinity.strategy(strategy); return this; } } public static final class OAuth2 { private final OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings; private OAuth2(OAuth2Settings<? extends ConnectionBuilder> oAuth2Settings) { this.oAuth2Settings = oAuth2Settings; } public OAuth2 tokenEndpointUri(String uri) {
this.oAuth2Settings.tokenEndpointUri(uri); return this; } public OAuth2 clientId(String clientId) { this.oAuth2Settings.clientId(clientId); return this; } public OAuth2 clientSecret(String clientSecret) { this.oAuth2Settings.clientSecret(clientSecret); return this; } public OAuth2 grantType(String grantType) { this.oAuth2Settings.grantType(grantType); return this; } public OAuth2 parameter(String name, String value) { this.oAuth2Settings.parameter(name, value); return this; } public OAuth2 shared(boolean shared) { this.oAuth2Settings.shared(shared); return this; } public OAuth2 sslContext(SSLContext sslContext) { this.oAuth2Settings.tls().sslContext(sslContext); return this; } } public static final class Recovery { private final ConnectionBuilder.RecoveryConfiguration recoveryConfiguration; private Recovery(ConnectionBuilder.RecoveryConfiguration recoveryConfiguration) { this.recoveryConfiguration = recoveryConfiguration; } public Recovery activated(boolean activated) { this.recoveryConfiguration.activated(activated); return this; } public Recovery backOffDelayPolicy(BackOffDelayPolicy backOffDelayPolicy) { this.recoveryConfiguration.backOffDelayPolicy(backOffDelayPolicy); return this; } public Recovery topology(boolean activated) { this.recoveryConfiguration.topology(activated); return this; } } }
repos\spring-amqp-main\spring-rabbitmq-client\src\main\java\org\springframework\amqp\rabbitmq\client\SingleAmqpConnectionFactory.java
1
请完成以下Java代码
protected String doIt() throws Exception { if (m_C_ProjectLine_ID == 0) throw new IllegalArgumentException("No Project Line"); MProjectLine projectLine = new MProjectLine (getCtx(), m_C_ProjectLine_ID, get_TrxName()); log.info("doIt - " + projectLine); if (projectLine.getM_Product_ID() == 0) throw new IllegalArgumentException("No Product"); // MProject project = new MProject (getCtx(), projectLine.getC_Project_ID(), get_TrxName()); if (project.getM_PriceList_ID() == 0) { throw new IllegalArgumentException("No PriceList"); } // boolean isSOTrx = true; MProductPricing pp = new MProductPricing ( OrgId.ofRepoId(project.getAD_Org_ID()), projectLine.getM_Product_ID(), project.getC_BPartner_ID(), null, /* countryId */ projectLine.getPlannedQty(),
isSOTrx); pp.setM_PriceList_ID(project.getM_PriceList_ID()); pp.setPriceDate(project.getDateContract()); // projectLine.setPlannedPrice(pp.getPriceStd()); projectLine.setPlannedMarginAmt(pp.getPriceStd().subtract(pp.getPriceLimit())); projectLine.save(); // String retValue = Msg.getElement(getCtx(), "PriceList") + pp.getPriceList() + " - " + Msg.getElement(getCtx(), "PriceStd") + pp.getPriceStd() + " - " + Msg.getElement(getCtx(), "PriceLimit") + pp.getPriceLimit(); return retValue; } // doIt } // ProjectLinePricing
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectLinePricing.java
1
请完成以下Java代码
public class Computer { private Processor processor; private Memory memory; private SoundCard soundCard; public Computer(Processor processor, Memory memory) { this.processor = processor; this.memory = memory; } public void setSoundCard(SoundCard soundCard) { this.soundCard = soundCard; } public Processor getProcessor() {
return processor; } public Memory getMemory() { return memory; } public Optional<SoundCard> getSoundCard() { return Optional.ofNullable(soundCard); } @Override public String toString() { return "Computer{" + "processor=" + processor + ", memory=" + memory + ", soundcard=" + soundCard +"}"; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\inheritancecomposition\model\Computer.java
1
请完成以下Java代码
public WebServer getWebServer(HttpHandler httpHandler) { Tomcat tomcat = createTomcat(); TomcatHttpHandlerAdapter servlet = new TomcatHttpHandlerAdapter(httpHandler); prepareContext(tomcat.getHost(), servlet); return getTomcatWebServer(tomcat); } protected void prepareContext(Host host, TomcatHttpHandlerAdapter servlet) { File docBase = createTempDir("tomcat-docbase"); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); WebResourceRoot resourceRoot = new StandardRoot(context); ignoringNoSuchMethodError(() -> resourceRoot.setReadOnly(true)); context.setResources(resourceRoot); context.setPath(""); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new Tomcat.FixContextListener()); ClassLoader parentClassLoader = ClassUtils.getDefaultClassLoader(); context.setParentClassLoader(parentClassLoader); skipAllTldScanning(context); WebappLoader loader = new WebappLoader(); loader.setLoaderInstance(new TomcatEmbeddedWebappClassLoader(parentClassLoader)); loader.setDelegate(true); context.setLoader(loader); Tomcat.addServlet(context, "httpHandlerServlet", servlet).setAsyncSupported(true); context.addServletMappingDecoded("/", "httpHandlerServlet"); host.addChild(context); configureContext(context); } private void ignoringNoSuchMethodError(Runnable method) { try { method.run(); } catch (NoSuchMethodError ex) { } }
private void skipAllTldScanning(TomcatEmbeddedContext context) { StandardJarScanFilter filter = new StandardJarScanFilter(); filter.setTldSkip("*.jar"); context.getJarScanner().setJarScanFilter(filter); } /** * Configure the Tomcat {@link Context}. * @param context the Tomcat context */ protected void configureContext(Context context) { this.getContextLifecycleListeners().forEach(context::addLifecycleListener); new DisableReferenceClearingContextCustomizer().customize(context); this.getContextCustomizers().forEach((customizer) -> customizer.customize(context)); } /** * Factory method called to create the {@link TomcatWebServer}. Subclasses can * override this method to return a different {@link TomcatWebServer} or apply * additional processing to the Tomcat server. * @param tomcat the Tomcat server. * @return a new {@link TomcatWebServer} instance */ protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown()); } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\reactive\TomcatReactiveWebServerFactory.java
1
请完成以下Java代码
public String retrieveAccessToken(final DhlClientConfig clientConfig) { // Build the form-encoded body for the request final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("grant_type", "password"); // As described by DHL formData.add("client_id", clientConfig.getApplicationID()); formData.add("client_secret", clientConfig.getApplicationToken()); formData.add("username", clientConfig.getUsername()); formData.add("password", clientConfig.getSignature()); // Assuming `signature` is the password field // Prepare the headers final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // Create the request entity final HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers); // Call the token endpoint final ResponseEntity<DhlOAuthTokenResponse> response = restTemplate.exchange( clientConfig.getBaseUrl() + DHL_OAUTH2_PATH, HttpMethod.POST,
requestEntity, DhlOAuthTokenResponse.class ); // Extract and return the access token return Objects.requireNonNull(response.getBody()).getAccess_token(); } // Response handling class for parsing the token response @Getter public static class DhlOAuthTokenResponse { private String access_token; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\oauth2\CustomOAuth2TokenRetriever.java
1
请完成以下Java代码
public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx) { this.processorCtx = processorCtx; } @Override public void process(final I_M_InOut item) throws Exception { // Also add invalid ones. The user can sort it out in the desadv window // final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); // final List<Exception> feedback = ediDocumentBL.isValidInOut(item); // if (!feedback.isEmpty()) // { // final String errorMessage = ediDocumentBL.buildFeedback(feedback); // throw new AdempiereException(errorMessage); // } final String trxNameBackup = InterfaceWrapperHelper.getTrxName(item); try { EDI_Desadv_Aggregate_M_InOuts.this.addLog("@Added@: @M_InOut_ID@ " + item.getDocumentNo()); InterfaceWrapperHelper.setTrxName(item, processorCtx.getTrxName()); final I_EDI_Desadv desadv = desadvBL.addToDesadvCreateForInOutIfNotExist(item); if (desadv == null) { EDI_Desadv_Aggregate_M_InOuts.this.addLog("Could not create desadv for M_InOut=" + item); } else {
InterfaceWrapperHelper.save(item); } } finally { InterfaceWrapperHelper.setTrxName(item, trxNameBackup); } } @Override public Void getResult() { return null; } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_Aggregate_M_InOuts.java
1
请完成以下Java代码
public VariableSerializers getVariableSerializers() { return variableSerializers; } public void setVariableSerializers(VariableSerializers variableSerializers) { this.variableSerializers = variableSerializers; } /** * <p>Provides the default Process Engine name to deploy to, if no Process Engine * was defined in <code>processes.xml</code>.</p> * * @return the default deploy-to Process Engine name. * The default value is "default". */
public String getDefaultDeployToEngineName() { return defaultDeployToEngineName; } /** * <p>Programmatically set the name of the Process Engine to deploy to if no Process Engine * is defined in <code>processes.xml</code>. This allows to circumvent the "default" Process * Engine name and set a custom one.</p> * * @param defaultDeployToEngineName */ protected void setDefaultDeployToEngineName(String defaultDeployToEngineName) { this.defaultDeployToEngineName = defaultDeployToEngineName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\AbstractProcessApplication.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCommentId() { return commentId; } public void setCommentId(Long commentId) { this.commentId = commentId; } public String getMemberNickName() { return memberNickName; } public void setMemberNickName(String memberNickName) { this.memberNickName = memberNickName; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @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(", commentId=").append(commentId); sb.append(", memberNickName=").append(memberNickName); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsCommentReplay.java
1
请完成以下Java代码
public class UserResponseDTO { @ApiModelProperty(position = 0) private Integer id; @ApiModelProperty(position = 1) private String username; @ApiModelProperty(position = 2) private String email; @ApiModelProperty(position = 3) List<Role> roles; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\dto\UserResponseDTO.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Direction AD_Reference_ID=540086 */ public static final int DIRECTION_AD_Reference_ID=540086; /** Import = I */ public static final String DIRECTION_Import = "I"; /** Export = E */ public static final String DIRECTION_Export = "E"; /** Set Richtung. @param Direction Richtung */ public void setDirection (String Direction) { set_Value (COLUMNNAME_Direction, Direction); } /** Get Richtung. @return Richtung */ public String getDirection () { return (String)get_Value(COLUMNNAME_Direction); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
1
请在Spring Boot框架中完成以下Java代码
private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) @Override public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) {
// 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\utils\ClassUtil.java
2
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<?> get(@Valid @PathVariable String username ) { Try<User> githubUserProfile = githubService.findGithubUser(username); if (githubUserProfile.isFailure()) { return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).body(githubUserProfile.getCause().getMessage()); } if (githubUserProfile.isEmpty()) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Response is empty"); } if (githubUserProfile.isSuccess()) { return ResponseEntity.status(HttpStatus.OK).body(githubUserProfile.get()); } return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("username is not valid"); } @GetMapping(path = "/fail/{username}", produces = "application/json;charset=UTF-8") public ResponseEntity<?> getFail(@Valid @PathVariable String username ) { Try<User> githubUserProfile = githubService.findGithubUserAndFail(username);
if (githubUserProfile.isFailure()) { System.out.println("Fail case"); return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(githubUserProfile.getCause().getMessage()); } if (githubUserProfile.isEmpty()) { System.out.println("Empty case"); return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Response is empty"); } if (githubUserProfile.isSuccess()) { System.out.println("Success case"); return ResponseEntity.status(HttpStatus.OK).body(githubUserProfile.get()); } return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("username is not valid"); } }
repos\springboot-demo-master\vavr\src\main\java\com\et\vavr\controller\GithubController.java
2
请完成以下Java代码
public class SystemInfo { private final String appId; private final String name; private final String version; private final long timestamp; private final long uptime; @JsonCreator public SystemInfo(@JsonProperty("appId") String appId, @JsonProperty("name") String name, @JsonProperty("version") String version, @JsonProperty("timestamp") long timestamp, @JsonProperty("uptime") long uptime) { this.appId = appId; this.name = name; this.version = version; this.timestamp = timestamp; this.uptime = uptime; } public String getAppId() { return appId; }
public String getName() { return name; } public String getVersion() { return version; } public long getTimestamp() { return timestamp; } public long getUptime() { return uptime; } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\dto\SystemInfo.java
1
请完成以下Java代码
public void setAD_Desktop_ID (int AD_Desktop_ID) { if (AD_Desktop_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, Integer.valueOf(AD_Desktop_ID)); } /** Get Desktop. @return Collection of Workbenches */ public int getAD_Desktop_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Image. @param AD_Image_ID Image or Icon */ public void setAD_Image_ID (int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID)); } /** Get Image. @return Image or Icon */ public int getAD_Image_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set 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_AD_Desktop.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
private static Saml2X509Credential getSaml2Credential(String privateKeyLocation, String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { RSAPrivateKey privateKey = readPrivateKey(privateKeyLocation); X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(privateKey, certificate, credentialType); } private static Saml2X509Credential getSaml2Credential(String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(certificate, credentialType); } private static RSAPrivateKey readPrivateKey(String privateKeyLocation) { Resource privateKey = resourceLoader.getResource(privateKeyLocation); try (InputStream inputStream = privateKey.getInputStream()) { return RsaKeyConverters.pkcs8().convert(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } }
private static X509Certificate readCertificate(String certificateLocation) { Resource certificate = resourceLoader.getResource(certificateLocation); try (InputStream inputStream = certificate.getInputStream()) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static String resolveAttribute(ParserContext pc, String value) { return pc.getReaderContext().getEnvironment().resolvePlaceholders(value); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\saml2\RelyingPartyRegistrationsBeanDefinitionParser.java
2
请完成以下Java代码
public static JSONDocumentFilter of(final DocumentFilter filter, final JSONOptions jsonOpts) { final String filterId = filter.getFilterId(); final List<JSONDocumentFilterParam> jsonParameters = filter.getParameters() .stream() .filter(filterParam -> !filter.isInternalParameter(filterParam.getFieldName())) .map(filterParam -> JSONDocumentFilterParam.of(filterParam, jsonOpts)) .filter(Optional::isPresent) .map(Optional::get) .collect(GuavaCollectors.toImmutableList()); return new JSONDocumentFilter(filterId, filter.getCaption(jsonOpts.getAdLanguage()), jsonParameters); } @JsonProperty("filterId") String filterId; @JsonProperty("caption") @JsonInclude(JsonInclude.Include.NON_EMPTY) String caption;
@JsonProperty("parameters") List<JSONDocumentFilterParam> parameters; @JsonCreator @Builder private JSONDocumentFilter( @JsonProperty("filterId") @NonNull final String filterId, @JsonProperty("caption") @Nullable final String caption, @JsonProperty("parameters") @Nullable @Singular final List<JSONDocumentFilterParam> parameters) { Check.assumeNotEmpty(filterId, "filterId is not empty"); this.filterId = filterId; this.caption = caption; this.parameters = parameters == null ? ImmutableList.of() : ImmutableList.copyOf(parameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\json\JSONDocumentFilter.java
1
请完成以下Java代码
public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate) { this.invoiceCandidate = invoiceCandidate; return this; } public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol) { this.iciol = iciol; return this; } /** * Adds an additional element to be considered part of the line aggregation key. * <p> * NOTE: basically this shall be always empty because everything which is related to line aggregation * shall be configured from aggregation definition, * but we are also leaving this door open in case we need to implement some quick/hot fixes.
* * @deprecated This method will be removed because we shall go entirely with standard aggregation definition. */ @Deprecated public Builder addLineAggregationKeyElement(@NonNull final Object aggregationKeyElement) { aggregationKeyElements.add(aggregationKeyElement); return this; } public void addInvoiceLineAttributes(@NonNull final Collection<IInvoiceLineAttribute> invoiceLineAttributes) { this.attributesFromInoutLines.addAll(invoiceLineAttributes); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAggregationRequest.java
1
请完成以下Java代码
public String getDeliveryToAddress() { return delegate.getDeliveryToAddress(); } @Override public void setDeliveryToAddress(final String address) { delegate.setDeliveryToAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from); } public void setFromDeliveryLocation(@NonNull final I_C_Order from) { setFrom(new OrderDropShipLocationAdapter(from).toDocumentLocation()); }
public void setFromShipLocation(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation()); } @Override public I_C_Order getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderDropShipLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderDropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderDropShipLocationAdapter.java
1
请完成以下Java代码
public class Article { /** * 文章id */ @Id private Long id; /** * 文章标题 */ private String title; /** * 文章内容 */ private String content; /** * 创建时间 */ private Date createTime; /**
* 更新时间 */ private Date updateTime; /** * 点赞数量 */ private Long thumbUp; /** * 访客数量 */ private Long visits; }
repos\spring-boot-demo-master\demo-mongodb\src\main\java\com\xkcoding\mongodb\model\Article.java
1
请完成以下Java代码
public LocatorId getPickFromLocatorId() {return pickFromLocator.getLocatorId();} public LocatorId getDropToLocatorId() {return dropToLocator.getLocatorId();} public I_C_UOM getUOM() {return qtyToMove.getUOM();} public boolean isInTransit() { return !steps.isEmpty() && steps.stream().anyMatch(DistributionJobStep::isInTransit); } public boolean isEligibleForPicking() {return getQtyInTransit().isLessThan(qtyToMove);} private Quantity getQtyInTransit() { return steps.stream() .map(DistributionJobStep::getQtyInTransit) .reduce(Quantity::add) .orElseGet(qtyToMove::toZero); } public boolean isFullyMoved() { return !steps.isEmpty() && steps.stream().allMatch(DistributionJobStep::isDroppedToLocator); } private static WFActivityStatus computeStatusFromSteps(final @NonNull List<DistributionJobStep> steps) { return steps.isEmpty() ? WFActivityStatus.NOT_STARTED : WFActivityStatus.computeStatusFromLines(steps, DistributionJobStep::getStatus); } public DDOrderLineId getDdOrderLineId() {return id.toDDOrderLineId();} public DistributionJobLine withNewStep(final DistributionJobStep stepToAdd) { final ArrayList<DistributionJobStep> changedSteps = new ArrayList<>(this.steps); boolean added = false; boolean changed = false; for (final DistributionJobStep step : steps) { if (DistributionJobStepId.equals(step.getId(), stepToAdd.getId())) { changedSteps.add(stepToAdd); added = true; if (!Objects.equals(step, stepToAdd)) { changed = true; } } else { changedSteps.add(step); } }
if (!added) { changedSteps.add(stepToAdd); changed = true; } return changed ? toBuilder().steps(ImmutableList.copyOf(changedSteps)).build() : this; } public DistributionJobLine withChangedSteps(@NonNull final UnaryOperator<DistributionJobStep> stepMapper) { final ImmutableList<DistributionJobStep> changedSteps = CollectionUtils.map(steps, stepMapper); return changedSteps.equals(steps) ? this : toBuilder().steps(changedSteps).build(); } public DistributionJobLine removeStep(@NonNull final DistributionJobStepId stepId) { final ImmutableList<DistributionJobStep> updatedStepCollection = steps.stream() .filter(step -> !step.getId().equals(stepId)) .collect(ImmutableList.toImmutableList()); return updatedStepCollection.equals(steps) ? this : toBuilder().steps(updatedStepCollection).build(); } @NonNull public Optional<DistributionJobStep> getStepById(@NonNull final DistributionJobStepId stepId) { return getSteps().stream().filter(step -> step.getId().equals(stepId)).findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobLine.java
1
请完成以下Java代码
public TableCalloutsMap getCallouts(final Properties ctx, final String tableName) { // if(tableName == ANY_TABLE) { return TableCalloutsMap.EMPTY; } final TableCalloutsMap.Builder tableCalloutsBuilder = TableCalloutsMap.builder(); for (final Entry<String, Supplier<ICalloutInstance>> entry : supplyCallouts(ctx, tableName).entries()) { final Supplier<ICalloutInstance> columnCalloutSupplier = entry.getValue(); try { final ICalloutInstance callout = columnCalloutSupplier.get(); if (callout == null) { continue; } final String columnName = entry.getKey(); tableCalloutsBuilder.put(columnName, callout); } catch (final Exception ex) { logger.warn("Failed creating callout instance for {}. Skipped.", columnCalloutSupplier, ex); } } return tableCalloutsBuilder.build(); } @Cached public ImmutableListMultimap<String, Supplier<ICalloutInstance>> supplyCallouts(@CacheCtx final Properties ctx, final String tableName) { final ListMultimap<String, I_AD_ColumnCallout> calloutsDef = Services.get(IADColumnCalloutDAO.class).retrieveAvailableCalloutsToRun(ctx, tableName); if (calloutsDef == null || calloutsDef.isEmpty()) { return ImmutableListMultimap.of(); } final ImmutableListMultimap.Builder<String, Supplier<ICalloutInstance>> callouts = ImmutableListMultimap.builder(); for (final Entry<String, I_AD_ColumnCallout> entry : calloutsDef.entries()) { final I_AD_ColumnCallout calloutDef = entry.getValue(); final Supplier<ICalloutInstance> calloutSupplier = supplyCalloutInstanceOrNull(calloutDef); if (calloutSupplier == null) { continue; } final String columnName = entry.getKey(); callouts.put(columnName, calloutSupplier); }
return callouts.build(); } /** * @return supplier or <code>null</code> but never throws exception */ private Supplier<ICalloutInstance> supplyCalloutInstanceOrNull(final I_AD_ColumnCallout calloutDef) { if (calloutDef == null) { return null; } if (!calloutDef.isActive()) { return null; } try { final String classname = calloutDef.getClassname(); Check.assumeNotEmpty(classname, "classname is not empty"); final Optional<String> ruleValue = ScriptEngineFactory.extractRuleValueFromClassname(classname); if(ruleValue.isPresent()) { return RuleCalloutInstance.supplier(ruleValue.get()); } else { return MethodNameCalloutInstance.supplier(classname); } } catch (final Exception e) { // We are just logging and discarding the error because there is nothing that we can do about it // More, we want to load the other callouts and not just fail logger.error("Failed creating callout instance for " + calloutDef, e); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\DefaultCalloutProvider.java
1
请完成以下Java代码
public ShipmentCandidateRow withChanges(@NonNull final ShipmentCandidateRowUserChangeRequest userChanges) { final ShipmentCandidateRowBuilder rowBuilder = toBuilder(); if (userChanges.getQtyToDeliverUserEntered() != null) { rowBuilder.qtyToDeliverUserEntered(userChanges.getQtyToDeliverUserEntered()); } if (userChanges.getQtyToDeliverCatchOverride() != null) { rowBuilder.qtyToDeliverCatchOverride(userChanges.getQtyToDeliverCatchOverride()); } if (userChanges.getAsi() != null) { rowBuilder.asi(userChanges.getAsi()); } return rowBuilder.build(); } @Override public WebuiASIEditingInfo getWebuiASIEditingInfo(@NonNull final AttributeSetInstanceId asiId) { final ProductId productId = product.getIdAs(ProductId::ofRepoIdOrNull); final ASIEditingInfo info = ASIEditingInfo.builder() .type(WindowType.Regular) .productId(productId) .attributeSetInstanceId(asiId) .callerTableName(null) .callerColumnId(-1) .soTrx(SOTrx.SALES) .build(); return WebuiASIEditingInfo.builder(info).build(); } Optional<ShipmentScheduleUserChangeRequest> createShipmentScheduleUserChangeRequest() { final ShipmentScheduleUserChangeRequestBuilder builder = ShipmentScheduleUserChangeRequest.builder() .shipmentScheduleId(shipmentScheduleId); boolean changes = false; if (qtyToDeliverUserEnteredInitial.compareTo(qtyToDeliverUserEntered) != 0) { BigDecimal qtyCUsToDeliver = packingInfo.computeQtyCUsByQtyUserEntered(qtyToDeliverUserEntered); builder.qtyToDeliverStockOverride(qtyCUsToDeliver); changes = true; } if (qtyToDeliverCatchOverrideIsChanged()) { builder.qtyToDeliverCatchOverride(qtyToDeliverCatchOverride); changes = true; } final AttributeSetInstanceId asiId = asi.getIdAs(AttributeSetInstanceId::ofRepoIdOrNone); if (!Objects.equals(asiIdInitial, asiId))
{ builder.asiId(asiId); changes = true; } return changes ? Optional.of(builder.build()) : Optional.empty(); } private boolean qtyToDeliverCatchOverrideIsChanged() { final Optional<Boolean> nullValuechanged = isNullValuesChanged(qtyToDeliverCatchOverrideInitial, qtyToDeliverCatchOverride); return nullValuechanged.orElseGet(() -> qtyToDeliverCatchOverrideInitial.compareTo(qtyToDeliverCatchOverride) != 0); } private static Optional<Boolean> isNullValuesChanged( @Nullable final Object initial, @Nullable final Object current) { final boolean wasNull = initial == null; final boolean isNull = current == null; if (wasNull) { if (isNull) { return Optional.of(false); } return Optional.of(true); // was null and is not null anymore } if (isNull) { return Optional.of(true); // was not null and is now } return Optional.empty(); // was not null and still is not null; will need to compare the current values } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRow.java
1
请完成以下Java代码
public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Container getCM_Container() throws RuntimeException { return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name) .getPO(getCM_Container_ID(), get_TrxName()); } /** Set Web Container. @param CM_Container_ID Web Container contains content like images, text etc. */ public void setCM_Container_ID (int CM_Container_ID) {
if (CM_Container_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessContainer.java
1
请完成以下Java代码
public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName) { throw new UnsupportedOperationException(); } @Override public ViewHeaderProperties getHeaderProperties() { return rowsData.getHeaderProperties(); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } public ViewId getInitialViewId() { return initialViewId != null ? initialViewId : getViewId(); } @Override public ViewId getParentViewId() { return initialViewId; } public Optional<OrderId> getOrderId() { return rowsData.getOrder().map(Order::getOrderId); } public Optional<BPartnerId> getBpartnerId() { return rowsData.getBpartnerId(); } public SOTrx getSoTrx() { return rowsData.getSoTrx(); } public CurrencyId getCurrencyId() { return rowsData.getCurrencyId(); } public Set<ProductId> getProductIds() { return rowsData.getProductIds(); } public Optional<PriceListVersionId> getSinglePriceListVersionId() { return rowsData.getSinglePriceListVersionId(); } public Optional<PriceListVersionId> getBasePriceListVersionId()
{ return rowsData.getBasePriceListVersionId(); } public PriceListVersionId getBasePriceListVersionIdOrFail() { return rowsData.getBasePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@")); } public List<ProductsProposalRow> getAllRows() { return ImmutableList.copyOf(getRows()); } public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests) { rowsData.addOrUpdateRows(requests); invalidateAll(); } public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request) { rowsData.patchRow(rowId, request); } public void removeRowsByIds(final Set<DocumentId> rowIds) { rowsData.removeRowsByIds(rowIds); invalidateAll(); } public ProductsProposalView filter(final ProductsProposalViewFilter filter) { rowsData.filter(filter); return this; } @Override public DocumentFilterList getFilters() { return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
1
请在Spring Boot框架中完成以下Java代码
public RabbitMqConsumer initRabbitMqConsumer() { return new RabbitMqConsumer(); } @Bean(name = "firstRabbitTemplate") public RabbitTemplate firstRabbitTemplate( @Qualifier("firstConnectionFactory") ConnectionFactory connectionFactory) { RabbitTemplate firstRabbitTemplate = new RabbitTemplate(connectionFactory); //使用外部事物 //ydtRabbitTemplate.setChannelTransacted(true); return firstRabbitTemplate; } @Bean(name = "secondConnectionFactory") public ConnectionFactory secondConnectionFactory( @Value("${spring.rabbitmq.second.host}") String host, @Value("${spring.rabbitmq.second.port}") int port, @Value("${spring.rabbitmq.second.username}") String username, @Value("${spring.rabbitmq.second.password}") String password, @Value("${spring.rabbitmq.second.virtual-host}") String virtualHost) { return getCachingConnectionFactory(host, port, username, password, virtualHost); } @Bean(name = "secondRabbitTemplate") @Primary public RabbitTemplate secondRabbitTemplate( @Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory) { RabbitTemplate secondRabbitTemplate = new RabbitTemplate(connectionFactory); //使用外部事物
//lpzRabbitTemplate.setChannelTransacted(true); return secondRabbitTemplate; } @Bean(name = "secondContainerFactory") public SimpleRabbitListenerContainerFactory secondFactory( SimpleRabbitListenerContainerFactoryConfigurer configurer, @Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; } private CachingConnectionFactory getCachingConnectionFactory(String host, int port, String username, String password, String virtualHost) { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost(host); connectionFactory.setPort(port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); connectionFactory.setVirtualHost(virtualHost); return connectionFactory; } }
repos\spring-boot-quick-master\quick-multi-rabbitmq\src\main\java\com\multi\rabbitmq\config\RabbitMqConfiguration.java
2
请完成以下Java代码
public Optional<String> getDeviceId() {return getByPathAsString("device", "deviceId");} public Optional<String> getTabId() {return getByPathAsString("device", "tabId");} public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");} public Optional<String> getByPathAsString(final String... path) { return getByPath(path).map(Object::toString); } public Optional<Object> getByPath(final String... path) { Object currentValue = properties; for (final String pathElement : path) { if (!(currentValue instanceof Map)) { //throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties); return Optional.empty(); } //noinspection unchecked final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null); if (value == null) { return Optional.empty(); } else { currentValue = value; }
} return Optional.of(currentValue); } private static Optional<Object> getByKey(final Map<String, Object> map, final String key) { return map.entrySet() .stream() .filter(e -> e.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getValue) .filter(Objects::nonNull) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java
1
请完成以下Java代码
protected boolean hasTokenExpired(OAuth2Token token) { return token.getExpiresAt() == null || ClockUtil.now().after(Date.from(token.getExpiresAt())); } protected void clearContext(HttpServletRequest request) { SecurityContextHolder.clearContext(); try { request.getSession().invalidate(); } catch (Exception ignored) { } } protected void authorizeToken(OAuth2AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) { // @formatter:off var authRequest = OAuth2AuthorizeRequest .withClientRegistrationId(token.getAuthorizedClientRegistrationId()) .principal(token) .attributes(attrs -> { attrs.put(HttpServletRequest.class.getName(), request); attrs.put(HttpServletResponse.class.getName(), response);
}).build(); // @formatter:on var name = token.getName(); try { var res = clientManager.authorize(authRequest); if (res == null || hasTokenExpired(res.getAccessToken())) { logger.warn("Authorize failed for '{}': could not re-authorize expired access token", name); clearContext(request); } else { logger.debug("Authorize successful for '{}', access token expiry: {}", name, res.getAccessToken().getExpiresAt()); } } catch (OAuth2AuthorizationException e) { logger.warn("Authorize failed for '{}': {}", name, e.getMessage()); clearContext(request); } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\AuthorizeTokenFilter.java
1
请完成以下Java代码
public void handle(OrderProcessContext orderProcessContext) { preHandle(orderProcessContext); // 获取产品Entity的Map OrderInsertReq orderInsertReq = (OrderInsertReq) orderProcessContext.getOrderProcessReq().getReqData(); Map<ProductEntity ,Integer> prodEntityCountMap = orderInsertReq.getProdEntityCountMap(); // 检查库存 checkStock(prodEntityCountMap); afterHandle(orderProcessContext); } /** * 校验库存是否足够
* @param prodEntityCountMap 产品-购买数量 集合 */ private void checkStock(Map<ProductEntity, Integer> prodEntityCountMap) { // 校验库存 for (ProductEntity productEntity : prodEntityCountMap.keySet()) { // 获取购买量 Integer count = prodEntityCountMap.get(productEntity); // 校验 if (productEntity.getStock() < count) { throw new CommonBizException(ExpCodeEnum.STOCK_LOW); } } } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\checkstock\BaseCheckStockComponent.java
1
请完成以下Java代码
private static PayPalEnvironment createPayPalEnvironment(@NonNull final PayPalConfig config) { if (!config.isSandbox()) { return new PayPalEnvironment( config.getClientId(), config.getClientSecret(), config.getBaseUrl(), config.getWebUrl()); } else { return new PayPalEnvironment.Sandbox( config.getClientId(), config.getClientSecret()); } } public PayPalConfig getConfig() { return payPalConfigProvider.getConfig(); } private <T> PayPalClientResponse<T, PayPalErrorResponse> executeRequest( @NonNull final HttpRequest<T> request, @NonNull final PayPalClientExecutionContext context) { final PayPalCreateLogRequestBuilder log = PayPalCreateLogRequest.builder() .paymentReservationId(context.getPaymentReservationId()) .paymentReservationCaptureId(context.getPaymentReservationCaptureId()) // .salesOrderId(context.getSalesOrderId()) .salesInvoiceId(context.getSalesInvoiceId()) .paymentId(context.getPaymentId()) // .internalPayPalOrderId(context.getInternalPayPalOrderId()); try { log.request(request); final PayPalHttpClient httpClient = createPayPalHttpClient(getConfig()); final HttpResponse<T> response = httpClient.execute(request); log.response(response); return PayPalClientResponse.ofResult(response.result()); } catch (final HttpException httpException) { log.response(httpException);
final String errorAsJson = httpException.getMessage(); try { final PayPalErrorResponse error = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(errorAsJson, PayPalErrorResponse.class); return PayPalClientResponse.ofError(error, httpException); } catch (final Exception jsonException) { throw AdempiereException.wrapIfNeeded(httpException) .suppressing(jsonException); } } catch (final IOException ex) { log.response(ex); throw AdempiereException.wrapIfNeeded(ex); } finally { logsRepo.log(log.build()); } } public Capture captureOrder( @NonNull final PayPalOrderAuthorizationId authId, @NonNull final Amount amount, @Nullable final Boolean finalCapture, @NonNull final PayPalClientExecutionContext context) { final AuthorizationsCaptureRequest request = new AuthorizationsCaptureRequest(authId.getAsString()) .requestBody(new CaptureRequest() .amount(new com.paypal.payments.Money() .currencyCode(amount.getCurrencyCode().toThreeLetterCode()) .value(amount.getAsBigDecimal().toPlainString())) .finalCapture(finalCapture)); return executeRequest(request, context) .getResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalClientService.java
1