instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setNetWeightKg (final @Nullable BigDecimal NetWeightKg) { set_Value (COLUMNNAME_NetWeightKg, NetWeightKg); } @Override public BigDecimal getNetWeightKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NetWeightKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() {
return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrder.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { @Autowired EmployeeService employeeService; @PostConstruct public void saveEmployees() { List<Employee> employees = new ArrayList<>(); employees.add(new Employee(123, "John Doe", "Delaware", "jdoe@xyz.com", 31)); employees.add(new Employee(324, "Adam Smith", "North Carolina", "asmith@xyz.com", 43)); employees.add(new Employee(355, "Kevin Dunner", "Virginia", "kdunner@xyz.com", 24)); employees.add(new Employee(643, "Mike Lauren", "New York", "mlauren@xyz.com", 41)); employeeService.initializeEmployees(employees); } @GetMapping("/list")
public Flux<Employee> getAllEmployees() { Flux<Employee> employees = employeeService.getAllEmployees(); return employees; } @GetMapping("/{id}") public Mono<Employee> getEmployeeById(@PathVariable int id) { return employeeService.getEmployeeById(id); } @GetMapping("/filterByAge/{age}") public Flux<Employee> getEmployeesFilterByAge(@PathVariable int age) { return employeeService.getEmployeesFilterByAge(age); } }
repos\tutorials-master\persistence-modules\spring-data-cassandra-reactive\src\main\java\com\baeldung\cassandra\reactive\controller\EmployeeController.java
2
请完成以下Java代码
public OrderPayScheduleLine getLineByPaymentTermBreakId(@NonNull final PaymentTermBreakId paymentTermBreakId) { return lines.stream() .filter(line -> PaymentTermBreakId.equals(line.getPaymentTermBreakId(), paymentTermBreakId)) .findFirst() .orElseThrow(() -> new AdempiereException("No line found for " + paymentTermBreakId)); } public OrderPayScheduleLine getLineById(@NonNull final OrderPayScheduleId payScheduleLineId) { return lines.stream() .filter(line -> line.getId().equals(payScheduleLineId)) .findFirst() .orElseThrow(() -> new AdempiereException("OrderPayScheduleLine not found for ID: " + payScheduleLineId)); } public void updateStatusFromContext(final OrderSchedulingContext context) { final PaymentTerm paymentTerm = context.getPaymentTerm(); for (final OrderPayScheduleLine line : lines)
{ if (line.getStatus().isPending()) { final PaymentTermBreak termBreak = paymentTerm.getBreakById(line.getPaymentTermBreakId()); final DueDateAndStatus dueDateAndStatus = context.computeDueDate(termBreak); line.applyAndProcess(dueDateAndStatus); } } } public void markAsPaid(final OrderPayScheduleId orderPayScheduleId) { final OrderPayScheduleLine line = getLineById(orderPayScheduleId); final DueDateAndStatus dueDateAndStatus = DueDateAndStatus.paid(line.getDueDate()); line.applyAndProcess(dueDateAndStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPaySchedule.java
1
请在Spring Boot框架中完成以下Java代码
public List<Author> fetchByGenre1(String genre) { StoredProcedureQuery storedProcedure = entityManager.createNamedStoredProcedureQuery("FetchByGenreProcedure"); storedProcedure.setParameter(GENRE_PARAM, genre); List<Author> storedProcedureResults; try { storedProcedureResults = storedProcedure.getResultList(); } finally { storedProcedure.unwrap(ProcedureOutputs.class).release(); } return storedProcedureResults; } @Override @Transactional public List<Author> fetchByGenre2(String genre) { StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FETCH_AUTHOR_BY_GENRE", Author.class); storedProcedure.registerStoredProcedureParameter(GENRE_PARAM, String.class, ParameterMode.IN); storedProcedure.setParameter(GENRE_PARAM, genre); List<Author> storedProcedureResults; try { storedProcedureResults = storedProcedure.getResultList(); } finally { storedProcedure.unwrap(ProcedureOutputs.class).release(); } return storedProcedureResults; } @Override @Transactional public List<AuthorDto> fetchByGenre3(String genre) { StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery( "FETCH_NICKNAME_AND_AGE_BY_GENRE", "AuthorDtoMapping"); storedProcedure.registerStoredProcedureParameter(GENRE_PARAM, String.class, ParameterMode.IN); storedProcedure.setParameter(GENRE_PARAM, genre); List<AuthorDto> storedProcedureResults; try { storedProcedureResults = storedProcedure.getResultList(); } finally { storedProcedure.unwrap(ProcedureOutputs.class).release(); }
return storedProcedureResults; } @Override @Transactional public List<AuthorDto> fetchByGenre4(String genre) { StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FETCH_NICKNAME_AND_AGE_BY_GENRE"); storedProcedure.registerStoredProcedureParameter(GENRE_PARAM, String.class, ParameterMode.IN); storedProcedure.setParameter(GENRE_PARAM, genre); List<AuthorDto> storedProcedureResults; try { List<Object[]> storedProcedureObjects = storedProcedure.getResultList(); storedProcedureResults = storedProcedureObjects.stream() .map(result -> new AuthorDto( (String) result[0], (Integer) result[1] )).collect(Collectors.toList()); } finally { storedProcedure.unwrap(ProcedureOutputs.class).release(); } return storedProcedureResults; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCallStoredProcedureReturnResultSet\src\main\java\com\bookstore\dao\DaoImpl.java
2
请完成以下Java代码
public String getDeleteReason() { return "cmmn-state-transition-terminate-case"; } @Override public void addAdditionalCallbackData(CallbackData callbackData) { if (callbackData.getAdditionalData() == null) { callbackData.setAdditionalData(new HashMap<>()); } callbackData.getAdditionalData().put(CallbackConstants.EXIT_TYPE, exitType); callbackData.getAdditionalData().put(CallbackConstants.EXIT_EVENT_TYPE, exitEventType); callbackData.getAdditionalData().put(CallbackConstants.MANUAL_TERMINATION, manualTermination); } @Override public CaseInstanceEntity getCaseInstanceEntity() { if (caseInstanceEntity == null) { caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceEntityId); if (caseInstanceEntity == null) { throw new FlowableObjectNotFoundException("No case instance found for id " + caseInstanceEntityId); } } return caseInstanceEntity; } public boolean isManualTermination() { return manualTermination; } public void setManualTermination(boolean manualTermination) { this.manualTermination = manualTermination; }
public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TerminateCaseInstanceOperation.java
1
请完成以下Java代码
public class C_OLCandEnqueueForSalesOrderCreation extends JavaProcess { private final IQueryBL queryBL = Services.get(IQueryBL.class); public static final String PARAM_C_OLCandProcessor_ID = I_C_OLCandProcessor.COLUMNNAME_C_OLCandProcessor_ID; @Param(mandatory = true, parameterName = PARAM_C_OLCandProcessor_ID) private int olCandProcessorId; private static final AdMessageKey MSG_OL_CANDENQUEUE_FOR_SALES_ORDER_CREATION_NO_VALID_RECORD_SELECTED = AdMessageKey.of("C_OLCandEnqueueForSalesOrderCreation.NoValidRecordSelected"); @Override protected void prepare() { // Display process logs only if the process failed. // NOTE: we do that because this process is called from window Gear and user shall only see the status line, and no popup shall be displayed. // gh #755 new note: this process is run manually from gear only rarely. So an (admin-) user who runs this should see what went on. // particularly if there were problems (and this process would still return "OK" in that case). setShowProcessLogs(ShowProcessLogs.Always); } @Override protected String doIt() throws Exception { Check.assume(olCandProcessorId > 0, "olCandProcessorId > 0");
// IMPORTANT: we shall create the selection out of transaction because // else the selection (T_Selection) won't be available when creating the main lock for records of this selection. final PInstanceId userSelectionId = queryBL.createQueryBuilderOutOfTrx(I_C_OLCand.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false) .filter(getProcessInfo().getQueryFilterOrElseTrue()) .create() .createSelection(); if (userSelectionId == null) { throw new AdempiereException(MSG_OL_CANDENQUEUE_FOR_SALES_ORDER_CREATION_NO_VALID_RECORD_SELECTED).markAsUserValidationError(); } final C_OLCandToOrderEnqueuer olCandToOrderEnqueuer = SpringContextHolder.instance.getBean(C_OLCandToOrderEnqueuer.class); final OlCandEnqueueResult result = olCandToOrderEnqueuer.enqueueSelection(userSelectionId); addLog("OlCandEnqueueResult: {}", result); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCandEnqueueForSalesOrderCreation.java
1
请在Spring Boot框架中完成以下Java代码
public WidgetType getWidgetTypeByBundleAliasAndTypeAlias( @Parameter(description = "System or Tenant", required = true) @RequestParam boolean isSystem, @Parameter(description = "Widget Bundle alias", required = true) @RequestParam String bundleAlias, @Parameter(description = "Widget Type alias", required = true) @RequestParam String alias) throws ThingsboardException { TenantId tenantId; if (isSystem) { tenantId = TenantId.fromUUID(ModelConstants.NULL_UUID); } else { tenantId = getCurrentUser().getTenantId(); } WidgetType widgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(tenantId, bundleAlias + "." + alias); checkNotNull(widgetType); accessControlService.checkPermission(getCurrentUser(), Resource.WIDGET_TYPE, Operation.READ, widgetType.getId(), widgetType); return widgetType; } @ApiOperation(value = "Get Widget Type (getWidgetType)", notes = "Get the Widget Type by FQN. " + WIDGET_TYPE_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER, hidden = true) @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @GetMapping(value = "/widgetType", params = {"fqn"}) public WidgetType getWidgetType( @Parameter(description = "Widget Type fqn", required = true) @RequestParam String fqn) throws ThingsboardException { String[] parts = fqn.split("\\."); String scopeQualifier = parts.length > 0 ? parts[0] : null; if (parts.length < 2 || (!scopeQualifier.equals("system") && !scopeQualifier.equals("tenant"))) { throw new ThingsboardException("Invalid fqn!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); }
TenantId tenantId; if ("system".equals(scopeQualifier)) { tenantId = TenantId.fromUUID(ModelConstants.NULL_UUID); } else { tenantId = getCurrentUser().getTenantId(); } String typeFqn = fqn.substring(scopeQualifier.length() + 1); WidgetType widgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(tenantId, typeFqn); checkNotNull(widgetType); accessControlService.checkPermission(getCurrentUser(), Resource.WIDGET_TYPE, Operation.READ, widgetType.getId(), widgetType); return widgetType; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\WidgetTypeController.java
2
请完成以下Java代码
public void setFrom(String value) { this.from = value; } /** * Gets the value of the to property. * * @return * possible object is * {@link String } * */ public String getTo() { return to; } /** * Sets the value of the to property. * * @param value * allowed object is * {@link String } * */ public void setTo(String value) { this.to = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="via" use="required" type="{http://www.forum-datenaustausch.ch/invoice}eanPartyType" /&gt; * &lt;attribute name="sequence_id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedShort" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Via { @XmlAttribute(name = "via", required = true) protected String via; @XmlAttribute(name = "sequence_id", required = true) @XmlSchemaType(name = "unsignedShort") protected int sequenceId; /** * Gets the value of the via property. * * @return
* possible object is * {@link String } * */ public String getVia() { return via; } /** * Sets the value of the via property. * * @param value * allowed object is * {@link String } * */ public void setVia(String value) { this.via = value; } /** * Gets the value of the sequenceId property. * */ public int getSequenceId() { return sequenceId; } /** * Sets the value of the sequenceId property. * */ public void setSequenceId(int value) { this.sequenceId = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransportType.java
1
请完成以下Java代码
public class DispatcherFilter implements Filter { private final Dispatcher dispatcher; public DispatcherFilter(Dispatcher dispatcher) { Assert.notNull(dispatcher, "'dispatcher' must not be null"); this.dispatcher = dispatcher; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } else { chain.doFilter(request, response); }
} private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ServerHttpRequest serverRequest = new ServletServerHttpRequest(request); ServerHttpResponse serverResponse = new ServletServerHttpResponse(response); if (!this.dispatcher.handle(serverRequest, serverResponse)) { chain.doFilter(request, response); } } @Override public void destroy() { } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\server\DispatcherFilter.java
1
请完成以下Java代码
public final class FieldReference { public static FieldReference of(@NonNull final Field field) { return new FieldReference(field); } private final AtomicReference<WeakReference<Field>> fieldRef; private final ClassReference<?> classRef; private final String fieldName; private FieldReference(@NonNull final Field field) { fieldRef = new AtomicReference<>(new WeakReference<>(field)); classRef = ClassReference.of(field.getDeclaringClass()); fieldName = field.getName(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("field", fieldName) .add("class", classRef) .toString(); } public Field getField() { // Get if not expired { final WeakReference<Field> weakRef = fieldRef.get(); final Field field = weakRef != null ? weakRef.get() : null; if (field != null) { return field;
} } // Load the class try { final Class<?> clazz = classRef.getReferencedClass(); final Field fieldNew = clazz.getDeclaredField(fieldName); fieldRef.set(new WeakReference<>(fieldNew)); return fieldNew; } catch (final Exception ex) { throw new IllegalStateException("Cannot load expired field: " + classRef + "/" + fieldName, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\FieldReference.java
1
请完成以下Java代码
private DDOrderCandidate toDDOrderCandidate(@NonNull final DDOrderCandidateRequestedEvent event) { final PPOrderId forwardPPOrderId = findForwardPPOrderId(event); final DDOrderCandidateData ddOrderCandidateData = event.getDdOrderCandidateData().withPPOrderId(forwardPPOrderId); return DDOrderCandidate.from(ddOrderCandidateData) .dateOrdered(event.getDateOrdered()) .traceId(event.getTraceId()) .build(); } @Nullable private PPOrderId findForwardPPOrderId(@NonNull final DDOrderCandidateRequestedEvent event) { return findForwardPPOrderId(event.getDdOrderCandidateData().getForwardPPOrderRef()); } @Nullable private PPOrderId findForwardPPOrderId(@Nullable final PPOrderRef forwardPPOrderRef) {
if (forwardPPOrderRef == null) { return null; } if (forwardPPOrderRef.getPpOrderId() != null) { return forwardPPOrderRef.getPpOrderId(); } if (forwardPPOrderRef.getPpOrderCandidateId() != null) { final PPOrderCandidateId ppOrderCandidateId = forwardPPOrderRef.getPpOrderCandidateId(); final ImmutableSet<PPOrderId> forwardPPOrderIds = ppOrderCandidateDAO.getPPOrderIds(ppOrderCandidateId); return forwardPPOrderIds.size() == 1 ? forwardPPOrderIds.iterator().next() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\DDOrderCandidateRequestedEventHandler.java
1
请完成以下Java代码
public int release() { return lockDatabase.unlock(this); } @Override public Future<Integer> releaseAfterTrxCommit(final String trxName) { final FutureValue<Integer> countUnlockedFuture = new FutureValue<>(); final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.getTrxListenerManagerOrAutoCommit(trxName) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> { try { final int countUnlocked = release(); countUnlockedFuture.set(countUnlocked); } catch (Exception e) { countUnlockedFuture.setError(e); } }); return countUnlockedFuture; } @Override public IUnlockCommand setOwner(final LockOwner owner) { this.owner = owner; return this; } @Override public final LockOwner getOwner() { Check.assumeNotNull(owner, UnlockFailedException.class, "owner not null"); return this.owner; } @Override public IUnlockCommand setRecordByModel(final Object model) { _recordsToUnlock.setRecordByModel(model); return this; } @Override public IUnlockCommand setRecordsByModels(final Collection<?> models) { _recordsToUnlock.setRecordsByModels(models); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final int tableId, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableId, recordId);
return this; } @Override public IUnlockCommand setRecordByTableRecordId(final String tableName, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableName, recordId); return this; } @Override public IUnlockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId adPIstanceId) { _recordsToUnlock.setRecordsBySelection(modelClass, adPIstanceId); return this; } @Override public final AdTableId getSelectionToUnlock_AD_Table_ID() { return _recordsToUnlock.getSelection_AD_Table_ID(); } @Override public final PInstanceId getSelectionToUnlock_AD_PInstance_ID() { return _recordsToUnlock.getSelection_PInstanceId(); } @Override public final Iterator<TableRecordReference> getRecordsToUnlockIterator() { return _recordsToUnlock.getRecordsIterator(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\UnlockCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class MaterialNeedsRepositorySaver implements SaveHandler { @NonNull private final IProductBL productBL = Services.get(IProductBL.class); @NonNull private final ReplenishInfoRepository replenishInfoRepository; @Override public @NonNull Set<String> getHandledTableName() {return ImmutableSet.of(I_M_Material_Needs_Planner_V.Table_Name);} @Override public boolean isReadonly(@NonNull final GridTabVO gridTabVO) {return false;} @Override public SaveResult save(@NonNull final Document document) { replenishInfoRepository.save(toReplenishInfo(document)); return SaveResult.builder() .needsRefresh(true)
.idNew(document.getDocumentId()) .build(); } private ReplenishInfo toReplenishInfo(@NotNull final Document document) { return MaterialNeedsPlannerRow.ofDocument(document).toReplenishInfo(); } @Override public void delete(@NonNull final Document document) { throw new AdempiereException(AdMessageKey.of("AccessCannotDelete")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\repository\MaterialNeedsRepositorySaver.java
2
请完成以下Java代码
public ADRefList getQtyRejectedReasons() { return adReferenceService.getRefListById(QtyRejectedReasonCode.REFERENCE_ID); } @NonNull public ImmutableMap<HuId, ImmutableSet<OrderId>> getOpenPickingOrderIdsByHuId(@NonNull final ImmutableSet<HuId> huIds) { final ImmutableList<PickingCandidate> openPickingCandidates = pickingCandidateRepository.getByHUIds(huIds) .stream() .filter(pickingCandidate -> !pickingCandidate.isProcessed()) .collect(ImmutableList.toImmutableList()); final ImmutableListMultimap<HuId, ShipmentScheduleId> huId2ShipmentScheduleIds = openPickingCandidates .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(pickingCandidate -> pickingCandidate.getPickFrom().getHuId(), PickingCandidate::getShipmentScheduleId)); final ImmutableMap<ShipmentScheduleId, OrderId> scheduleId2OrderId = shipmentSchedulePA.getByIds(ImmutableSet.copyOf(huId2ShipmentScheduleIds.values())) .values() .stream() .filter(shipmentSchedule -> shipmentSchedule.getC_Order_ID() > 0) .collect(ImmutableMap.toImmutableMap(shipSchedule -> ShipmentScheduleId.ofRepoId(shipSchedule.getM_ShipmentSchedule_ID()), shipSchedule -> OrderId.ofRepoId(shipSchedule.getC_Order_ID()))); return huIds.stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), huId -> { final ImmutableList<ShipmentScheduleId> scheduleIds = Optional .ofNullable(huId2ShipmentScheduleIds.get(huId)) .orElseGet(ImmutableList::of); return scheduleIds.stream() .map(scheduleId2OrderId::get) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); })); } @Override public void beforeReleasePickingSlot(final @NonNull ReleasePickingSlotRequest request) {
final boolean clearedAllUnprocessedHUs = clearPickingSlot(request.getPickingSlotId(), request.isRemoveUnprocessedHUsFromSlot()); if (!clearedAllUnprocessedHUs) { throw new AdempiereException(DRAFTED_PICKING_CANDIDATES_ERR_MSG).markAsUserValidationError(); } } /** * @return true, if all drafted picking candidates have been removed from the slot, false otherwise */ private boolean clearPickingSlot(@NonNull final PickingSlotId pickingSlotId, final boolean removeUnprocessedHUsFromSlot) { if (removeUnprocessedHUsFromSlot) { RemoveHUFromPickingSlotCommand.builder() .pickingCandidateRepository(pickingCandidateRepository) .pickingSlotId(pickingSlotId) .build() .perform(); } return !pickingCandidateRepository.hasDraftCandidatesForPickingSlot(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateService.java
1
请在Spring Boot框架中完成以下Java代码
public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public void updateSuspensionState(ProcessEngine engine) { if (processDefinitionId != null && processDefinitionKey != null) { String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } RepositoryService repositoryService = engine.getRepositoryService(); Date delayedExecutionDate = null; if (executionDate != null && !executionDate.equals("")) { delayedExecutionDate = DateTimeUtil.parseDate(executionDate); } if (processDefinitionId != null) { // activate/suspend process definition by id if (getSuspended()) { repositoryService.suspendProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate); } else { repositoryService.activateProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate); }
} else if (processDefinitionKey != null) { // activate/suspend process definition by key if (getSuspended()) { repositoryService.suspendProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate); } else { repositoryService.activateProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate); } } else { String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionSuspensionStateDto.java
2
请完成以下Java代码
public String getCamundaCalledElementVersion() { return camundaCalledElementVersionAttribute.getValue(this); } public void setCamundaCalledElementVersion(String camundaCalledElementVersion) { camundaCalledElementVersionAttribute.setValue(this, camundaCalledElementVersion); } public String getCamundaCalledElementVersionTag() { return camundaCalledElementVersionTagAttribute.getValue(this); } public void setCamundaCalledElementVersionTag(String camundaCalledElementVersionTag) { camundaCalledElementVersionTagAttribute.setValue(this, camundaCalledElementVersionTag); } public String getCamundaCaseRef() { return camundaCaseRefAttribute.getValue(this); } public void setCamundaCaseRef(String camundaCaseRef) { camundaCaseRefAttribute.setValue(this, camundaCaseRef); } public String getCamundaCaseBinding() { return camundaCaseBindingAttribute.getValue(this); } public void setCamundaCaseBinding(String camundaCaseBinding) { camundaCaseBindingAttribute.setValue(this, camundaCaseBinding); } public String getCamundaCaseVersion() { return camundaCaseVersionAttribute.getValue(this); } public void setCamundaCaseVersion(String camundaCaseVersion) { camundaCaseVersionAttribute.setValue(this, camundaCaseVersion); } public String getCamundaCalledElementTenantId() { return camundaCalledElementTenantIdAttribute.getValue(this); } public void setCamundaCalledElementTenantId(String tenantId) { camundaCalledElementTenantIdAttribute.setValue(this, tenantId); } public String getCamundaCaseTenantId() { return camundaCaseTenantIdAttribute.getValue(this); }
public void setCamundaCaseTenantId(String tenantId) { camundaCaseTenantIdAttribute.setValue(this, tenantId); } @Override public String getCamundaVariableMappingClass() { return camundaVariableMappingClassAttribute.getValue(this); } @Override public void setCamundaVariableMappingClass(String camundaClass) { camundaVariableMappingClassAttribute.setValue(this, camundaClass); } @Override public String getCamundaVariableMappingDelegateExpression() { return camundaVariableMappingDelegateExpressionAttribute.getValue(this); } @Override public void setCamundaVariableMappingDelegateExpression(String camundaExpression) { camundaVariableMappingDelegateExpressionAttribute.setValue(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallActivityImpl.java
1
请完成以下Java代码
public Date getDateAfter() { Calendar date = getCalendarAfter(); return date == null ? null : date.getTime(); } private Calendar getDateAfterRepeat(Calendar date) { Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone()); if (repeatWithNoBounds) { while (current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping Calendar newTime = add(current, period); if (newTime.equals(current) || newTime.before(current)) { break; } current = newTime; } } else { int maxLoops = times; if (maxIterations > 0) { maxLoops = maxIterations - times; } for (int i = 0; i < maxLoops + 1 && !current.after(date); i++) { current = add(current, period); } } return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone()); } protected Calendar add(Calendar date, Duration duration) { Calendar calendar = (Calendar) date.clone(); // duration.addTo does not account for daylight saving time (xerces), // reversing order of addition fixes the problem calendar.add(Calendar.SECOND, duration.getSeconds() * duration.getSign());
calendar.add(Calendar.MINUTE, duration.getMinutes() * duration.getSign()); calendar.add(Calendar.HOUR, duration.getHours() * duration.getSign()); calendar.add(Calendar.DAY_OF_MONTH, duration.getDays() * duration.getSign()); calendar.add(Calendar.MONTH, duration.getMonths() * duration.getSign()); calendar.add(Calendar.YEAR, duration.getYears() * duration.getSign()); return calendar; } protected Calendar parseDate(String date) throws Exception { Calendar dateCalendar = null; try { dateCalendar = ISODateTimeFormat.dateTimeParser() .withZone(DateTimeZone.forTimeZone(clockReader.getCurrentTimeZone())) .parseDateTime(date) .toCalendar(null); } catch (IllegalArgumentException e) { // try to parse a java.util.date to string back to a java.util.date dateCalendar = new GregorianCalendar(); DateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH); dateCalendar.setTime(DATE_FORMAT.parse(date)); } return dateCalendar; } protected Duration parsePeriod(String period) throws Exception { return datatypeFactory.newDuration(period); } protected boolean isDuration(String time) { return time.startsWith("P"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\DurationHelper.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrefix (final @Nullable java.lang.String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } @Override public java.lang.String getPrefix() { return get_ValueAsString(COLUMNNAME_Prefix); } /** * RestartFrequency AD_Reference_ID=541879 * Reference name: AD_SequenceRestart Frequency */ public static final int RESTARTFREQUENCY_AD_Reference_ID=541879; /** Year = Y */ public static final String RESTARTFREQUENCY_Year = "Y"; /** Month = M */ public static final String RESTARTFREQUENCY_Month = "M"; /** Day = D */ public static final String RESTARTFREQUENCY_Day = "D"; @Override public void setRestartFrequency (final @Nullable java.lang.String RestartFrequency) { set_Value (COLUMNNAME_RestartFrequency, RestartFrequency); } @Override public java.lang.String getRestartFrequency() { return get_ValueAsString(COLUMNNAME_RestartFrequency);
} @Override public void setStartNo (final int StartNo) { set_Value (COLUMNNAME_StartNo, StartNo); } @Override public int getStartNo() { return get_ValueAsInt(COLUMNNAME_StartNo); } @Override public void setSuffix (final @Nullable java.lang.String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } @Override public java.lang.String getSuffix() { return get_ValueAsString(COLUMNNAME_Suffix); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence.java
1
请完成以下Java代码
public void setKeyword (String Keyword) { set_Value (COLUMNNAME_Keyword, Keyword); } /** Get Keyword. @return Case insensitive keyword */ public String getKeyword () { return (String)get_Value(COLUMNNAME_Keyword); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getKeyword()); } /** Set Index Stop. @param K_IndexStop_ID Keyword not to be indexed */ public void setK_IndexStop_ID (int K_IndexStop_ID) { if (K_IndexStop_ID < 1) set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, null); else set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, Integer.valueOf(K_IndexStop_ID)); } /** Get Index Stop. @return Keyword not to be indexed */ public int getK_IndexStop_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID); if (ii == null) return 0; return ii.intValue();
} public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_K_IndexStop.java
1
请完成以下Java代码
public void addBook(Book book) { books.add(book); } // standard getters and setters public Author() { } public Author(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Book> getBooks() { return books; } public void setBooks(Set<Book> books) { this.books = books; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\Author.java
1
请完成以下Java代码
public I_M_HU_Item getVHU_Item() { return vhuItem; } @Override public IHUTransactionCandidate getCounterpart() { return counterpartTrx; } private void setCounterpart(@NonNull final IHUTransactionCandidate counterpartTrx) { Check.assume(this != counterpartTrx, "counterpartTrx != this"); if (this.counterpartTrx == null) { this.counterpartTrx = counterpartTrx; } else if (this.counterpartTrx == counterpartTrx) { // do nothing; it was already set } else { throw new HUException("Posible development error: changing the counterpart transaction is not allowed" + "\n Transaction: " + this + "\n Counterpart trx (old): " + this.counterpartTrx + "\n Counterpart trx (new): " + counterpartTrx); } }
@Override public void pair(final IHUTransactionCandidate counterpartTrx) { Check.errorUnless(counterpartTrx instanceof HUTransactionCandidate, "Param counterPartTrx needs to be a HUTransaction counterPartTrx={}", counterpartTrx); this.setCounterpart(counterpartTrx); // by casting to HUTransaction (which currently is the only implementation of IHUTransaction), we don't have to make setCounterpart() public. ((HUTransactionCandidate)counterpartTrx).setCounterpart(this); } @Override public LocatorId getLocatorId() { return locatorId; } @Override public void setSkipProcessing() { skipProcessing = true; } @Override public String getHUStatus() { return huStatus; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTransactionCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public Page<UserDTO> getAllPublicUsers(Pageable pageable) { return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthorities() { return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). */
@Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { userRepository .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) .forEach(user -> { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); }); } /** * Gets a list of all the authorities. * @return a list of all the authorities. */ @Transactional(readOnly = true) public List<String> getAuthorities() { return authorityRepository.findAll().stream().map(Authority::getName).toList(); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public class PostgRESTClient { private static final Logger log = LogManager.getLogger(PostgRESTClient.class); private final PostgRESTConfigRepository configRepository; public PostgRESTClient(final PostgRESTConfigRepository configRepository) { this.configRepository = configRepository; } public Resource performGet(@NonNull final GetRequest getRequest) { final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(getRequest.getBaseURL()); Loggables.withLogger(log, Level.DEBUG).addLog("*** performGet(): for request {}", getRequest); if (!Check.isEmpty(getRequest.getPathVariables())) { builder.pathSegment(getRequest.getPathVariables().toArray(new String[0])); } if (!Check.isEmpty(getRequest.getQueryParameters())) { builder.queryParams(getRequest.getQueryParameters()); } final HttpEntity<String> request = new HttpEntity<>(buildHttpHeaders(getRequest)); final URI uri = builder.build().encode().toUri(); final ResponseEntity<Resource> responseEntity = restTemplate().exchange(uri, HttpMethod.GET, request, Resource.class); final boolean responseWithErrors = !responseEntity.getStatusCode().is2xxSuccessful(); if (responseWithErrors) {
throw new AdempiereException("Something went wrong when retrieving from postgREST!, response body:" + responseEntity.getBody()); } log.debug("*** PostgRESTClient.performGet(), response: {}", responseEntity.getBody()); return responseEntity.getBody(); } private HttpHeaders buildHttpHeaders(@NonNull final GetRequest request) { final PostgRESTResponseFormat responseFormat = request.getResponseFormat(); final List<MediaType> acceptableMediaTypes = new ArrayList<>(); request.getAdditionalAccepts().forEach(a -> acceptableMediaTypes.add(MediaType.valueOf(a))); acceptableMediaTypes.add(MediaType.valueOf(responseFormat.getContentType())); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(acceptableMediaTypes); return headers; } private RestTemplate restTemplate() { final OrgId orgId = Env.getOrgId(); final PostgRESTConfig config = configRepository.getConfigFor(orgId); return new RestTemplateBuilder() .setConnectTimeout(config.getConnectionTimeout()) .setReadTimeout(config.getReadTimeout()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\client\PostgRESTClient.java
2
请完成以下Java代码
public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setMobileUI_HUManager_Attribute_ID (final int MobileUI_HUManager_Attribute_ID) { if (MobileUI_HUManager_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, MobileUI_HUManager_Attribute_ID); } @Override public int getMobileUI_HUManager_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_Attribute_ID); } @Override public org.compiere.model.I_MobileUI_HUManager getMobileUI_HUManager() { return get_ValueAsPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class); } @Override public void setMobileUI_HUManager(final org.compiere.model.I_MobileUI_HUManager MobileUI_HUManager) { set_ValueFromPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class, MobileUI_HUManager); } @Override public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID) {
if (MobileUI_HUManager_ID < 1) set_Value (COLUMNNAME_MobileUI_HUManager_ID, null); else set_Value (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID); } @Override public int getMobileUI_HUManager_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager_Attribute.java
1
请完成以下Java代码
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
请完成以下Java代码
public class WorkflowValidate extends JavaProcess { private final IADWorkflowBL workflowBL = Services.get(IADWorkflowBL.class); private WorkflowId p_AD_Worlflow_ID; /** * Prepare */ @Override protected void prepare() { p_AD_Worlflow_ID = WorkflowId.ofRepoId(getRecord_ID()); } @Override protected String doIt() {
final I_AD_Workflow workflow = load(p_AD_Worlflow_ID, I_AD_Workflow.class); Check.assumeNotNull(workflow, "Parameter workflow is not null"); final String errorMsg = workflowBL.validateAndGetErrorMsg(workflow); // Make sure IsValid state is saved InterfaceWrapperHelper.save(workflow); if (Check.isEmpty(errorMsg, true)) { return MSG_OK; } else { return "@Error@: " + errorMsg; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\wf\WorkflowValidate.java
1
请完成以下Java代码
private void createLogEntry( @NonNull final BusinessRuleLogLevel level, @Nullable final Duration duration, @Nullable final String message, @Nullable final Object[] args) { final Object[] argsNorm; final AdIssueId errorId; if (args != null && args.length > 0 && args[args.length - 1] instanceof Throwable) { // Remove exception from args array final AdempiereException exception = AdempiereException.wrapIfNeeded((Throwable)args[args.length - 1]); errorId = errorManager.createIssue(exception); argsNorm = new Object[args.length - 1]; System.arraycopy(args, 0, argsNorm, 0, argsNorm.length); } else { argsNorm = args; errorId = null; } final BusinessRuleLoggerContext context = contextHolder.get(); logRepository.create(BusinessRuleLogEntryRequest.fromContext(context) .level(level) .message(MessageFormatter.format(message, argsNorm)) .errorId(errorId) .duration(duration) .build()); } public IAutoCloseable temporaryChangeContext(@NonNull final Consumer<BusinessRuleLoggerContextBuilder> updater) { final BusinessRuleLoggerContext previousContext = contextHolder.get(); final BusinessRuleLoggerContext newContext = previousContext.newChild(updater); contextHolder.set(newContext); return () -> contextHolder.set(previousContext); } public void setTargetRecordRef(@Nullable final TableRecordReference recordRef) { changeContext(context -> context.withTargetRecordRef(recordRef)); } public void setRootTargetRecordRef(@Nullable final TableRecordReference rootRecordRef) { changeContext(context -> context.withRootTargetRecordRef(rootRecordRef));
} public BusinessRuleStopwatch newStopwatch() { return BusinessRuleStopwatch.createStarted(); } private void changeContext(@NonNull final UnaryOperator<BusinessRuleLoggerContext> updater) { final BusinessRuleLoggerContext previousContext = contextHolder.get(); if (previousContext.isRootContext()) { throw new AdempiereException("Changing root context not allowed. Use temporaryChangeContext() instead"); } final BusinessRuleLoggerContext newContext = updater.apply(previousContext); contextHolder.set(newContext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\log\BusinessRuleLogger.java
1
请在Spring Boot框架中完成以下Java代码
public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } @Override public String toString() { return "RpMicroSubmitRecord{" + "businessCode='" + businessCode + '\'' + ", subMchId='" + subMchId + '\'' + ", idCardCopy='" + idCardCopy + '\'' + ", idCardNational='" + idCardNational + '\'' + ", idCardName='" + idCardName + '\'' + ", idCardNumber='" + idCardNumber + '\'' + ", idCardValidTime='" + idCardValidTime + '\'' + ", accountBank='" + accountBank + '\'' + ", bankAddressCode='" + bankAddressCode + '\'' + ", accountNumber='" + accountNumber + '\'' +
", storeName='" + storeName + '\'' + ", storeAddressCode='" + storeAddressCode + '\'' + ", storeStreet='" + storeStreet + '\'' + ", storeEntrancePic='" + storeEntrancePic + '\'' + ", indoorPic='" + indoorPic + '\'' + ", merchantShortname='" + merchantShortname + '\'' + ", servicePhone='" + servicePhone + '\'' + ", productDesc='" + productDesc + '\'' + ", rate='" + rate + '\'' + ", contactPhone='" + contactPhone + '\'' + ", idCardValidTimeBegin='" + idCardValidTimeBegin + '\'' + ", idCardValidTimeEnd='" + idCardValidTimeEnd + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpMicroSubmitRecord.java
2
请完成以下Java代码
public class SpringTransactionInterceptor extends AbstractCommandInterceptor { private static final Logger LOGGER = LoggerFactory.getLogger(SpringTransactionInterceptor.class); protected PlatformTransactionManager transactionManager; public SpringTransactionInterceptor(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public <T> T execute(final CommandConfig config, final Command<T> command) { LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation()); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setPropagationBehavior(getPropagation(config)); T result = transactionTemplate.execute( new TransactionCallback<T>() { public T doInTransaction(TransactionStatus status) { return next.execute(config, command); } } );
return result; } private int getPropagation(CommandConfig config) { switch (config.getTransactionPropagation()) { case NOT_SUPPORTED: return TransactionTemplate.PROPAGATION_NOT_SUPPORTED; case REQUIRED: return TransactionTemplate.PROPAGATION_REQUIRED; case REQUIRES_NEW: return TransactionTemplate.PROPAGATION_REQUIRES_NEW; default: throw new ActivitiIllegalArgumentException( "Unsupported transaction propagation: " + config.getTransactionPropagation() ); } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionInterceptor.java
1
请完成以下Java代码
public boolean isOpen() { return readableChannel.isOpen(); } @Override public void close() throws IOException { closeThenDeleteFile(readableChannel); } @Override public int read(ByteBuffer dst) throws IOException { return readableChannel.read(dst); } }; } @Override public InputStream getInputStream() throws IOException { return new FilterInputStream(super.getInputStream()) { @Override public void close() throws IOException { closeThenDeleteFile(this.in); } }; } private void closeThenDeleteFile(Closeable closeable) throws IOException { try { closeable.close(); } finally { deleteFile();
} } private void deleteFile() { try { Files.delete(getFile().toPath()); } catch (IOException ex) { TemporaryFileSystemResource.this.logger .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } @Override public boolean isFile() { // Prevent zero-copy so we can delete the file on close return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
public class UserRepositoryUserDetailsService implements UserDetailsService { private final UserRepository userRepository; @Autowired public UserRepositoryUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } /* * @see * org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername * (java.lang.String) */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.userRepository.findByEmail(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } return new CustomUserDetails(user); } private static final class CustomUserDetails extends User implements UserDetails { private CustomUserDetails(User user) { super(user); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return AuthorityUtils.createAuthorityList("ROLE_USER"); } @Override public String getUsername() { return getEmail(); } @Override public boolean isAccountNonExpired() {
return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } private static final long serialVersionUID = 5639683223516504866L; } }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\security\UserRepositoryUserDetailsService.java
2
请完成以下Java代码
private String getFrontendURL(@NonNull final String pathSysConfigName, final Map<String, Object> params) { String url = getFrontendURL(); if (url == null) { return null; } final String path = StringUtils.trimBlankToNull(sysConfigBL.getValue(pathSysConfigName, defaultsBySysConfigName.get(pathSysConfigName))); if (path == null || "-".equals(path)) { return null; } url = url + path; if (params != null && !params.isEmpty()) { url = MapFormat.format(url, params); } return url; } @Nullable public String getDocumentUrl(@NonNull final AdWindowId windowId, final int documentId) { return getDocumentUrl(String.valueOf(windowId.getRepoId()), String.valueOf(documentId)); } @Nullable public String getDocumentUrl(@NonNull final String windowId, @NonNull final String documentId) { return getFrontendURL(SYSCONFIG_DOCUMENT_PATH, ImmutableMap.<String, Object>builder() .put(WebuiURLs.PARAM_windowId, windowId) .put(WebuiURLs.PARAM_documentId, documentId) .build()); } @Nullable public String getViewUrl(@NonNull final AdWindowId adWindowId, @NonNull final String viewId) { return getViewUrl(String.valueOf(adWindowId.getRepoId()), viewId); } @Nullable public String getViewUrl(@NonNull final String windowId, @NonNull final String viewId) { return getFrontendURL(SYSCONFIG_VIEW_PATH, ImmutableMap.<String, Object>builder() .put(PARAM_windowId, windowId) .put(PARAM_viewId, viewId) .build()); }
@Nullable public String getResetPasswordUrl(final String token) { Check.assumeNotEmpty(token, "token is not empty"); return getFrontendURL(SYSCONFIG_RESET_PASSWORD_PATH, ImmutableMap.<String, Object>builder() .put(PARAM_ResetPasswordToken, token) .build()); } public boolean isCrossSiteUsageAllowed() { return sysConfigBL.getBooleanValue(SYSCONFIG_IsCrossSiteUsageAllowed, false); } public String getAppApiUrl() { final String url = StringUtils.trimBlankToNull(sysConfigBL.getValue(SYSCONFIG_APP_API_URL)); if (url != null && !url.equals("-")) { return url; } final String frontendUrl = getFrontendURL(); if (frontendUrl != null) { return frontendUrl + "/app"; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui\web\WebuiURLs.java
1
请在Spring Boot框架中完成以下Java代码
public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the freetextqual property. * * @return * possible object is * {@link String } * */ public String getFREETEXTQUAL() { return freetextqual; } /** * Sets the value of the freetextqual property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTQUAL(String value) { this.freetextqual = value; } /** * Gets the value of the freetext property. * * @return * possible object is * {@link String } * */ public String getFREETEXT() { return freetext; } /** * Sets the value of the freetext property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXT(String value) { this.freetext = value; } /** * Gets the value of the freetextcode property. * * @return * possible object is
* {@link String } * */ public String getFREETEXTCODE() { return freetextcode; } /** * Sets the value of the freetextcode property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTCODE(String value) { this.freetextcode = value; } /** * Gets the value of the freetextlanguage property. * * @return * possible object is * {@link String } * */ public String getFREETEXTLANGUAGE() { return freetextlanguage; } /** * Sets the value of the freetextlanguage property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTLANGUAGE(String value) { this.freetextlanguage = value; } /** * Gets the value of the freetextfunction property. * * @return * possible object is * {@link String } * */ public String getFREETEXTFUNCTION() { return freetextfunction; } /** * Sets the value of the freetextfunction property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTFUNCTION(String value) { this.freetextfunction = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HTEXT1.java
2
请完成以下Java代码
public OAuth2TokenClaimsSet.Builder getClaims() { return get(OAuth2TokenClaimsSet.Builder.class); } /** * Constructs a new {@link Builder} with the provided claims. * @param claimsBuilder the claims to initialize the builder * @return the {@link Builder} */ public static Builder with(OAuth2TokenClaimsSet.Builder claimsBuilder) { return new Builder(claimsBuilder); } /** * A builder for {@link OAuth2TokenClaimsContext}. */ public static final class Builder extends AbstractBuilder<OAuth2TokenClaimsContext, Builder> { private Builder(OAuth2TokenClaimsSet.Builder claimsBuilder) {
Assert.notNull(claimsBuilder, "claimsBuilder cannot be null"); put(OAuth2TokenClaimsSet.Builder.class, claimsBuilder); } /** * Builds a new {@link OAuth2TokenClaimsContext}. * @return the {@link OAuth2TokenClaimsContext} */ @Override public OAuth2TokenClaimsContext build() { return new OAuth2TokenClaimsContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsContext.java
1
请完成以下Java代码
public PublicKeyCredentialBuilder id(String id) { this.id = id; return this; } /** * Sets the {@link #getType()} property. * @param type the type * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder type(PublicKeyCredentialType type) { this.type = type; return this; } /** * Sets the {@link #getRawId()} property. * @param rawId the raw id * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder rawId(Bytes rawId) { this.rawId = rawId; return this; } /** * Sets the {@link #getResponse()} property. * @param response the response * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder response(R response) { this.response = response; return this; } /** * Sets the {@link #getAuthenticatorAttachment()} property. * @param authenticatorAttachment the authenticator attachement * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder authenticatorAttachment(AuthenticatorAttachment authenticatorAttachment) { this.authenticatorAttachment = authenticatorAttachment; return this;
} /** * Sets the {@link #getClientExtensionResults()} property. * @param clientExtensionResults the client extension results * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder clientExtensionResults( AuthenticationExtensionsClientOutputs clientExtensionResults) { this.clientExtensionResults = clientExtensionResults; return this; } /** * Creates a new {@link PublicKeyCredential} * @return a new {@link PublicKeyCredential} */ public PublicKeyCredential<R> build() { Assert.notNull(this.id, "id cannot be null"); Assert.notNull(this.rawId, "rawId cannot be null"); Assert.notNull(this.response, "response cannot be null"); return new PublicKeyCredential(this.id, this.type, this.rawId, this.response, this.authenticatorAttachment, this.clientExtensionResults); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredential.java
1
请完成以下Java代码
public class Question { private String question; private int balance; public Question(String question, int balance) { this.question = question; this.balance = balance; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question;
} public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } public String toString() { return "Question(question=" + question + ", balance=" + balance + ")"; } }
repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\model\Question.java
1
请在Spring Boot框架中完成以下Java代码
private ExternalSystemServiceInstance getInstanceByConfigIdAndServiceId(@NonNull final ExternalSystemParentConfigId configId, @NonNull final ExternalSystemServiceId serviceId) { return serviceInstanceRepo.getByConfigAndServiceId(configId, serviceId) .orElseThrow(() -> new AdempiereException("No ExternalSystemServiceInstance found by given configId and serviceId!") .appendParametersToMessage() .setParameter("ExternalSystemConfigId", configId) .setParameter("ExternalSystemServiceId", serviceId)); } @NonNull private ExternalSystemServiceModel getServiceNotNull(@NonNull final String serviceValue) { return serviceRepo.getByValue(serviceValue) .orElseThrow(() -> new AdempiereException("No ExternalSystemService found by given value!") .appendParametersToMessage() .setParameter("ExternalSystemService.value", serviceValue)); } private void createInstanceIfRequired(@NonNull final ExternalSystemParentConfigId configId, @NonNull final String command) { final String parentConfigType = externalSystemConfigRepo.getParentTypeById(configId); getServiceByTypeAndCommand(ExternalSystemType.ofValue(parentConfigType), command) .map(service -> CreateServiceInstanceRequest.builder() .configId(configId) .serviceId(service.getId()) .expectedStatus(service.getStatusByCommand(command)) .build()) .ifPresent(serviceInstanceRepo::create); } @NonNull private Optional<ExternalSystemServiceModel> getServiceByTypeAndCommand(@NonNull final ExternalSystemType type, @NonNull final String command) { final List<ExternalSystemServiceModel> externalSystemServices = serviceRepo.getAllByType(type)
.stream() .filter(service -> service.matchesCommand(command)) .collect(ImmutableList.toImmutableList()); if (externalSystemServices.size() > 1) { //dev-note: should never happen hence "command" is an InvokeExternalSystemProcess#externalRequest meant to uniquely identify a camel service route throw new AdempiereException("More than one ExternalSystemService found for given type and command! This is most probably a misconfiguration issue.") .appendParametersToMessage() .setParameter("type", type) .setParameter("command", command); } if (externalSystemServices.isEmpty()) { return Optional.empty(); } return Optional.of(externalSystemServices.get(0)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\ExternalServices.java
2
请完成以下Java代码
public static BufferedImage modifiedQRCode(BitMatrix matrix, String topText, String bottomText) throws IOException { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, matrixWidth, matrixHeight); graphics.setColor(Color.BLACK); for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixHeight; j++) { if (matrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } FontMetrics fontMetrics = graphics.getFontMetrics(); int topTextWidth = fontMetrics.stringWidth(topText);
int bottomTextWidth = fontMetrics.stringWidth(bottomText); int finalWidth = Math.max(matrixWidth, Math.max(topTextWidth, bottomTextWidth)) + 1; int finalHeight = matrixHeight + fontMetrics.getHeight() + fontMetrics.getAscent() + 1; BufferedImage finalImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB); Graphics2D finalGraphics = finalImage.createGraphics(); finalGraphics.setColor(Color.WHITE); finalGraphics.fillRect(0, 0, finalWidth, finalHeight); finalGraphics.setColor(Color.BLACK); finalGraphics.drawImage(image, (finalWidth - matrixWidth) / 2, fontMetrics.getAscent() + 2, null); finalGraphics.drawString(topText, (finalWidth - topTextWidth) / 2, fontMetrics.getAscent() + 2); finalGraphics.drawString(bottomText, (finalWidth - bottomTextWidth) / 2, finalHeight - fontMetrics.getDescent() - 2); return finalImage; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\generators\ZxingBarcodeGeneratorWithText.java
1
请完成以下Java代码
public boolean isOracle() { return dbSqlSessionFactory.getDatabaseType().equals("oracle"); } // query factory methods // //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ModelQueryImpl createModelQueryImpl() { return new ModelQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); } public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl();
} public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); } public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请完成以下Java代码
public String getFunctionPrefix () { return (String)get_Value(COLUMNNAME_FunctionPrefix); } /** Set Function Suffix. @param FunctionSuffix Data sent after the function */ public void setFunctionSuffix (String FunctionSuffix) { set_Value (COLUMNNAME_FunctionSuffix, FunctionSuffix); } /** Get Function Suffix. @return Data sent after the function */ public String getFunctionSuffix () { return (String)get_Value(COLUMNNAME_FunctionSuffix); } /** Set XY Position. @param IsXYPosition The Function is XY position */ public void setIsXYPosition (boolean IsXYPosition) { set_Value (COLUMNNAME_IsXYPosition, Boolean.valueOf(IsXYPosition)); } /** Get XY Position. @return The Function is XY position */ public boolean isXYPosition () { Object oo = get_Value(COLUMNNAME_IsXYPosition); 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 XY Separator. @param XYSeparator The separator between the X and Y function. */ public void setXYSeparator (String XYSeparator) { set_Value (COLUMNNAME_XYSeparator, XYSeparator); } /** Get XY Separator. @return The separator between the X and Y function. */ public String getXYSeparator () { return (String)get_Value(COLUMNNAME_XYSeparator); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java
1
请完成以下Java代码
public void iterateParallel() { list.forEach(System.out::print); System.out.print(" "); list.parallelStream().forEach(System.out::print); } public void iterateReverse() { List<String> myList = new ReverseList(); myList.addAll(list); myList.forEach(System.out::print); System.out.print(" "); myList.stream().forEach(System.out::print); } public void removeInCollectionForEach() { list.forEach(removeElement);
} public void removeInStreamForEach() { list.stream().forEach(removeElement); } public static void main(String[] argv) { ReverseList collectionForEach = new ReverseList(); collectionForEach.iterateParallel(); collectionForEach.iterateReverse(); collectionForEach.removeInCollectionForEach(); collectionForEach.removeInStreamForEach(); } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\forEach\ReverseList.java
1
请完成以下Java代码
public final class WindowMaxQueryRecordsConstraint extends Constraint { public static WindowMaxQueryRecordsConstraint of(final int maxQueryRecordsPerRole, final int confirmQueryRecords) { return new WindowMaxQueryRecordsConstraint(maxQueryRecordsPerRole, confirmQueryRecords); } private static final int DEFAULT_MaxQueryRecordsPerTab = 0; // i.e. infinite private static final int DEFAULT_ConfirmQueryRecords = 500; public static final WindowMaxQueryRecordsConstraint DEFAULT = new WindowMaxQueryRecordsConstraint(DEFAULT_MaxQueryRecordsPerTab, DEFAULT_ConfirmQueryRecords); private final int maxQueryRecordsPerRole; private final int confirmQueryRecords; private WindowMaxQueryRecordsConstraint(final int maxQueryRecordsPerRole, final int confirmQueryRecords) { this.maxQueryRecordsPerRole = Math.max(maxQueryRecordsPerRole, 0); // NOTE: instead of throw exception it's better to fallback to default. Else, all our roles on will fail now. // Before changing this, please make sure u check AD_Role.ConfirmQueryRecords. // Check.assume(confirmQueryRecords > 0, "confirmQueryRecords > 0 but it was {}", confirmQueryRecords); this.confirmQueryRecords = confirmQueryRecords <= 0 ? DEFAULT_ConfirmQueryRecords : confirmQueryRecords; } @Override public String toString() { // NOTE: we are making it translatable friendly because it's displayed in Preferences->Info->Role final int queryRecordsPerRole = getMaxQueryRecordsPerRole(); final int confirmQueryRecords = getConfirmQueryRecords(); return "WindowMaxQueryRecords[" + "@MaxQueryRecords@: " + queryRecordsPerRole + ", @ConfirmQueryRecords@: " + confirmQueryRecords + "]"; }
/** @return false, i.e. never inherit this constraint because it shall be defined by current role itself */ @Override public boolean isInheritable() { return false; } /** * @return maximum allowed rows to be presented to user in a window or ZERO if no restriction. */ public int getMaxQueryRecordsPerRole() { return maxQueryRecordsPerRole; } /** * Gets the maximum allowed records to be presented to user, without asking him to confirm/refine the initial query. * * @return maximum allowed records to be presented to user, without asking him to confirm/refine the initial query; always returns greater than zero. */ public int getConfirmQueryRecords() { return confirmQueryRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\WindowMaxQueryRecordsConstraint.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringAsyncConfig implements AsyncConfigurer { /** * Defines a custom Executor used by @Async("threadPoolTaskExecutor") calls. */ @Bean(name = "threadPoolTaskExecutor") public Executor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); executor.setThreadNamePrefix("CustomPool-"); executor.initialize(); return executor; } /** * Defines the default Executor used by un-named @Async calls. */ @Override public Executor getAsyncExecutor() { // You could return the named bean here, or create a new one.
// Creating a new one for demonstration purposes. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(4); executor.setThreadNamePrefix("DefaultAsync-"); executor.initialize(); return executor; } /** * Defines the exception handler for asynchronous method calls. */ @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new CustomAsyncExceptionHandler(); } }
repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\async\config\SpringAsyncConfig.java
2
请完成以下Java代码
private static final OnVariableNotFound getOnVariableNotFoundForInternalParameter(final OnVariableNotFound onVariableNotFound) { switch (onVariableNotFound) { case Preserve: // Preserve is not supported because we don't know which expression to pick if the deciding parameter is not determined return OnVariableNotFound.Fail; default: return onVariableNotFound; } } @Override public IStringExpression resolvePartial(final Evaluatee ctx) { try { boolean changed = false; final IStringExpression expressionBaseLangNew = expressionBaseLang.resolvePartial(ctx); if (!expressionBaseLang.equals(expressionBaseLangNew)) { changed = true; } final IStringExpression expressionTrlNew = expressionTrl.resolvePartial(Evaluatees.excludingVariables(ctx, adLanguageParam.getName())); if (!changed && !expressionTrl.equals(expressionTrlNew))
{ changed = true; } if (!changed) { return this; } return new TranslatableParameterizedStringExpression(adLanguageParam, expressionBaseLangNew, expressionTrlNew); } catch (final Exception e) { throw ExpressionEvaluationException.wrapIfNeeded(e) .addExpression(this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\TranslatableParameterizedStringExpression.java
1
请完成以下Spring Boot application配置
spring: application: name: sc-user-service # Spring 应用名 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 soul: # Soul 针对 SpringMVC 的配置项,对应 SoulSpringCloudConfig 配置类 springcloud: admin-url: http://127.0.0.1:9095 # Soul Admin 地址 context-path: /sc-user-service-api # 设置在 Soul 网关的
路由前缀,例如说 /order、/product 等等。 # 后续,网关会根据该 context-path 来进行路由 app-name: sc-user-service # 应用名。未配置情况下,默认使用 `spring.application.name` 配置项
repos\SpringBoot-Labs-master\lab-60\lab-60-soul-spring-cloud-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw) { ppOrder.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw); } @Override public BigDecimal getQM_QtyDeliveredPercOfRaw() { return ppOrder.getQM_QtyDeliveredPercOfRaw(); } @Override public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg) { ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg); } @Override public BigDecimal getQM_QtyDeliveredAvg() { return ppOrder.getQM_QtyDeliveredAvg(); } @Override public Object getModel() { return ppOrder; } @Override public String getVariantGroup() { return null; } @Override public BOMComponentType getComponentType() { return null;
} @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { if (!_handlingUnitsInfoLoaded) { _handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder); _handlingUnitsInfoLoaded = true; } return _handlingUnitsInfo; } @Override public I_M_Product getMainComponentProduct() { // there is no substitute for a produced material return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java
1
请完成以下Java代码
public void setModel(String model) { this.model = model; } } @JsonIgnoreProperties({ "model", "seatingCapacity" }) public static abstract class Car extends Vehicle { private int seatingCapacity; @JsonIgnore private double topSpeed; protected Car() { } protected Car(String make, String model, int seatingCapacity, double topSpeed) { super(make, model); this.seatingCapacity = seatingCapacity; this.topSpeed = topSpeed; } public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed;
} } public static class Sedan extends Car { public Sedan() { } public Sedan(String make, String model, int seatingCapacity, double topSpeed) { super(make, model, seatingCapacity, topSpeed); } } public static class Crossover extends Car { private double towingCapacity; public Crossover() { } public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) { super(make, model, seatingCapacity, topSpeed); this.towingCapacity = towingCapacity; } public double getTowingCapacity() { return towingCapacity; } public void setTowingCapacity(double towingCapacity) { this.towingCapacity = towingCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\IgnoranceAnnotationStructure.java
1
请在Spring Boot框架中完成以下Java代码
public class PackagingCodeId implements RepoIdAware { @JsonCreator public static PackagingCodeId ofRepoId(final int repoId) { return new PackagingCodeId(repoId); } public static PackagingCodeId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final PackagingCodeId packagingCodeId) { return packagingCodeId != null ? packagingCodeId.getRepoId() : -1; }
int repoId; private PackagingCodeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PackagingCode"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\PackagingCodeId.java
2
请完成以下Java代码
public Builder setDevices(@NonNull final DeviceDescriptorsList devices) { this._devices = devices; return this; } private DeviceDescriptorsList getDevices() { return _devices; } public Builder setSupportZoomInto(final boolean supportZoomInto) { this.supportZoomInto = supportZoomInto; return this; }
private boolean isSupportZoomInto() { return supportZoomInto; } public Builder setForbidNewRecordCreation(final boolean forbidNewRecordCreation) { this.forbidNewRecordCreation = forbidNewRecordCreation; return this; } private boolean isForbidNewRecordCreation() { return forbidNewRecordCreation; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementFieldDescriptor.java
1
请完成以下Java代码
private void updateOrderLineRecord( @NonNull final OrderLineId orderLineId, @NonNull final Quantities quantities, @NonNull final ColorId insufficientQtyAvailableForSalesColorId) { final I_C_OrderLine salesOrderLineRecord = ordersDAO.getOrderLineById(orderLineId, I_C_OrderLine.class); // We do everything in the order line's UOM right from the start in order to depend on QtyEntered as opposed to QtyOrdered. // Because QtyEntered is what the user can see.. (who knows, QtyOrdered might even be zero in some cases) final ProductId productId = ProductId.ofRepoId(salesOrderLineRecord.getM_Product_ID()); final Quantity qtyToBeShippedInOrderLineUOM = orderLineBL.convertQtyToUOM(Quantitys.of(quantities.getQtyToBeShipped(), productId), salesOrderLineRecord); final Quantity qtyOnHandInOrderLineUOM = orderLineBL.convertQtyToUOM(Quantitys.of(quantities.getQtyOnHandStock(), productId), salesOrderLineRecord); // QtyToBeShippedInOrderLineUOM includes the salesOrderLineRecord.getQtyEntered(). // We subtract it again to make it comparable with the orderLine's qtyOrdered. final BigDecimal qtyToBeShippedEff = qtyToBeShippedInOrderLineUOM.toBigDecimal().subtract(salesOrderLineRecord.getQtyEntered()); final BigDecimal qtyAvailableForSales = qtyOnHandInOrderLineUOM.toBigDecimal().subtract(qtyToBeShippedEff); salesOrderLineRecord.setQtyAvailableForSales(qtyAvailableForSales); if (qtyAvailableForSales.compareTo(salesOrderLineRecord.getQtyEntered()) < 0) { salesOrderLineRecord.setInsufficientQtyAvailableForSalesColor_ID(insufficientQtyAvailableForSalesColorId.getRepoId()); } else { salesOrderLineRecord.setInsufficientQtyAvailableForSalesColor(null); } ordersDAO.save(salesOrderLineRecord); } @NonNull private Quantities computeQuantitiesForQuery(@Nullable final List<AvailableForSalesResult> results) { if (results == null) {
return Quantities.builder() .qtyOnHandStock(BigDecimal.ZERO) .qtyToBeShipped(BigDecimal.ZERO) .build(); } final BigDecimal qtyOnHandStock = results .stream() .map(AvailableForSalesResult::getQuantities) .map(Quantities::getQtyOnHandStock) .reduce(BigDecimal.ZERO, BigDecimal::add); final BigDecimal qtyToBeShipped = results .stream() .map(AvailableForSalesResult::getQuantities) .map(Quantities::getQtyToBeShipped) .reduce(BigDecimal.ZERO, BigDecimal::add); return Quantities.builder() .qtyOnHandStock(qtyOnHandStock) .qtyToBeShipped(qtyToBeShipped) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\interceptor\AvailableForSalesUtil.java
1
请在Spring Boot框架中完成以下Java代码
public void setWithoutDueDate(Boolean withoutDueDate) { this.withoutDueDate = withoutDueDate; } public Boolean getWithoutDueDate() { return withoutDueDate; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLike() { return tenantIdLike; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public Boolean getWithoutProcessInstanceId() { return withoutProcessInstanceId; } public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) { this.withoutProcessInstanceId = withoutProcessInstanceId; } public String getCandidateOrAssigned() { return candidateOrAssigned; } public void setCandidateOrAssigned(String candidateOrAssigned) { this.candidateOrAssigned = candidateOrAssigned; } public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; } public List<String> getCategoryIn() { return categoryIn; } public void setCategoryIn(List<String> categoryIn) { this.categoryIn = categoryIn; } public List<String> getCategoryNotIn() { return categoryNotIn; } public void setCategoryNotIn(List<String> categoryNotIn) { this.categoryNotIn = categoryNotIn; } public Boolean getWithoutCategory() { return withoutCategory; } public void setWithoutCategory(Boolean withoutCategory) { this.withoutCategory = withoutCategory; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java
2
请完成以下Java代码
public static void main(String[] args) { org.compiere.Adempiere.startupEnvironment(true); Color[] colors = new Color[] {Color.black, Color.red, Color.green, Color.blue, Color.darkGray, Color.gray, Color.lightGray, Color.white, Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow, SystemColor.textHighlight}; String[] names = new String[] {"Black", "Red", "Green", "Blue", "Gray dark", "Gray", "Gray light", "White", "Cyan", "Magenta", "Orange", "Pink", "Yellow", "Blue dark"}; for (int i = 0; i < colors.length; i++) System.out.println(names[i] + " = " + colors[i] + " RGB=" + colors[i].getRGB() + " -> " + new Color(colors[i].getRGB(), false) + " -> " + new Color(colors[i].getRGB(), true)); /** // Create Colors for (int i = 0; i < colors.length; i++) create(colors[i], names[i]); create(whiteGray, "Gray white"); create(darkGreen, "Green dark"); create(blackGreen, "Green black");
create(blackBlue, "Blue black"); create(brown, "Brown"); create(darkBrown, "Brown dark"); **/ // Read All Colors int[] IDs = PO.getAllIDs ("AD_PrintColor", null, null); for (int i = 0; i < IDs.length; i++) { MPrintColor pc = new MPrintColor(Env.getCtx(), IDs[i], null); System.out.println(IDs[i] + ": " + pc + " = " + pc.getColor() + ", RGB=" + pc.getColor().getRGB()); } } // main } // MPrintColor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintColor.java
1
请完成以下Java代码
public final class IOStreamUtils { public static String toString(@NonNull final InputStream in) { return new String(toByteArray(in), StandardCharsets.UTF_8); } public static byte[] toByteArray(@NonNull final InputStream in) throws RuntimeException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { final byte[] buf = new byte[1024 * 4]; int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final IOException e) { throw new RuntimeException(e); } return out.toByteArray(); } /** * Close given closeable stream. * * No errors will be thrown. * * @param closeable */ public static void close(final Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (final IOException e) { e.printStackTrace(); } } /** * Close all given input streams. * * No errors will be thrown.
* * @param closeables */ public static void close(final Closeable... closeables) { if (closeables == null || closeables.length == 0) { return; } for (final Closeable closeable : closeables) { close(closeable); } } /** * Copy data from input stream to output stream. * * NOTE: no matter what, both streams are closed after this call. * * @throws RuntimeException if something fails */ public static void copy(@NonNull final OutputStream out, @NonNull final InputStream in) { try { final byte[] buf = new byte[4 * 1024]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final IOException e) { throw new RuntimeException(e.getLocalizedMessage(), e); } finally { close(out); close(in); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\IOStreamUtils.java
1
请完成以下Java代码
public void warnReservedErrorCode(int initialCode) { logWarn("048", "With error code {} you are using a reserved error code. Falling back to default error code 0. " + "If you want to override built-in error codes, please disable the built-in error code provider.", initialCode); } public void warnResetToBuiltinCode(Integer builtinCode, int initialCode) { logWarn("049", "You are trying to override the built-in code {} with {}. " + "Falling back to built-in code. If you want to override built-in error codes, " + "please disable the built-in error code provider.", builtinCode, initialCode); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoJobsSpecified() { return new ProcessEngineException(exceptionMessage( "050", "You must specify at least one of jobIds or jobQuery.")); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoProcessesSpecified() { return new ProcessEngineException(exceptionMessage( "051", "You must specify at least one of or one of processInstanceIds, processInstanceQuery, or historicProcessInstanceQuery.")); } public ProcessEngineException exceptionSettingJobRetriesJobsNotSpecifiedCorrectly() { return new ProcessEngineException(exceptionMessage(
"052", "You must specify exactly one of jobId, jobIds or jobDefinitionId as parameter. The parameter can not be null.")); } public ProcessEngineException exceptionNoJobFoundForId(String jobId) { return new ProcessEngineException(exceptionMessage( "053", "No job found with id '{}'.'", jobId)); } public ProcessEngineException exceptionJobRetriesMustNotBeNegative(Integer retries) { return new ProcessEngineException(exceptionMessage( "054", "The number of job retries must be a non-negative Integer, but '{}' has been provided.", retries)); } public ProcessEngineException exceptionWhileRetrievingDiagnosticsDataRegistryNull() { return new ProcessEngineException( exceptionMessage("055", "Error while retrieving diagnostics data. Diagnostics registry was not initialized.")); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CommandLogger.java
1
请完成以下Java代码
public String getEntityType(String uuid) { return this.allEntityIdsAndTypes.get(uuid); } private boolean isBlockFinished(String line) { return StringUtils.isBlank(line) || line.equals("\\."); } private void processAllTables(LineIterator lineIterator) throws IOException { String currentLine; try { while (lineIterator.hasNext()) { currentLine = lineIterator.nextLine(); for(Map.Entry<String, EntityType> entry : tableNameAndEntityType.entrySet()) { if(currentLine.startsWith(entry.getKey())) { processBlock(lineIterator, entry.getValue()); }
} } } finally { lineIterator.close(); } } private void processBlock(LineIterator lineIterator, EntityType entityType) { String currentLine; while(lineIterator.hasNext()) { currentLine = lineIterator.nextLine(); if(isBlockFinished(currentLine)) { return; } allEntityIdsAndTypes.put(currentLine.split("\t")[0], entityType.name()); } } }
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\RelatedEntitiesParser.java
1
请完成以下Java代码
public RuleChainId getRootRuleChainId() { return this.rootRuleChainId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge") @Override public String getName() { return this.name; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos") public String getType() { return this.type; } @Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field")
public String getLabel() { return this.label; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud") public String getRoutingKey() { return this.routingKey; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud") public String getSecret() { return this.secret; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java
1
请完成以下Java代码
public class MaterialCockpitView extends AbstractCustomView<MaterialCockpitRow> { public static MaterialCockpitView cast(final IView view) { return (MaterialCockpitView)view; } private final DocumentFilterList filters; private final List<RelatedProcessDescriptor> relatedProcessDescriptors; @Builder private MaterialCockpitView( @NonNull final ViewId viewId, @NonNull final ITranslatableString description, @NonNull final IRowsData<MaterialCockpitRow> rowsData, @NonNull final DocumentFilterList filters, @NonNull final DocumentFilterDescriptorsProvider filterDescriptors, @Singular final List<RelatedProcessDescriptor> relatedProcessDescriptors) { super(viewId, description, rowsData, filterDescriptors); this.filters = filters; this.relatedProcessDescriptors = ImmutableList.copyOf(relatedProcessDescriptors); } /** * @return {@code null}, because each record of this view is based on > 1 tables. */ @Override public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override public DocumentFilterList getFilters() {
return filters; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.ofList( ImmutableList.of( DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate), DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_ProductValue)) ); } @Override protected boolean isEligibleInvalidateEvent(final TableRecordReference recordRef) { final String tableName = recordRef.getTableName(); return I_MD_Cockpit.Table_Name.equals(tableName) || I_MD_Stock.Table_Name.equals(tableName); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return relatedProcessDescriptors; } @Override public ViewActionDescriptorsList getActions() { return ViewActionDescriptorsFactory.instance .getFromClass(MD_Cockpit_DocumentDetail_Display.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitView.java
1
请完成以下Java代码
public static Builder builder() { return new Builder(); } /** * A builder for {@link RequestMatcherDelegatingAuthenticationManagerResolver}. */ public static final class Builder { private final List<RequestMatcherEntry<AuthenticationManager>> entries = new ArrayList<>(); private Builder() { } /** * Maps a {@link RequestMatcher} to an {@link AuthorizationManager}. * @param matcher the {@link RequestMatcher} to use * @param manager the {@link AuthenticationManager} to use * @return the {@link Builder} for further * customizationServerWebExchangeDelegatingReactiveAuthenticationManagerResolvers */ public Builder add(RequestMatcher matcher, AuthenticationManager manager) { Assert.notNull(matcher, "matcher cannot be null"); Assert.notNull(manager, "manager cannot be null");
this.entries.add(new RequestMatcherEntry<>(matcher, manager)); return this; } /** * Creates a {@link RequestMatcherDelegatingAuthenticationManagerResolver} * instance. * @return the {@link RequestMatcherDelegatingAuthenticationManagerResolver} * instance */ public RequestMatcherDelegatingAuthenticationManagerResolver build() { return new RequestMatcherDelegatingAuthenticationManagerResolver(this.entries); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\RequestMatcherDelegatingAuthenticationManagerResolver.java
1
请完成以下Java代码
public boolean isPluFileExportAuditEnabled() { return get_ValueAsBoolean(COLUMNNAME_IsPluFileExportAuditEnabled); } /** * PluFileDestination AD_Reference_ID=541911 * Reference name: PluFileDestination */ public static final int PLUFILEDESTINATION_AD_Reference_ID=541911; /** Disk = 2DSK */ public static final String PLUFILEDESTINATION_Disk = "2DSK"; /** TCP = 1TCP */ public static final String PLUFILEDESTINATION_TCP = "1TCP"; @Override public void setPluFileDestination (final java.lang.String PluFileDestination) { set_Value (COLUMNNAME_PluFileDestination, PluFileDestination); } @Override public java.lang.String getPluFileDestination() { return get_ValueAsString(COLUMNNAME_PluFileDestination); } @Override public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder) { set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder); } @Override public java.lang.String getPluFileLocalFolder() { return get_ValueAsString(COLUMNNAME_PluFileLocalFolder); } @Override public void setProduct_BaseFolderName (final String Product_BaseFolderName) { set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName); } @Override public String getProduct_BaseFolderName() {
return get_ValueAsString(COLUMNNAME_Product_BaseFolderName); } @Override public void setTCP_Host (final String TCP_Host) { set_Value (COLUMNNAME_TCP_Host, TCP_Host); } @Override public String getTCP_Host() { return get_ValueAsString(COLUMNNAME_TCP_Host); } @Override public void setTCP_PortNumber (final int TCP_PortNumber) { set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber); } @Override public int getTCP_PortNumber() { return get_ValueAsInt(COLUMNNAME_TCP_PortNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
1
请完成以下Java代码
public class Size { private Double height; private Double width; private String uom; public Size(Double height, Double width, String uom) { this.height = height; this.width = width; this.uom = uom; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public Double getWidth() { return width; } public void setWidth(Double width) { this.width = width; } public String getUom() { return uom; }
public void setUom(String uom) { this.uom = uom; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Size size = (Size) o; return Objects.equals(height, size.height) && Objects.equals(width, size.width) && Objects.equals(uom, size.uom); } @Override public int hashCode() { return Objects.hash(height, width, uom); } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\Size.java
1
请完成以下Java代码
public abstract class NeedsActiveTaskCmd<T> implements Command<T>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; public NeedsActiveTaskCmd(String taskId) { this.taskId = taskId; } public T execute(CommandContext commandContext) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } TaskEntity task = commandContext.getTaskEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class); }
if (task.isSuspended()) { throw new ActivitiException(getSuspendedTaskException()); } return execute(commandContext, task); } /** * Subclasses must implement in this method their normal command logic. The provided task is ensured to be active. */ protected abstract T execute(CommandContext commandContext, TaskEntity task); /** * Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended. */ protected String getSuspendedTaskException() { return "Cannot execute operation: task is suspended"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\NeedsActiveTaskCmd.java
1
请完成以下Java代码
public class RestServiceVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { Router router = Router.router(vertx); router.get("/api/baeldung/articles/article/:id") .handler(this::getArticles); vertx.createHttpServer() .requestHandler(router::accept) .listen(config().getInteger("http.port", 8080), result -> { if (result.succeeded()) { future.complete(); } else { future.fail(result.cause()); }
}); } private void getArticles(RoutingContext routingContext) { String articleId = routingContext.request() .getParam("id"); Article article = new Article(articleId, "This is an intro to vertx", "baeldung", "01-02-2017", 1578); routingContext.response() .putHeader("content-type", "application/json") .setStatusCode(200) .end(Json.encodePrettily(article)); } }
repos\tutorials-master\vertx-modules\vertx\src\main\java\com\baeldung\rest\RestServiceVerticle.java
1
请完成以下Java代码
public class AttributeRestrictedException extends AdempiereException { /** * */ private static final long serialVersionUID = 7812550089813860111L; private static final AdMessageKey MSG = AdMessageKey.of("de.metas.swat.Attribute.attributeRestricted"); private static final AdMessageKey MSG_SOTransaction = AdMessageKey.of("de.metas.swat.SOTrx"); private static final AdMessageKey MSG_POTransaction = AdMessageKey.of("de.metas.swat.POTrx"); /** * * @param ctx * @param isSOTrx * @param attributeValue * @param referenceName name of referenced model on which given attribute value is restricted */
public AttributeRestrictedException(final Properties ctx, final SOTrx soTrx, final AttributeListValue attributeValue, final String referenceName) { super(buildMsg(ctx, soTrx, attributeValue, referenceName)); } private static String buildMsg(Properties ctx, SOTrx soTrx, AttributeListValue attributeValue, final String referenceName) { final boolean isSOTrx = SOTrx.toBoolean(soTrx); final String transactionType = Services.get(IMsgBL.class).getMsg(ctx, (isSOTrx ? MSG_SOTransaction : MSG_POTransaction)); final String adLanguage = Env.getAD_Language(ctx); final String attributeName = Services.get(IAttributesBL.class).getAttributeById(attributeValue.getAttributeId()).getName(); return Services.get(IMsgBL.class).getMsg(adLanguage, MSG, new Object[] { attributeName, referenceName, transactionType }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\exceptions\AttributeRestrictedException.java
1
请完成以下Java代码
void setSeqNo(final int seqNo) { this.seqNo = seqNo; } @Override public int getSeqNo() { return seqNo; } @Override public String getLookupTableName() { return lookupTableName; } void setLookupTableName(final String lookupTableName) { this.lookupTableName = lookupTableName; } @Override public String getLookupColumnName() { return lookupColumnName; } void setLookupColumnName(final String lookupColumnName) { this.lookupColumnName = lookupColumnName; } @Override public String getPrototypeValue()
{ return prototypeValue; } void setPrototypeValue(final String prototypeValue) { this.prototypeValue = prototypeValue; } public int getDisplayType(final int defaultDisplayType) { return displayType > 0 ? displayType : defaultDisplayType; } public int getDisplayType() { return displayType; } void setDisplayType(int displayType) { this.displayType = displayType; } public boolean isSelectionColumn() { return selectionColumn; } public void setSelectionColumn(boolean selectionColumn) { this.selectionColumn = selectionColumn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java
1
请完成以下Java代码
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()); } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
} /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthController { private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class); @Value("${auth.username:sentinel}") private String authUsername; @Value("${auth.password:sentinel}") private String authPassword; @Autowired private AuthService<HttpServletRequest> authService; @PostMapping("/login") public Result<AuthService.AuthUser> login(HttpServletRequest request, String username, String password) { if (StringUtils.isNotBlank(DashboardConfig.getAuthUsername())) { authUsername = DashboardConfig.getAuthUsername(); } if (StringUtils.isNotBlank(DashboardConfig.getAuthPassword())) { authPassword = DashboardConfig.getAuthPassword(); } /* * If auth.username or auth.password is blank(set in application.properties or VM arguments), * auth will pass, as the front side validate the input which can't be blank, * so user can input any username or password(both are not blank) to login in that case. */ if (StringUtils.isNotBlank(authUsername) && !authUsername.equals(username) || StringUtils.isNotBlank(authPassword) && !authPassword.equals(password)) { LOGGER.error("Login failed: Invalid username or password, username=" + username); return Result.ofFail(-1, "Invalid username or password"); } AuthService.AuthUser authUser = new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(username); request.getSession().setAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY, authUser);
return Result.ofSuccess(authUser); } @PostMapping(value = "/logout") public Result<?> logout(HttpServletRequest request) { request.getSession().invalidate(); return Result.ofSuccess(null); } @PostMapping(value = "/check") public Result<?> check(HttpServletRequest request) { AuthService.AuthUser authUser = authService.getAuthUser(request); if (authUser == null) { return Result.ofFail(-1, "Not logged in"); } return Result.ofSuccess(authUser); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AuthController.java
2
请完成以下Java代码
public class QrCodeSettingsEntity extends BaseSqlEntity<QrCodeSettings> { @Column(name = ModelConstants.TENANT_ID_COLUMN, columnDefinition = "uuid") protected UUID tenantId; @Column(name = ModelConstants.QR_CODE_SETTINGS_USE_DEFAULT_APP_PROPERTY) private boolean useDefaultApp; @Column(name = ModelConstants.QR_CODE_SETTINGS_ANDROID_ENABLED_PROPERTY) private boolean androidEnabled; @Column(name = ModelConstants.QR_CODE_SETTINGS_IOS_ENABLED_PROPERTY) private boolean iosEnabled; @Column(name = ModelConstants.QR_CODE_SETTINGS_BUNDLE_ID_PROPERTY) private UUID mobileAppBundleId; @Convert(converter = JsonConverter.class) @Column(name = ModelConstants.QR_CODE_SETTINGS_CONFIG_PROPERTY) private JsonNode qrCodeConfig; public QrCodeSettingsEntity(QrCodeSettings qrCodeSettings) { this.setId(qrCodeSettings.getUuidId()); this.setCreatedTime(qrCodeSettings.getCreatedTime()); this.tenantId = qrCodeSettings.getTenantId().getId(); this.useDefaultApp = qrCodeSettings.isUseDefaultApp(); this.androidEnabled = qrCodeSettings.isAndroidEnabled(); this.iosEnabled = qrCodeSettings.isIosEnabled(); if (qrCodeSettings.getMobileAppBundleId() != null) { this.mobileAppBundleId = qrCodeSettings.getMobileAppBundleId().getId(); } this.qrCodeConfig = toJson(qrCodeSettings.getQrCodeConfig()); }
@Override public QrCodeSettings toData() { QrCodeSettings qrCodeSettings = new QrCodeSettings(new QrCodeSettingsId(getUuid())); qrCodeSettings.setCreatedTime(createdTime); qrCodeSettings.setTenantId(TenantId.fromUUID(tenantId)); qrCodeSettings.setUseDefaultApp(useDefaultApp); qrCodeSettings.setAndroidEnabled(androidEnabled); qrCodeSettings.setIosEnabled(iosEnabled); if (mobileAppBundleId != null) { qrCodeSettings.setMobileAppBundleId(new MobileAppBundleId(mobileAppBundleId)); } qrCodeSettings.setQrCodeConfig(fromJson(qrCodeConfig, QRCodeConfig.class)); return qrCodeSettings; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\QrCodeSettingsEntity.java
1
请完成以下Java代码
public Integer[] getChildIDs (int ID) { ArrayList<Integer> list = new ArrayList<Integer>(); // MTreeNode node = m_tree.getRoot().findNode(ID); log.trace("Root=" + node); // if (node != null && node.isSummary()) { Enumeration en = node.preorderEnumeration(); while (en.hasMoreElements()) { MTreeNode nn = (MTreeNode)en.nextElement(); if (!nn.isSummary()) { list.add(new Integer(nn.getNode_ID())); log.trace("- " + nn); } else log.trace("- skipped parent (" + nn + ")"); } } else // not found or not summary list.add(new Integer(ID)); // Integer[] retValue = new Integer[list.size()]; list.toArray(retValue); return retValue; } // getWhereClause
/** * String Representation * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("MReportTree[ElementType="); sb.append(elementType).append(",TreeType=").append(m_TreeType) .append(",").append(m_tree) .append("]"); return sb.toString(); } // toString } // MReportTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportTree.java
1
请完成以下Java代码
public void start() throws InterruptedException { new Thread(() -> { bossGroup = new NioEventLoopGroup(); workGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); // bossGroup辅助客户端的tcp连接请求, workGroup负责与客户端之前的读写操作 bootstrap.group(bossGroup, workGroup); // 设置NIO类型的channel bootstrap.channel(NioServerSocketChannel.class); // 设置监听端口 bootstrap.localAddress(new InetSocketAddress(port)); // 设置管道 bootstrap.childHandler(nettyInitializer); // 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功 ChannelFuture channelFuture = null; try { channelFuture = bootstrap.bind().sync(); log.info("Server started and listen on:{}", channelFuture.channel().localAddress()); // 对关闭通道进行监听 channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } }).start();
} /** * 释放资源 */ @PreDestroy public void destroy() throws InterruptedException { if (bossGroup != null) { bossGroup.shutdownGracefully().sync(); } if (workGroup != null) { workGroup.shutdownGracefully().sync(); } } }
repos\springboot-demo-master\netty\src\main\java\com\et\netty\server\NettyServer.java
1
请完成以下Java代码
public class CurrencyAndAmountRange2 { @XmlElement(name = "Amt", required = true) protected ImpliedCurrencyAmountRangeChoice amt; @XmlElement(name = "CdtDbtInd") @XmlSchemaType(name = "string") protected CreditDebitCode cdtDbtInd; @XmlElement(name = "Ccy", required = true) protected String ccy; /** * Gets the value of the amt property. * * @return * possible object is * {@link ImpliedCurrencyAmountRangeChoice } * */ public ImpliedCurrencyAmountRangeChoice getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ImpliedCurrencyAmountRangeChoice } * */ public void setAmt(ImpliedCurrencyAmountRangeChoice value) { this.amt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } *
*/ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } * */ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public void setCcy(String value) { this.ccy = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CurrencyAndAmountRange2.java
1
请完成以下Java代码
public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=" + getAD_AlertProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog /** * Get Alerts * @param reload reload data * @return array of alerts */ public MAlert[] getAlerts (boolean reload) { MAlert[] alerts = s_cacheAlerts.get(get_ID()); if (alerts != null && !reload) return alerts; String sql = "SELECT * FROM AD_Alert " + "WHERE AD_AlertProcessor_ID=? AND IsActive='Y' "; ArrayList<MAlert> list = new ArrayList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlert (getCtx(), rs, null)); } catch (Exception e) {
log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } // alerts = new MAlert[list.size ()]; list.toArray (alerts); s_cacheAlerts.put(get_ID(), alerts); return alerts; } // getAlerts @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MAlertProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessor.java
1
请完成以下Java代码
public boolean isReadOnly(ELContext context, Object base, Object property) { Objects.requireNonNull(context, "context is null"); if (isResolvable(base)) { List<?> list = (List<?>) base; context.setPropertyResolved(base, property); try { int idx = coerce(property); checkBounds(list, idx); } catch (IllegalArgumentException e) { // ignore } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return readOnly; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return isResolvable(base) ? Integer.class : null; } /** * Test whether the given base should be resolved by this ELResolver. * * @param base * The bean to analyze. * @return base instanceof List */ private static boolean isResolvable(Object base) { return base instanceof List<?>; } private static void checkBounds(List<?> list, int idx) { if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException(new ArrayIndexOutOfBoundsException(idx).getMessage()); }
} private static int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return (Character) property; } if (property instanceof Boolean) { return (Boolean) property ? 1 : 0; } if (property instanceof String) { try { return Integer.parseInt((String) property); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse list index: " + property, e); } } throw new IllegalArgumentException("Cannot coerce property to list index: " + property); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ListELResolver.java
1
请完成以下Java代码
public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_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 setQtyDelivered (final BigDecimal QtyDelivered) { set_Value (COLUMNNAME_QtyDelivered, QtyDelivered); } @Override public BigDecimal getQtyDelivered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDelivered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInTransit (final BigDecimal QtyInTransit) { set_Value (COLUMNNAME_QtyInTransit, QtyInTransit); } @Override public BigDecimal getQtyInTransit()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInTransit); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOrdered (final BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine_Alternative.java
1
请完成以下Java代码
protected ListenableFuture<UUID> doEvalScript(TenantId tenantId, ScriptType scriptType, String scriptBody, UUID scriptId, String[] argNames) { String scriptHash = hash(tenantId, scriptBody); String functionName = constructFunctionName(scriptId, scriptHash); String jsScript = generateJsScript(scriptType, functionName, scriptBody, argNames); return doEval(scriptId, new JsScriptInfo(scriptHash, functionName), jsScript); } @Override protected void doRelease(UUID scriptId) throws Exception { doRelease(scriptId, scriptInfoMap.remove(scriptId)); } @Override public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; } protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody); protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception;
private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); } throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); } protected String constructFunctionName(UUID scriptId, String scriptHash) { return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrder { /** * Can contain the {@code PP_Order_ID} of the production order document this is all about, but also note that there might not yet exist one. */ PPOrderId ppOrderId; DocStatus docStatus; PPOrderData ppOrderData; /** * Attention, might be {@code null}. */ List<PPOrderLine> lines;
@JsonCreator @Builder(toBuilder = true) public PPOrder( @JsonProperty("ppOrderId") final PPOrderId ppOrderId, @JsonProperty("docStatus") @Nullable final DocStatus docStatus, @JsonProperty("ppOrderData") @NonNull final PPOrderData ppOrderData, @JsonProperty("lines") @Singular final List<PPOrderLine> lines) { this.ppOrderId = ppOrderId; this.docStatus = docStatus; this.ppOrderData = ppOrderData; this.lines = lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrder.java
2
请完成以下Java代码
public class DocumentLineIdentification1 { @XmlElement(name = "Tp") protected DocumentLineType1 tp; @XmlElement(name = "Nb") protected String nb; @XmlElement(name = "RltdDt") @XmlSchemaType(name = "date") protected XMLGregorianCalendar rltdDt; /** * Gets the value of the tp property. * * @return * possible object is * {@link DocumentLineType1 } * */ public DocumentLineType1 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link DocumentLineType1 } * */ public void setTp(DocumentLineType1 value) { this.tp = value; } /** * Gets the value of the nb property. * * @return * possible object is * {@link String } * */ public String getNb() { return nb; } /**
* Sets the value of the nb property. * * @param value * allowed object is * {@link String } * */ public void setNb(String value) { this.nb = value; } /** * Gets the value of the rltdDt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRltdDt() { return rltdDt; } /** * Sets the value of the rltdDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRltdDt(XMLGregorianCalendar value) { this.rltdDt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\DocumentLineIdentification1.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<User>> queryAll() { List<User> users = userDao.findAllUsers(); return ResultGenerator.genSuccessResult(users); } // 新增一条记录 @RequestMapping(value = "/users", method = RequestMethod.POST) @ResponseBody public Result<Boolean> insert(@RequestBody User user) { // 参数验证 if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0); } // 修改一条记录 @RequestMapping(value = "/users", method = RequestMethod.PUT) @ResponseBody public Result<Boolean> update(@RequestBody User tempUser) { //参数验证 if (tempUser.getId() == null || tempUser.getId() < 1 || StringUtils.isEmpty(tempUser.getName()) || StringUtils.isEmpty(tempUser.getPassword())) {
return ResultGenerator.genFailResult("缺少参数"); } //实体验证,不存在则不继续修改操作 User user = userDao.getUserById(tempUser.getId()); if (user == null) { return ResultGenerator.genFailResult("参数异常"); } user.setName(tempUser.getName()); user.setPassword(tempUser.getPassword()); return ResultGenerator.genSuccessResult(userDao.updUser(user) > 0); } // 删除一条记录 @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE) @ResponseBody public Result<Boolean> delete(@PathVariable("id") Integer id) { if (id == null || id < 1) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.delUser(id) > 0); } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-RESTful-api\src\main\java\cn\lanqiao\springboot3\controller\ApiController.java
2
请完成以下Java代码
public int findC_Invoice_Candidate_HeaderAggregationKey_ID(@NonNull final I_C_Invoice_Candidate ic) { try { return findC_Invoice_Candidate_HeaderAggregationKey_ID0(ic); } catch (final DBUniqueConstraintException e) { final String msg = "Caught DBUniqueConstraintException while trying to get or create C_Invoice_Candidate_HeaderAggregationKey for C_Invoice_Candidate_ID=" + ic.getC_Invoice_Candidate_ID() + ". => Retrying"; logger.info(msg, e); Loggables.get().addLog(msg); // retrying is not super-cool and we minimized the possibility for concurrent invocations, // but I couldn't figure out how to get rid of them at de.metas.invoicecandidate.api.impl.InvoiceCandBL.handleCompleteForInvoice return findC_Invoice_Candidate_HeaderAggregationKey_ID0(ic); } } private static int findC_Invoice_Candidate_HeaderAggregationKey_ID0(@NonNull final I_C_Invoice_Candidate ic) { final String headerAggregationKeyCalc = ic.getHeaderAggregationKey_Calc(); if (Check.isBlank(headerAggregationKeyCalc)) { return -1; } final int bpartnerId = ic.getBill_BPartner_ID(); if (bpartnerId <= 0) { return -1; } // // Find existing header aggregation key ID final int headerAggregationKeyId = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Candidate_HeaderAggregation.class, ic) .addEqualsFilter(I_C_Invoice_Candidate_HeaderAggregation.COLUMN_HeaderAggregationKey, headerAggregationKeyCalc)
.create() .firstIdOnly(); if (headerAggregationKeyId > 0) { return headerAggregationKeyId; } // // Create a new header aggregation key record and return it final I_C_Invoice_Candidate_HeaderAggregation headerAggregationKeyRecord = InterfaceWrapperHelper.newInstance(I_C_Invoice_Candidate_HeaderAggregation.class, ic); headerAggregationKeyRecord.setHeaderAggregationKey(headerAggregationKeyCalc); headerAggregationKeyRecord.setHeaderAggregationKeyBuilder_ID(ic.getHeaderAggregationKeyBuilder_ID()); headerAggregationKeyRecord.setC_BPartner_ID(bpartnerId); headerAggregationKeyRecord.setIsSOTrx(ic.isSOTrx()); headerAggregationKeyRecord.setIsActive(true); InterfaceWrapperHelper.save(headerAggregationKeyRecord); return headerAggregationKeyRecord.getC_Invoice_Candidate_HeaderAggregation_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\AggregationDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public List<Author> fetchAllAuthors() { return authorRepository.fetchAll(); } public Author fetchAuthorByNameAndAge() { return authorRepository.fetchByNameAndAge("Joana Nimar", 34); } /* causes exception public List<Author> fetchAuthorsViaSort() { return authorRepository.fetchViaSort(Sort.by(Direction.DESC, "name")); } */ /* causes exception public List<Author> fetchAuthorsViaSortWhere() { return authorRepository.fetchViaSortWhere(30, Sort.by(Direction.DESC, "name")); } */ public Page<Author> fetchAuthorsPageSort() { return authorRepository.fetchPageSort(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Page<Author> fetchAuthorsPageSortWhere() { return authorRepository.fetchPageSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSort() { return authorRepository.fetchSliceSort(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhere() { return authorRepository.fetchSliceSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public List<Author> fetchAllAuthorsNative() { return authorRepository.fetchAllNative(); } public Author fetchAuthorByNameAndAgeNative() { return authorRepository.fetchByNameAndAgeNative("Joana Nimar", 34);
} /* causes exception public List<Author> fetchAuthorsViaSortNative() { return authorRepository.fetchViaSortNative(Sort.by(Direction.DESC, "name")); } */ /* causes exception public List<Author> fetchAuthorsViaSortWhereNative() { return authorRepository.fetchViaSortWhereNative(30, Sort.by(Direction.DESC, "name")); } */ public Page<Author> fetchAuthorsPageSortNative() { return authorRepository.fetchPageSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Page<Author> fetchAuthorsPageSortWhereNative() { return authorRepository.fetchPageSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortNative() { return authorRepository.fetchSliceSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhereNative() { return authorRepository.fetchSliceSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedQueriesInOrmXml\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
private I_AD_Table getAD_Table(final String trxName) { final I_AD_MigrationStep step = getAD_MigrationStep(); I_AD_Table table = step.getAD_Table(); if (table != null && !step.getTableName().equalsIgnoreCase(table.getTableName())) { logger.warn("Table ID collision '" + step.getTableName() + "' with existing '" + table.getTableName() + "' (ID=" + step.getAD_Table_ID() + "). Attempting to retrieve table by name."); table = null; } if (table == null) { final Properties ctx = InterfaceWrapperHelper.getCtx(step); final String whereClause = I_AD_Table.COLUMNNAME_TableName + "=?"; table = new TypedSqlQuery<I_AD_Table>(ctx, I_AD_Table.class, whereClause, trxName) .setParameters(step.getTableName()) .firstOnly(I_AD_Table.class); } return table; } private List<I_AD_MigrationData> getMigrationData() { if (m_migrationData == null) { m_migrationData = Services.get(IMigrationDAO.class).retrieveMigrationData(getAD_MigrationStep()); m_migrationDataKeys = null; } return m_migrationData; } private List<I_AD_MigrationData> getKeyData() { if (m_migrationDataKeys != null) { return m_migrationDataKeys; } final List<I_AD_MigrationData> dataKeys = new ArrayList<I_AD_MigrationData>(); final List<I_AD_MigrationData> dataParents = new ArrayList<I_AD_MigrationData>(); for (final I_AD_MigrationData data : getMigrationData()) { final I_AD_Column column = data.getAD_Column(); if (column == null) {
logger.warn("Column is null for data: {}", new Object[] { data }); continue; } if (column.isKey()) { dataKeys.add(data); } if (column.isParent()) { dataParents.add(data); } } if (dataKeys.size() == 1) { m_migrationDataKeys = dataKeys; } else if (!dataParents.isEmpty()) { m_migrationDataKeys = dataParents; } else { throw new AdempiereException("Invalid key/parent constraints. Keys: " + dataKeys + ", Parents: " + dataParents); } return m_migrationDataKeys; } private void syncDBColumn(final I_AD_Column column, final boolean drop) { final IMigrationExecutorContext migrationCtx = getMigrationExecutorContext(); final ColumnSyncDDLExecutable ddlExecutable = new ColumnSyncDDLExecutable(AdColumnId.ofRepoId(column.getAD_Column_ID()), drop); migrationCtx.addPostponedExecutable(ddlExecutable); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\POMigrationStepExecutor.java
1
请在Spring Boot框架中完成以下Java代码
UserDetailsService userDetailsService(final PasswordEncoder passwordEncoder) { return username -> { log.debug("Searching user: {}", username); switch (username) { case "guest": { return new User(username, passwordEncoder.encode(username + "Password"), Collections.emptyList()); } case "user": { final List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_GREET")); return new User(username, passwordEncoder.encode(username + "Password"), authorities); } default: { throw new UsernameNotFoundException("Could not find user!"); } } }; } @Bean // One of your authentication providers. // They ensure that the credentials are valid and populate the user's authorities. DaoAuthenticationProvider daoAuthenticationProvider( final UserDetailsService userDetailsService, final PasswordEncoder passwordEncoder) { final DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService); provider.setPasswordEncoder(passwordEncoder); return provider; } @Bean // Add the authentication providers to the manager. AuthenticationManager authenticationManager(final DaoAuthenticationProvider daoAuthenticationProvider) { final List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(daoAuthenticationProvider); return new ProviderManager(providers); } @Bean // Configure which authentication types you support. GrpcAuthenticationReader authenticationReader() { return new BasicGrpcAuthenticationReader(); // final List<GrpcAuthenticationReader> readers = new ArrayList<>(); // readers.add(new BasicGrpcAuthenticationReader()); // readers.add(new SSLContextGrpcAuthenticationReader()); // return new CompositeGrpcAuthenticationReader(readers); } }
repos\grpc-spring-master\examples\security-grpc-server\src\main\java\net\devh\boot\grpc\examples\security\server\SecurityConfiguration.java
2
请完成以下Java代码
public void setId(I id) { this.id = id; } public I getId() { return id; } @JsonIgnore public UUID getUuidId() { if (id != null) { return id.getId(); } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; }
@SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IdBased other = (IdBased) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\id\IdBased.java
1
请完成以下Spring Boot application配置
server: port: 9999 knife4j: gateway: enabled: true spring: application: name: jeecg-gateway main: allow-circular-references: true config: import: - optional:nacos:${spring.application.name}-@profile.name@.yaml cloud: nacos: config: server-addr: @config.server-addr@ group: @config.group@ namespace: @config.namespace@ username: @config.username@ password: @config.password@ discovery: server-addr: ${spring.cloud.nacos.config.server-addr} group: @config.group@ namespace: @config.namespace@ username: @config.username@ password: @config.password@ gateway: server: webflux: discovery: locator: enabled: true globalcors: cors-configurations: '[/**]': allow-credentials: true allowed-origin-patterns: - "*" allowed-methods: - "*" allowed-headers: - "*" #Sentinel配置 sentinel: transport: dashboard: jeecg-boot-sentinel:9000 # 支持链路限流 web-context-unify: false filter: enabled: false # 取消Sentinel控制台懒加载 eager: false datasource: #流控规则 flow: # 指定数据源名称 # 指定nacos数据源 nacos: server-addr: @config.server-addr@ # 指定配置文件 dataId: ${spring.application.name}-flow-rules # 指定分组 groupId: SENTINEL_GROUP # 指定配置文件规则类型 rule-type: flow # 指定配置文件数据格式 data-type: json #降级规则 degrade: nacos: server-addr: @config.server-addr@ dataId: ${spring.application.name}-degrade-rules groupId: SENTINEL_GROUP rule-type: degrade data-type: json #系统规则 system: nacos: server-addr: @config.server-addr@ dataId: ${spring.application.name}-system-rules groupId: SENTINEL_GROUP rule-type: system data-type: json #授权规则 authority: nacos:
server-addr: @config.server-addr@ dataId: ${spring.application.name}-authority-rules groupId: SENTINEL_GROUP rule-type: authority data-type: json #热点参数 param-flow: nacos: server-addr: @config.server-addr@ dataId: ${spring.application.name}-param-rules groupId: SENTINEL_GROUP rule-type: param-flow data-type: json #网关流控规则 gw-flow: nacos: server-addr: @config.server-addr@ dataId: ${spring.application.name}-flow-rules groupId: SENTINEL_GROUP rule-type: gw-flow data-type: json #API流控规则 gw-api-group: nacos: server-addr: @config.server-addr@ dataId: ${spring.application.name}-api-rules groupId: SENTINEL_GROUP rule-type: gw-api-group data-type: json
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
void setFilterChainPostProcessor(ObjectPostProcessor<WebFilterChainDecorator> postProcessor) { this.postProcessor = postProcessor; } @Bean(SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME) @Order(WEB_FILTER_CHAIN_FILTER_ORDER) WebFilterChainProxy springSecurityWebFilterChainFilter(ObjectProvider<ServerWebExchangeFirewall> firewall, ObjectProvider<ServerExchangeRejectedHandler> rejectedHandler) { WebFilterChainProxy proxy = new WebFilterChainProxy(getSecurityWebFilterChains()); WebFilterChainDecorator decorator = this.postProcessor.postProcess(new DefaultWebFilterChainDecorator()); proxy.setFilterChainDecorator(decorator); firewall.ifUnique(proxy::setFirewall); rejectedHandler.ifUnique(proxy::setExchangeRejectedHandler); return proxy; } @Bean(name = AbstractView.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME) CsrfRequestDataValueProcessor requestDataValueProcessor() { return new CsrfRequestDataValueProcessor(); } @Bean static RsaKeyConversionServicePostProcessor conversionServicePostProcessor() { return new RsaKeyConversionServicePostProcessor(); } private List<SecurityWebFilterChain> getSecurityWebFilterChains() { List<SecurityWebFilterChain> result = this.securityWebFilterChains; if (ObjectUtils.isEmpty(result)) { return Arrays.asList(springSecurityFilterChain()); } return result; } private SecurityWebFilterChain springSecurityFilterChain() { ServerHttpSecurity http = this.context.getBean(ServerHttpSecurity.class); return springSecurityFilterChain(http); } /**
* The default {@link ServerHttpSecurity} configuration. * @param http * @return */ private SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated()); if (isOAuth2Present && OAuth2ClasspathGuard.shouldConfigure(this.context)) { OAuth2ClasspathGuard.configure(this.context, http); } else { http.httpBasic(withDefaults()); http.formLogin(withDefaults()); } SecurityWebFilterChain result = http.build(); return result; } private static class OAuth2ClasspathGuard { static void configure(ApplicationContext context, ServerHttpSecurity http) { http.oauth2Login(withDefaults()); http.oauth2Client(withDefaults()); } static boolean shouldConfigure(ApplicationContext context) { ClassLoader loader = context.getClassLoader(); Class<?> reactiveClientRegistrationRepositoryClass = ClassUtils .resolveClassName(REACTIVE_CLIENT_REGISTRATION_REPOSITORY_CLASSNAME, loader); return context.getBeanNamesForType(reactiveClientRegistrationRepositoryClass).length == 1; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\reactive\WebFluxSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getReasonCode() { return reasonCode; } /** * Sets the value of the reasonCode property. * * @param value * allowed object is * {@link String } * */ public void setReasonCode(String value) { this.reasonCode = value; } /** * Monetary amount of the actual adjustment. * * @return * possible object is * {@link MonetaryAmountType } * */ public MonetaryAmountType getAdjustmentMonetaryAmount() { return adjustmentMonetaryAmount; } /** * Sets the value of the adjustmentMonetaryAmount property. * * @param value * allowed object is * {@link MonetaryAmountType } * */ public void setAdjustmentMonetaryAmount(MonetaryAmountType value) { this.adjustmentMonetaryAmount = value; } /** * Taxes applied to the adjustment.
* * @return * possible object is * {@link TaxType } * */ public TaxType getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxType } * */ public void setTax(TaxType value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdjustmentType.java
2
请完成以下Java代码
public void registerHandler(IIterateResultHandler handler) { handlerSupport.registerListener(handler); } @Override public List<IIterateResultHandler> getRegisteredHandlers() { return handlerSupport.getRegisteredHandlers(); } @Override public boolean isHandlerSignaledToStop() { return handlerSupport.isHandlerSignaledToStop(); } public boolean isFoundGoalRecord() { return foundGoal; } @Override public boolean contains(final ITableRecordReference forwardReference) { return g.containsVertex(forwardReference); } public List<ITableRecordReference> getPath() { final List<ITableRecordReference> result = new ArrayList<>(); final AsUndirectedGraph<ITableRecordReference, DefaultEdge> undirectedGraph = new AsUndirectedGraph<>(g);
final List<DefaultEdge> path = DijkstraShortestPath.<ITableRecordReference, DefaultEdge> findPathBetween( undirectedGraph, start, goal); if (path == null || path.isEmpty()) { return ImmutableList.of(); } result.add(start); for (final DefaultEdge e : path) { final ITableRecordReference edgeSource = undirectedGraph.getEdgeSource(e); if (!result.contains(edgeSource)) { result.add(edgeSource); } else { result.add(undirectedGraph.getEdgeTarget(e)); } } return ImmutableList.copyOf(result); } /* package */ Graph<ITableRecordReference, DefaultEdge> getGraph() { return g; } @Override public String toString() { return "FindPathIterateResult [start=" + start + ", goal=" + goal + ", size=" + size + ", foundGoal=" + foundGoal + ", queueItemsToProcess.size()=" + queueItemsToProcess.size() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\graph\FindPathIterateResult.java
1
请在Spring Boot框架中完成以下Java代码
private SwaggerInfo swaggerInfo() { SwaggerInfo info = new SwaggerInfo(); info.setDescription("OpenAPI 接口列表"); info.setVersion("3.9.0"); info.setTitle("OpenAPI 接口列表"); info.setTermsOfService("https://jeecg.com"); SwaggerInfoContact contact = new SwaggerInfoContact(); contact.setName("jeecg@qq.com"); info.setContact(contact); SwaggerInfoLicense license = new SwaggerInfoLicense(); license.setName("Apache 2.0"); license.setUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); info.setLicense(license); return info;
} /** * 生成接口路径 * @return */ @GetMapping("genPath") public Result<String> genPath() { Result<String> r = new Result<String>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(PathGenerator.genPath()); return r; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiController.java
2
请完成以下Java代码
public class ConsumeFromBeginning { private static Logger logger = LoggerFactory.getLogger(ConsumeFromBeginning.class); private static String TOPIC = "baeldung"; private static int messagesInTopic = 10; private static KafkaProducer<String, String> producer; private static KafkaConsumer<String, String> consumer; public static void main(String[] args) { setup(); publishMessages(); consumeFromBeginning(); } private static void consumeFromBeginning() { consumer.subscribe(Arrays.asList(TOPIC)); ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(10)); for (ConsumerRecord<String, String> record : records) { logger.info(record.value()); } consumer.seekToBeginning(consumer.assignment()); records = consumer.poll(Duration.ofSeconds(10)); for (ConsumerRecord<String, String> record : records) { logger.info(record.value()); } } private static void publishMessages() { for (int i = 1; i <= messagesInTopic; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, String.valueOf(i)); producer.send(record); } } private static void setup() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); Properties consumerProperties = new Properties(); consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID() .toString()); producer = new KafkaProducer<>(producerProperties); consumer = new KafkaConsumer<>(consumerProperties); } }
repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\consumer\ConsumeFromBeginning.java
1
请在Spring Boot框架中完成以下Java代码
public Amount getTotal() { return total; } public void setTotal(Amount total) { this.total = total; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PricingSummary pricingSummary = (PricingSummary)o; return Objects.equals(this.adjustment, pricingSummary.adjustment) && Objects.equals(this.deliveryCost, pricingSummary.deliveryCost) && Objects.equals(this.deliveryDiscount, pricingSummary.deliveryDiscount) && Objects.equals(this.fee, pricingSummary.fee) && Objects.equals(this.priceDiscountSubtotal, pricingSummary.priceDiscountSubtotal) && Objects.equals(this.priceSubtotal, pricingSummary.priceSubtotal) && Objects.equals(this.tax, pricingSummary.tax) && Objects.equals(this.total, pricingSummary.total); } @Override public int hashCode() { return Objects.hash(adjustment, deliveryCost, deliveryDiscount, fee, priceDiscountSubtotal, priceSubtotal, tax, total); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PricingSummary {\n");
sb.append(" adjustment: ").append(toIndentedString(adjustment)).append("\n"); sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n"); sb.append(" deliveryDiscount: ").append(toIndentedString(deliveryDiscount)).append("\n"); sb.append(" fee: ").append(toIndentedString(fee)).append("\n"); sb.append(" priceDiscountSubtotal: ").append(toIndentedString(priceDiscountSubtotal)).append("\n"); sb.append(" priceSubtotal: ").append(toIndentedString(priceSubtotal)).append("\n"); sb.append(" tax: ").append(toIndentedString(tax)).append("\n"); sb.append(" total: ").append(toIndentedString(total)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PricingSummary.java
2
请完成以下Java代码
public OptionalInt getMinPrecision() { return documentField.getMinPrecision(); } @Override public Object getValueAsJsonObject(final JSONOptions jsonOpts) { return documentField.getValueAsJsonObject(jsonOpts); } @Override public LogicExpressionResult getReadonly() { return documentField.getReadonly(); } @Override public LogicExpressionResult getMandatory() { return documentField.getMandatory(); }
@Override public LogicExpressionResult getDisplayed() { return documentField.getDisplayed(); } @Override public DocumentValidStatus getValidStatus() { return documentField.getValidStatus(); } @Override public DeviceDescriptorsList getDevices() { return documentField.getDescriptor() .getDeviceDescriptorsProvider() .getDeviceDescriptors(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\DocumentFieldAsProcessInstanceParameter.java
1
请完成以下Java代码
public class ListJacksonJsonTypeDetector implements TypeDetector { public boolean canHandle(Object object) { return object instanceof List; } public String detectType(Object object) { return constructType(object).toCanonical(); } protected JavaType constructType(Object object) { TypeFactory typeFactory = TypeFactory.defaultInstance(); if (object instanceof List && !((List<?>) object).isEmpty()) { List<?> list = (List<?>) object; Object firstElement = list.get(0); if (bindingsArePresent(list.getClass())) { final JavaType elementType = constructType(firstElement); return typeFactory.constructCollectionType(list.getClass(), elementType);
} } return typeFactory.constructType(object.getClass()); } private boolean bindingsArePresent(Class<?> erasedType) { TypeVariable<?>[] vars = erasedType.getTypeParameters(); int varLen = (vars == null) ? 0 : vars.length; if (varLen == 0) { return false; } if (varLen != 1) { throw new IllegalArgumentException("Cannot create TypeBindings for class " + erasedType.getName() + " with 1 type parameter: class expects " + varLen); } return true; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\ListJacksonJsonTypeDetector.java
1
请完成以下Java代码
private String buildETagString() { final StringBuilder etagString = new StringBuilder(); etagString.append("v=").append(version); if (!attributes.isEmpty()) { final String attributesStr = attributes.entrySet() .stream() .sorted(Comparator.comparing(entry -> entry.getKey())) .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.joining("#")); etagString.append("#").append(attributesStr); } return etagString.toString(); }
public final ETag overridingAttributes(final Map<String, String> overridingAttributes) { if (overridingAttributes.isEmpty()) { return this; } if (attributes.isEmpty()) { return new ETag(version, ImmutableMap.copyOf(overridingAttributes)); } final Map<String, String> newAttributes = new HashMap<>(attributes); newAttributes.putAll(overridingAttributes); return new ETag(version, ImmutableMap.copyOf(newAttributes)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETag.java
1
请完成以下Java代码
public class FunctionParameter { public static int performOperation(int a, int b, Operation operation) { return operation.execute(a, b); } public static int passFunctionUsingAnnonymousClass(int a, int b) { return performOperation(a, b, new Operation() { @Override public int execute(int a, int b) { return a + b; } }); } public static int passFunctionUsingLambda(int a, int b) { return performOperation(a, b, (i, k) -> i + k); } private static int add(int a, int b) { return a + b; } public static int passFunctionUsingMethodReferrences(int a, int b) { return performOperation(a, b, FunctionParameter::add); }
private static int executeFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) { return function.apply(a, b); } public static int passFunctionUsingFunction(int a, int b) { return executeFunction((i, k) -> i + k, a, b); } private static int executeCallable(Callable<Integer> task) throws Exception { return task.call(); } public static int passFunctionUsingCallable(int a, int b) throws Exception { Callable<Integer> task = () -> a + b; return executeCallable(task); } }
repos\tutorials-master\core-java-modules\core-java-function\src\main\java\com\baeldung\functionparameter\FunctionParameter.java
1
请在Spring Boot框架中完成以下Java代码
public JmsPoolConnectionFactoryProperties getPool() { return this.pool; } public Packages getPackages() { return this.packages; } String determineBrokerUrl() { if (this.brokerUrl != null) { return this.brokerUrl; } if (this.embedded.isEnabled()) { return DEFAULT_EMBEDDED_BROKER_URL; } return DEFAULT_NETWORK_BROKER_URL; } /** * Configuration for an embedded ActiveMQ broker. */ public static class Embedded { /** * Whether to enable embedded mode if the ActiveMQ Broker is available. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Packages { /** * Whether to trust all packages. */ private @Nullable Boolean trustAll;
/** * List of specific packages to trust (when not trusting all packages). */ private List<String> trusted = new ArrayList<>(); public @Nullable Boolean getTrustAll() { return this.trustAll; } public void setTrustAll(@Nullable Boolean trustAll) { this.trustAll = trustAll; } public List<String> getTrusted() { return this.trusted; } public void setTrusted(List<String> trusted) { this.trusted = trusted; } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
2
请完成以下Java代码
public DocumentNoInfo build() { return new DocumentNoInfo(this); } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setDocBaseType(final String docBaseType) { this.docBaseType = docBaseType; return this; } public Builder setDocSubType(final String docSubType) { this.docSubType = docSubType; return this; } public Builder setHasChanges(final boolean hasChanges) { this.hasChanges = hasChanges;
return this; } public Builder setDocNoControlled(final boolean docNoControlled) { this.docNoControlled = docNoControlled; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { soTrx = isSOTrx; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoInfo.java
1
请完成以下Java代码
public boolean isChanged() { return getProductPriceId() == null || !getPrice().isPriceListPriceUsed(); } public boolean isMatching(@NonNull final ProductsProposalViewFilter filter) { return Check.isEmpty(filter.getProductName()) || getProductName().toLowerCase().contains(filter.getProductName().toLowerCase()); } public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine) { if(existingOrderLine == null) { return this;
} final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode()); return toBuilder() .qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity() ? existingOrderLine.getQtyEnteredCU() : BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU())) .price(ProductProposalPrice.builder() .priceListPrice(existingPrice) .build()) .existingOrderLineId(existingOrderLine.getOrderLineId()) .description(existingOrderLine.getDescription()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java
1
请完成以下Java代码
private static OTP computeOTP(final long step, @NonNull final SecretKey secretKey) { String steps = Long.toHexString(step).toUpperCase(); while (steps.length() < 16) { steps = "0" + steps; } // Get the HEX in a Byte[] final byte[] msg = hexStr2Bytes(steps); final byte[] k = hexStr2Bytes(secretKey.toHexString()); final byte[] hash = hmac_sha1(k, msg); // put selected bytes into result int final int offset = hash[hash.length - 1] & 0xf; final int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); final int otp = binary % 1000000; String result = Integer.toString(otp); while (result.length() < 6) { result = "0" + result; } return OTP.ofString(result); } /** * @return hex string converted to byte array */ private static byte[] hexStr2Bytes(final CharSequence hex) { // Adding one byte to get the right conversion // values starting with "0" can be converted final byte[] bArray = new BigInteger("10" + hex, 16).toByteArray(); final byte[] ret = new byte[bArray.length - 1]; // Copy all the REAL bytes, not the "first" System.arraycopy(bArray, 1, ret, 0, ret.length); return ret; } /**
* This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash * algorithm as a parameter. * * @param keyBytes the bytes to use for the HMAC key * @param text the message or text to be authenticated. */ private static byte[] hmac_sha1(final byte[] keyBytes, final byte[] text) { try { final Mac hmac = Mac.getInstance("HmacSHA1"); final SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (final GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\TOTPUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthController { @Autowired private AuthenticationController authenticationController; @Autowired private AuthConfig config; private static final String AUTH0_TOKEN_URL = "https://dev-example.auth0.com/oauth/token"; @GetMapping(value = "/login") protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectUri = config.getContextPath(request) + "/callback"; String authorizeUrl = authenticationController.buildAuthorizeUrl(request, response, redirectUri) .withScope("openid email") .build(); response.sendRedirect(authorizeUrl); } @GetMapping(value="/callback") public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, IdentityVerificationException { Tokens tokens = authenticationController.handle(request, response); DecodedJWT jwt = JWT.decode(tokens.getIdToken()); TestingAuthenticationToken authToken2 = new TestingAuthenticationToken(jwt.getSubject(), jwt.getToken()); authToken2.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authToken2); response.sendRedirect(config.getContextPath(request) + "/"); } public String getManagementApiToken() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject requestBody = new JSONObject(); requestBody.put("client_id", config.getManagementApiClientId()); requestBody.put("client_secret", config.getManagementApiClientSecret()); requestBody.put("audience", "https://dev-example.auth0.com/api/v2/"); requestBody.put("grant_type", config.getGrantType()); HttpEntity<String> request = new HttpEntity<String>(requestBody.toString(), headers); RestTemplate restTemplate = new RestTemplate(); HashMap<String, String> result = restTemplate.postForObject(AUTH0_TOKEN_URL, request, HashMap.class); return result.get("access_token"); } }
repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\java\com\baeldung\auth0\controller\AuthController.java
2
请完成以下Java代码
public String getTableNameOrNull(@Nullable final DocumentId ignored) { return I_M_PickingSlot.Table_Name; } @Override public ViewId getParentViewId() { return parentViewId; } @Override public DocumentId getParentRowId() { return parentRowId; } @Override public long size() { return rows.size(); } @Override public int getQueryLimit() { return -1; } @Override public boolean isQueryLimitHit() { return false; } @Override public ViewResult getPage( final int firstRow, final int pageLength, @NonNull final ViewRowsOrderBy orderBys) { final List<PickingSlotRow> pageRows = rows.getPage(firstRow, pageLength); return ViewResult.ofViewAndPage(this, firstRow, pageLength, orderBys.toDocumentQueryOrderByList(), pageRows); } @Override public PickingSlotRow getById(@NonNull final DocumentId id) throws EntityNotFoundException { return rows.getById(id); } @Override public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return filters; }
@Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerDepartmentId implements RepoIdAware { int repoId; @NonNull BPartnerId bpartnerId; public static BPartnerDepartmentId none(@NonNull final BPartnerId bpartnerId) { return new BPartnerDepartmentId(bpartnerId); } public static BPartnerDepartmentId ofRepoId(@NonNull final BPartnerId bpartnerId, final int bpartnerDepartmentId) { return new BPartnerDepartmentId(bpartnerId, bpartnerDepartmentId); } public static BPartnerDepartmentId ofRepoId(final int bpartnerId, final int bpartnerDepartmentId) { return new BPartnerDepartmentId(BPartnerId.ofRepoId(bpartnerId), bpartnerDepartmentId); } @NonNull public static BPartnerDepartmentId ofRepoIdOrNone( @NonNull final BPartnerId bpartnerId, @Nullable final Integer bpartnerDepartmentId) { return bpartnerDepartmentId != null && bpartnerDepartmentId > 0 ? ofRepoId(bpartnerId, bpartnerDepartmentId) : none(bpartnerId); } private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId, final int bpartnerDepartmentId) {
this.repoId = Check.assumeGreaterThanZero(bpartnerDepartmentId, "bpartnerDepartmentId"); this.bpartnerId = bpartnerId; } private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId) { this.repoId = -1; this.bpartnerId = bpartnerId; } public static int toRepoId(@Nullable final BPartnerDepartmentId bpartnerDepartmentId) { return bpartnerDepartmentId != null && !bpartnerDepartmentId.isNone() ? bpartnerDepartmentId.getRepoId() : -1; } public boolean isNone() { return repoId <= 0; } @Nullable public static Integer toRepoIdOrNull(@Nullable final BPartnerDepartmentId bPartnerDepartmentId) { return bPartnerDepartmentId != null && !bPartnerDepartmentId.isNone() ? bPartnerDepartmentId.getRepoId() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\department\BPartnerDepartmentId.java
2