instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private BPartnerContact extract0(@NonNull final IdentifierString contactIdentifier) { switch (contactIdentifier.getType()) { case METASFRESH_ID: if (bpartnerId != null) { final BPartnerContactId bpartnerContactId = BPartnerContactId.of(bpartnerId, contactIdentifier.asMetasfreshId(UserId::ofRepoId)); return id2Contact.get(bpartnerContactId); } else { return null; } case EXTERNAL_ID: final BPartnerContact resultByExternalId = externalId2Contact.get(contactIdentifier.asExternalId()); return resultByExternalId; case VALUE: final BPartnerContact resultByValue = value2Contact.get(contactIdentifier.asValue()); return resultByValue; default: throw new InvalidIdentifierException(contactIdentifier); } } public BPartnerContact newContact(@NonNull final IdentifierString contactIdentifier) { final BPartnerContact contact; final BPartnerContactBuilder contactBuilder = BPartnerContact.builder(); switch (contactIdentifier.getType()) { case METASFRESH_ID: if (bpartnerId != null) { final BPartnerContactId bpartnerContactId = BPartnerContactId.of(bpartnerId, contactIdentifier.asMetasfreshId(UserId::ofRepoId)); contact = contactBuilder.id(bpartnerContactId).build(); id2Contact.put(bpartnerContactId, contact); } else { contact = contactBuilder.build(); } break; case EXTERNAL_ID: contact = contactBuilder.externalId(contactIdentifier.asExternalId()).build(); externalId2Contact.put(contactIdentifier.asExternalId(), contact); break; case VALUE: contact = contactBuilder.value(contactIdentifier.asValue()).build(); value2Contact.put(contactIdentifier.asValue(), contact); break; default: throw new InvalidIdentifierException(contactIdentifier); } bpartnerComposite .getContacts() .add(contact); return contact; } public Collection<BPartnerContact> getUnusedContacts() { return id2UnusedContact.values(); } public void resetDefaultContactFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setDefaultContact(false); } }
public void resetShipToDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setShipToDefault(false); } } public void resetPurchaseDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setPurchaseDefault(false); } } public void resetSalesDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setSalesDefault(false); } } public void resetBillToDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setBillToDefault(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\ShortTermContactIndex.java
1
请完成以下Java代码
public void clear() { for (List<Vertex> vertexList : vertexes) { vertexList.clear(); } size = 0; } /** * 清理from属性 */ public void clean() { for (List<Vertex> vertexList : vertexes) {
for (Vertex vertex : vertexList) { vertex.from = null; } } } /** * 获取内部顶点表格,谨慎操作! * * @return */ public LinkedList<Vertex>[] getVertexes() { return vertexes; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\WordNet.java
1
请完成以下Java代码
private void moveHandlingUnits(final I_M_MovementLine movementLine, final boolean doReversal) { final I_M_Locator locatorFrom; final I_M_Locator locatorTo; if (!doReversal) { locatorFrom = movementLine.getM_Locator(); locatorTo = movementLine.getM_LocatorTo(); } else { locatorFrom = movementLine.getM_LocatorTo(); locatorTo = movementLine.getM_Locator(); } final List<I_M_HU> hus = huAssignmentDAO.retrieveTopLevelHUsForModel(movementLine); for (final I_M_HU hu : hus) { final int huLocatorId = hu.getM_Locator_ID(); Check.assume(huLocatorId > 0 && (huLocatorId == locatorFrom.getM_Locator_ID() || huLocatorId == locatorTo.getM_Locator_ID()), "HU Locator was supposed to be {} or {}, but was {}", locatorFrom, locatorTo, huLocatorId); moveHandlingUnit(hu, LocatorId.ofRecord(locatorTo)); } } private void moveHandlingUnit(final I_M_HU hu, final LocatorId locatorToId) { final SourceHUsService sourceHuService = SourceHUsService.get(); // // Make sure HU's current locator is the locator from which we need to move // final int huLocatorIdOld = hu.getM_Locator_ID(); final LocatorId locatorFromId = IHandlingUnitsBL.extractLocatorId(hu); // If already moved, then do nothing. if (Objects.equals(locatorFromId, locatorToId)) { return; } final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); final boolean isSourceHU = sourceHuService.isSourceHu(huId); if (isSourceHU)
{ sourceHuService.deleteSourceHuMarker(huId); } // // Update HU's Locator // FIXME: refactor this and have a common way of setting HU's locator hu.setM_Locator_ID(locatorToId.getRepoId()); // Activate HU (not needed, but we want to be sure) // (even if we do reversals) // NOTE: as far as we know, HUContext won't be used by setHUStatus, because the // status "active" doesn't // trigger a movement to/from empties warehouse. In this case a movement is // already created from a lager to another. // So no HU leftovers. final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(hu); final IMutableHUContext huContext = huContextFactory.createMutableHUContext(contextProvider); huStatusBL.setHUStatus(huContext, hu, X_M_HU.HUSTATUS_Active); // Save changed HU handlingUnitsDAO.saveHU(hu); final I_M_Locator locatorTo = warehousesDAO.getLocatorById(locatorToId); final I_M_Warehouse warehouseTo = warehousesDAO.getById(WarehouseId.ofRepoId(locatorTo.getM_Warehouse_ID())); if (warehouseTo.isReceiveAsSourceHU()) { sourceHuService.addSourceHuMarker(huId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\api\impl\HUMovementBL.java
1
请在Spring Boot框架中完成以下Java代码
public Store getKeystore() { return this.keystore; } public Store getTruststore() { return this.truststore; } /** * Store properties. */ public static class Store { /** * Type of the store to create, e.g. JKS. */ private @Nullable String type; /** * Location or content of the certificate or certificate chain in PEM format. */ private @Nullable String certificate; /** * Location or content of the private key in PEM format. */ private @Nullable String privateKey; /** * Password used to decrypt an encrypted private key. */ private @Nullable String privateKeyPassword; /** * Whether to verify that the private key matches the public key. */ private boolean verifyKeys; public @Nullable String getType() { return this.type; } public void setType(@Nullable String type) { this.type = type; } public @Nullable String getCertificate() { return this.certificate; }
public void setCertificate(@Nullable String certificate) { this.certificate = certificate; } public @Nullable String getPrivateKey() { return this.privateKey; } public void setPrivateKey(@Nullable String privateKey) { this.privateKey = privateKey; } public @Nullable String getPrivateKeyPassword() { return this.privateKeyPassword; } public void setPrivateKeyPassword(@Nullable String privateKeyPassword) { this.privateKeyPassword = privateKeyPassword; } public boolean isVerifyKeys() { return this.verifyKeys; } public void setVerifyKeys(boolean verifyKeys) { this.verifyKeys = verifyKeys; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\PemSslBundleProperties.java
2
请完成以下Java代码
public int signum() {return toMoney().signum();} /** * @return absolute balance, negated if reversal */ public Money getPostBalance() { Money balanceAbs = toMoney().abs(); if (isReversal()) { return balanceAbs.negate(); } return balanceAbs; } /** * @return true if the balance (debit - credit) is zero */ public boolean isBalanced() {return signum() == 0;} /** * @return true if both DR/CR are negative or zero */ public boolean isReversal() {return debit.signum() <= 0 && credit.signum() <= 0;} public boolean isDebit() { if (isReversal()) { return toMoney().signum() <= 0; } else { return toMoney().signum() >= 0; } } public CurrencyId getCurrencyId() {return Money.getCommonCurrencyIdOfAll(debit, credit);} public Balance negateAndInvert() { return new Balance(this.credit.negate(), this.debit.negate()); } public Balance negateAndInvertIf(final boolean condition) { return condition ? negateAndInvert() : this; } public Balance toSingleSide() { final Money min = debit.min(credit); if (min.isZero()) { return this; } return new Balance(this.debit.subtract(min), this.credit.subtract(min)); } public Balance computeDiffToBalance() { final Money diff = toMoney(); if (isReversal()) { return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate()); } else { return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff); } } public Balance invert() { return new Balance(this.credit, this.debit); }
// // // // // @ToString private static class BalanceBuilder { private Money debit; private Money credit; public void add(@NonNull Balance balance) { add(balance.getDebit(), balance.getCredit()); } public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder) { add(balanceBuilder.debit, balanceBuilder.credit); return this; } public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd) { if (debitToAdd != null) { this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd; } if (creditToAdd != null) { this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd; } } public Optional<Balance> build() { return debit != null || credit != null ? Optional.of(new Balance(debit, credit)) : Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java
1
请完成以下Java代码
protected List<ExecutionEntity> fetchExecutions(CommandContext commandContext, String processInstanceId) { return commandContext.getExecutionManager().findExecutionsByProcessInstanceId(processInstanceId); } protected List<EventSubscriptionEntity> fetchEventSubscriptions(CommandContext commandContext, String processInstanceId) { return commandContext.getEventSubscriptionManager().findEventSubscriptionsByProcessInstanceId(processInstanceId); } protected List<ExternalTaskEntity> fetchExternalTasks(CommandContext commandContext, String processInstanceId) { return commandContext.getExternalTaskManager().findExternalTasksByProcessInstanceId(processInstanceId); } protected List<JobEntity> fetchJobs(CommandContext commandContext, String processInstanceId) { return commandContext.getJobManager().findJobsByProcessInstanceId(processInstanceId); } protected List<IncidentEntity> fetchIncidents(CommandContext commandContext, String processInstanceId) {
return commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId); } protected List<TaskEntity> fetchTasks(CommandContext commandContext, String processInstanceId) { return commandContext.getTaskManager().findTasksByProcessInstanceId(processInstanceId); } protected List<JobDefinitionEntity> fetchJobDefinitions(CommandContext commandContext, String processDefinitionId) { return commandContext.getJobDefinitionManager().findByProcessDefinitionId(processDefinitionId); } protected List<VariableInstanceEntity> fetchVariables(CommandContext commandContext, String processInstanceId) { return commandContext.getVariableInstanceManager().findVariableInstancesByProcessInstanceId(processInstanceId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\MigratingInstanceParser.java
1
请完成以下Java代码
protected void validateParentScopeMigrates(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl sourceActivity = instruction.getSourceActivity(); ScopeImpl flowScope = sourceActivity.getFlowScope(); if (flowScope != flowScope.getProcessDefinition()) { if (instructions.getInstructionsBySourceScope(flowScope).isEmpty()) { report.addFailure("The gateway's flow scope '" + flowScope.getId() + "' must be mapped"); } } } protected void validateSingleInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl targetActivity = instruction.getTargetActivity(); List<ValidatingMigrationInstruction> instructionsToTargetGateway =
instructions.getInstructionsByTargetScope(targetActivity); if (instructionsToTargetGateway.size() > 1) { report.addFailure("Only one gateway can be mapped to gateway '" + targetActivity.getId() + "'"); } } protected boolean isWaitStateGateway(ActivityImpl activity) { ActivityBehavior behavior = activity.getActivityBehavior(); return behavior instanceof ParallelGatewayActivityBehavior || behavior instanceof InclusiveGatewayActivityBehavior; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\GatewayMappingValidator.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; }
public void setBooks(List<Book> books) { this.books = books; } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public Date getCreateTime() { return startTime; } public void setCreateTime(Date createTime) { setStartTime(createTime); } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public boolean isAvailable() { return caseActivityInstanceState == AVAILABLE.getStateCode(); } public boolean isEnabled() { return caseActivityInstanceState == ENABLED.getStateCode(); } public boolean isDisabled() { return caseActivityInstanceState == DISABLED.getStateCode(); } public boolean isActive() { return caseActivityInstanceState == ACTIVE.getStateCode(); } public boolean isSuspended() { return caseActivityInstanceState == SUSPENDED.getStateCode(); } public boolean isCompleted() { return caseActivityInstanceState == COMPLETED.getStateCode(); }
public boolean isTerminated() { return caseActivityInstanceState == TERMINATED.getStateCode(); } public String toString() { return this.getClass().getSimpleName() + "[caseActivityId=" + caseActivityId + ", caseActivityName=" + caseActivityName + ", caseActivityInstanceId=" + id + ", caseActivityInstanceState=" + caseActivityInstanceState + ", parentCaseActivityInstanceId=" + parentCaseActivityInstanceId + ", taskId=" + taskId + ", calledProcessInstanceId=" + calledProcessInstanceId + ", calledCaseInstanceId=" + calledCaseInstanceId + ", durationInMillis=" + durationInMillis + ", createTime=" + startTime + ", endTime=" + endTime + ", eventType=" + eventType + ", caseExecutionId=" + caseExecutionId + ", caseDefinitionId=" + caseDefinitionId + ", caseInstanceId=" + caseInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseActivityInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void addQueueTask(String url) { blockingQueue.add(url); } @Override public String takeQueueTask() throws InterruptedException { return blockingQueue.take(); } @Override public void initPDFCachePool(Integer capacity) { pdfCache = new ConcurrentLinkedHashMap.Builder<String, String>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } @Override public void initIMGCachePool(Integer capacity) { imgCache = new ConcurrentLinkedHashMap.Builder<String, List<String>>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build();
} @Override public void initPdfImagesCachePool(Integer capacity) { pdfImagesCache = new ConcurrentLinkedHashMap.Builder<String, Integer>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } @Override public void initMediaConvertCachePool(Integer capacity) { mediaConvertCache = new ConcurrentLinkedHashMap.Builder<String, String>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceJDKImpl.java
2
请在Spring Boot框架中完成以下Java代码
private void createMissingRefListForLabels(@NonNull final ImmutableList<IssueLabel> issueLabels) { issueLabels.stream() .filter(label -> adReferenceService.retrieveListItemOrNull(LABEL_AD_Reference_ID, label.getValue()) == null) .map(this::buildRefList) .forEach(adReferenceService::saveRefList); } private ADRefListItemCreateRequest buildRefList(@NonNull final IssueLabel issueLabel) { return ADRefListItemCreateRequest .builder() .name(TranslatableStrings.constant(issueLabel.getValue())) .value(issueLabel.getValue()) .referenceId(ReferenceId.ofRepoId(LABEL_AD_Reference_ID)) .build(); }
private void extractAndPropagateAdempiereException(final CompletableFuture completableFuture) { try { completableFuture.get(); } catch (final ExecutionException ex) { throw AdempiereException.wrapIfNeeded(ex.getCause()); } catch (final InterruptedException ex1) { throw AdempiereException.wrapIfNeeded(ex1); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\importer\IssueImporterService.java
2
请完成以下Java代码
private List<ProductEntity> queryProduct(Map<String, Integer> prodIdCountMap) { // 查询结果集 List<ProductEntity> productEntityList = Lists.newArrayList(); // 构建查询请求 List<ProdQueryReq> prodQueryReqList = buildProdQueryReq(prodIdCountMap); // 批量查询 for (ProdQueryReq prodQueryReq : prodQueryReqList) { List<ProductEntity> productEntitys = productService.findProducts(prodQueryReq).getData(); // 产品ID不存在 if (productEntitys.size() <= 0) { logger.error("查询产品详情时,上线中 & 产品ID=" + prodQueryReq.getId() + "的产品不存在!"); throw new CommonBizException(ExpCodeEnum.PRODUCT_NO_EXISTENT); } productEntityList.add(productEntitys.get(0)); } return productEntityList; } /** * 构建产品查询请求 * @param prodIdCountMap 产品ID-库存 映射
* @return 产品查询请求列表 */ private List<ProdQueryReq> buildProdQueryReq(Map<String, Integer> prodIdCountMap) { List<ProdQueryReq> prodQueryReqList = Lists.newArrayList(); for (String prodId : prodIdCountMap.keySet()) { ProdQueryReq prodQueryReq = new ProdQueryReq(); prodQueryReq.setId(prodId); // 必须是"上线中"的产品 prodQueryReq.setProdStateCode(ProdStateEnum.OPEN.getCode()); prodQueryReqList.add(prodQueryReq); } return prodQueryReqList; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdCountMapTransferComponent.java
1
请完成以下Java代码
public class Country implements Externalizable { private static final long serialVersionUID = 1L; private String name; private String capital; private int code; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(name); out.writeUTF(capital);
out.writeInt(code); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.name = in.readUTF(); this.capital = in.readUTF(); this.code = in.readInt(); } @Override public String toString() { return "Country{" + "name='" + name + '\'' + ", capital='" + capital + '\'' + ", code=" + code + '}'; } }
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\externalizable\Country.java
1
请完成以下Java代码
public IInfoColumnController getColumnController() { return columnController; } public void setColumnController(IInfoColumnController columnController) { this.columnController = columnController; } final List<Info_Column> dependentColumns = new ArrayList<Info_Column>(); public List<Info_Column> getDependentColumns() { return dependentColumns; } private int widthMin = -1; public ColumnInfo setWidthMin(final int widthMin) { this.widthMin = widthMin; return this; } public int getWidthMin(final int widthMinDefault) { if (widthMin < 0) { return widthMinDefault; } return widthMin; } private String columnName = null; /** * Sets internal (not translated) name of this column. * * @param columnName * @return this */ public ColumnInfo setColumnName(final String columnName) { this.columnName = columnName; return this; } /** * * @return internal (not translated) column name */ public String getColumnName() { return columnName; } private int precision = -1; /** * Sets precision to be used in case it's a number. * * If not set, default displayType's precision will be used. * * @param precision * @return this
*/ public ColumnInfo setPrecision(final int precision) { this.precision = precision; return this; } /** * * @return precision to be used in case it's a number */ public int getPrecision() { return this.precision; } public ColumnInfo setSortNo(final int sortNo) { this.sortNo = sortNo; return this; } /** * Gets SortNo. * * @return * @see I_AD_Field#COLUMNNAME_SortNo. */ public int getSortNo() { return sortNo; } @Override public String toString() { return ObjectUtils.toString(this); } } // infoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\minigrid\ColumnInfo.java
1
请完成以下Java代码
protected void loadFilterRules(FilterConfig filterConfig, String applicationPath) throws ServletException { String configFileName = filterConfig.getInitParameter("configFile"); InputStream configFileResource = filterConfig.getServletContext().getResourceAsStream(configFileName); if (configFileResource == null) { throw new ServletException("Could not read security filter config file '"+configFileName+"': no such resource in servlet context."); } else { try { filterRules = FilterRules.load(configFileResource, applicationPath); } catch (Exception e) { throw new RuntimeException("Exception while parsing '" + configFileName + "'", e); } finally { IoUtil.closeSilently(configFileResource); } } } protected void sendForbidden(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403); }
protected void sendUnauthorized(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(401); } protected void sendForbiddenApplicationAccess(String application, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403, "No access rights for " + application); } protected boolean isAuthenticated(HttpServletRequest request) { return Authentications.getCurrent() != null; } protected String getRequestUri(HttpServletRequest request) { String contextPath = request.getContextPath(); return request.getRequestURI().substring(contextPath.length()); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SecurityFilter.java
1
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNSignalImpl that = (BPMNSignalImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(signalPayload, that.getSignalPayload()) ); } @Override public int hashCode() { return Objects.hash( getElementId(), signalPayload != null ? signalPayload.getId() : null, signalPayload != null ? signalPayload.getName() : null ); }
@Override public String toString() { return ( "BPMNActivityImpl{" + ", elementId='" + getElementId() + '\'' + ", signalPayload='" + (signalPayload != null ? signalPayload.toString() : null) + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNSignalImpl.java
1
请完成以下Java代码
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { if (!(parentElement instanceof EndEvent)) { return; } TerminateEventDefinition eventDefinition = new TerminateEventDefinition(); parseTerminateAllAttribute(xtr, eventDefinition); parseTerminateMultiInstanceAttribute(xtr, eventDefinition); BpmnXMLUtil.addXMLLocation(eventDefinition, xtr); BpmnXMLUtil.parseChildElements(ELEMENT_EVENT_TERMINATEDEFINITION, eventDefinition, xtr, model); ((Event) parentElement).getEventDefinitions().add(eventDefinition); } protected void parseTerminateAllAttribute(XMLStreamReader xtr, TerminateEventDefinition eventDefinition) { String terminateAllValue = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TERMINATE_ALL); if (terminateAllValue != null && "true".equals(terminateAllValue)) { eventDefinition.setTerminateAll(true);
} else { eventDefinition.setTerminateAll(false); } } protected void parseTerminateMultiInstanceAttribute(XMLStreamReader xtr, TerminateEventDefinition eventDefinition) { String terminateMiValue = xtr.getAttributeValue( ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TERMINATE_MULTI_INSTANCE ); if (terminateMiValue != null && "true".equals(terminateMiValue)) { eventDefinition.setTerminateMultiInstance(true); } else { eventDefinition.setTerminateMultiInstance(false); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\TerminateEventDefinitionParser.java
1
请完成以下Java代码
public final class PharmaCustomerPermissions { public static PharmaCustomerPermissions of(@NonNull final org.compiere.model.I_C_BPartner bpartner) { if (!bpartner.isCustomer()) { return NONE; } final I_C_BPartner pharmaBPartner = InterfaceWrapperHelper.create(bpartner, I_C_BPartner.class); final ImmutableSet.Builder<PharmaCustomerPermission> permissionsBuilder = ImmutableSet.builder(); if (pharmaBPartner.isPharmaAgentPermission()) { permissionsBuilder.add(PharmaCustomerPermission.PHARMA_AGENT); } if (pharmaBPartner.isPharmaciePermission()) { permissionsBuilder.add(PharmaCustomerPermission.PHARMACIE); } if (pharmaBPartner.isPharmaManufacturerPermission()) { permissionsBuilder.add(PharmaCustomerPermission.PHARMA_MANUFACTURER); } if (pharmaBPartner.isPharmaWholesalePermission()) { permissionsBuilder.add(PharmaCustomerPermission.PHARMA_WHOLESALE); } if (pharmaBPartner.isVeterinaryPharmacyPermission()) { permissionsBuilder.add(PharmaCustomerPermission.VETERINARY_PHARMACY); } if (pharmaBPartner.isPharmaCustomerNarcoticsPermission()) { permissionsBuilder.add(PharmaCustomerPermission.PHARMA_NARCOTICS); } final ImmutableSet<PharmaCustomerPermission> permissions = permissionsBuilder.build(); if (permissions.isEmpty()) { return NONE; } return new PharmaCustomerPermissions(permissions); } private static final PharmaCustomerPermissions NONE = new PharmaCustomerPermissions(ImmutableSet.of()); private final ImmutableSet<PharmaCustomerPermission> permissions; private PharmaCustomerPermissions(final Set<PharmaCustomerPermission> permissions) { this.permissions = ImmutableSet.copyOf(permissions); }
public boolean hasAtLeastOnePermission() { return !permissions.isEmpty(); } public boolean hasPermission(final PharmaCustomerPermission permission) { return permissions.contains(permission); } public boolean hasOnlyPermission(final PharmaCustomerPermission permission) { return permissions.size() == 1 && permissions.contains(permission); } public ITranslatableString toTrlString() { if (permissions.isEmpty()) { return TranslatableStrings.anyLanguage("-"); } final IMsgBL msgBL = Services.get(IMsgBL.class); final TranslatableStringBuilder builder = TranslatableStrings.builder(); for (final PharmaCustomerPermission permission : permissions) { if (!builder.isEmpty()) { builder.append(", "); } builder.append(msgBL.translatable(permission.getDisplayNameAdMessage())); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\PharmaCustomerPermissions.java
1
请完成以下Java代码
public class WelcomeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CookieReader cookieReader = new CookieReader(request); Optional<String> uiColor = cookieReader.readCookie("uiColor"); Optional<String> userName = cookieReader.readCookie("userName"); if (!userName.isPresent()) { response.sendRedirect("/login"); } else { request.setAttribute("uiColor", uiColor.orElse("blue")); request.setAttribute("userName", userName.get()); request.setAttribute("sessionAttribute", request.getSession() .getAttribute("sampleKey"));
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/welcome.jsp"); dispatcher.forward(request, response); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie userNameCookieRemove = new Cookie("userName", ""); userNameCookieRemove.setMaxAge(0); response.addCookie(userNameCookieRemove); response.sendRedirect("/login"); } }
repos\tutorials-master\web-modules\jakarta-servlets\src\main\java\com\baeldung\servlets\WelcomeServlet.java
1
请在Spring Boot框架中完成以下Java代码
public class User implements UserDetails { @Id @GeneratedValue private Long id; private String username; private String password; @ManyToMany(cascade = {CascadeType.REFRESH},fetch = FetchType.EAGER) private List<Role> roles; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } // 下面为实现UserDetails而需要的重写方法! @Override
public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : roles) { authorities.add( new SimpleGrantedAuthority( role.getName() ) ); } return authorities; } @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } }
repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\model\entity\User.java
2
请完成以下Java代码
public ResponseEntity<Order> placeOrderWithHttpInfo(Order body) throws RestClientException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder"); } String path = apiClient.expandPath("/store/order", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { "application/json", "application/xml" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Order> returnType = new ParameterizedTypeReference<Order>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\api\StoreApi.java
1
请完成以下Java代码
public final void setErrorConverter(Converter<Map<String, String>, OAuth2Error> errorConverter) { Assert.notNull(errorConverter, "errorConverter cannot be null"); this.errorConverter = errorConverter; } /** * Sets the {@link Converter} used for converting the {@link OAuth2Error} to a * {@code Map} representation of the OAuth 2.0 Error parameters. * @param errorParametersConverter the {@link Converter} used for converting to a * {@code Map} representation of the Error parameters */ public final void setErrorParametersConverter( Converter<OAuth2Error, Map<String, String>> errorParametersConverter) { Assert.notNull(errorParametersConverter, "errorParametersConverter cannot be null"); this.errorParametersConverter = errorParametersConverter; } /** * A {@link Converter} that converts the provided OAuth 2.0 Error parameters to an * {@link OAuth2Error}. */ private static class OAuth2ErrorConverter implements Converter<Map<String, String>, OAuth2Error> { @Override public OAuth2Error convert(Map<String, String> parameters) { String errorCode = parameters.get(OAuth2ParameterNames.ERROR); String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION); String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI); return new OAuth2Error(errorCode, errorDescription, errorUri); } } /**
* A {@link Converter} that converts the provided {@link OAuth2Error} to a {@code Map} * representation of OAuth 2.0 Error parameters. */ private static class OAuth2ErrorParametersConverter implements Converter<OAuth2Error, Map<String, String>> { @Override public Map<String, String> convert(OAuth2Error oauth2Error) { Map<String, String> parameters = new HashMap<>(); parameters.put(OAuth2ParameterNames.ERROR, oauth2Error.getErrorCode()); if (StringUtils.hasText(oauth2Error.getDescription())) { parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, oauth2Error.getDescription()); } if (StringUtils.hasText(oauth2Error.getUri())) { parameters.put(OAuth2ParameterNames.ERROR_URI, oauth2Error.getUri()); } return parameters; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverter.java
1
请完成以下Java代码
public abstract class DelegateFormHandler { protected String deploymentId; protected FormHandler formHandler; public DelegateFormHandler(FormHandler formHandler, String deploymentId) { this.formHandler = formHandler; this.deploymentId = deploymentId; } public void parseConfiguration(Element activityElement, DeploymentEntity deployment, ProcessDefinitionEntity processDefinition, BpmnParse bpmnParse) { // should not be called! } protected <T> T performContextSwitch(final Callable<T> callable) { ProcessApplicationReference targetProcessApplication = ProcessApplicationContextUtil.getTargetProcessApplication(deploymentId); if(targetProcessApplication != null) { return Context.executeWithinProcessApplication(new Callable<T>() { public T call() throws Exception { return doCall(callable); } }, targetProcessApplication); } else {
return doCall(callable); } } protected <T> T doCall(Callable<T> callable) { try { return callable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ProcessEngineException(e); } } public void submitFormVariables(final VariableMap properties, final VariableScope variableScope) { performContextSwitch(new Callable<Void> () { public Void call() throws Exception { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new SubmitFormVariablesInvocation(formHandler, properties, variableScope)); return null; } }); } public abstract FormHandler getFormHandler(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DelegateFormHandler.java
1
请在Spring Boot框架中完成以下Java代码
public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientDeliveryAddress patientDeliveryAddress = (PatientDeliveryAddress) o; return Objects.equals(this.gender, patientDeliveryAddress.gender) && Objects.equals(this.title, patientDeliveryAddress.title) && Objects.equals(this.name, patientDeliveryAddress.name) && Objects.equals(this.address, patientDeliveryAddress.address) && Objects.equals(this.postalCode, patientDeliveryAddress.postalCode) && Objects.equals(this.city, patientDeliveryAddress.city); } @Override public int hashCode() { return Objects.hash(gender, title, name, address, postalCode, city); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientDeliveryAddress {\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientDeliveryAddress.java
2
请完成以下Java代码
public void enqueueEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().enqueueEvent(event); } } @Override public void enqueueObject(final Object obj) { delegate().enqueueObject(obj); } @Override public void enqueueObjectsCollection(@NonNull final Collection<?> objs) { delegate().enqueueObjectsCollection(objs); } @Override
public boolean isDestroyed() { return delegate().isDestroyed(); } @Override public boolean isAsync() { return delegate().isAsync(); } @Override public EventBusStats getStats() { return delegate().getStats(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\ForwardingEventBus.java
1
请在Spring Boot框架中完成以下Java代码
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) { ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle"); for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) { for (Resource resource : getResources(context.getClassLoader(), name)) { if (resource.exists()) { return ConditionOutcome.match(message.found("bundle").items(resource)); } } } return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll()); } private Resource[] getResources(@Nullable ClassLoader classLoader, String name) { String target = name.replace('.', '/'); try { return new PathMatchingResourcePatternResolver(classLoader) .getResources("classpath*:" + target + ".properties");
} catch (Exception ex) { return NO_RESOURCES; } } } static class MessageSourceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("messages.properties").registerPattern("messages_*.properties"); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceAutoConfiguration.java
2
请完成以下Java代码
public String getScriptFormat() { return implementationType; } public void setScriptFormat(String scriptFormat) { this.implementationType = scriptFormat; } public String getScript() { for (FieldExtension fieldExtension : fieldExtensions) { if ("script".equalsIgnoreCase(fieldExtension.getFieldName())) { String script = fieldExtension.getStringValue(); if (StringUtils.isNotEmpty(script)) { return script; } return fieldExtension.getExpression(); } } return null; } public boolean isAutoStoreVariables() { return autoStoreVariables; } public void setAutoStoreVariables(boolean autoStoreVariables) { this.autoStoreVariables = autoStoreVariables; } public boolean isDoNotIncludeVariables() { return doNotIncludeVariables; } public void setDoNotIncludeVariables(boolean doNotIncludeVariables) { this.doNotIncludeVariables = doNotIncludeVariables; } @Override public List<IOParameter> getInParameters() { return inParameters; }
@Override public void addInParameter(IOParameter inParameter) { if (inParameters == null) { inParameters = new ArrayList<>(); } inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public ScriptServiceTask clone() { ScriptServiceTask clone = new ScriptServiceTask(); clone.setValues(this); return clone; } public void setValues(ScriptServiceTask otherElement) { super.setValues(otherElement); setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables()); inParameters = null; if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { inParameters = new ArrayList<>(); for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ScriptServiceTask.java
1
请完成以下Java代码
private Document convertObjectToDocument0(final Object xmlObj) throws JAXBException, ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); final Document document = documentBuilder.newDocument(); final JAXBElement<Object> jaxbElement = ObjectFactoryHelper.createJAXBElement(new ObjectFactory(), xmlObj); jaxbMarshaller.marshal(jaxbElement, document); return document; } private String createTransactionId()
{ final String transactionId = UUID.randomUUID().toString(); return transactionId; } @Override public LoginResponse login(final LoginRequest loginRequest) { throw new UnsupportedOperationException(); // final PRTLoginRequestType xmlLoginRequest = LoginRequestConverter.instance.convert(loginRequest); // final PRTLoginRequestType xmlLoginResponse = sendXmlObject(xmlLoginRequest); // final LoginResponse loginResponse = LoginResponseConverter.instance.convert(xmlLoginResponse); // return loginResponse; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.embedded-client\src\main\java\de\metas\printing\client\endpoint\LoopbackPrintConnectionEndpoint.java
1
请完成以下Java代码
public byte[] getBytes() { return bytes; } public Object getPersistentState() { return (bytes != null ? bytes : PERSISTENTSTATE_NULL); } public int getRevisionNext() { return revision+1; } // getters and setters ////////////////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type;
} public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请完成以下Java代码
public static final class Builder { private Integer adTabId = null; private Integer adTableId = null; private Integer adUserId = null; private Collection<IUserQueryField> searchFields; private ColumnDisplayTypeProvider columnDisplayTypeProvider; private Builder() { } public UserQueryRepository build() { return new UserQueryRepository(this); } @SuppressWarnings("unchecked") public Builder setSearchFields(final Collection<? extends IUserQueryField> searchFields) { this.searchFields = (Collection<IUserQueryField>)searchFields; return this; } private Collection<IUserQueryField> getSearchFields() { Check.assumeNotNull(searchFields, "searchFields not null"); return searchFields; } public Builder setAD_Tab_ID(final int adTabId) { this.adTabId = adTabId; return this; } private int getAD_Tab_ID() { Check.assumeNotNull(adTabId, "adTabId not null"); return adTabId; } public Builder setAD_Table_ID(final int adTableId) {
this.adTableId = adTableId; return this; } private int getAD_Table_ID() { Check.assumeNotNull(adTableId, "adTableId not null"); Check.assume(adTableId > 0, "adTableId > 0"); return adTableId; } public Builder setAD_User_ID(final int adUserId) { this.adUserId = adUserId; return this; } public Builder setAD_User_ID_Any() { this.adUserId = -1; return this; } private int getAD_User_ID() { Check.assumeNotNull(adUserId, "Parameter adUserId is not null"); return adUserId; } public Builder setColumnDisplayTypeProvider(@NonNull final ColumnDisplayTypeProvider columnDisplayTypeProvider) { this.columnDisplayTypeProvider = columnDisplayTypeProvider; return this; } public ColumnDisplayTypeProvider getColumnDisplayTypeProvider() { return columnDisplayTypeProvider; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\UserQueryRepository.java
1
请完成以下Java代码
public String getBlockingExpression() { return blockingExpression; } public void setBlockingExpression(String blockingExpression) { this.blockingExpression = blockingExpression; } public boolean isAsync() { return async; } public void setAsync(boolean async) { this.async = async; } public boolean isExclusive() { return exclusive; } public void setExclusive(boolean exclusive) { this.exclusive = exclusive; } public boolean isAsyncLeave() { return asyncLeave;
} public void setAsyncLeave(boolean asyncLeave) { this.asyncLeave = asyncLeave; } public boolean isAsyncLeaveExclusive() { return asyncLeaveExclusive; } public void setAsyncLeaveExclusive(boolean asyncLeaveExclusive) { this.asyncLeaveExclusive = asyncLeaveExclusive; } public void setValues(Task otherElement) { super.setValues(otherElement); setBlocking(otherElement.isBlocking()); setBlockingExpression(otherElement.getBlockingExpression()); setAsync(otherElement.isAsync()); setAsyncLeave(otherElement.isAsync()); setExclusive(otherElement.isExclusive()); setAsyncLeaveExclusive(otherElement.isAsyncLeaveExclusive()); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Task.java
1
请完成以下Java代码
public void setParameterDisplayLogic (String ParameterDisplayLogic) { set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic); } public String getParameterDisplayLogic () { return (String)get_Value(COLUMNNAME_ParameterDisplayLogic); } public void setColumnName (String ColumnName) { set_Value (COLUMNNAME_ColumnName, ColumnName); } public String getColumnName () { return (String)get_Value(COLUMNNAME_ColumnName); } /** Set Query Criteria Function. @param QueryCriteriaFunction column used for adding a sql function to query criteria */ public void setQueryCriteriaFunction (String QueryCriteriaFunction) { set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction); }
/** Get Query Criteria Function. @return column used for adding a sql function to query criteria */ public String getQueryCriteriaFunction () { return (String)get_Value(COLUMNNAME_QueryCriteriaFunction); } @Override public void setDefaultValue (String DefaultValue) { set_Value (COLUMNNAME_DefaultValue, DefaultValue); } @Override public String getDefaultValue () { return (String)get_Value(COLUMNNAME_DefaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java
1
请完成以下Java代码
public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Role Record Access Config. @param AD_Role_Record_Access_Config_ID Role Record Access Config */ @Override public void setAD_Role_Record_Access_Config_ID (int AD_Role_Record_Access_Config_ID) { if (AD_Role_Record_Access_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_Record_Access_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_Record_Access_Config_ID, Integer.valueOf(AD_Role_Record_Access_Config_ID)); } /** Get Role Record Access Config. @return Role Record Access Config */ @Override public int getAD_Role_Record_Access_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_Record_Access_Config_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class); } @Override public void setAD_Table(org.compiere.model.I_AD_Table AD_Table) { set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table); } /** Set DB-Tabelle. @param AD_Table_ID Database Table information */
@Override public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** * Type AD_Reference_ID=540987 * Reference name: AD_Role_Record_Access_Config_Type */ public static final int TYPE_AD_Reference_ID=540987; /** Table = T */ public static final String TYPE_Table = "T"; /** Business Partner Hierarchy = BPH */ public static final String TYPE_BusinessPartnerHierarchy = "BPH"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Record_Access_Config.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (joinP060P100Lines == null ? 0 : joinP060P100Lines.hashCode()); result = prime * result + (levelNo == null ? 0 : levelNo.hashCode()); result = prime * result + (messageNo == null ? 0 : messageNo.hashCode()); result = prime * result + (p102Lines == null ? 0 : p102Lines.hashCode()); result = prime * result + (packageQty == null ? 0 : packageQty.hashCode()); result = prime * result + (packageType == null ? 0 : packageType.hashCode()); result = prime * result + (partner == null ? 0 : partner.hashCode()); result = prime * result + (record == null ? 0 : record.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final P050 other = (P050)obj; if (joinP060P100Lines == null) { if (other.joinP060P100Lines != null) { return false; } } else if (!joinP060P100Lines.equals(other.joinP060P100Lines)) { return false; } if (levelNo == null) { if (other.levelNo != null) { return false; } } else if (!levelNo.equals(other.levelNo)) { return false; } if (messageNo == null) { if (other.messageNo != null) { return false; } } else if (!messageNo.equals(other.messageNo)) { return false; } if (p102Lines == null) { if (other.p102Lines != null) { return false; } } else if (!p102Lines.equals(other.p102Lines)) {
return false; } if (packageQty == null) { if (other.packageQty != null) { return false; } } else if (!packageQty.equals(other.packageQty)) { return false; } if (packageType == null) { if (other.packageType != null) { return false; } } else if (!packageType.equals(other.packageType)) { return false; } if (partner == null) { if (other.partner != null) { return false; } } else if (!partner.equals(other.partner)) { return false; } if (record == null) { if (other.record != null) { return false; } } else if (!record.equals(other.record)) { return false; } return true; } @Override public String toString() { return "P050 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", levelNo=" + levelNo + ", packageQty=" + packageQty + ", packageType=" + packageType + ", p102Lines=" + p102Lines + ", joinP060P100Lines=" + joinP060P100Lines + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\compudata\P050.java
2
请完成以下Java代码
public class JsonCacheResetRequest { @JsonAnySetter @JsonAnyGetter @NonNull private final HashMap<String, String> map = new HashMap<>(); public static JsonCacheResetRequest extractFrom(HttpServletRequest httpRequest) { final JsonCacheResetRequest request = new JsonCacheResetRequest(); httpRequest.getParameterMap() .forEach((name, values) -> request.setValue(name, values != null && values.length > 0 ? values[0] : null)); return request; } public JsonCacheResetRequest setValue(@NonNull String name, @Nullable String value)
{ map.put(name, value); return this; } public JsonCacheResetRequest setValue(@NonNull String name, boolean value) { return setValue(name, String.valueOf(value)); } public boolean getValueAsBoolean(@NonNull final String name) { return StringUtils.toBoolean(map.get(name)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\JsonCacheResetRequest.java
1
请在Spring Boot框架中完成以下Java代码
public int create(PmsProductAttributeParam pmsProductAttributeParam) { PmsProductAttribute pmsProductAttribute = new PmsProductAttribute(); BeanUtils.copyProperties(pmsProductAttributeParam, pmsProductAttribute); int count = productAttributeMapper.insertSelective(pmsProductAttribute); //新增商品属性以后需要更新商品属性分类数量 PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId()); if(pmsProductAttribute.getType()==0){ pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()+1); }else if(pmsProductAttribute.getType()==1){ pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()+1); } productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory); return count; } @Override public int update(Long id, PmsProductAttributeParam productAttributeParam) { PmsProductAttribute pmsProductAttribute = new PmsProductAttribute(); pmsProductAttribute.setId(id); BeanUtils.copyProperties(productAttributeParam, pmsProductAttribute); return productAttributeMapper.updateByPrimaryKeySelective(pmsProductAttribute); } @Override public PmsProductAttribute getItem(Long id) { return productAttributeMapper.selectByPrimaryKey(id); } @Override public int delete(List<Long> ids) { //获取分类 PmsProductAttribute pmsProductAttribute = productAttributeMapper.selectByPrimaryKey(ids.get(0)); Integer type = pmsProductAttribute.getType(); PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId());
PmsProductAttributeExample example = new PmsProductAttributeExample(); example.createCriteria().andIdIn(ids); int count = productAttributeMapper.deleteByExample(example); //删除完成后修改数量 if(type==0){ if(pmsProductAttributeCategory.getAttributeCount()>=count){ pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()-count); }else{ pmsProductAttributeCategory.setAttributeCount(0); } }else if(type==1){ if(pmsProductAttributeCategory.getParamCount()>=count){ pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()-count); }else{ pmsProductAttributeCategory.setParamCount(0); } } productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory); return count; } @Override public List<ProductAttrInfo> getProductAttrInfo(Long productCategoryId) { return productAttributeDao.getProductAttrInfo(productCategoryId); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductAttributeServiceImpl.java
2
请完成以下Java代码
public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item getM_HU_Item() { return get_ValueAsPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class); } @Override public void setM_HU_Item(final de.metas.handlingunits.model.I_M_HU_Item M_HU_Item) { set_ValueFromPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, M_HU_Item); } @Override public void setM_HU_Item_ID (final int M_HU_Item_ID) { if (M_HU_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, M_HU_Item_ID); } @Override public int getM_HU_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID); } @Override public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); }
@Override public int getM_HU_Item_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage.java
1
请完成以下Java代码
public class NewUserForm { private String email; private String verifyEmail; private String password; private String verifyPassword; public NewUserForm() { } public NewUserForm(String email, String verifyEmail, String password, String verifyPassword) { super(); this.email = email; this.verifyEmail = verifyEmail; this.password = password; this.verifyPassword = verifyPassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getVerifyEmail() { return verifyEmail; }
public void setVerifyEmail(String verifyEmail) { this.verifyEmail = verifyEmail; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getVerifyPassword() { return verifyPassword; } public void setVerifyPassword(String verifyPassword) { this.verifyPassword = verifyPassword; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\customvalidator\NewUserForm.java
1
请完成以下Java代码
public void setIsSameLine (boolean IsSameLine) { set_Value (COLUMNNAME_IsSameLine, Boolean.valueOf(IsSameLine)); } /** Get Same Line. @return Displayed on same line as previous field */ public boolean isSameLine () { Object oo = get_Value(COLUMNNAME_IsSameLine); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Updateable. @param IsUpdateable Determines, if the field can be updated */ public void setIsUpdateable (boolean IsUpdateable) { set_Value (COLUMNNAME_IsUpdateable, Boolean.valueOf(IsUpdateable)); } /** Get Updateable. @return Determines, if the field can be updated */ public boolean isUpdateable () { Object oo = get_Value(COLUMNNAME_IsUpdateable); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set 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(); } /** Set Max. Value. @param ValueMax Maximum Value for a field */ public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value. @return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */ public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java
1
请完成以下Java代码
private void enqueueNow(@NonNull final RequestsCollector requestsCollector) { final List<ModelToIndexEnqueueRequest> requests = requestsCollector.getRequestsAndMarkedProcessed(); enqueueNow(requests); } public void enqueueNow(@NonNull final List<ModelToIndexEnqueueRequest> requests) { repository.addToQueue(requests); } @ToString private static class RequestsCollector { private boolean processed = false; private final ArrayList<ModelToIndexEnqueueRequest> requests = new ArrayList<>(); public synchronized void addRequests(@NonNull final Collection<ModelToIndexEnqueueRequest> requests) { assertNotProcessed(); this.requests.addAll(requests);
} private void assertNotProcessed() { if (processed) { throw new AdempiereException("already processed: " + this); } } public synchronized List<ModelToIndexEnqueueRequest> getRequestsAndMarkedProcessed() { assertNotProcessed(); this.processed = true; return requests; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelsToIndexQueueService.java
1
请在Spring Boot框架中完成以下Java代码
public final class KafkaMetricsAutoConfiguration { @Bean DefaultKafkaProducerFactoryCustomizer kafkaProducerMetrics(MeterRegistry meterRegistry) { return (producerFactory) -> addListener(producerFactory, meterRegistry); } @Bean DefaultKafkaConsumerFactoryCustomizer kafkaConsumerMetrics(MeterRegistry meterRegistry) { return (consumerFactory) -> addListener(consumerFactory, meterRegistry); } private <K, V> void addListener(DefaultKafkaConsumerFactory<K, V> factory, MeterRegistry meterRegistry) { factory.addListener(new MicrometerConsumerListener<>(meterRegistry)); }
private <K, V> void addListener(DefaultKafkaProducerFactory<K, V> factory, MeterRegistry meterRegistry) { factory.addListener(new MicrometerProducerListener<>(meterRegistry)); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ KafkaStreamsMetrics.class, StreamsBuilderFactoryBean.class }) static class KafkaStreamsMetricsConfiguration { @Bean StreamsBuilderFactoryBeanConfigurer kafkaStreamsMetrics(MeterRegistry meterRegistry) { return (factoryBean) -> factoryBean.addListener(new KafkaStreamsMicrometerListener(meterRegistry)); } } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\metrics\KafkaMetricsAutoConfiguration.java
2
请完成以下Java代码
public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } /** * Operation AD_Reference_ID=205 * Reference name: AD_Find Operation */ public static final int OPERATION_AD_Reference_ID=205; /** = = == */ public static final String OPERATION_Eq = "=="; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** > = >> */ public static final String OPERATION_Gt = ">>"; /** < = << */ public static final String OPERATION_Le = "<<"; /** ~ = ~~ */ public static final String OPERATION_Like = "~~"; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** |<x>| = AB */ public static final String OPERATION_X = "AB"; /** sql = SQ */ public static final String OPERATION_Sql = "SQ"; /** != = != */ public static final String OPERATION_NotEq = "!="; @Override public void setOperation (final java.lang.String Operation) { set_Value (COLUMNNAME_Operation, Operation); } @Override public java.lang.String getOperation() { return get_ValueAsString(COLUMNNAME_Operation); }
@Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValue2 (final java.lang.String Value2) { set_Value (COLUMNNAME_Value2, Value2); } @Override public java.lang.String getValue2() { return get_ValueAsString(COLUMNNAME_Value2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NextCondition.java
1
请完成以下Java代码
public boolean isWithoutTenantId() { return withoutTenantId; } public String getEngineVersion() { return engineVersion; } public String getAuthorizationUserId() { return authorizationUserId; } public String getProcDefId() { return procDefId; } public String getEventSubscriptionName() { return eventSubscriptionName; } public String getEventSubscriptionType() {
return eventSubscriptionType; } public boolean isIncludeAuthorization() { return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty()); } public List<List<String>> getSafeAuthorizationGroups() { return safeAuthorizationGroups; } public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) { this.safeAuthorizationGroups = safeAuthorizationGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessDefinitionQueryImpl.java
1
请完成以下Java代码
public boolean isLastRow() { if (m_totalRows == 0) { return true; } return m_currentRow == m_totalRows - 1; } // isLastRow /** * Set Changed Column * * @param col column * @param columnName column name */ public void setChangedColumn(final int col, final String columnName) { m_changedColumn = col; m_columnName = columnName; } // setChangedColumn /** * Get Changed Column * * @return changed column */ public int getChangedColumn() { return m_changedColumn; } // getChangedColumn /** * Get Column Name * * @return column name */ public String getColumnName() { return m_columnName; } // getColumnName /** * Set Confirmed toggle * * @param confirmed confirmed */ public void setConfirmed(final boolean confirmed) { m_confirmed = confirmed; } // setConfirmed /** * Is Confirmed (e.g. user has seen it) * * @return true if confirmed */ public boolean isConfirmed() { return m_confirmed; } // isConfirmed public void setCreated(final Integer createdBy, final Timestamp created)
{ this.createdBy = createdBy; this.created = created; } public void setUpdated(final Integer updatedBy, final Timestamp updated) { this.updatedBy = updatedBy; this.updated = updated; } public void setAdTableId(final int adTableId) { this.adTableId = adTableId; this.recordId = null; } public void setSingleKeyRecord(final int adTableId, @NonNull final String keyColumnName, final int recordId) { setRecord(adTableId, ComposedRecordId.singleKey(keyColumnName, recordId)); } public void setRecord(final int adTableId, @NonNull final ComposedRecordId recordId) { Check.assumeGreaterThanZero(adTableId, "adTableId"); this.adTableId = adTableId; this.recordId = recordId; } public OptionalInt getSingleRecordId() { if (recordId == null) { return OptionalInt.empty(); } return recordId.getSingleRecordId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\DataStatusEvent.java
1
请完成以下Java代码
public abstract class FrontCommand implements OnIntercept { protected HttpServletRequest request; protected HttpServletResponse response; private boolean intercept; public FrontCommand() { } public void init(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } public void process() throws ServletException, IOException { FilterManager.process(request, response, this); }
public void forward(String target) throws ServletException, IOException { if (intercept) { return; } String path = String.format("/WEB-INF/jsp/%s.jsp", target); RequestDispatcher dispatcher = request.getServletContext() .getRequestDispatcher(path); dispatcher.forward(request, response); } @Override public void intercept() { intercept = true; } }
repos\tutorials-master\patterns-modules\intercepting-filter\src\main\java\com\baeldung\patterns\intercepting\filter\commands\FrontCommand.java
1
请在Spring Boot框架中完成以下Java代码
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } } public static String serialize(Object object) { try { return Base64.getUrlEncoder() .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object));
} catch (JsonProcessingException e) { throw new IllegalArgumentException("The given Json object value: " + object + " cannot be transformed to a String", e); } } public static <T> T deserialize(Cookie cookie, Class<T> cls) { byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue()); try { return OBJECT_MAPPER.readValue(decodedBytes, cls); } catch (IOException e) { throw new IllegalArgumentException("The given string value: " + Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\CookieUtils.java
2
请完成以下Java代码
public void cloneAllByOrderId( @NonNull final OrderId orderId, @NonNull final OrderCostCloneMapper mapper) { final List<OrderCost> originalOrderCosts = orderCostRepository.getByOrderId(orderId); final ImmutableList<OrderCost> clonedOrderCosts = originalOrderCosts.stream() .map(originalOrderCost -> originalOrderCost.copy(mapper)) .collect(ImmutableList.toImmutableList()); orderCostRepository.saveAll(clonedOrderCosts); } public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo) { orderCostRepository.changeByOrderLineId( orderLineInfo.getOrderLineId(), orderCost -> { orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL); updateCreatedOrderLineIfAny(orderCost); }); } private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost) { if (orderCost.getCreatedOrderLineId() == null) {
return; } CreateOrUpdateOrderLineFromOrderCostCommand.builder() .orderBL(orderBL) .moneyService(moneyService) .orderCost(orderCost) .build() .execute(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId); } public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId) { return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java
1
请完成以下Java代码
public void setDateProjected (java.sql.Timestamp DateProjected) { set_ValueNoCheck (COLUMNNAME_DateProjected, DateProjected); } @Override public java.sql.Timestamp getDateProjected() { return get_ValueAsTimestamp(COLUMNNAME_DateProjected); } @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
} @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public java.math.BigDecimal getQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (java.lang.String StorageAttributesKey) { set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java
1
请完成以下Java代码
public Flux<ServerSentEvent<InstanceEvent>> eventStream() { return Flux.from(eventStore).map((event) -> ServerSentEvent.builder(event).build()).mergeWith(ping()); } /** * Stream events for a specific instance as Server-Sent Events (SSE). Streams events * for the instance identified by its ID. Each event is delivered as an SSE message. * @param id the instance ID * @return flux of {@link ServerSentEvent} containing {@link Instance} */ @GetMapping(path = "/instances/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<Instance>> instanceStream(@PathVariable String id) { return Flux.from(eventStore) .filter((event) -> event.getInstance().equals(InstanceId.of(id))) .flatMap((event) -> registry.getInstance(event.getInstance())) .map((event) -> ServerSentEvent.builder(event).build()) .mergeWith(ping()); } /** * Returns a periodic Server-Sent Event (SSE) comment-only ping every 10 seconds. * <p> * This method is used to keep SSE connections alive for all event stream endpoints in * Spring Boot Admin. The ping event is sent as a comment (": ping") and does not * contain any data payload. <br> * <b>Why?</b> Many proxies, firewalls, and browsers may close idle HTTP connections. * The ping event provides regular activity on the stream, ensuring the connection * remains open even when no instance events are emitted. <br>
* <b>Technical details:</b> * <ul> * <li>Interval: 10 seconds</li> * <li>Format: SSE comment-only event</li> * <li>Applies to: All event stream endpoints (e.g., /instances/events, * /instances/{id} with Accept: text/event-stream)</li> * </ul> * </p> * @param <T> the type of event data (unused for ping) * @return flux of ServerSentEvent representing periodic ping comments */ @SuppressWarnings("unchecked") private static <T> Flux<ServerSentEvent<T>> ping() { return (Flux<ServerSentEvent<T>>) (Flux) PING_FLUX; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\InstancesController.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reminder Days. @param RemindDays Days between sending Reminder Emails for a due or inactive Document */ public void setRemindDays (int RemindDays) { set_Value (COLUMNNAME_RemindDays, Integer.valueOf(RemindDays)); } /** Get Reminder Days. @return Days between sending Reminder Emails for a due or inactive Document */ public int getRemindDays () { Integer ii = (Integer)get_Value(COLUMNNAME_RemindDays);
if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_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_AD_WorkflowProcessor.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge.
@param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_ListValue.java
1
请完成以下Java代码
protected void deleteProcessDefinitionsForDeployment(String deploymentId) { getProcessDefinitionEntityManager().deleteProcessDefinitionsByDeploymentId(deploymentId); } protected void deleteProcessInstancesForProcessDefinitions(List<ProcessDefinition> processDefinitions) { for (ProcessDefinition processDefinition : processDefinitions) { getExecutionEntityManager().deleteProcessInstancesByProcessDefinition(processDefinition.getId(), "deleted deployment", true); } } protected void deleteHistoricTaskEventLogEntriesForProcessDefinitions(List<ProcessDefinition> processDefinitions) { for (ProcessDefinition processDefinition : processDefinitions) { engineConfiguration.getTaskServiceConfiguration().getHistoricTaskService().deleteHistoricTaskLogEntriesForProcessDefinition(processDefinition.getId()); } } @Override public long findDeploymentCountByQueryCriteria(DeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentCountByQueryCriteria(deploymentQuery); } @Override public List<Deployment> findDeploymentsByQueryCriteria(DeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentsByQueryCriteria(deploymentQuery); } @Override public List<String> getDeploymentResourceNames(String deploymentId) { return dataManager.getDeploymentResourceNames(deploymentId); } @Override public List<Deployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentsByNativeQuery(parameterMap); } @Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentCountByNativeQuery(parameterMap); } protected ResourceEntityManager getResourceEntityManager() {
return engineConfiguration.getResourceEntityManager(); } protected ModelEntityManager getModelEntityManager() { return engineConfiguration.getModelEntityManager(); } protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return engineConfiguration.getProcessDefinitionEntityManager(); } protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() { return engineConfiguration.getProcessDefinitionInfoEntityManager(); } protected ExecutionEntityManager getExecutionEntityManager() { return engineConfiguration.getExecutionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityManagerImpl.java
1
请完成以下Java代码
public void addIdentityLinkChanges(String type, String oldProperty, String newProperty) { identityLinkChanges.add(new PropertyChange(type, oldProperty, newProperty)); } @Override public void setVariablesLocal(Map<String, ?> variables, boolean skipJavaSerializationFormatCheck) { super.setVariablesLocal(variables, skipJavaSerializationFormatCheck); Context.getCommandContext().getDbEntityManager().forceUpdate(this); } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (processDefinitionId != null) { referenceIdAndClass.put(processDefinitionId, ProcessDefinitionEntity.class); } if (processInstanceId != null) { referenceIdAndClass.put(processInstanceId, ExecutionEntity.class); } if (executionId != null) { referenceIdAndClass.put(executionId, ExecutionEntity.class); } if (caseDefinitionId != null) { referenceIdAndClass.put(caseDefinitionId, CaseDefinitionEntity.class); } if (caseExecutionId != null) { referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } return referenceIdAndClass; } public void bpmnError(String errorCode, String errorMessage, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); BpmnError bpmnError = null; if (errorMessage != null) { bpmnError = new BpmnError(errorCode, errorMessage); } else { bpmnError = new BpmnError(errorCode); } try { if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); }
BpmnExceptionHandler.propagateBpmnError(bpmnError, activityExecution); } catch (Exception ex) { throw ProcessEngineLogger.CMD_LOGGER.exceptionBpmnErrorPropagationFailed(errorCode, ex); } } @Override public boolean hasAttachment() { return attachmentExists; } @Override public boolean hasComment() { return commentExists; } public void escalation(String escalationCode, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); } EscalationHandler.propagateEscalation(activityExecution, escalationCode); } public static enum TaskState { STATE_INIT ("Init"), STATE_CREATED ("Created"), STATE_COMPLETED ("Completed"), STATE_DELETED ("Deleted"), STATE_UPDATED ("Updated"); private String taskState; private TaskState(String taskState) { this.taskState = taskState; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskEntity.java
1
请完成以下Java代码
public static <T> void printAllIterative(int n, T[] elements, char delimiter) { int[] indexes = new int[n]; for (int i = 0; i < n; i++) { indexes[i] = 0; } printArray(elements, delimiter); int i = 0; while (i < n) { if (indexes[i] < i) { swap(elements, i % 2 == 0 ? 0: indexes[i], i); printArray(elements, delimiter); indexes[i]++; i = 0; } else { indexes[i] = 0; i++; } } } public static <T extends Comparable<T>> void printAllOrdered(T[] elements, char delimiter) { Arrays.sort(elements); boolean hasNext = true; while(hasNext) { printArray(elements, delimiter); int k = 0, l = 0; hasNext = false; for (int i = elements.length - 1; i > 0; i--) { if (elements[i].compareTo(elements[i - 1]) > 0) { k = i - 1; hasNext = true; break; } } for (int i = elements.length - 1; i > k; i--) { if (elements[i].compareTo(elements[k]) > 0) { l = i; break; } } swap(elements, k, l); Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length)); } } public static <T> void printRandom(T[] elements, char delimiter) { Collections.shuffle(Arrays.asList(elements)); printArray(elements, delimiter); } private static <T> void swap(T[] elements, int a, int b) { T tmp = elements[a]; elements[a] = elements[b]; elements[b] = tmp; }
private static <T> void printArray(T[] elements, char delimiter) { String delimiterSpace = delimiter + " "; for(int i = 0; i < elements.length; i++) { System.out.print(elements[i] + delimiterSpace); } System.out.print('\n'); } public static void main(String[] argv) { Integer[] elements = {1,2,3,4}; System.out.println("Rec:"); printAllRecursive(elements, ';'); System.out.println("Iter:"); printAllIterative(elements.length, elements, ';'); System.out.println("Orderes:"); printAllOrdered(elements, ';'); System.out.println("Random:"); printRandom(elements, ';'); System.out.println("Random:"); printRandom(elements, ';'); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\permutation\Permutation.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstLetter() { return firstLetter; } public void setFirstLetter(String firstLetter) { this.firstLetter = firstLetter; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getFactoryStatus() { return factoryStatus; } public void setFactoryStatus(Integer factoryStatus) { this.factoryStatus = factoryStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public Integer getProductCommentCount() { return productCommentCount; }
public void setProductCommentCount(Integer productCommentCount) { this.productCommentCount = productCommentCount; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getBigPic() { return bigPic; } public void setBigPic(String bigPic) { this.bigPic = bigPic; } public String getBrandStory() { return brandStory; } public void setBrandStory(String brandStory) { this.brandStory = brandStory; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", firstLetter=").append(firstLetter); sb.append(", sort=").append(sort); sb.append(", factoryStatus=").append(factoryStatus); sb.append(", showStatus=").append(showStatus); sb.append(", productCount=").append(productCount); sb.append(", productCommentCount=").append(productCommentCount); sb.append(", logo=").append(logo); sb.append(", bigPic=").append(bigPic); sb.append(", brandStory=").append(brandStory); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java
1
请完成以下Java代码
public DmnTransformException requiredDecisionLoopDetected(String decisionId) { return new DmnTransformException(exceptionMessage( "015", "The decision '{}' has a loop.", decisionId) ); } public DmnTransformException errorWhileTransformingDefinitions(Throwable cause) { return new DmnTransformException(exceptionMessage( "016", "Error while transforming decision requirements graph: " + cause.getMessage()), cause ); }
public DmnTransformException drdIdIsMissing(DmnDecisionRequirementsGraph drd) { return new DmnTransformException(exceptionMessage( "017", "The decision requirements graph '{}' must have an 'id' attribute set.", drd) ); } public DmnTransformException decisionVariableIsMissing(String decisionId) { return new DmnTransformException(exceptionMessage( "018", "The decision '{}' must have an 'variable' element if it contains a literal expression.", decisionId)); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnTransformLogger.java
1
请完成以下Java代码
public final class InboundProcessorBL implements IInboundProcessorBL { public List<File> getFiles(final String localFolderName) { final File localFolder = new File(localFolderName); if (!localFolder.isDirectory() || !localFolder.canRead()) { ConfigException.throwNew(ConfigException.LOCALFOLDER_CANT_READ_1P, null, localFolderName); } return Arrays.asList(localFolder.listFiles()); } public String moveToArchive(final File importedFile, final String archiveFolder) { final File archiveDir = new File(archiveFolder); checkArchiveDir(archiveDir); final File destFile = new File(archiveDir, importedFile.getName()); if (!importedFile
.renameTo(destFile)) { ConfigException.throwNew(ConfigException.ARCHIVE_RENAME_FAILED_2P, importedFile.getAbsolutePath(), archiveDir .getAbsolutePath()); } return null; } private void checkArchiveDir(final File archiveDir) { if (!archiveDir.isDirectory()) { ConfigException.throwNew(ConfigException.ARCHIVE_NOT_A_DIR_1P, archiveDir.getAbsolutePath()); } if (!archiveDir.canWrite()) { ConfigException.throwNew(ConfigException.ARCHIVE_CANT_WRITE_1P, archiveDir.getAbsolutePath()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\api\impl\InboundProcessorBL.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(annotations); result = prime * result + ((base == null) ? 0 : base.hashCode()); result = prime * result + Arrays.deepHashCode(evaluatedParameters); result = prime * result + ((methodInfo == null) ? 0 : methodInfo.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; }
MethodReference other = (MethodReference) obj; if (!Arrays.equals(annotations, other.annotations)) { return false; } if (base == null) { if (other.base != null) { return false; } } else if (!base.equals(other.base)) { return false; } if (!Arrays.deepEquals(evaluatedParameters, other.evaluatedParameters)) { return false; } if (methodInfo == null) { return other.methodInfo == null; } else { return methodInfo.equals(other.methodInfo); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodReference.java
1
请完成以下Java代码
public org.compiere.model.I_C_OrderLine getC_OrderLine() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_OrderLine(org.compiere.model.I_C_OrderLine C_OrderLine) { set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine); } /** Set Auftragsposition. @param C_OrderLine_ID Auftragsposition */ @Override public void setC_OrderLine_ID (int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, Integer.valueOf(C_OrderLine_ID)); } /** Get Auftragsposition. @return Auftragsposition */ @Override public int getC_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override
public de.metas.esb.edi.model.I_EDI_Desadv getEDI_Desadv() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class); } @Override public void setEDI_Desadv(de.metas.esb.edi.model.I_EDI_Desadv EDI_Desadv) { set_ValueFromPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class, EDI_Desadv); } /** Set DESADV. @param EDI_Desadv_ID DESADV */ @Override public void setEDI_Desadv_ID (int EDI_Desadv_ID) { if (EDI_Desadv_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, Integer.valueOf(EDI_Desadv_ID)); } /** Get DESADV. @return DESADV */ @Override public int getEDI_Desadv_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EDI_Desadv_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_NullDelivery_C_OrderLine_v.java
1
请在Spring Boot框架中完成以下Java代码
protected void cleanupForComparison(TbResource resource) { super.cleanupForComparison(resource); resource.setSearchText(null); if (resource.getDescriptor() != null && resource.getDescriptor().isNull()) { resource.setDescriptor(null); } } @Override protected TbResource saveOrUpdate(EntitiesImportCtx ctx, TbResource resource, EntityExportData<TbResource> exportData, IdProvider idProvider, CompareResult compareResult) { if (resource.getResourceType() == ResourceType.IMAGE) { return new TbResource(imageService.saveImage(resource)); } else { if (compareResult.isExternalIdChangedOnly()) { resource = resourceService.saveResource(resource, false); } else { resource = resourceService.saveResource(resource); } resource.setData(null);
resource.setPreview(null); return resource; } } @Override protected void onEntitySaved(User user, TbResource savedResource, TbResource oldResource) throws ThingsboardException { super.onEntitySaved(user, savedResource, oldResource); clusterService.onResourceChange(savedResource, null); } @Override public EntityType getEntityType() { return EntityType.TB_RESOURCE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\ResourceImportService.java
2
请完成以下Java代码
protected ByteArrayEntity getByteArrayEntity() { if (byteArrayValue == null) { if (byteArrayId != null) { // no lazy fetching outside of command context if (Context.getCommandContext() != null) { return byteArrayValue = Context .getCommandContext() .getDbEntityManager() .selectById(ByteArrayEntity.class, byteArrayId); } } } return byteArrayValue; } public void setByteArrayValue(byte[] bytes) { setByteArrayValue(bytes, false); } public void setByteArrayValue(byte[] bytes, boolean isTransient) { if (bytes != null) { // note: there can be cases where byteArrayId is not null // but the corresponding byte array entity has been removed in parallel; // thus we also need to check if the actual byte array entity still exists if (this.byteArrayId != null && getByteArrayEntity() != null) { byteArrayValue.setBytes(bytes); } else { deleteByteArrayValue(); byteArrayValue = new ByteArrayEntity(nameProvider.getName(), bytes, type, rootProcessInstanceId, removalTime); // avoid insert of byte array value for a transient variable if (!isTransient) { Context. getCommandContext() .getByteArrayManager() .insertByteArray(byteArrayValue); byteArrayId = byteArrayValue.getId(); } } }
else { deleteByteArrayValue(); } } public void deleteByteArrayValue() { if (byteArrayId != null) { // the next apparently useless line is probably to ensure consistency in the DbSqlSession cache, // but should be checked and docked here (or removed if it turns out to be unnecessary) getByteArrayEntity(); if (byteArrayValue != null) { Context.getCommandContext() .getDbEntityManager() .delete(byteArrayValue); } byteArrayId = null; } } public void setByteArrayValue(ByteArrayEntity byteArrayValue) { this.byteArrayValue = byteArrayValue; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\util\ByteArrayField.java
1
请完成以下Java代码
public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @Override public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; }
public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCorrelationId() { // v5 Jobs have no correlationId return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java
1
请完成以下Java代码
public class BlockingServer { private static final int PORT = 6000; public static void main(String[] args) { try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) { serverSocket.bind(new InetSocketAddress(PORT)); System.out.println("Blocking Server listening on port " + PORT); while (true) { try (SocketChannel clientSocket = serverSocket.accept()) { System.out.println("Client connected"); MyObject obj = receiveObject(clientSocket); System.out.println("Received: " + obj.getName() + ", " + obj.getAge()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } private static MyObject receiveObject(SocketChannel channel) throws IOException, ClassNotFoundException { ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = channel.read(buffer)) > 0) { buffer.flip(); byteStream.write(buffer.array(), 0, buffer.limit()); buffer.clear(); } byte[] bytes = byteStream.toByteArray(); try (ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(bytes))) { return (MyObject) objIn.readObject(); } } }
repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\socketchannel\BlockingServer.java
1
请在Spring Boot框架中完成以下Java代码
public static void applyTo(ConfigurableEnvironment environment, ResourceLoader resourceLoader, @Nullable ConfigurableBootstrapContext bootstrapContext, String... additionalProfiles) { applyTo(environment, resourceLoader, bootstrapContext, Arrays.asList(additionalProfiles)); } /** * Apply {@link ConfigData} post-processing to an existing {@link Environment}. This * method can be useful when working with an {@link Environment} that has been created * directly and not necessarily as part of a {@link SpringApplication}. * @param environment the environment to apply {@link ConfigData} to * @param resourceLoader the resource loader to use * @param bootstrapContext the bootstrap context to use or {@code null} to use a * throw-away context * @param additionalProfiles any additional profiles that should be applied */ public static void applyTo(ConfigurableEnvironment environment, @Nullable ResourceLoader resourceLoader, @Nullable ConfigurableBootstrapContext bootstrapContext, Collection<String> additionalProfiles) { DeferredLogFactory logFactory = Supplier::get; bootstrapContext = (bootstrapContext != null) ? bootstrapContext : new DefaultBootstrapContext(); ConfigDataEnvironmentPostProcessor postProcessor = new ConfigDataEnvironmentPostProcessor(logFactory, bootstrapContext); postProcessor.postProcessEnvironment(environment, resourceLoader, additionalProfiles); } /** * Apply {@link ConfigData} post-processing to an existing {@link Environment}. This
* method can be useful when working with an {@link Environment} that has been created * directly and not necessarily as part of a {@link SpringApplication}. * @param environment the environment to apply {@link ConfigData} to * @param resourceLoader the resource loader to use * @param bootstrapContext the bootstrap context to use or {@code null} to use a * throw-away context * @param additionalProfiles any additional profiles that should be applied * @param environmentUpdateListener optional * {@link ConfigDataEnvironmentUpdateListener} that can be used to track * {@link Environment} updates. */ public static void applyTo(ConfigurableEnvironment environment, @Nullable ResourceLoader resourceLoader, @Nullable ConfigurableBootstrapContext bootstrapContext, Collection<String> additionalProfiles, ConfigDataEnvironmentUpdateListener environmentUpdateListener) { DeferredLogFactory logFactory = Supplier::get; bootstrapContext = (bootstrapContext != null) ? bootstrapContext : new DefaultBootstrapContext(); ConfigDataEnvironmentPostProcessor postProcessor = new ConfigDataEnvironmentPostProcessor(logFactory, bootstrapContext, environmentUpdateListener); postProcessor.postProcessEnvironment(environment, resourceLoader, additionalProfiles); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentPostProcessor.java
2
请完成以下Java代码
public NotificationMessageFormatter bottomUrl(final String bottomURL) { this.bottomURL = bottomURL; return this; } private String getBottomText() { if (Check.isEmpty(bottomURL, true)) { return null; } final String bottomURLText; if (html) { bottomURLText = new a(bottomURL, bottomURL).toString(); } else { bottomURLText = bottomURL; } String bottomText = msgBL.getTranslatableMsgText(MSG_BottomText, bottomURLText) .translate(getLanguage()); return bottomText; } // // // // // private static final class ReplaceAfterFormatCollector { private final Map<String, String> map = new HashMap<>(); public String addAndGetKey(@NonNull final String partToReplace) { final String key = "#{" + map.size() + 1 + "}"; map.put(key, partToReplace); return key;
} public String replaceAll(@NonNull final String string) { if (map.isEmpty()) { return string; } String result = string; for (final Map.Entry<String, String> e : map.entrySet()) { result = result.replace(e.getKey(), e.getValue()); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\NotificationMessageFormatter.java
1
请完成以下Java代码
private static CertificateFactory getCertificateFactory() { try { return CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { throw new IllegalStateException("Unable to get X.509 certificate factory", ex); } } private static void readCertificates(String text, CertificateFactory factory, Consumer<X509Certificate> consumer) { try { Matcher matcher = PATTERN.matcher(text); while (matcher.find()) { String encodedText = matcher.group(1); byte[] decodedBytes = decodeBase64(encodedText); ByteArrayInputStream inputStream = new ByteArrayInputStream(decodedBytes);
while (inputStream.available() > 0) { consumer.accept((X509Certificate) factory.generateCertificate(inputStream)); } } } catch (CertificateException ex) { throw new IllegalStateException("Error reading certificate: " + ex.getMessage(), ex); } } private static byte[] decodeBase64(String content) { byte[] bytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); return Base64.getDecoder().decode(bytes); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemCertificateParser.java
1
请完成以下Java代码
public class X_M_PickingSlot_HU extends org.compiere.model.PO implements I_M_PickingSlot_HU, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1800807011L; /** Standard Constructor */ public X_M_PickingSlot_HU (final Properties ctx, final int M_PickingSlot_HU_ID, @Nullable final String trxName) { super (ctx, M_PickingSlot_HU_ID, trxName); } /** Load Constructor */ public X_M_PickingSlot_HU (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public de.metas.handlingunits.model.I_M_HU getM_HU() { return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override
public void setM_PickingSlot_HU_ID (final int M_PickingSlot_HU_ID) { if (M_PickingSlot_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_HU_ID, M_PickingSlot_HU_ID); } @Override public int getM_PickingSlot_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_HU_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_PickingSlot_HU.java
1
请完成以下Java代码
public void setConfigHostKey (java.lang.String ConfigHostKey) { set_Value (COLUMNNAME_ConfigHostKey, ConfigHostKey); } @Override public java.lang.String getConfigHostKey() { return (java.lang.String)get_Value(COLUMNNAME_ConfigHostKey); } @Override public void setIsSharedPrinterConfig (boolean IsSharedPrinterConfig) { set_Value (COLUMNNAME_IsSharedPrinterConfig, Boolean.valueOf(IsSharedPrinterConfig)); } @Override public boolean isSharedPrinterConfig() { return get_ValueAsBoolean(COLUMNNAME_IsSharedPrinterConfig); } @Override public org.compiere.model.I_C_Workplace getC_Workplace() { return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class); } @Override public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace) { set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
} @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Config.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getDiscountDays() { return discountDays; } /** * Sets the value of the discountDays property. * * @param value * allowed object is * {@link BigInteger } * */ public void setDiscountDays(BigInteger value) { this.discountDays = value; } /** * Gets the value of the ediCctop140VID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getEDICctop140VID() { return ediCctop140VID; } /** * Sets the value of the ediCctop140VID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop140VID(BigInteger value) { this.ediCctop140VID = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setRate(BigDecimal value) { this.rate = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /**
* Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the discountAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getDiscountAmt() { return discountAmt; } /** * Sets the value of the discountAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setDiscountAmt(BigDecimal value) { this.discountAmt = value; } /** * Gets the value of the discountBaseAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getDiscountBaseAmt() { return discountBaseAmt; } /** * Sets the value of the discountBaseAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setDiscountBaseAmt(BigDecimal value) { this.discountBaseAmt = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop140VType.java
2
请完成以下Java代码
public TbMsgBuilder customerId(CustomerId customerId) { this.customerId = customerId; return this; } public TbMsgBuilder metaData(TbMsgMetaData metaData) { this.metaData = metaData; return this; } public TbMsgBuilder copyMetaData(TbMsgMetaData metaData) { this.metaData = metaData.copy(); return this; } public TbMsgBuilder dataType(TbMsgDataType dataType) { this.dataType = dataType; return this; } public TbMsgBuilder data(String data) { this.data = data; return this; } public TbMsgBuilder ruleChainId(RuleChainId ruleChainId) { this.ruleChainId = ruleChainId; return this; } public TbMsgBuilder ruleNodeId(RuleNodeId ruleNodeId) { this.ruleNodeId = ruleNodeId; return this; } public TbMsgBuilder resetRuleNodeId() { return ruleNodeId(null); } public TbMsgBuilder correlationId(UUID correlationId) {
this.correlationId = correlationId; return this; } public TbMsgBuilder partition(Integer partition) { this.partition = partition; return this; } public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds); return this; } public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) { this.ctx = ctx; return this; } public TbMsgBuilder callback(TbMsgCallback callback) { this.callback = callback; return this; } public TbMsg build() { return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback); } public String toString() { return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts + ", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator + ", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType + ", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId + ", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds + ", ctx=" + this.ctx + ", callback=" + this.callback + ")"; } } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
1
请完成以下Java代码
public Descriptors.Descriptor getAttributesDynamicMessageDescriptor(String deviceAttributesProtoSchema) { return DynamicProtoUtils.getDescriptor(deviceAttributesProtoSchema, ATTRIBUTES_PROTO_SCHEMA); } public Descriptors.Descriptor getRpcResponseDynamicMessageDescriptor(String deviceRpcResponseProtoSchema) { return DynamicProtoUtils.getDescriptor(deviceRpcResponseProtoSchema, RPC_RESPONSE_PROTO_SCHEMA); } public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder(String deviceRpcRequestProtoSchema) { return DynamicProtoUtils.getDynamicMessageBuilder(deviceRpcRequestProtoSchema, RPC_REQUEST_PROTO_SCHEMA); } public String getDeviceRpcResponseProtoSchema() { if (StringUtils.isNotEmpty(deviceRpcResponseProtoSchema)) { return deviceRpcResponseProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcResponseMsg {\n" + " optional string payload = 1;\n" + "}"; } } public String getDeviceRpcRequestProtoSchema() {
if (StringUtils.isNotEmpty(deviceRpcRequestProtoSchema)) { return deviceRpcRequestProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcRequestMsg {\n" + " optional string method = 1;\n" + " optional int32 requestId = 2;\n" + " optional string params = 3;\n" + "}"; } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\profile\ProtoTransportPayloadConfiguration.java
1
请完成以下Java代码
public final class PayPalOrderExternalId { @JsonCreator public static PayPalOrderExternalId ofString(@NonNull final String orderId) { return new PayPalOrderExternalId(orderId); } public static PayPalOrderExternalId ofNullableString(@Nullable final String orderId) { return !Check.isEmpty(orderId, true) ? new PayPalOrderExternalId(orderId) : null; } private final String id; private PayPalOrderExternalId(final String id) { Check.assumeNotEmpty(id, "id is not empty"); this.id = id; }
@Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return id; } public static String toString(@Nullable final PayPalOrderExternalId id) { return id != null ? id.getAsString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderExternalId.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpClientProperties extends HttpClientSettingsProperties { /** * Base url to set in the underlying HTTP client group. By default, set to * {@code null}. */ private @Nullable String baseUrl; /** * Default request headers for interface client group. By default, set to empty * {@link Map}. */ private Map<String, List<String>> defaultHeader = new LinkedHashMap<>(); /** * API version properties. */ @NestedConfigurationProperty private final ApiversionProperties apiversion = new ApiversionProperties(); public @Nullable String getBaseUrl() { return this.baseUrl; } public void setBaseUrl(@Nullable String baseUrl) { this.baseUrl = baseUrl;
} public Map<String, List<String>> getDefaultHeader() { return this.defaultHeader; } public void setDefaultHeader(Map<String, List<String>> defaultHeaders) { this.defaultHeader = defaultHeaders; } public ApiversionProperties getApiversion() { return this.apiversion; } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\HttpClientProperties.java
2
请在Spring Boot框架中完成以下Java代码
public List<Product> getProducts() { final TreeSet<Product> products = new TreeSet<>(Product.COMPARATOR_Id); for (final Contract contract : getContracts()) { products.addAll(contract.getProducts()); } return new ArrayList<>(products); } @Nullable public ContractLine getContractLineOrNull(final Product product, final LocalDate date) { final List<ContractLine> matchingLinesWithRfq = new LinkedList<>(); final List<ContractLine> matchingLinesOthers = new LinkedList<>(); for (final Contract contract : getContracts()) { if (!contract.matchesDate(date)) { continue; } final ContractLine contractLine = contract.getContractLineForProductOrNull(product); if (contractLine == null) { continue; } if (contract.isRfq()) { matchingLinesWithRfq.add(contractLine); } else { matchingLinesOthers.add(contractLine); } }
// Contracts with RfQ (priority) if (!matchingLinesWithRfq.isEmpty()) { if (matchingLinesWithRfq.size() > 1) { logger.warn("More then one matching contracts (with RfQ) found for {}/{}: {}", product, date, matchingLinesWithRfq); } return matchingLinesWithRfq.get(0); } // Contracts without RfQ if (!matchingLinesOthers.isEmpty()) { if (matchingLinesOthers.size() > 1) { logger.warn("More then one matching contracts found for {}/{}: {}", product, date, matchingLinesOthers); } return matchingLinesOthers.get(0); } // No matching contract line return null; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contracts.java
2
请完成以下Java代码
public class Book { private final String title; private final Author author; private final int year; public Book(String title, Author author, int year) { this.title = title; this.author = author; this.year = year; } public String getTitle() { return title; } public Author getAuthor() { return author; } public int getYear() { return year; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; return year == book.year && Objects.equals(title, book.title) && Objects.equals(author, book.author); } @Override public int hashCode() { return Objects.hash(title, author, year); } }
repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\microstream\Book.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<NumberWrapper> getVeryLongNumber() { return ResponseEntity.ok(new NumberWrapper(4855910445484272258L)); } private Map<String, String> createCookiesMap(Cookie[] cookies) { Map<String, String> cookiesMap = new HashMap<>(); if (cookies != null) { for (Cookie cookie : cookies) { String id = cookie.getDomain() + ":" + cookie.getName(); cookiesMap.put(id, cookie.toString()); } } return cookiesMap; } private Map<String, List<String>> createHeaderMap(HttpServletRequest request) { Map<String, List<String>> headers = new HashMap<>(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) {
while (headerNames.hasMoreElements()) { List<String> headerValues = new ArrayList<>(); String headerName = headerNames.nextElement(); Enumeration<String> values = request.getHeaders(headerName); while (values.hasMoreElements()) { headerValues.add(values.nextElement()); } headers.put(headerName, headerValues); } } return headers; } private String createRemoteInfo(HttpServletRequest request) { return request.getRemoteHost() + ":" + request.getRemotePort(); } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\controller\DataServiceController.java
2
请完成以下Java代码
public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override public int getSpanX() {
return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); } @Override public void setC_Workplace_ProductCategory_ID (final int C_Workplace_ProductCategory_ID) { if (C_Workplace_ProductCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Workplace_ProductCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Workplace_ProductCategory_ID, C_Workplace_ProductCategory_ID); } @Override public int getC_Workplace_ProductCategory_ID()
{ return get_ValueAsInt(COLUMNNAME_C_Workplace_ProductCategory_ID); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_ProductCategory.java
1
请完成以下Java代码
public void doFilter(final ServletRequest req, final ServletResponse resp, FilterChain chain) throws IOException, ServletException { final boolean isContentTypeJson = CONTENT_TYPE_JSON_PATTERN.matcher(req.getContentType() == null ? "" : req.getContentType()).find(); if (isContentTypeJson) { final PushbackInputStream requestBody = new PushbackInputStream(req.getInputStream()); int firstByte = requestBody.read(); final boolean isBodyEmpty = firstByte == -1; requestBody.unread(firstByte); chain.doFilter(wrapRequest((HttpServletRequest) req, isBodyEmpty, requestBody), resp); } else { chain.doFilter(req, resp); } } public InputStream getRequestBody(boolean isBodyEmpty, PushbackInputStream requestBody) {
return isBodyEmpty ? new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8)) : requestBody; } public abstract HttpServletRequestWrapper wrapRequest(HttpServletRequest req, boolean isBodyEmpty, PushbackInputStream requestBody); @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } public BufferedReader getReader(final ServletInputStream inputStream) { return new BufferedReader(new InputStreamReader(inputStream)); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\AbstractEmptyBodyFilter.java
1
请完成以下Java代码
public class DoubleToString { public static String truncateByCast(double d) { return String.valueOf((int) d); } public static String roundWithStringFormat(double d) { return String.format("%.0f", d); } public static String truncateWithNumberFormat(double d) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(0); nf.setRoundingMode(RoundingMode.FLOOR); return nf.format(d); } public static String roundWithNumberFormat(double d) { NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); return nf.format(d); } public static String truncateWithDecimalFormat(double d) { DecimalFormat df = new DecimalFormat("#,###"); df.setRoundingMode(RoundingMode.FLOOR); return df.format(d); } public static String roundWithDecimalFormat(double d) { DecimalFormat df = new DecimalFormat("#,###"); return df.format(d); } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\string\DoubleToString.java
1
请完成以下Java代码
public class SpringBootPropertySource implements PropertySource { private static final String PREFIX = "log4j."; private final Map<String, String> properties = Collections .singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false"); @Override public void forEach(BiConsumer<String, String> action) { this.properties.forEach(action::accept); } @Override public CharSequence getNormalForm(Iterable<? extends CharSequence> tokens) { return PREFIX + Util.joinAsCamelCase(tokens); } @Override public int getPriority() { return -200; }
@Override public @Nullable String getProperty(String key) { return this.properties.get(key); } @Override public boolean containsProperty(String key) { return this.properties.containsKey(key); } @Override public Collection<String> getPropertyNames() { return this.properties.keySet(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringBootPropertySource.java
1
请完成以下Java代码
public void setWebapps(Set<String> webapps) { this.webapps = webapps; } public Date getDataCollectionStartDate() { return dataCollectionStartDate; } public void setDataCollectionStartDate(Date dataCollectionStartDate) { this.dataCollectionStartDate = dataCollectionStartDate; } public static InternalsDto fromEngineDto(Internals other) { LicenseKeyData licenseKey = other.getLicenseKey(); InternalsDto dto = new InternalsDto( DatabaseDto.fromEngineDto(other.getDatabase()), ApplicationServerDto.fromEngineDto(other.getApplicationServer()), licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null, JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate(); dto.commands = new HashMap<>(); other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount()))); dto.metrics = new HashMap<>(); other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount()))); dto.setWebapps(other.getWebapps()); dto.setCamundaIntegration(other.getCamundaIntegration()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
1
请在Spring Boot框架中完成以下Java代码
public class StockPriceProducer { public static final String[] STOCKS = {"AAPL", "GOOG", "MSFT", "AMZN", "TSLA"}; private static final String CURRENCY = "USD"; private final ReactiveKafkaProducerTemplate<String, StockUpdate> kafkaProducer; private final NewTopic topic; private final Random random = new Random(); @SuppressWarnings("all") public StockPriceProducer(@NonNull KafkaProperties properties, @Qualifier(TopicConfig.STOCK_PRICES_IN) NewTopic topic) { this.kafkaProducer = new ReactiveKafkaProducerTemplate<>(SenderOptions.create(properties.buildProducerProperties())); this.topic = topic; } public Flux<SenderResult<Void>> produceStockPrices(int count) {
return Flux.range(0, count) .map(i -> { String stock = STOCKS[random.nextInt(STOCKS.length)]; double price = 100 + (200 * random.nextDouble()); return MessageBuilder.withPayload(new StockUpdate(stock, price, CURRENCY, Instant.now())) .setHeader(MessageHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .build(); }) .flatMap(stock -> { var newRecord = new ProducerRecord<>(topic.name(), stock.getPayload().symbol(), stock.getPayload()); stock.getHeaders().forEach((key, value) -> newRecord.headers().add(key, value.toString().getBytes())); return kafkaProducer.send(newRecord); }); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-kafka-stream-binder\src\main\java\com\baeldung\reactive\kafka\stream\binder\kafka\producer\StockPriceProducer.java
2
请完成以下Java代码
public Set<String> headerNames() { Set<String> headerNames = super.headerNames(); for (String headerName : headerNames) { validateAllowedHeaderName(headerName); } return headerNames; } } private final class StrictFirewallBuilder implements Builder { private final Builder delegate; private StrictFirewallBuilder(Builder delegate) { this.delegate = delegate; } @Override public Builder method(HttpMethod httpMethod) { return new StrictFirewallBuilder(this.delegate.method(httpMethod)); } @Override public Builder uri(URI uri) { return new StrictFirewallBuilder(this.delegate.uri(uri)); } @Override public Builder path(String path) { return new StrictFirewallBuilder(this.delegate.path(path)); } @Override public Builder contextPath(String contextPath) { return new StrictFirewallBuilder(this.delegate.contextPath(contextPath)); } @Override public Builder header(String headerName, String... headerValues) { return new StrictFirewallBuilder(this.delegate.header(headerName, headerValues)); } @Override
public Builder headers(Consumer<HttpHeaders> headersConsumer) { return new StrictFirewallBuilder(this.delegate.headers(headersConsumer)); } @Override public Builder sslInfo(SslInfo sslInfo) { return new StrictFirewallBuilder(this.delegate.sslInfo(sslInfo)); } @Override public Builder remoteAddress(InetSocketAddress remoteAddress) { return new StrictFirewallBuilder(this.delegate.remoteAddress(remoteAddress)); } @Override public Builder localAddress(InetSocketAddress localAddress) { return new StrictFirewallBuilder(this.delegate.localAddress(localAddress)); } @Override public ServerHttpRequest build() { return new StrictFirewallHttpRequest(this.delegate.build()); } } } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\StrictServerWebExchangeFirewall.java
1
请完成以下Java代码
public String ifunless(ModelMap map) { map.addAttribute("flag", "yes"); return "if"; } @RequestMapping("/list") public String list(ModelMap map) { map.addAttribute("users", getUserList()); return "list"; } @RequestMapping("/url") public String url(ModelMap map) { map.addAttribute("type", "link"); map.addAttribute("pageId", "springcloud/2017/09/11/"); map.addAttribute("img", "http://www.ityouknow.com/assets/images/neo.jpg"); return "url"; } @RequestMapping("/eq") public String eq(ModelMap map) { map.addAttribute("name", "neo"); map.addAttribute("age", 30); map.addAttribute("flag", "yes"); return "eq"; }
@RequestMapping("/switch") public String switchcase(ModelMap map) { map.addAttribute("sex", "woman"); return "switch"; } private List<User> getUserList(){ List<User> list=new ArrayList<User>(); User user1=new User("大牛",12,"123456"); User user2=new User("小牛",6,"123563"); User user3=new User("纯洁的微笑",66,"666666"); list.add(user1); list.add(user2); list.add(user3); return list; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-3 课 模板引擎 Thymeleaf 基础使用\spring-boot-thymeleaf\src\main\java\com\neo\web\ExampleController.java
1
请在Spring Boot框架中完成以下Java代码
public class GetArticlesHandler implements QueryHandler<GetArticlesResult, GetArticles> { private final AuthenticationService authenticationService; private final ArticleRepository articleRepository; private final UserRepository userRepository; private final TagRepository tagRepository; private final ConversionService conversionService; @Transactional(readOnly = true) @Override public GetArticlesResult handle(GetArticles query) { var currentUserId = authenticationService.getCurrentUserId(); Long tagId; if (query.getTag() == null) { tagId = null; } else { tagId = tagRepository.findByName(query.getTag()) .map(Tag::id) .orElse(null); if (tagId == null) { return new GetArticlesResult(List.of(), 0L); } } Long authorId; if (query.getAuthor() == null) { authorId = null; } else { authorId = userRepository.findByUsername(query.getAuthor()) .map(User::id) .orElse(null); if (authorId == null) { return new GetArticlesResult(List.of(), 0L); } } Long favoritedById; if (query.getFavorited() == null) { favoritedById = null;
} else { favoritedById = userRepository.findByUsername(query.getFavorited()) .map(User::id) .orElse(null); if (favoritedById == null) { return new GetArticlesResult(List.of(), 0L); } } var articles = articleRepository.findAllAssemblyByFilters(currentUserId, tagId, authorId, favoritedById, query.getLimit(), query.getOffset()); var results = articles.stream() .map(a -> conversionService.convert(a, ArticleDto.class)) .toList(); var count = articleRepository.countByFilters(tagId, authorId, favoritedById); return new GetArticlesResult(results, count); } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\application\query\GetArticlesHandler.java
2
请完成以下Java代码
public final String getFax() { return orgContact.getFax(); } public ClientSetup setEMail(final String email) { if (!Check.isEmpty(email, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setEMail(email.trim()); } return this; } public final String getEMail() { return orgContact.getEMail(); } public ClientSetup setBPartnerDescription(final String bpartnerDescription)
{ if (Check.isEmpty(bpartnerDescription, true)) { return this; } orgBPartner.setDescription(bpartnerDescription.trim()); return this; } public String getBPartnerDescription() { return orgBPartner.getDescription(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractService { // this method configuration is equivalent to xml configuration @Cacheable(value = "addresses", key = "#customer.name") public String getAddress(final Customer customer) { return customer.getAddress(); } /** * The method returns the customer's address, only it doesn't find it the cache- addresses and directory. * * @param customer the customer * @return the address */ @Cacheable({ "addresses", "directory" }) public String getAddress1(final Customer customer) { return customer.getAddress(); } /** * The method returns the customer's address, but refreshes all the entries in the cache to load new ones. * * @param customer the customer * @return the address */ @CacheEvict(value = "addresses", allEntries = true) public String getAddress2(final Customer customer) { return customer.getAddress(); } /** * The method returns the customer's address, but not before selectively evicting the cache as per specified paramters. * * @param customer the customer * @return the address */ @Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") }) public String getAddress3(final Customer customer) { return customer.getAddress(); } /** * The method uses the class level cache to look up for entries.
* * @param customer the customer * @return the address */ @Cacheable // parameter not required as we have declared it using @CacheConfig public String getAddress4(final Customer customer) { return customer.getAddress(); } /** * The method selectively caches the results that meet the predefined criteria. * * @param customer the customer * @return the address */ @CachePut(value = "addresses", condition = "#customer.name=='Tom'") // @CachePut(value = "addresses", unless = "#result.length>64") public String getAddress5(final Customer customer) { return customer.getAddress(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\example\AbstractService.java
2
请完成以下Java代码
public void setattributes (final String attributes) { set_ValueNoCheck (COLUMNNAME_attributes, attributes); } @Override public String getattributes() { return get_ValueAsString(COLUMNNAME_attributes); } @Override public void setDisplayableQRCode (final String DisplayableQRCode) { set_Value (COLUMNNAME_DisplayableQRCode, DisplayableQRCode); } @Override public String getDisplayableQRCode() { return get_ValueAsString(COLUMNNAME_DisplayableQRCode); } @Override public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID) { if (M_HU_QRCode_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID); }
@Override public int getM_HU_QRCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID); } @Override public void setRenderedQRCode (final String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); } @Override public String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } @Override public void setUniqueId (final String UniqueId) { set_ValueNoCheck (COLUMNNAME_UniqueId, UniqueId); } @Override public String getUniqueId() { return get_ValueAsString(COLUMNNAME_UniqueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode.java
1
请完成以下Java代码
public class FailedJobListener implements CommandContextCloseListener { private static final Logger log = LoggerFactory.getLogger(FailedJobListener.class); protected CommandExecutor commandExecutor; protected Job job; public FailedJobListener(CommandExecutor commandExecutor, Job job) { this.commandExecutor = commandExecutor; this.job = job; } @Override public void closing(CommandContext commandContext) {} @Override public void afterSessionsFlush(CommandContext commandContext) {} @Override public void closed(CommandContext context) { if (context.getEventDispatcher().isEnabled()) { context .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_EXECUTION_SUCCESS, job)); } } @Override
public void closeFailure(CommandContext commandContext) { if (commandContext.getEventDispatcher().isEnabled()) { commandContext .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityExceptionEvent( ActivitiEventType.JOB_EXECUTION_FAILURE, job, commandContext.getException() ) ); } CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew(); FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory(); Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), commandContext.getException()); log.trace( "Using FailedJobCommandFactory '" + failedJobCommandFactory.getClass() + "' and command of type '" + cmd.getClass() + "'" ); commandExecutor.execute(commandConfig, cmd); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\jobexecutor\FailedJobListener.java
1
请在Spring Boot框架中完成以下Java代码
public Quantity getQtyToReserve() { return getQtyRequired().subtract(getQtyReservedOrConsumed()).toZeroIfNegative(); } public Quantity getQtyReservedOrConsumed() { return getQtyReserved().add(getQtyConsumed()); } public ServiceRepairProjectTask reduce(@NonNull final AddQtyToProjectTaskRequest request) { if (!ProductId.equals(getProductId(), request.getProductId())) { return this; } return toBuilder() .qtyReserved(getQtyReserved().add(request.getQtyReserved())) .qtyConsumed(getQtyConsumed().add(request.getQtyConsumed())) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withUpdatedStatus() { final ServiceRepairProjectTaskStatus newStatus = computeStatus(); return !newStatus.equals(getStatus()) ? toBuilder().status(newStatus).build() : this; } private ServiceRepairProjectTaskStatus computeStatus() { final @NonNull ServiceRepairProjectTaskType type = getType(); switch (type) { case REPAIR_ORDER: return computeStatusForRepairOrderType(); case SPARE_PARTS: return computeStatusForSparePartsType(); default: throw new AdempiereException("Unknown type for " + this); } } private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType() { if (getRepairOrderId() == null) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return isRepairOrderDone() ? ServiceRepairProjectTaskStatus.COMPLETED : ServiceRepairProjectTaskStatus.IN_PROGRESS; } } private ServiceRepairProjectTaskStatus computeStatusForSparePartsType() { if (getQtyToReserve().signum() <= 0) { return ServiceRepairProjectTaskStatus.COMPLETED; } else if (getQtyReservedOrConsumed().signum() == 0) { return ServiceRepairProjectTaskStatus.NOT_STARTED; }
else { return ServiceRepairProjectTaskStatus.IN_PROGRESS; } } public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId) { return toBuilder() .repairOrderId(repairOrderId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderDone( @Nullable final String repairOrderSummary, @Nullable final ProductId repairServicePerformedId) { return toBuilder() .isRepairOrderDone(true) .repairOrderSummary(repairOrderSummary) .repairServicePerformedId(repairServicePerformedId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderNotDone() { return toBuilder() .isRepairOrderDone(false) .repairOrderSummary(null) .repairServicePerformedId(null) .build() .withUpdatedStatus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
2
请完成以下Java代码
public List<Review> getReviews() { return reviews; } public void setReviews(List<Review> reviews) { this.reviews = reviews; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) {
return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public class GeocodingProviderFactory { private final GeocodingConfigRepository configRepository; private final CCache<GeocodingConfig, GeocodingProvider> providers = CCache.<GeocodingConfig, GeocodingProvider>builder() .cacheMapType(CacheMapType.LRU) .initialCapacity(10) .build(); public GeocodingProviderFactory( @NonNull final GeocodingConfigRepository configRepository) { this.configRepository = configRepository; } @NonNull public Optional<GeocodingProvider> getProvider() { final GeocodingConfig config = configRepository.getGeocodingConfig().orElse(null); if (config == null) { return Optional.empty(); } final GeocodingProvider provider = providers.getOrLoad(config, this::createProvider); return Optional.of(provider); } private GeocodingProvider createProvider(@NonNull final GeocodingConfig config) { final GeocodingProviderName providerName = config.getProviderName(); if (GeocodingProviderName.GOOGLE_MAPS.equals(providerName)) { return createGoogleMapsProvider(config.getGoogleMapsConfig()); } else if (GeocodingProviderName.OPEN_STREET_MAPS.equals(providerName)) { return createOSMProvider(config.getOpenStreetMapsConfig());
} else { throw new AdempiereException("Unknown provider: " + providerName); } } @NonNull private GoogleMapsGeocodingProviderImpl createGoogleMapsProvider(@NonNull final GoogleMapsConfig config) { final String apiKey = config.getApiKey(); final int cacheCapacity = config.getCacheCapacity(); final GeoApiContext context = new GeoApiContext.Builder() .apiKey(apiKey) .build(); return new GoogleMapsGeocodingProviderImpl(context, cacheCapacity); } @NonNull private NominatimOSMGeocodingProviderImpl createOSMProvider(@NonNull final OpenStreetMapsConfig config) { final String baseURL = config.getBaseURL(); final int cacheCapacity = config.getCacheCapacity(); final long millisBetweenRequests = config.getMillisBetweenRequests(); return new NominatimOSMGeocodingProviderImpl(baseURL, millisBetweenRequests, cacheCapacity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\GeocodingProviderFactory.java
2
请完成以下Java代码
public final class EMailAddress { @Nullable public static EMailAddress ofNullableString(@Nullable final String emailStr) { final String emailStrNorm = StringUtils.trimBlankToNull(emailStr); return emailStrNorm != null ? new EMailAddress(emailStrNorm) : null; } public static Optional<EMailAddress> optionalOfNullable(@Nullable final String emailStr) { return Optional.ofNullable(ofNullableString(emailStr)); } @JsonCreator public static EMailAddress ofString(@NonNull final String emailStr) { return new EMailAddress(emailStr); } public static List<EMailAddress> ofSemicolonSeparatedList(@Nullable final String emailsListStr) { if (emailsListStr == null || Check.isBlank(emailsListStr)) { return ImmutableList.of(); } return Splitter.on(";") .trimResults() .omitEmptyStrings() .splitToList(emailsListStr) .stream() .map(EMailAddress::ofNullableString) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Nullable public static ITranslatableString checkEMailValid(@Nullable final EMailAddress email) { if (email == null) { return TranslatableStrings.constant("no email"); } return checkEMailValid(email.getAsString()); } @Nullable public static ITranslatableString checkEMailValid(@Nullable final String email) { if (email == null || Check.isBlank(email)) { return TranslatableStrings.constant("no email"); } try { final InternetAddress ia = new InternetAddress(email, true); ia.validate(); // throws AddressException if (ia.getAddress() == null) { return TranslatableStrings.constant("invalid email"); }
return null; // OK } catch (final AddressException ex) { logger.warn("Invalid email address: {}", email, ex); return TranslatableStrings.constant(ex.getLocalizedMessage()); } } private static final Logger logger = LogManager.getLogger(EMailAddress.class); private final String emailStr; private EMailAddress(@NonNull final String emailStr) { this.emailStr = emailStr.trim(); if (this.emailStr.isEmpty()) { throw new AdempiereException("Empty email address is not valid"); } } @JsonValue public String getAsString() { return emailStr; } @Nullable public static String toStringOrNull(@Nullable final EMailAddress emailAddress) { return emailAddress != null ? emailAddress.getAsString() : null; } @Deprecated @Override public String toString() { return getAsString(); } public InternetAddress toInternetAddress() throws AddressException { return new InternetAddress(emailStr, true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAddress.java
1
请完成以下Java代码
private String jwtPayloadFromUser(User user) { var jwtPayload = UserJWTPayload.of(user, now().getEpochSecond() + durationSeconds); return base64URLFromString(jwtPayload.toString()); } @Override public JWTPayload jwtPayloadFromJWT(String jwtToken) { if (!JWT_PATTERN.matcher(jwtToken).matches()) { throw new IllegalArgumentException("Malformed JWT: " + jwtToken); } final var splintedTokens = jwtToken.split("\\."); if (!splintedTokens[0].equals(JWT_HEADER)) { throw new IllegalArgumentException("Malformed JWT! Token must starts with header: " + JWT_HEADER); }
final var signatureBytes = HmacSHA256.sign(secret, splintedTokens[0].concat(".").concat(splintedTokens[1])); if (!base64URLFromBytes(signatureBytes).equals(splintedTokens[2])) { throw new IllegalArgumentException("Token has invalid signature: " + jwtToken); } try { final var decodedPayload = stringFromBase64URL(splintedTokens[1]); final var jwtPayload = objectMapper.readValue(decodedPayload, UserJWTPayload.class); if (jwtPayload.isExpired()) { throw new IllegalArgumentException("Token expired"); } return jwtPayload; } catch (Exception exception) { throw new IllegalArgumentException(exception); } } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\infrastructure\jwt\HmacSHA256JWTService.java
1
请完成以下Java代码
private Optional<WFProcessHeaderProperty> getLastPickedBestBeforeDate( @NonNull final PickingJobLine line, @NonNull final PickingJobOptions pickingJobOptions, @NonNull final HUCache huCache, @NonNull final JsonOpts opts) { if (!pickingJobOptions.isShowLastPickedBestBeforeDateForLines()) { return Optional.empty(); } final String lastPickedHUBestBeforeDate = line.getLastPickedHUId() .map(huId -> huService.getAttributeValue(huCache.getOrLoad(huId), ATTR_BestBeforeDate)) .map(IAttributeValue::getValueAsDate) .map(date -> JsonHUAttributeConverters.toDisplayValue(date, opts.getAdLanguage())) .map(String::valueOf) .orElse(""); return Optional.of(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adMessage(LAST_PICKED_HU_BEST_BEFORE_DATE)) .value(lastPickedHUBestBeforeDate) .build()); } private void cacheLastPickedHUsForEachLineIfNeeded( @NonNull final HUCache cache, @NonNull final PickingJobOptions pickingJobOptions, @NonNull final PickingJob job) { if (!pickingJobOptions.isShowLastPickedBestBeforeDateForLines()) { return; } final Set<HuId> huIds = job.streamLines() .map(PickingJobLine::getLastPickedHUId) .filter(Optional::isPresent) .map(Optional::get) .collect(ImmutableSet.toImmutableSet()); cache.cacheHUs(huService.getByIds(huIds)); } @Value
@Builder private static class HUCache { public static HUCache init(@NonNull Function<HuId, I_M_HU> loadHU) { return HUCache.builder() .loadHU(loadHU) .build(); } @NonNull Function<HuId, I_M_HU> loadHU; Map<HuId, I_M_HU> huById = new ConcurrentHashMap<>(); public void cacheHUs(@NonNull final List<I_M_HU> hus) { hus.forEach(hu -> huById.put(HuId.ofRepoId(hu.getM_HU_ID()), hu)); } @NonNull public I_M_HU getOrLoad(@NonNull final HuId huId) { return huById.computeIfAbsent(huId, loadHU); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\ActualPickingWFActivityHandler.java
1
请完成以下Java代码
public String toString() { final String fromTableRecordStr = fromTableRecord == null ? null : "" + fromTableRecord.getTableName() + "/" + fromTableRecord.getRecord_ID(); return "AllocationRequest [" + "product=" + productId + ", qty=" + (isInfiniteQty() ? "inifinite" : quantity) + ", date=" + date + ", fromTableRecord=" + fromTableRecordStr + ", forceQtyAllocation=" + forceQtyAllocation + ", clearanceStatusInfo=" + clearanceStatusInfo + "]"; } @Override public BigDecimal getQty() { return quantity.toBigDecimal(); } @Override public boolean isZeroQty() { return quantity.isZero(); } @Override public boolean isInfiniteQty() { return quantity.isInfinite(); } @Override public I_C_UOM getC_UOM() {
return quantity.getUOM(); } @Override public TableRecordReference getReference() { return fromTableRecord; } @Override public boolean isDeleteEmptyAndJustCreatedAggregatedTUs() { return deleteEmptyAndJustCreatedAggregatedTUs; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequest.java
1
请完成以下Java代码
public void setB_Topic_ID (int B_Topic_ID) { if (B_Topic_ID < 1) set_Value (COLUMNNAME_B_Topic_ID, null); else set_Value (COLUMNNAME_B_Topic_ID, Integer.valueOf(B_Topic_ID)); } /** Get Topic. @return Auction Topic */ public int getB_Topic_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_Topic_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_BidComment.java
1
请完成以下Java代码
public void deleteNode(int valueToDelete) { Node currentNode = head; if (head == null) { return; } do { Node nextNode = currentNode.nextNode; if (nextNode.value == valueToDelete) { if (tail == head) { head = null; tail = null; } else { currentNode.nextNode = nextNode.nextNode; if (head == nextNode) { head = head.nextNode; } if (tail == nextNode) { tail = currentNode; } } break; } currentNode = nextNode; } while (currentNode != head); } public void traverseList() { Node currentNode = head; if (head != null) {
do { logger.info(currentNode.value + " "); currentNode = currentNode.nextNode; } while (currentNode != head); } } } class Node { int value; Node nextNode; public Node(int value) { this.value = value; } }
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\circularlinkedlist\CircularLinkedList.java
1