instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
abstract class OracleR2dbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> { private final String defaultDatabase; OracleR2dbcDockerComposeConnectionDetailsFactory(OracleContainer container) { super(container.getImageName(), "io.r2dbc.spi.ConnectionFactoryOptions"); this.defaultDatabase = container.getDefaultDatabase(); } @Override protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new OracleDbR2dbcDockerComposeConnectionDetails(source.getRunningService(), this.defaultDatabase); } /** * {@link R2dbcConnectionDetails} backed by a {@code gvenzl/oracle-xe} * {@link RunningService}. */ static class OracleDbR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements R2dbcConnectionDetails { private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder( "oracle", 1521); private final ConnectionFactoryOptions connectionFactoryOptions;
OracleDbR2dbcDockerComposeConnectionDetails(RunningService service, String defaultDatabase) { super(service); OracleEnvironment environment = new OracleEnvironment(service.env(), defaultDatabase); this.connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, environment.getDatabase(), environment.getUsername(), environment.getPassword()); } @Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return this.connectionFactoryOptions; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\OracleR2dbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public void setValue(String value) { this.value = value; } // persistent object methods //////////////////////////////////////////////// @Override public String getId() { return name; } @Override public Object getPersistentState() { return value; } @Override
public void setId(String id) { throw new ActivitiException("only provided id generation allowed for properties"); } @Override public int getRevisionNext() { return revision + 1; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "PropertyEntity[name=" + name + ", value=" + value + "]"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\PropertyEntity.java
1
请完成以下Java代码
public Object get(final String name) { return context.get(name); } public static final class Builder { private final ImmutableMap.Builder<String, Object> context = ImmutableMap.builder(); private Builder() { super(); } public ExpressionContext build() { final ImmutableMap<String, Object> context = this.context.build(); if (context.isEmpty()) {
return EMPTY; } return new ExpressionContext(context); } public Builder putContext(final String name, final Object value) { if (value == null) { return this; } context.put(name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ExpressionContext.java
1
请完成以下Java代码
public void setBackground() { } // setBackground /** * Action Listener - data binding * @param e */ @Override public void actionPerformed(ActionEvent e) { try { fireVetoableChange(m_columnName, null, getValue()); } catch (PropertyVetoException pve) { } } // actionPerformed /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic ()
{ return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic @Override public boolean isAutoCommit() { return true; } } // VCheckBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCheckBox.java
1
请完成以下Java代码
class NumberCruncherThread implements Runnable { @Override public void run() { String thisThreadName = Thread.currentThread().getName(); List<Integer> partialResult = new ArrayList<>(); for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { Integer num = random.nextInt(10); System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num); partialResult.add(num); } partialResults.add(partialResult); try { System.out.println(thisThreadName + " waiting for others to reach barrier."); cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } class AggregatorThread implements Runnable { @Override public void run() { String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); int sum = 0; for (List<Integer> threadResult : partialResults) { System.out.print("Adding "); for (Integer partialResult : threadResult) { System.out.print(partialResult + " "); sum += partialResult; } System.out.println(); } System.out.println(Thread.currentThread().getName() + ": Final result = " + sum); } } public static void main(String[] args) { CyclicBarrierDemo play = new CyclicBarrierDemo(); play.runSimulation(5, 3); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\cyclicbarrier\CyclicBarrierDemo.java
1
请完成以下Java代码
public Component getDefaultComponent (Container aContainer) { // info ("Root: ", aContainer); m_default = true; Component c = super.getDefaultComponent (aContainer); // info (" Default: ", c); m_default = false; return c; } // getDefaultComponent /** * Determines whether the specified <code>Component</code> * is an acceptable choice as the new focus owner. * This method performs the following sequence of operations: * <ol> * <li>Checks whether <code>aComponent</code> is visible, displayable, * enabled, and focusable. If any of these properties is * <code>false</code>, this method returns <code>false</code>. * <li>If <code>aComponent</code> is an instance of <code>JTable</code>, * returns <code>true</code>. * <li>If <code>aComponent</code> is an instance of <code>JComboBox</code>, * then returns the value of * <code>aComponent.getUI().isFocusTraversable(aComponent)</code>. * <li>If <code>aComponent</code> is a <code>JComponent</code> * with a <code>JComponent.WHEN_FOCUSED</code> * <code>InputMap</code> that is neither <code>null</code> * nor empty, returns <code>true</code>. * <li>Returns the value of * <code>DefaultFocusTraversalPolicy.accept(aComponent)</code>. * </ol> * * @param aComponent the <code>Component</code> whose fitness * as a focus owner is to be tested * @see java.awt.Component#isVisible * @see java.awt.Component#isDisplayable * @see java.awt.Component#isEnabled * @see java.awt.Component#isFocusable * @see javax.swing.plaf.ComboBoxUI#isFocusTraversable * @see javax.swing.JComponent#getInputMap() * @see java.awt.DefaultFocusTraversalPolicy#accept * @return <code>true</code> if <code>aComponent</code> is a valid choice * for a focus owner; * otherwise <code>false</code> */ @Override protected boolean accept(Component aComponent) { if (!super.accept(aComponent)) return false; // TabbedPane if (aComponent instanceof JTabbedPane) return false; // R/O Editors if (aComponent instanceof CEditor) { final CEditor ed = (CEditor)aComponent; if (!ed.isReadWrite()) return false;
if (m_default // get Default Focus && ("AD_Client_ID".equals(aComponent.getName()) || "AD_Org_ID".equals(aComponent.getName()) )) return false; } // Toolbar Buttons if (aComponent.getParent() instanceof JToolBar) return false; // return true; } // accept /************************************************************************** * Dump info * @param title * @param c */ private void info (String title, Component c) { System.out.print (title); if (c == null) System.out.println (" - null"); else { System.out.print (c.getClass().getName()); System.out.println (" - " + c.getName()); } } // info } // AFocusTraversalPolicy
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AFocusTraversalPolicy.java
1
请完成以下Java代码
public void setPermissionServiceFactory(@NonNull final PermissionServiceFactory permissionServiceFactory) { this.permissionServiceFactory = permissionServiceFactory; } @PostMapping public ResponseEntity<JsonOLCandCreateBulkResponse> createOrderLineCandidate(@RequestBody @NonNull final JsonOLCandCreateRequest request) { return createOrderLineCandidates(JsonOLCandCreateBulkRequest.of(request)); } @PostMapping(PATH_BULK) public ResponseEntity<JsonOLCandCreateBulkResponse> createOrderLineCandidates(@RequestBody @NonNull final JsonOLCandCreateBulkRequest bulkRequest) { try { bulkRequest.validate(); final MasterdataProvider masterdataProvider = MasterdataProvider.builder() .permissionService(permissionServiceFactory.createPermissionService()) .bpartnerRestController(bpartnerRestController) .externalReferenceRestControllerService(externalReferenceRestControllerService) .jsonRetrieverService(jsonRetrieverService) .externalSystemRepository(externalSystemRepository) .bPartnerMasterdataProvider(bPartnerMasterdataProvider) .build(); final ITrxManager trxManager = Services.get(ITrxManager.class); final JsonOLCandCreateBulkResponse response = trxManager .callInNewTrx(() -> orderCandidateRestControllerService.creatOrderLineCandidatesBulk(bulkRequest, masterdataProvider));
return Check.isEmpty(response.getErrors()) ? new ResponseEntity<>(response, HttpStatus.CREATED) : new ResponseEntity<>(response, HttpStatus.MULTI_STATUS); } catch (final Exception ex) { logger.warn("Got exception while processing {}", bulkRequest, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.badRequest() .body(JsonOLCandCreateBulkResponse.error(JsonErrors.ofThrowable(ex, adLanguage))); } } @PutMapping(PATH_PROCESS) public ResponseEntity<JsonProcessCompositeResponse> processOLCands(@RequestBody @NonNull final JsonOLCandProcessRequest request) { try { final JsonProcessCompositeResponse response = orderCandidateRestControllerService.processOLCands(request); return ResponseEntity.ok(response); } catch (final Exception ex) { logger.warn("Got exception while processing {}", request, ex); return ResponseEntity.badRequest().build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\OrderCandidatesRestController.java
1
请完成以下Java代码
public List<int[]> generate(int n, int r) { List<int[]> combinations = new ArrayList<>(); helper(combinations, new int[r], 0, n - 1, 0); return combinations; } /** * Choose elements from set by recursing over elements selected * @param combinations - List to store generated combinations * @param data - current combination * @param start - starting element of remaining set * @param end - last element of remaining set * @param index - number of elements chosen so far. */ private void helper(List<int[]> combinations, int data[], int start, int end, int index) { if (index == data.length) { int[] combination = data.clone(); combinations.add(combination); } else { int max = Math.min(end, end + 1 - data.length + index); for (int i = start; i <= max; i++) {
data[index] = i; helper(combinations, data, i + 1, end, index + 1); } } } public static void main(String[] args) { SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator(); List<int[]> combinations = generator.generate(N, R); for (int[] combination : combinations) { System.out.println(Arrays.toString(combination)); } System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N); } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\combination\SelectionRecursiveCombinationGenerator.java
1
请完成以下Java代码
public class TenantAwareDataSource implements DataSource { protected TenantInfoHolder tenantInfoHolder; protected Map<Object, DataSource> dataSources = new HashMap<Object, DataSource>(); public TenantAwareDataSource(TenantInfoHolder tenantInfoHolder) { this.tenantInfoHolder = tenantInfoHolder; } public void addDataSource(Object key, DataSource dataSource) { dataSources.put(key, dataSource); } public void removeDataSource(Object key) { dataSources.remove(key); } public Connection getConnection() throws SQLException { return getCurrentDataSource().getConnection(); } public Connection getConnection(String username, String password) throws SQLException { return getCurrentDataSource().getConnection(username, password); } protected DataSource getCurrentDataSource() { String tenantId = tenantInfoHolder.getCurrentTenantId(); DataSource dataSource = dataSources.get(tenantId); if (dataSource == null) { throw new ActivitiException("Could not find a dataSource for tenant " + tenantId); } return dataSource; } public int getLoginTimeout() throws SQLException { return 0; // Default } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
} @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName()); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } public Map<Object, DataSource> getDataSources() { return dataSources; } public void setDataSources(Map<Object, DataSource> dataSources) { this.dataSources = dataSources; } // Unsupported ////////////////////////////////////////////////////////// public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } public void setLogWriter(PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } public void setLoginTimeout(int seconds) throws SQLException { throw new UnsupportedOperationException(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\multitenant\TenantAwareDataSource.java
1
请完成以下Java代码
/* private */default Map<DocumentId, T> getDocumentId2AllRows() { return RowsDataTool.extractAllRows(getDocumentId2TopLevelRows().values()); } /** @return all rows (top level and included ones) */ default Collection<T> getAllRows() { return getDocumentId2AllRows().values(); } default Collection<T> getTopLevelRows() { return getDocumentId2TopLevelRows().values(); } /** @return top level or include row */ default T getById(final DocumentId rowId) throws EntityNotFoundException { final T row = getByIdOrNull(rowId); if (row == null)
{ throw new EntityNotFoundException("Row not found") .appendParametersToMessage() .setParameter("rowId", rowId); } return row; } @Nullable default T getByIdOrNull(final DocumentId rowId) { return getDocumentId2AllRows().get(rowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\IRowsData.java
1
请在Spring Boot框架中完成以下Java代码
public HUQRCode getQRCodeByHuId(@NonNull final HuId huId) {return huQRCodesService.getQRCodeByHuId(huId);} @NonNull public HUQRCode resolveHUQRCode(@NonNull final ScannedCode scannedCode) { final IHUQRCode parsedHUQRCode = huQRCodesService.parse(scannedCode); if (parsedHUQRCode instanceof HUQRCode) { return (HUQRCode)parsedHUQRCode; } else { throw new AdempiereException("Cannot convert " + scannedCode + " to actual HUQRCode") .setParameter("parsedHUQRCode", parsedHUQRCode) .setParameter("parsedHUQRCode type", parsedHUQRCode.getClass().getSimpleName()); } } public HuId resolveHUId(@NonNull final ScannedCode scannedCode) { final HUQRCode huQRCode = resolveHUQRCode(scannedCode); return huQRCodesService.getHuIdByQRCode(huQRCode); } public PackToHUsProducer newPackToHUsProducer() { return PackToHUsProducer.builder() .handlingUnitsBL(handlingUnitsBL) .huPIItemProductBL(hupiItemProductBL) .uomConversionBL(uomConversionBL) .inventoryService(inventoryService) .build(); } public IAutoCloseable newContext() { return HUContextHolder.temporarySet(handlingUnitsBL.createMutableHUContextForProcessing()); }
public ProductId getSingleProductId(@NonNull final HUQRCode huQRCode) { final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode); return getSingleHUProductStorage(huId).getProductId(); } public IHUProductStorage getSingleHUProductStorage(@NonNull final HuId huId) { return handlingUnitsBL.getSingleHUProductStorage(huId); } public Quantity getProductQuantity(@NonNull final HuId huId, @NonNull ProductId productId) { return getHUProductStorage(huId, productId) .map(IHUProductStorage::getQty) .filter(Quantity::isPositive) .orElseThrow(() -> new AdempiereException(PRODUCT_DOES_NOT_MATCH)); } private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId) { final I_M_HU hu = handlingUnitsBL.getById(huId); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId)); } public void assetHUContainsProduct(@NonNull final HUQRCode huQRCode, @NonNull final ProductId productId) { final HuId huId = huQRCodesService.getHuIdByQRCode(huQRCode); getProductQuantity(huId, productId); // shall throw exception if no qty found } public void deleteReservationsByDocumentRefs(final ImmutableSet<HUReservationDocRef> huReservationDocRefs) { huReservationService.deleteReservationsByDocumentRefs(huReservationDocRefs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\hu\DistributionHUService.java
2
请完成以下Java代码
private CustomerId getCustomerIdFromMsg(TbMsg msg) { return msg != null ? msg.getCustomerId() : null; } private EntityId getOriginatorId(TbContext ctx) throws TbNodeException { if (EntityType.RULE_NODE.equals(config.getOriginatorType())) { return ctx.getSelfId(); } if (EntityType.TENANT.equals(config.getOriginatorType())) { return ctx.getTenantId(); } if (StringUtils.isBlank(config.getOriginatorId())) { throw new TbNodeException("Originator entity must be selected.", true); } var entityId = EntityIdFactory.getByTypeAndUuid(config.getOriginatorType(), config.getOriginatorId()); ctx.checkTenantEntity(entityId); return entityId; } @Override public void destroy() { log.debug("[{}] Stopping generator", originatorId); initialized.set(false); prevMsg = null; nextTickId = null; lastScheduledTs = 0; if (scriptEngine != null) { scriptEngine.destroy(); scriptEngine = null; } } @Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: if (oldConfiguration.has(QUEUE_NAME)) { hasChanges = true; ((ObjectNode) oldConfiguration).remove(QUEUE_NAME); } case 1: String originatorType = "originatorType"; String originatorId = "originatorId"; boolean hasType = oldConfiguration.hasNonNull(originatorType); boolean hasOriginatorId = oldConfiguration.hasNonNull(originatorId) && StringUtils.isNotBlank(oldConfiguration.get(originatorId).asText()); boolean hasOriginatorFields = hasType && hasOriginatorId; if (!hasOriginatorFields) { hasChanges = true; ((ObjectNode) oldConfiguration).put(originatorType, EntityType.RULE_NODE.name()); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\debug\TbMsgGeneratorNode.java
1
请完成以下Java代码
public T orElseGet(@NonNull final Supplier<? extends T> other) { return value != null ? value : other.get(); } public T orElseThrow() { return orElseThrow(AdempiereException::new); } public T orElseThrow(@NonNull final AdMessageKey adMessageKey) { return orElseThrow(message -> new AdempiereException(adMessageKey).setParameter("detail", message)); } public T orElseThrow(@NonNull final Function<ITranslatableString, RuntimeException> exceptionFactory) { if (value != null) { return value; } else { throw exceptionFactory.apply(explanation); } } public T get() { return orElseThrow(); } public boolean isPresent() { return value != null; } public <U> ExplainedOptional<U> map(@NonNull final Function<? super T, ? extends U> mapper) { if (!isPresent()) { return emptyBecause(explanation); } else { final U newValue = mapper.apply(value); if (newValue == null) { return emptyBecause(explanation); } else { return of(newValue); } } } public ExplainedOptional<T> ifPresent(@NonNull final Consumer<T> consumer) { if (isPresent()) { consumer.accept(value); } return this; } @SuppressWarnings("UnusedReturnValue")
public ExplainedOptional<T> ifAbsent(@NonNull final Consumer<ITranslatableString> consumer) { if (!isPresent()) { consumer.accept(explanation); } return this; } /** * @see #resolve(Function, Function) */ public <R> Optional<R> mapIfAbsent(@NonNull final Function<ITranslatableString, R> mapper) { return isPresent() ? Optional.empty() : Optional.ofNullable(mapper.apply(getExplanation())); } /** * @see #mapIfAbsent(Function) */ public <R> R resolve( @NonNull final Function<T, R> mapPresent, @NonNull final Function<ITranslatableString, R> mapAbsent) { return isPresent() ? mapPresent.apply(value) : mapAbsent.apply(explanation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ExplainedOptional.java
1
请完成以下Java代码
class ClassPathFileChangeListener implements FileChangeListener { private final ApplicationEventPublisher eventPublisher; private final ClassPathRestartStrategy restartStrategy; private final @Nullable FileSystemWatcher fileSystemWatcherToStop; /** * Create a new {@link ClassPathFileChangeListener} instance. * @param eventPublisher the event publisher used send events * @param restartStrategy the restart strategy to use * @param fileSystemWatcherToStop the file system watcher to stop on a restart (or * {@code null}) */ ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher, ClassPathRestartStrategy restartStrategy, @Nullable FileSystemWatcher fileSystemWatcherToStop) { Assert.notNull(eventPublisher, "'eventPublisher' must not be null"); Assert.notNull(restartStrategy, "'restartStrategy' must not be null"); this.eventPublisher = eventPublisher; this.restartStrategy = restartStrategy; this.fileSystemWatcherToStop = fileSystemWatcherToStop; } @Override public void onChange(Set<ChangedFiles> changeSet) { boolean restart = isRestartRequired(changeSet); publishEvent(new ClassPathChangedEvent(this, changeSet, restart)); } private void publishEvent(ClassPathChangedEvent event) { this.eventPublisher.publishEvent(event); if (event.isRestartRequired() && this.fileSystemWatcherToStop != null) {
this.fileSystemWatcherToStop.stop(); } } private boolean isRestartRequired(Set<ChangedFiles> changeSet) { if (AgentReloader.isActive()) { return false; } for (ChangedFiles changedFiles : changeSet) { for (ChangedFile changedFile : changedFiles) { if (this.restartStrategy.isRestartRequired(changedFile)) { return true; } } } return false; } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\classpath\ClassPathFileChangeListener.java
1
请完成以下Java代码
public Iterator<I_C_Order> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } @Override public void invalidateCandidatesFor(final Object model) { final I_C_Order order = create(model, I_C_Order.class); // services final IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class); final IOrderDAO orderDAO = Services.get(IOrderDAO.class); final Properties ctx = InterfaceWrapperHelper.getCtx(order); final List<IInvoiceCandidateHandler> invalidators = invoiceCandidateHandlerBL.retrieveImplementationsForTable(ctx, I_C_OrderLine.Table_Name); for (final I_C_OrderLine ol : orderDAO.retrieveOrderLines(order)) { for (final IInvoiceCandidateHandler invalidator : invalidators) { invalidator.invalidateCandidatesFor(ol); } } } @Override public String getSourceTable() { return I_C_Order.Table_Name; } @Override public boolean isUserInChargeUserEditable() { return false; } @Override
public void setOrderedData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic) { throw new UnsupportedOperationException(); } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { throw new IllegalStateException("Not supported"); } @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { throw new IllegalStateException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\invoicecandidate\C_Order_Handler.java
1
请完成以下Java代码
public class FormDto { private String key; private CamundaFormRef camundaFormRef; private String contextPath; public void setKey(String form) { this.key = form; } public String getKey() { return key; } public CamundaFormRef getCamundaFormRef() { return camundaFormRef; } public void setCamundaFormRef(CamundaFormRef camundaFormRef) { this.camundaFormRef = camundaFormRef;
} public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getContextPath() { return contextPath; } public static FormDto fromFormData(FormData formData) { FormDto dto = new FormDto(); if (formData != null) { dto.key = formData.getFormKey(); dto.camundaFormRef = formData.getCamundaFormRef(); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\FormDto.java
1
请完成以下Java代码
public DhlClientConfig getByShipperId(@NonNull final ShipperId shipperId) { final int repoId = shipperId.getRepoId(); return cache.getOrLoad(repoId, () -> retrieveConfig(repoId)); } private static DhlClientConfig retrieveConfig(final int shipperId) { final I_DHL_Shipper_Config configPO = Services.get(IQueryBL.class) .createQueryBuilder(I_DHL_Shipper_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DHL_Shipper_Config.COLUMNNAME_M_Shipper_ID, shipperId) .orderBy(I_DHL_Shipper_Config.COLUMNNAME_DHL_Shipper_Config_ID) .create() .first(); if (configPO == null) { throw new AdempiereException("No DHL shipper configuration found for shipperId=" + shipperId); }
return DhlClientConfig.builder() .applicationID(configPO.getapplicationID()) .applicationToken(configPO.getApplicationToken()) .baseUrl(configPO.getdhl_api_url()) .accountNumber(configPO.getAccountNumber()) .username(configPO.getUserName()) .signature(configPO.getSignature()) .lengthUomId(UomId.ofRepoId(configPO.getDhl_LenghtUOM_ID())) .trackingUrlBase(retrieveTrackingUrl(configPO.getM_Shipper_ID())) .build(); } private static String retrieveTrackingUrl(final int m_shipper_id) { final I_M_Shipper shipperPo = InterfaceWrapperHelper.load(m_shipper_id, I_M_Shipper.class); return shipperPo.getTrackingURL(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlClientConfigRepository.java
1
请在Spring Boot框架中完成以下Java代码
public Quantity allocate(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { if (!headerAggKey.equals(ppOrderCandidateToAllocate.getHeaderAggregationKey())) { return capacityPerProductionCycle.toZero(); } if (isFullCapacityReached()) { return capacityPerProductionCycle.toZero(); } ppOrderCreateRequestBuilder.addRecord(ppOrderCandidateToAllocate.getPpOrderCandidate()); final Quantity qtyToAllocate = getQtyToAllocate(ppOrderCandidateToAllocate); allocateQuantity(ppOrderCandidateToAllocate, qtyToAllocate); return qtyToAllocate; } @NonNull public PPOrderCreateRequest getPPOrderCreateRequest() { return ppOrderCreateRequestBuilder.build(allocatedQty); } private boolean isFullCapacityReached() { return !isInfiniteCapacity() && capacityPerProductionCycle.compareTo(allocatedQty) <= 0;
} private void allocateQuantity(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate, @NonNull final Quantity quantityToAllocate) { allocatedQty = allocatedQty.add(quantityToAllocate); final PPOrderCandidateId ppOrderCandidateId = PPOrderCandidateId.ofRepoId(ppOrderCandidateToAllocate.getPpOrderCandidate().getPP_Order_Candidate_ID()); ppOrderCand2AllocatedQty.put(ppOrderCandidateId, quantityToAllocate); } @NonNull private Quantity getQtyToAllocate(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate) { if (isInfiniteCapacity()) { return ppOrderCandidateToAllocate.getOpenQty(); } final Quantity remainingCapacity = capacityPerProductionCycle.subtract(allocatedQty); return ppOrderCandidateToAllocate.getOpenQty().min(remainingCapacity); } private boolean isInfiniteCapacity() { return capacityPerProductionCycle.signum() == 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\produce\PPOrderAllocator.java
2
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 获得 token ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); String token = headers.getFirst(config.getTokenHeaderName()); // 如果没有 token,则不进行认证。因为可能是无需认证的 API 接口 if (!StringUtils.hasText(token)) { return chain.filter(exchange); } // 进行认证 ServerHttpResponse response = exchange.getResponse(); Integer userId = tokenMap.get(token); // 通过 token 获取不到 userId,说明认证不通过 if (userId == null) { // 响应 401 状态码 response.setStatusCode(HttpStatus.UNAUTHORIZED); // 响应提示 DataBuffer buffer = exchange.getResponse().bufferFactory().wrap("认证不通过".getBytes()); return response.writeWith(Flux.just(buffer)); } // 认证通过,将 userId 添加到 Header 中 request = request.mutate().header(config.getUserIdHeaderName(), String.valueOf(userId)) .build(); return chain.filter(exchange.mutate().request(request).build()); } }; } public static class Config { private static final String DEFAULT_TOKEN_HEADER_NAME = "token"; private static final String DEFAULT_HEADER_NAME = "user-id"; private String tokenHeaderName = DEFAULT_TOKEN_HEADER_NAME; private String userIdHeaderName = DEFAULT_HEADER_NAME; public String getTokenHeaderName() { return tokenHeaderName;
} public String getUserIdHeaderName() { return userIdHeaderName; } public Config setTokenHeaderName(String tokenHeaderName) { this.tokenHeaderName = tokenHeaderName; return this; } public Config setUserIdHeaderName(String userIdHeaderName) { this.userIdHeaderName = userIdHeaderName; return this; } } }
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo05-custom-gateway-filter\src\main\java\cn\iocoder\springcloud\labx08\gatewaydemo\filter\AuthGatewayFilterFactory.java
1
请完成以下Java代码
public class ExecutionTreeBfsIterator implements Iterator<ExecutionTreeNode> { protected ExecutionTreeNode rootNode; protected boolean reverseOrder; protected LinkedList<ExecutionTreeNode> flattenedList; protected Iterator<ExecutionTreeNode> flattenedListIterator; public ExecutionTreeBfsIterator(ExecutionTreeNode executionTree) { this(executionTree, false); } public ExecutionTreeBfsIterator(ExecutionTreeNode rootNode, boolean reverseOrder) { this.rootNode = rootNode; this.reverseOrder = reverseOrder; } protected void flattenTree() { flattenedList = new LinkedList<ExecutionTreeNode>(); LinkedList<ExecutionTreeNode> nodesToHandle = new LinkedList<ExecutionTreeNode>(); nodesToHandle.add(rootNode); while (!nodesToHandle.isEmpty()) { ExecutionTreeNode currentNode = nodesToHandle.pop(); if (reverseOrder) { flattenedList.addFirst(currentNode); } else { flattenedList.add(currentNode); } if (currentNode.getChildren() != null && currentNode.getChildren().size() > 0) { for (ExecutionTreeNode childNode : currentNode.getChildren()) { nodesToHandle.add(childNode); } } }
flattenedListIterator = flattenedList.iterator(); } @Override public boolean hasNext() { if (flattenedList == null) { flattenTree(); } return flattenedListIterator.hasNext(); } @Override public ExecutionTreeNode next() { if (flattenedList == null) { flattenTree(); } return flattenedListIterator.next(); } @Override public void remove() { if (flattenedList == null) { flattenTree(); } flattenedListIterator.remove(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTreeBfsIterator.java
1
请完成以下Spring Boot application配置
server: port: 9000 spring: security: oauth2: authorizationserver: client: public-client: registration: client-id: "public-client" client-authentication-methods: - "none" authorization-grant-types: - "authorization_code" redirect-uris: - "http://127.0.0.1:3000/callback"
scopes: - "openid" - "profile" - "email" require-authorization-consent: true require-proof-key: true
repos\tutorials-master\spring-security-modules\spring-security-pkce-spa\pkce-spa-auth-server\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public List<UserRole> getUserRoles(@NonNull final UserId userId) { final List<UserAssignedRoleId> assignedRoleIds = assignedUserRoleCache.getOrLoad(userId, this::getAssignedRoleIds); final Set<UserRoleId> roleIds = assignedRoleIds.stream() .map(UserAssignedRoleId::getUserRoleId) .collect(ImmutableSet.toImmutableSet()); final Collection<I_C_User_Role> userRoles = userRoleCache.getAllOrLoad(roleIds, this::loadUserRoles); final Map<UserRoleId, I_C_User_Role> userRoleById = Maps.uniqueIndex(userRoles, (userRole) -> UserRoleId.ofRepoId(userRole.getC_User_Role_ID())); return assignedRoleIds.stream() .map(assignedRoleId -> { final I_C_User_Role role = userRoleById.get(assignedRoleId.getUserRoleId()); return toUserRole(assignedRoleId, role); }) .collect(ImmutableList.toImmutableList()); } @NonNull private Map<UserRoleId, I_C_User_Role> loadUserRoles(@NonNull final Set<UserRoleId> userRoleId) { return queryBL.createQueryBuilder(I_C_User_Role.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_User_Role.COLUMN_C_User_Role_ID, userRoleId) .create() .stream() .collect(Collectors.toMap( role -> UserRoleId.ofRepoId(role.getC_User_Role_ID()), Function.identity() )); } @NonNull private List<UserAssignedRoleId> getAssignedRoleIds(@NonNull final UserId userId) { return queryBL.createQueryBuilder(I_C_User_Assigned_Role.class)
.addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_User_Assigned_Role.COLUMNNAME_AD_User_ID, userId) .create() .stream() .map(record -> { final UserRoleId roleId = UserRoleId.ofRepoId(record.getC_User_Role_ID()); return UserAssignedRoleId.ofRepoId(roleId, record.getC_User_Assigned_Role_ID()); }) .collect(ImmutableList.toImmutableList()); } @NonNull private UserRole toUserRole(@NonNull final UserAssignedRoleId assignedRoleId, @NonNull final I_C_User_Role role) { return UserRole.builder() .name(role.getName()) .uniquePerBpartner(role.isUniqueForBPartner()) .userAssignedRoleId(assignedRoleId) .build(); } public List<UserId> getAssignedUsers(@NonNull final UserRoleId userRoleId) { return queryBL.createQueryBuilder(I_C_User_Assigned_Role.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_User_Assigned_Role.COLUMNNAME_C_User_Role_ID, userRoleId) .create() .listDistinct(I_C_User_Assigned_Role.COLUMNNAME_AD_User_ID, Integer.class) .stream() .map(UserId::ofRepoId) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\user\role\repository\UserRoleRepository.java
2
请完成以下Java代码
public void setArticleUnit (final String ArticleUnit) { set_Value (COLUMNNAME_ArticleUnit, ArticleUnit); } @Override public String getArticleUnit() { return get_ValueAsString(COLUMNNAME_ArticleUnit); } @Override public void setM_Product_AlbertaPackagingUnit_ID (final int M_Product_AlbertaPackagingUnit_ID) { if (M_Product_AlbertaPackagingUnit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, M_Product_AlbertaPackagingUnit_ID); } @Override public int getM_Product_AlbertaPackagingUnit_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaPackagingUnit_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); }
@Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaPackagingUnit.java
1
请完成以下Java代码
public class ModelImporter extends JavaProcess { /** Client Parameter */ protected int p_AD_Client_ID = 0; /** Document Type Parameter */ protected int p_C_DocType_ID = 0; /** Record ID */ protected int p_Record_ID = 0; /** EXP_Format_ID */ protected int p_EXP_Format_ID = 0; /** File Name **/ protected String p_FileName = ""; /** Table ID */ int AD_Table_ID = 0; /** * Get Parameters */ @Override protected void prepare() { p_Record_ID = getRecord_ID(); if (p_AD_Client_ID == 0) p_AD_Client_ID = Env.getAD_Client_ID(getCtx()); AD_Table_ID = getTable_ID(); StringBuffer sb = new StringBuffer("AD_Table_ID=").append(AD_Table_ID); sb.append("; Record_ID=").append(getRecord_ID()); // Parameter ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("EXP_Format_ID")) p_EXP_Format_ID = para[i].getParameterAsInt(); else if (name.equals("FileName")) p_FileName = (String)para[i].getParameter(); else log.error("Unknown Parameter: " + name); } if(p_EXP_Format_ID == 0) p_EXP_Format_ID = p_Record_ID;
if(p_FileName == null) { // Load XML file and parse it String fileNameOr = org.compiere.util.Ini.getMetasfreshHome() + System.getProperty("file.separator") + "data" + System.getProperty("file.separator") + "ExportFile.xml"; p_FileName = fileNameOr; } log.info(sb.toString()); } /** * Process * * @return info */ @Override protected String doIt() throws Exception { StringBuilder result = new StringBuilder(""); // Load XML file and parse it /*String fileNameOr = org.compiere.util.Ini.findAdempiereHome() + System.getProperty("file.separator") + "data" + System.getProperty("file.separator"); String pathToXmlFile = fileNameOr+"XmlExport-test.xml"; Document documentToBeImported = XMLHelper.createDocumentFromFile(pathToXmlFile);*/ Document documentToBeImported = XMLHelper.createDocumentFromFile(p_FileName); final IImportHelper impHelper = Services.get(IIMPProcessorBL.class).createImportHelper(getCtx()); impHelper.importXMLDocument(result, documentToBeImported, get_TrxName()); addLog("@ImportModelProcessResult@" + "\n" + result.toString()); return result.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\imp\ModelImporter.java
1
请完成以下Java代码
public CaseInstanceMigrationDocumentBuilder addChangePlanItemDefinitionWithNewTargetIdsMappings(List<ChangePlanItemDefinitionWithNewTargetIdsMapping> mappings) { this.changePlanItemDefinitionWithNewTargetIdsMappings.addAll(mappings); return this; } @Override public CaseInstanceMigrationDocumentBuilder addCaseInstanceVariable(String variableName, Object variableValue) { this.caseInstanceVariables.put(variableName, variableValue); return this; } @Override public CaseInstanceMigrationDocumentBuilder addCaseInstanceVariables(Map<String, Object> caseInstanceVariables) { this.caseInstanceVariables.putAll(caseInstanceVariables); return this; } @Override public CaseInstanceMigrationDocumentBuilder preUpgradeExpression(String preUpgradeExpression) { this.preUpgradeExpression = preUpgradeExpression; return this; } @Override
public CaseInstanceMigrationDocumentBuilder postUpgradeExpression(String postUpgradeExpression) { this.postUpgradeExpression = postUpgradeExpression; return this; } @Override public CaseInstanceMigrationDocument build() { CaseInstanceMigrationDocumentImpl caseInstanceMigrationDocument = new CaseInstanceMigrationDocumentImpl(); caseInstanceMigrationDocument.setMigrateToCaseDefinitionId(this.migrateToCaseDefinitionId); caseInstanceMigrationDocument.setMigrateToCaseDefinition(this.migrateToCaseDefinitionKey, this.migrateToCaseDefinitionVersion, this.migrateToCaseDefinitionTenantId); caseInstanceMigrationDocument.setActivatePlanItemDefinitionMappings(this.activatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setTerminatePlanItemDefinitionMappings(this.terminatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setMoveToAvailablePlanItemDefinitionMappings(this.moveToAvailablePlanItemDefinitionMappings); caseInstanceMigrationDocument.setWaitingForRepetitionPlanItemDefinitionMappings(this.waitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setRemoveWaitingForRepetitionPlanItemDefinitionMappings(this.removeWaitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setChangePlanItemIdMappings(this.changePlanItemIdMappings); caseInstanceMigrationDocument.setChangePlanItemIdWithDefinitionIdMappings(this.changePlanItemIdWithDefinitionIdMappings); caseInstanceMigrationDocument.setChangePlanItemDefinitionWithNewTargetIdsMappings(this.changePlanItemDefinitionWithNewTargetIdsMappings); caseInstanceMigrationDocument.setCaseInstanceVariables(this.caseInstanceVariables); caseInstanceMigrationDocument.setPreUpgradeExpression(this.preUpgradeExpression); caseInstanceMigrationDocument.setPostUpgradeExpression(this.postUpgradeExpression); return caseInstanceMigrationDocument; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentBuilderImpl.java
1
请完成以下Java代码
public I_PP_Product_BOM verifyProductBOMAndReturnIt( @NonNull final ProductId ppOrderProductId, @NonNull final Date ppOrderStartSchedule, @NonNull final I_PP_Product_BOM ppOrderProductBOM) { // Product BOM should be completed if (!DocStatus.ofCode(ppOrderProductBOM.getDocStatus()).isCompleted()) { throw new MrpException(StringUtils.formatMessage( "Product BOM is not completed; PP_Product_BOM={}", ppOrderProductBOM)); } // Product from Order should be same as product from BOM - teo_sarca [ 2817870 ] if (ppOrderProductId.getRepoId() != ppOrderProductBOM.getM_Product_ID()) { throw new MrpException("@NotMatch@ @PP_Product_BOM_ID@ , @M_Product_ID@"); } // Product BOM Configuration should be verified - teo_sarca [ 2817870 ] final IProductDAO productsRepo = Services.get(IProductDAO.class); final I_M_Product product = productsRepo.getById(ppOrderProductBOM.getM_Product_ID()); if (!product.isVerified()) { throw new MrpException( StringUtils.formatMessage( "Product with Value={} of Product BOM Configuration not verified; PP_Product_BOM={}; product={}", product.getValue(), ppOrderProductBOM, product)); } // // Create BOM Head final IProductBOMBL productBOMBL = Services.get(IProductBOMBL.class); if (!productBOMBL.isValidFromTo(ppOrderProductBOM, ppOrderStartSchedule)) { throw new BOMExpiredException(ppOrderProductBOM, ppOrderStartSchedule); } return ppOrderProductBOM; } public static void updateBOMLineWarehouseAndLocatorFromOrder( @NonNull final I_PP_Order_BOMLine orderBOMLine, @NonNull final I_PP_Order fromOrder) { orderBOMLine.setAD_Org_ID(fromOrder.getAD_Org_ID()); orderBOMLine.setM_Warehouse_ID(fromOrder.getM_Warehouse_ID()); orderBOMLine.setM_Locator_ID(fromOrder.getM_Locator_ID()); } /**
* @return {@code true} if the respective ppOrder's matching product planning exists and has {@code PP_Product_Planning.IsPickDirectlyIfFeasible='Y'} */ public boolean pickIfFeasible(@NonNull final PPOrderData ppOrderData) { final IProductPlanningDAO productPlanningDAO = Services.get(IProductPlanningDAO.class); final ProductId productId = ProductId.ofRepoId(ppOrderData.getProductDescriptor().getProductId()); final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(ppOrderData.getProductDescriptor().getAttributeSetInstanceId()); final IProductPlanningDAO.ProductPlanningQuery productPlanningQuery = IProductPlanningDAO.ProductPlanningQuery.builder() .orgId(ppOrderData.getClientAndOrgId().getOrgId()) .warehouseId(ppOrderData.getWarehouseId()) .plantId(ppOrderData.getPlantId()) .productId(productId) .includeWithNullProductId(false) .attributeSetInstanceId(asiId) .build(); return productPlanningDAO.find(productPlanningQuery) .map(ProductPlanning::isPickDirectlyIfFeasible) .orElse(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPOrderUtil.java
1
请完成以下Java代码
protected JobEntity createJob(int[] minuteChunk, int maxRetries) { HistoryCleanupContext context = createCleanupContext(minuteChunk, maxRetries); return HISTORY_CLEANUP_JOB_DECLARATION.createJobInstance(context); } protected HistoryCleanupContext createCleanupContext(int[] minuteChunk, int maxRetries) { int minuteFrom = minuteChunk[0]; int minuteTo = minuteChunk[1]; return new HistoryCleanupContext(immediatelyDue, minuteFrom, minuteTo, maxRetries); } protected void writeUserOperationLog(CommandContext commandContext) { PropertyChange propertyChange = new PropertyChange("immediatelyDue", null, immediatelyDue); commandContext.getOperationLogManager() .logJobOperation(UserOperationLogEntry.OPERATION_TYPE_CREATE_HISTORY_CLEANUP_JOB,
null, null, null, null, null, propertyChange); } protected void acquireExclusiveLock(CommandContext commandContext) { PropertyManager propertyManager = commandContext.getPropertyManager(); //exclusive lock propertyManager.acquireExclusiveLockForHistoryCleanupJob(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HistoryCleanupCmd.java
1
请在Spring Boot框架中完成以下Java代码
public CmmnDeploymentBuilder category(String category) { deployment.setCategory(category); return this; } @Override public CmmnDeploymentBuilder key(String key) { deployment.setKey(key); return this; } @Override public CmmnDeploymentBuilder disableSchemaValidation() { this.isCmmn20XsdValidationEnabled = false; return this; } @Override public CmmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } @Override public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public CmmnDeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this;
} @Override public CmmnDeployment deploy() { return repositoryService.deploy(this); } public CmmnDeploymentEntity getDeployment() { return deployment; } public boolean isCmmnXsdValidationEnabled() { return isCmmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java
2
请完成以下Java代码
private static String buildSqlInsert() { final StringBuilder sqlColumns = new StringBuilder( I_T_ES_FTS_Search_Result.COLUMNNAME_Search_UUID // 1 + "," + I_T_ES_FTS_Search_Result.COLUMNNAME_Line // 2 + "," + I_T_ES_FTS_Search_Result.COLUMNNAME_JSON // 3 ); final StringBuilder sqlValues = new StringBuilder("?, ?, ?"); for (final String keyColumnName : I_T_ES_FTS_Search_Result.COLUMNNAME_ALL_Keys) { sqlColumns.append(", ").append(keyColumnName); sqlValues.append(", ?"); } return "INSERT INTO " + I_T_ES_FTS_Search_Result.Table_Name + " (" + sqlColumns + ")" + " VALUES (" + sqlValues + ")"; } public void saveNew(@NonNull final FTSSearchResult result) { final ImmutableList<FTSSearchResultItem> items = result.getItems(); if (items.isEmpty()) { return; } PreparedStatement pstmt = null; try { int nextLineNo = 1; pstmt = DB.prepareStatement(SQL_INSERT, ITrx.TRXNAME_None); final ArrayList<Object> sqlParams = new ArrayList<>(); for (final FTSSearchResultItem item : items) { final int lineNo = nextLineNo++; sqlParams.clear(); sqlParams.add(result.getSearchId()); sqlParams.add(lineNo); sqlParams.add(item.getJson()); for (final String keyColumnName : I_T_ES_FTS_Search_Result.COLUMNNAME_ALL_Keys) {
final Object value = item.getKey().getValueBySelectionTableColumnName(keyColumnName); sqlParams.add(value); } DB.setParameters(pstmt, sqlParams); pstmt.addBatch(); } pstmt.executeBatch(); } catch (final SQLException ex) { throw new DBException(ex, SQL_INSERT); } finally { DB.close(pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchResultRepository.java
1
请完成以下Java代码
public void setM_Label(org.compiere.model.I_M_Label M_Label) { set_ValueFromPO(COLUMNNAME_M_Label_ID, org.compiere.model.I_M_Label.class, M_Label); } /** Set Label List. @param M_Label_ID Label List */ @Override public void setM_Label_ID (int M_Label_ID) { if (M_Label_ID < 1) set_Value (COLUMNNAME_M_Label_ID, null); else set_Value (COLUMNNAME_M_Label_ID, Integer.valueOf(M_Label_ID)); } /** Get Label List. @return Label List */ @Override public int getM_Label_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Label_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Label_ID. @param M_Product_Certificate_ID Label_ID */ @Override public void setM_Product_Certificate_ID (int M_Product_Certificate_ID) { if (M_Product_Certificate_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, Integer.valueOf(M_Product_Certificate_ID)); } /** Get Label_ID. @return Label_ID */ @Override public int getM_Product_Certificate_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Certificate_ID); if (ii == null) return 0; return ii.intValue();
} @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Certificate.java
1
请完成以下Java代码
public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public long getRepeatOffset() { return repeatOffset; } public void setRepeatOffset(long repeatOffset) { this.repeatOffset = repeatOffset; } @Override public String getType() { return TYPE; } @Override public Object getPersistentState() { Map<String, Object> persistentState = (HashMap) super.getPersistentState(); persistentState.put("repeat", repeat);
return persistentState; } @Override public String toString() { return this.getClass().getSimpleName() + "[repeat=" + repeat + ", id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", repeatOffset=" + repeatOffset + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TimerEntity.java
1
请完成以下Java代码
public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city;
} public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "Address [id=" + id + ", name=" + name + ", city=" + city + ", postalCode=" + postalCode + "]"; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\putvspost\Address.java
1
请完成以下Java代码
private InputStreamReader newInputStreamReaderForSource(String encoding) throws UnsupportedEncodingException { if (encoding != null) { return new InputStreamReader(streamSource.getInputStream(), encoding); } else { return new InputStreamReader(streamSource.getInputStream()); } } public EventDefinitionParse name(String name) { this.name = name; return this; } public EventDefinitionParse sourceInputStream(InputStream inputStream) { if (name == null) { name("inputStream"); } setStreamSource(new InputStreamSource(inputStream)); return this; } public String getSourceSystemId() { return sourceSystemId; } public EventDefinitionParse setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; return this; } public EventDefinitionParse sourceUrl(URL url) { if (name == null) { name(url.toString()); } setStreamSource(new UrlStreamSource(url)); return this; } public EventDefinitionParse sourceUrl(String url) { try { return sourceUrl(new URL(url)); } catch (MalformedURLException e) { throw new FlowableException("malformed url: " + url, e); } } public EventDefinitionParse sourceResource(String resource) {
if (name == null) { name(resource); } setStreamSource(new ResourceStreamSource(resource)); return this; } public EventDefinitionParse sourceString(String string) { if (name == null) { name("string"); } setStreamSource(new StringStreamSource(string)); return this; } protected void setStreamSource(StreamSource streamSource) { if (this.streamSource != null) { throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource); } this.streamSource = streamSource; } /* * ------------------- GETTERS AND SETTERS ------------------- */ public List<EventDefinitionEntity> getEventDefinitions() { return eventDefinitions; } public EventDeploymentEntity getDeployment() { return deployment; } public void setDeployment(EventDeploymentEntity deployment) { this.deployment = deployment; } public EventModel getEventModel() { return eventModel; } public void setEventModel(EventModel eventModel) { this.eventModel = eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\parser\EventDefinitionParse.java
1
请完成以下Java代码
public static HUConsolidationJob getHUConsolidationJob(final @NonNull WFProcess wfProcess) { return wfProcess.getDocumentAs(HUConsolidationJob.class); } public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<HUConsolidationJob> mapper) { final HUConsolidationJob job = getHUConsolidationJob(wfProcess); final HUConsolidationJob jobChanged = mapper.apply(job); return !Objects.equals(job, jobChanged) ? toWFProcess(jobChanged) : wfProcess; } public JsonHUConsolidationJobAvailableTargets getAvailableTargets( @NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId) { final WFProcess wfProcess = getWFProcessById(wfProcessId); wfProcess.assertHasAccess(callerId); final HUConsolidationJob job = getHUConsolidationJob(wfProcess); return JsonHUConsolidationJobAvailableTargets.builder() .targets(jobService.getAvailableTargets(job) .stream() .map(JsonHUConsolidationTarget::of) .collect(ImmutableList.toImmutableList())) .build(); } public WFProcess setTarget( @NonNull final WFProcessId wfProcessId, @Nullable final HUConsolidationTarget target, @NonNull final UserId callerId) { final HUConsolidationJob job = jobService.setTarget(HUConsolidationJobId.ofWFProcessId(wfProcessId), target, callerId); return toWFProcess(job); } public WFProcess closeTarget( @NonNull final WFProcessId wfProcessId, final @NotNull UserId callerId) { final HUConsolidationJob job = jobService.closeTarget(HUConsolidationJobId.ofWFProcessId(wfProcessId), callerId); return toWFProcess(job);
} public void printTargetLabel( @NonNull final WFProcessId wfProcessId, @NotNull final UserId callerId) { jobService.printTargetLabel(HUConsolidationJobId.ofWFProcessId(wfProcessId), callerId); } public WFProcess consolidate(@NonNull final JsonConsolidateRequest request, @NonNull final UserId callerId) { final HUConsolidationJob job = jobService.consolidate(ConsolidateRequest.builder() .callerId(callerId) .jobId(HUConsolidationJobId.ofWFProcessId(request.getWfProcessIdNotNull())) .fromPickingSlotId(request.getFromPickingSlotId()) .huId(request.getHuId()) .build()); return toWFProcess(job); } public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId) { return jobService.getPickingSlotContent(jobId, pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\HUConsolidationApplication.java
1
请完成以下Java代码
public String getUsername() { return this.environment.getUsername(); } @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } private static final class SqlServerJdbcUrlBuilder extends JdbcUrlBuilder {
private SqlServerJdbcUrlBuilder(String driverProtocol, int containerPort) { super(driverProtocol, containerPort); } @Override protected void appendParameters(StringBuilder url, String parameters) { url.append(";").append(parameters); } } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\SqlServerJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public class FileReaderExample { public static String readAllCharactersOneByOne(Reader reader) throws IOException { StringBuilder content = new StringBuilder(); int nextChar; while ((nextChar = reader.read()) != -1) { content.append((char) nextChar); } return String.valueOf(content); } public static String readMultipleCharacters(Reader reader, int length) throws IOException { char[] buffer = new char[length]; int charactersRead = reader.read(buffer, 0, length); if (charactersRead != -1) { return new String(buffer, 0, charactersRead); } else { return ""; } } public static String readFile(String path) { FileReader fileReader = null; try { fileReader = new FileReader(path); return readAllCharactersOneByOne(fileReader); } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); }
} } return null; } public static String readFileUsingTryWithResources(String path) { try (FileReader fileReader = new FileReader(path)) { return readAllCharactersOneByOne(fileReader); } catch (IOException e) { e.printStackTrace(); } return null; } }
repos\tutorials-master\core-java-modules\core-java-io-apis-3\src\main\java\com\baeldung\filereader\FileReaderExample.java
1
请在Spring Boot框架中完成以下Java代码
private Set<LocatorId> getDeviceLocatorIds(final String deviceName) { final String sysconfigPrefix = CFG_DEVICE_PREFIX + "." + deviceName + "." + DEVICE_PARAM_M_Locator_ID; final Set<Integer> locatorIds = sysConfigBL.getValuesForPrefix(sysconfigPrefix, clientAndOrgId) .values() .stream() .map(locatorIdStr -> { try { return Integer.parseInt(locatorIdStr); } catch (final Exception ex) { logger.warn("Failed parsing {} for {}*", locatorIdStr, sysconfigPrefix, ex); return null; } }) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); return warehouseBL.getLocatorIdsByRepoIds(locatorIds); } /** * @return device implementation classname; never returns null * @throws DeviceConfigException if no classname was found */ private String getDeviceClassname(@NonNull final String deviceName) { // note: assume not null because in that case, the method above would fail return getSysconfigValueWithHostNameFallback(CFG_DEVICE_PREFIX + "." + deviceName, DEVICE_PARAM_DeviceClass, null); } private Set<String> getDeviceRequestClassnames(final String deviceName, final AttributeCode attributeCode) { final Map<String, String> requestClassNames = sysConfigBL.getValuesForPrefix(CFG_DEVICE_PREFIX + "." + deviceName + "." + attributeCode.getCode(), clientAndOrgId); return ImmutableSet.copyOf(requestClassNames.values()); } /** * @return value; never returns null * @throws DeviceConfigException if configuration parameter was not found and given <code>defaultStr</code> is <code>null</code>. */ private String getSysconfigValueWithHostNameFallback(final String prefix, final String suffix, final @Nullable String defaultValue) { // // Try by hostname final String deviceKeyWithHostName = prefix + "." + clientHost.getHostName() + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithHostName, clientAndOrgId); if (value != null) { return value; }
} // // Try by host's IP final String deviceKeyWithIP = prefix + "." + clientHost.getIP() + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithIP, clientAndOrgId); if (value != null) { return value; } } // // Try by any host (i.e. 0.0.0.0) final String deviceKeyWithWildCard = prefix + "." + IPADDRESS_ANY + "." + suffix; { final String value = sysConfigBL.getValue(deviceKeyWithWildCard, clientAndOrgId); if (value != null) { return value; } } // // Fallback to default if (defaultValue != null) { return defaultValue; } // // Throw exception throw new DeviceConfigException("@NotFound@: @AD_SysConfig@ " + deviceKeyWithHostName + ", " + deviceKeyWithIP + ", " + deviceKeyWithWildCard + "; @AD_Client_ID@=" + clientAndOrgId.getClientId() + " @AD_Org_ID@=" + clientAndOrgId.getOrgId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\SysConfigDeviceConfigPool.java
2
请完成以下Java代码
public class Documents_FactAcct_Creation_For_Posted extends JavaProcess { private final IPostingService postingService = Services.get(IPostingService.class); @Param(parameterName = "DateStart") private Date p_Date; @Override protected String doIt() throws Exception { // this process is posting documents that were created one day before the process runs final Timestamp startTime; if (p_Date != null) { startTime = TimeUtil.truncToDay(p_Date); } else { startTime = SystemTime.asDayTimestamp(); } // list all the documents that are marked as posted but have no fact accounts. // this list will not include the documents with no fact accounts that were not supposed to be posted (always 0 in posting) final List<IDocument> documentsPostedNoFacts = Services.get(IDocumentRepostingSupplierService.class).retrievePostedWithoutFactAcct(getCtx(), startTime); if (documentsPostedNoFacts.isEmpty()) {
// do nothing return "All documents are posted"; } final ILoggable loggable = Loggables.get(); for (final IDocument document : documentsPostedNoFacts) { final ClientId clientId = ClientId.ofRepoId(document.getAD_Client_ID()); final TableRecordReference documentRef = document.toTableRecordReference(); final String documentNo = document.getDocumentNo(); // Note: Do not change this message! // The view de_metas_acct.Reposted_Documents is based on it. loggable.addLog("Document Reposted: {}, DocumentNo = {}.", documentRef, documentNo); postingService.schedule( DocumentPostRequest.builder() .record(documentRef) .clientId(clientId) .build() ); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\Documents_FactAcct_Creation_For_Posted.java
1
请在Spring Boot框架中完成以下Java代码
public void setProtocols(final String protocols) { this.protocols = protocols.split("[ :,]"); } } /** * Gets the port the server should listen on. Defaults to {@code 9090}. If set to {@code 0} a random available port * will be selected and used. * * @return The server port to listen to. * * @see #setPort(int) */ public int getPort() { if (this.port == 0) { this.port = SocketUtils.findAvailableTcpPort(); } return this.port; } /** * Sets the maximum message size allowed to be received by the server. If not set ({@code null}) then it will * default to {@link GrpcUtil#DEFAULT_MAX_MESSAGE_SIZE gRPC's default}. If set to {@code -1} then it will use the * highest possible limit (not recommended). * * @param maxInboundMessageSize The new maximum size allowed for incoming messages. {@code -1} for max possible. * Null to use the gRPC's default. * * @see ServerBuilder#maxInboundMessageSize(int) */ public void setMaxInboundMessageSize(final DataSize maxInboundMessageSize) { if (maxInboundMessageSize == null || maxInboundMessageSize.toBytes() >= 0) { this.maxInboundMessageSize = maxInboundMessageSize; } else if (maxInboundMessageSize.toBytes() == -1) { this.maxInboundMessageSize = DataSize.ofBytes(Integer.MAX_VALUE); } else { throw new IllegalArgumentException("Unsupported maxInboundMessageSize: " + maxInboundMessageSize); } }
/** * Sets the maximum metadata size allowed to be received by the server. If not set ({@code null}) then it will * default to {@link GrpcUtil#DEFAULT_MAX_HEADER_LIST_SIZE gRPC's default}. If set to {@code -1} then it will use * the highest possible limit (not recommended). * * @param maxInboundMetadataSize The new maximum size allowed for incoming metadata. {@code -1} for max possible. * Null to use the gRPC's default. * * @see ServerBuilder#maxInboundMetadataSize(int) */ public void setMaxInboundMetadataSize(final DataSize maxInboundMetadataSize) { if (maxInboundMetadataSize == null || maxInboundMetadataSize.toBytes() >= 0) { this.maxInboundMetadataSize = maxInboundMetadataSize; } else if (maxInboundMetadataSize.toBytes() == -1) { this.maxInboundMetadataSize = DataSize.ofBytes(Integer.MAX_VALUE); } else { throw new IllegalArgumentException("Unsupported maxInboundMetadataSize: " + maxInboundMetadataSize); } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\config\GrpcServerProperties.java
2
请完成以下Java代码
protected String doIt() throws Exception { final Timestamp startTime = SystemTime.asTimestamp(); addLog("Creating/updating C_Subscription_Progress records"); final int countProcessedTerms = createOrUpdateSubscriptionProgress(); addLog("Creating/updating shipment schedules"); final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.runInNewTrx(() -> { subscriptionBL.evalDeliveries(getCtx()); }); addLog("Done after {}" + " (evaluated {} terms)", TimeUtil.formatElapsed(startTime), countProcessedTerms); return "@Success@"; } private int createOrUpdateSubscriptionProgress() { final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); try (final IAutoCloseable createMissingScheds = shipmentScheduleBL.postponeMissingSchedsCreationUntilClose()) { return createOrUpdateSubscriptionProgress0(); } } private int createOrUpdateSubscriptionProgress0() { int errorCount = 0; int count = 0; final Iterator<I_C_Flatrate_Term> termsToEvaluate = retrieveTermsToEvaluate(); while (termsToEvaluate.hasNext()) { final I_C_Flatrate_Term term = termsToEvaluate.next(); if (invokeEvalCurrentSPs(term)) { count++; } else { errorCount++; } } addLog(errorCount + " errors on updating subscriptions"); return count; } private Iterator<I_C_Flatrate_Term> retrieveTermsToEvaluate() { final Iterator<I_C_Flatrate_Term> termsToEval = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyContextClient(getCtx()) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, X_C_Flatrate_Term.CONTRACTSTATUS_DeliveryPause, X_C_Flatrate_Term.CONTRACTSTATUS_Running, X_C_Flatrate_Term.CONTRACTSTATUS_Waiting,
X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate).addColumn(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID).endOrderBy() .create() .iterate(I_C_Flatrate_Term.class); return termsToEval; } private boolean invokeEvalCurrentSPs(final I_C_Flatrate_Term flatrateTerm) { final Mutable<Boolean> success = new Mutable<>(false); Services.get(ITrxManager.class).runInNewTrx(() -> { try { subscriptionBL.evalCurrentSPs(flatrateTerm, currentDate); success.setValue(true); } catch (final AdempiereException e) { addLog("Error updating " + flatrateTerm + ": " + e.getMessage()); } }); return success.getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgress_Evaluate.java
1
请完成以下Java代码
public Expression getFormKeyExpression() { return formKeyExpression; } public void setFormKeyExpression(Expression formKeyExpression) { this.formKeyExpression = formKeyExpression; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Expression getDueDateExpression() { return dueDateExpression; } public void setDueDateExpression(Expression dueDateExpression) { this.dueDateExpression = dueDateExpression; } public Expression getBusinessCalendarNameExpression() { return businessCalendarNameExpression; } public void setBusinessCalendarNameExpression(Expression businessCalendarNameExpression) { this.businessCalendarNameExpression = businessCalendarNameExpression; } public Expression getCategoryExpression() { return categoryExpression; } public void setCategoryExpression(Expression categoryExpression) { this.categoryExpression = categoryExpression; } public Map<String, List<TaskListener>> getTaskListeners() { return taskListeners;
} public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) { this.taskListeners = taskListeners; } public List<TaskListener> getTaskListener(String eventName) { return taskListeners.get(eventName); } public void addTaskListener(String eventName, TaskListener taskListener) { if (TaskListener.EVENTNAME_ALL_EVENTS.equals(eventName)) { // In order to prevent having to merge the "all" tasklisteners with the ones for a specific eventName, // every time "getTaskListener()" is called, we add the listener explicitly to the individual lists this.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener); this.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener); } else { List<TaskListener> taskEventListeners = taskListeners.get(eventName); if (taskEventListeners == null) { taskEventListeners = new ArrayList<>(); taskListeners.put(eventName, taskEventListeners); } taskEventListeners.add(taskListener); } } public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\task\TaskDefinition.java
1
请完成以下Spring Boot application配置
server.port=8081 keycloak.enabled=true spring.security.oauth2.client.registration.keycloak.client-id=login-app spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.keycloak.scope=openid spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak spring.security.o
auth2.client.provider.keycloak.user-name-attribute=preferred_username spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-2\src\main\resources\application-disabling-keycloak.properties
2
请完成以下Java代码
void build() { _ranks = new int[_units.size()]; _numOnes = 0; for (int i = 0; i < _units.size(); ++i) { _ranks[i] = _numOnes; _numOnes += popCount(_units.get(i)); } } /** * 清空 */ void clear() { _units.clear(); _ranks = null; } /** * 整型大小 */ private static final int UNIT_SIZE = 32; // sizeof(int) * 8 /** * 1的数量 * @param unit * @return */ private static int popCount(int unit) { unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555); unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333); unit = ((unit >>> 4) + unit) & 0x0F0F0F0F; unit += unit >>> 8; unit += unit >>> 16; return unit & 0xFF; }
/** * 储存空间 */ private AutoIntPool _units = new AutoIntPool(); /** * 是每个元素的1的个数的累加 */ private int[] _ranks; /** * 1的数量 */ private int _numOnes; /** * 大小 */ private int _size; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
1
请完成以下Java代码
public String getNewAssigneeId() { return newAssigneeId; } public void setNewAssigneeId(String newAssigneeId) { this.newAssigneeId = newAssigneeId; } public Map<String, PlanItemInstanceEntity> getContinueParentPlanItemInstanceMap() { return continueParentPlanItemInstanceMap; } public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) { this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap; } public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) { continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance); } public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) { return continueParentPlanItemInstanceMap.get(planItemInstanceId); } public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() { return moveToPlanItemMap; } public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) { this.moveToPlanItemMap = moveToPlanItemMap; } public PlanItemMoveEntry getMoveToPlanItem(String planItemId) { return moveToPlanItemMap.get(planItemId); }
public List<PlanItemMoveEntry> getMoveToPlanItems() { return new ArrayList<>(moveToPlanItemMap.values()); } public static class PlanItemMoveEntry { protected PlanItem originalPlanItem; protected PlanItem newPlanItem; public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) { this.originalPlanItem = originalPlanItem; this.newPlanItem = newPlanItem; } public PlanItem getOriginalPlanItem() { return originalPlanItem; } public PlanItem getNewPlanItem() { return newPlanItem; } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentFieldDefaultFilterDescriptor { boolean defaultFilter; int defaultFilterSeqNo; FilterOperator operator; boolean showFilterIncrementButtons; Object autoFilterInitialValue; boolean showFilterInline; @Nullable AdValRuleId adValRuleId; boolean facetFilter; int facetFilterSeqNo; OptionalInt maxFacetsToFetch; @Builder public DocumentFieldDefaultFilterDescriptor( final int seqNo, // final boolean defaultFilter, final int defaultFilterSeqNo, final FilterOperator operator, final boolean showFilterIncrementButtons, final boolean showFilterInline, @Nullable final Object autoFilterInitialValue, @Nullable AdValRuleId adValRuleId, // final boolean facetFilter, final int facetFilterSeqNo, @Nullable final OptionalInt maxFacetsToFetch) { if (!defaultFilter && !facetFilter) { throw new AdempiereException("defaultFilter or facetFilter shall be true"); } if (defaultFilter) { this.defaultFilter = true; this.defaultFilterSeqNo = defaultFilterSeqNo > 0 ? defaultFilterSeqNo : Integer.MAX_VALUE; this.operator = operator != null ? operator : FilterOperator.EQUALS_OR_ILIKE; this.showFilterIncrementButtons = showFilterIncrementButtons; this.autoFilterInitialValue = autoFilterInitialValue; this.showFilterInline = showFilterInline; this.adValRuleId = adValRuleId; } else { this.defaultFilter = false; this.defaultFilterSeqNo = Integer.MAX_VALUE; this.operator = FilterOperator.EQUALS_OR_ILIKE; this.showFilterIncrementButtons = false; this.autoFilterInitialValue = null; this.showFilterInline = false; this.adValRuleId = null; } if (facetFilter) { this.facetFilter = true; this.facetFilterSeqNo = facetFilterSeqNo > 0 ? facetFilterSeqNo : Integer.MAX_VALUE; this.maxFacetsToFetch = maxFacetsToFetch != null ? maxFacetsToFetch : OptionalInt.empty(); } else {
this.facetFilter = false; this.facetFilterSeqNo = Integer.MAX_VALUE; this.maxFacetsToFetch = OptionalInt.empty(); } } public enum FilterOperator implements ReferenceListAwareEnum { EQUALS_OR_ILIKE(X_AD_Column.FILTEROPERATOR_EqualsOrLike), BETWEEN(X_AD_Column.FILTEROPERATOR_Between), IS_NOT_NULL(X_AD_Column.FILTEROPERATOR_NotNull), ; @Getter private final String code; private static final ReferenceListAwareEnums.ValuesIndex<FilterOperator> index = ReferenceListAwareEnums.index(FilterOperator.values()); FilterOperator(@NonNull final String code) { this.code = code; } public static FilterOperator ofNullableStringOrEquals(@Nullable final String code) { final FilterOperator type = index.ofNullableCode(code); return type != null ? type : EQUALS_OR_ILIKE; } public static FilterOperator ofCode(@NonNull final String code) { return index.ofCode(code); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDefaultFilterDescriptor.java
2
请完成以下Java代码
public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Relative Priority. @param PromotionPriority Which promotion should be apply to a product */ public void setPromotionPriority (int PromotionPriority) { set_Value (COLUMNNAME_PromotionPriority, Integer.valueOf(PromotionPriority)); } /** Get Relative Priority. @return Which promotion should be apply to a product */ public int getPromotionPriority () { Integer ii = (Integer)get_Value(COLUMNNAME_PromotionPriority); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Promotion.java
1
请完成以下Java代码
public <T> T getDynAttribute(final String attributeName) { if (recordId2dynAttributes == null) { return null; } final int recordId = getGridTab().getRecord_ID(); final Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId); // Cleanup old entries to avoid weird cases // e.g. dynattributes shall be destroyed when user is switching to another record removeOldDynAttributesEntries(recordId); if (dynAttributes == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)dynAttributes.get(attributeName); return value; } public Object setDynAttribute(final String attributeName, final Object value) { Check.assumeNotEmpty(attributeName, "attributeName not empty"); final int recordId = getGridTab().getRecord_ID(); Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId); if (dynAttributes == null) { dynAttributes = new HashMap<>(); recordId2dynAttributes.put(recordId, dynAttributes); } final Object valueOld = dynAttributes.put(attributeName, value); // Cleanup old entries because in most of the cases we won't use them removeOldDynAttributesEntries(recordId); // // return the old value return valueOld; } private void removeOldDynAttributesEntries(final int recordIdToKeep) { for (final Iterator<Integer> recordIds = recordId2dynAttributes.keySet().iterator(); recordIds.hasNext();) { final Integer dynAttribute_recordId = recordIds.next();
if (dynAttribute_recordId != null && dynAttribute_recordId == recordIdToKeep) { continue; } recordIds.remove(); } } public final IModelInternalAccessor getModelInternalAccessor() { return modelInternalAccessorSupplier.get(); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final GridTabWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GridTabWrapper.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param QtyEntered Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public void setQtyEntered (BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } /** Get Menge. @return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit */ public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; }
/** Set Quantity Invoiced. @param QtyInvoiced Invoiced Quantity */ public void setQtyInvoiced (BigDecimal QtyInvoiced) { set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced); } /** Get Quantity Invoiced. @return Invoiced Quantity */ public BigDecimal getQtyInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=12345678 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.database
-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto=create
repos\SpringBoot-Learning-master\2.x\chapter3-10\src\main\resources\application.properties
2
请完成以下Java代码
public void setIsDueFixed (final boolean IsDueFixed) { set_Value (COLUMNNAME_IsDueFixed, IsDueFixed); } @Override public boolean isDueFixed() { return get_ValueAsBoolean(COLUMNNAME_IsDueFixed); } @Override public void setIsNextBusinessDay (final boolean IsNextBusinessDay) { set_Value (COLUMNNAME_IsNextBusinessDay, IsNextBusinessDay); } @Override public boolean isNextBusinessDay() { return get_ValueAsBoolean(COLUMNNAME_IsNextBusinessDay); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setName_Invoice (final @Nullable java.lang.String Name_Invoice) { set_Value (COLUMNNAME_Name_Invoice, Name_Invoice); } @Override public java.lang.String getName_Invoice() { return get_ValueAsString(COLUMNNAME_Name_Invoice); } /** * NetDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int NETDAY_AD_Reference_ID=167; /** Sunday = 7 */ public static final String NETDAY_Sunday = "7"; /** Monday = 1 */ public static final String NETDAY_Monday = "1"; /** Tuesday = 2 */ public static final String NETDAY_Tuesday = "2";
/** Wednesday = 3 */ public static final String NETDAY_Wednesday = "3"; /** Thursday = 4 */ public static final String NETDAY_Thursday = "4"; /** Friday = 5 */ public static final String NETDAY_Friday = "5"; /** Saturday = 6 */ public static final String NETDAY_Saturday = "6"; @Override public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay() { return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentTerm.java
1
请完成以下Java代码
private String getLookupColumnName(final Method method) { if (method == null) { return null; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return null; } final String lookupColumnName = info.lookupColumnName(); if (Check.isEmpty(lookupColumnName)) { return null; } return lookupColumnName; } private String getPrototypeValue(final PropertyDescriptor pd) { String prototypeValue = getPrototypeValue(pd.getReadMethod()); if (Check.isEmpty(prototypeValue)) { prototypeValue = getPrototypeValue(pd.getWriteMethod()); } return prototypeValue; } private String getPrototypeValue(final Method method) { if (method == null) { return null; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return null; } final String prototypeValue = info.prototypeValue(); if (Check.isEmpty(prototypeValue, false)) { return null; } return prototypeValue; } private int getDisplayType(final PropertyDescriptor pd) { int displayType = getDisplayType(pd.getReadMethod()); if (displayType <= 0) { displayType = getDisplayType(pd.getWriteMethod()); } if (displayType <= 0) { displayType = suggestDisplayType(pd.getReadMethod().getReturnType()); } return displayType; } private static final int suggestDisplayType(final Class<?> returnType) { if (returnType == String.class) { return DisplayType.String; } else if (returnType == Boolean.class || returnType == boolean.class) { return DisplayType.YesNo; } else if (returnType == BigDecimal.class) { return DisplayType.Amount; } else if (returnType == Integer.class) { return DisplayType.Integer; } else if (Date.class.isAssignableFrom(returnType))
{ return DisplayType.Date; } else { return -1; } } private int getDisplayType(final Method method) { if (method == null) { return -1; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return -1; } final int displayType = info.displayType(); return displayType > 0 ? displayType : -1; } private boolean isSelectionColumn(final PropertyDescriptor pd) { Boolean selectionColumn = getSelectionColumn(pd.getReadMethod()); if (selectionColumn == null) { selectionColumn = getSelectionColumn(pd.getWriteMethod()); } return selectionColumn != null ? selectionColumn : false; } private Boolean getSelectionColumn(final Method method) { if (method == null) { return null; } final ColumnInfo info = method.getAnnotation(ColumnInfo.class); if (info == null) { return null; } return info.selectionColumn(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableModelMetaInfo.java
1
请在Spring Boot框架中完成以下Java代码
public AppDefinitionQuery orderByAppDefinitionId() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_ID); } @Override public AppDefinitionQuery orderByAppDefinitionVersion() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_VERSION); } @Override public AppDefinitionQuery orderByAppDefinitionName() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_NAME); } @Override public AppDefinitionQuery orderByTenantId() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionCountByQueryCriteria(this); } @Override public List<AppDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public Integer getVersion() { return version; } public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; } public Integer getVersionLt() {
return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String login(HttpServletRequest request, Map<String, Object> map) { _logger.info("登录方法start........."); // 登录失败从request中获取shiro处理的异常信息。shiroLoginFailure:就是shiro异常类的全类名. Object exception = request.getAttribute("shiroLoginFailure"); String msg; if (exception != null) { if (UnknownAccountException.class.isInstance(exception)) { msg = "用户名不正确,请重新输入"; } else if (IncorrectCredentialsException.class.isInstance(exception)) { msg = "密码错误,请重新输入"; } else if (IncorrectCaptchaException.class.isInstance(exception)) { msg = "验证码错误"; } else if (ForbiddenUserException.class.isInstance(exception)) { msg = "该用户已被禁用,如有疑问请联系系统管理员。"; } else { msg = "发生未知错误,请联系管理员。"; } map.put("username", request.getParameter("username")); map.put("password", request.getParameter("password")); map.put("msg", msg); return "login"; } //如果已经登录,直接跳转主页面 return "index"; } /** * 主页 * @param session * @param model * @return */ @RequestMapping({"/", "/index"}) public String index(HttpSession session, Model model) { // _logger.info("访问首页start...");
// 做一些其他事情,比如把项目的数量放到session中 if (ShiroKit.hasRole("admin") && session.getAttribute("projectNum") == null) { session.setAttribute("projectNum", 2); } if (session.getAttribute("picsUrlPrefix") == null) { // 图片访问URL前缀 session.setAttribute("picsUrlPrefix", myProperties.getPicsUrlPrefix()); } return "index"; } /** * 欢迎页面 * @param request * @param model * @return */ @RequestMapping("/welcome") public String welcome(HttpServletRequest request, Model model) { return "modules/common/welcome"; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\controller\LoginController.java
2
请在Spring Boot框架中完成以下Java代码
protected Customer prepare(EntitiesImportCtx ctx, Customer customer, Customer old, EntityExportData<Customer> exportData, IdProvider idProvider) { if (customer.isPublic()) { Customer publicCustomer = customerService.findOrCreatePublicCustomer(ctx.getTenantId()); publicCustomer.setExternalId(customer.getExternalId()); return publicCustomer; } else { return customer; } } @Override protected Customer saveOrUpdate(EntitiesImportCtx ctx, Customer customer, EntityExportData<Customer> exportData, IdProvider idProvider, CompareResult compareResult) { if (!customer.isPublic()) { return customerService.saveCustomer(customer); } else {
return customerDao.save(ctx.getTenantId(), customer); } } @Override protected Customer deepCopy(Customer customer) { return new Customer(customer); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\CustomerImportService.java
2
请在Spring Boot框架中完成以下Java代码
public Object getCredentials() { return getSaml2Response(); } /** * Always returns null. * @return null */ @Override public Object getPrincipal() { return null; } /** * Get the resolved {@link RelyingPartyRegistration} associated with the request * @return the resolved {@link RelyingPartyRegistration} * @since 5.4 */ public RelyingPartyRegistration getRelyingPartyRegistration() { return this.relyingPartyRegistration; } /** * Returns inflated and decoded XML representation of the SAML 2 Response * @return inflated and decoded XML representation of the SAML 2 Response */ public String getSaml2Response() { return this.saml2Response; } /** * @return false */
@Override public boolean isAuthenticated() { return false; } /** * The state of this object cannot be changed. Will always throw an exception * @param authenticated ignored */ @Override public void setAuthenticated(boolean authenticated) { throw new IllegalArgumentException(); } /** * Returns the authentication request sent to the assertion party or {@code null} if * no authentication request is present * @return the authentication request sent to the assertion party * @since 5.6 */ public AbstractSaml2AuthenticationRequest getAuthenticationRequest() { return this.authenticationRequest; } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2AuthenticationToken.java
2
请完成以下Java代码
public void toStop(){ // 1、stop schedule scheduleThreadToStop = true; try { TimeUnit.SECONDS.sleep(1); // wait } catch (InterruptedException e) { logger.error(e.getMessage(), e); } if (scheduleThread.getState() != Thread.State.TERMINATED){ // interrupt and wait scheduleThread.interrupt(); try { scheduleThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } // if has ring data boolean hasRingData = false; if (!ringData.isEmpty()) { for (int second : ringData.keySet()) { List<Integer> tmpData = ringData.get(second); if (tmpData!=null && tmpData.size()>0) { hasRingData = true; break; } } } if (hasRingData) { try { TimeUnit.SECONDS.sleep(8); } catch (InterruptedException e) { logger.error(e.getMessage(), e); }
} // stop ring (wait job-in-memory stop) ringThreadToStop = true; try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } if (ringThread.getState() != Thread.State.TERMINATED){ // interrupt and wait ringThread.interrupt(); try { ringThread.join(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } logger.info(">>>>>>>>>>> xxl-job, JobScheduleHelper stop"); } // ---------------------- tools ---------------------- public static Date generateNextValidTime(XxlJobInfo jobInfo, Date fromTime) throws Exception { ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null); if (ScheduleTypeEnum.CRON == scheduleTypeEnum) { Date nextValidTime = new CronExpression(jobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime); return nextValidTime; } else if (ScheduleTypeEnum.FIX_RATE == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) { return new Date(fromTime.getTime() + Integer.valueOf(jobInfo.getScheduleConf())*1000 ); } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobScheduleHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class MTLinkRequest { /** What to do if the model is already linked to a different material tracking */ public enum IfModelAlreadyLinked { /** If the model is already linked an exception is thrown. */ FAIL, /** * If the model is already linked, it unassigns the model from old material tracking. */ UNLINK_FROM_PREVIOUS, ADD_ADDITIONAL_LINK } @Default IfModelAlreadyLinked ifModelAlreadyLinked = IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS; /** Required if {@link IfModelAlreadyLinked#UNLINK_FROM_PREVIOUS}, if there are more than one previously linked material trackings */ Integer previousMaterialTrackingId; @NonNull Object model;
@Default IParams params = IParams.NULL; @NonNull I_M_Material_Tracking materialTrackingRecord; /** Can be set if this request is about linking a PP_Order. Note that unfortunately there is no UOM-field; The UOM is implicitly the product's stocking-UOM. */ BigDecimal qtyIssued; /** * Convenience method that uses the {@link InterfaceWrapperHelper} to get the mode as an instance of the given <code>clazz</code>. */ public <T> T getModel(final Class<T> clazz) { return InterfaceWrapperHelper.create(model, clazz); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\MTLinkRequest.java
2
请完成以下Java代码
public Collection<DocumentFilterDescriptor> getAll() { return providers .stream() .map(DocumentFilterDescriptorsProvider::getAll) .flatMap(Collection::stream) .sorted(Comparator.comparing(DocumentFilterDescriptor::getSortNo)) .collect(GuavaCollectors.toImmutableMapByKey(DocumentFilterDescriptor::getFilterId)) // make sure each filterId is unique! .values(); } @Override public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId) { return providers .stream() .map(provider -> provider.getByFilterIdOrNull(filterId)) .filter(Objects::nonNull) .findFirst() .orElse(null); }
@Override public DocumentFilter unwrap(@NonNull final JSONDocumentFilter jsonFilter) { return getProviderByFilterId(jsonFilter.getFilterId()) .map(provider -> provider.unwrap(jsonFilter)) .orElseGet(() -> JSONDocumentFilter.unwrapAsGenericFilter(jsonFilter)); } private Optional<DocumentFilterDescriptorsProvider> getProviderByFilterId(@NonNull final String filterId) { return providers .stream() .filter(provider -> provider.getByFilterIdOrNull(filterId) != null) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\CompositeDocumentFilterDescriptorsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class JavaReflectionsScannerService implements SampleAnnotationScanner { @Override public List<String> scanAnnotatedMethods() { try { Class<?> clazz = ClassLoader.getSystemClassLoader() .loadClass("com.baeldung.annotation.scanner.SampleAnnotatedClass"); Method[] methods = clazz.getMethods(); List<String> annotatedMethods = new ArrayList<>(); for (Method method : methods) { SampleAnnotation annotation = method.getAnnotation(SampleAnnotation.class); if (annotation != null) { annotatedMethods.add(annotation.name()); } } return Collections.unmodifiableList(annotatedMethods); } catch (ClassNotFoundException e) { throw new UnexpectedScanException(e); } } @Override public List<String> scanAnnotatedClasses() { try { Class<?> clazz = ClassLoader.getSystemClassLoader() .loadClass("com.baeldung.annotation.scanner.SampleAnnotatedClass");
List<String> annotatedClasses = new ArrayList<>(); Annotation[] classAnnotations = clazz.getAnnotations(); for (Annotation annotation : classAnnotations) { if (annotation.annotationType() .equals(SampleAnnotation.class)) { annotatedClasses.add(((SampleAnnotation) annotation).name()); } } return Collections.unmodifiableList(annotatedClasses); } catch (ClassNotFoundException e) { throw new UnexpectedScanException(e); } } @Override public boolean supportsMethodScan() { return true; } @Override public boolean supportsClassScan() { return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-2\src\main\java\com\baeldung\annotation\scanner\javareflectionlib\JavaReflectionsScannerService.java
2
请完成以下Java代码
public Printable getPrintable() { return printable; } public void setPrintable(final Printable printable) { this.printable = printable; } public int getNumPages() { return numPages; } public void setNumPages(final int numPages) { this.numPages = numPages;
} @Override public String toString() { return "PrintPackageRequest [" + "printPackage=" + printPackage + ", printPackageInfo=" + printPackageInfo + ", attributes=" + attributes + ", printService=" + printService + ", printJobName=" + printJobName + ", printable=" + printable + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintPackageRequest.java
1
请在Spring Boot框架中完成以下Java代码
public static class HeadersExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo04Queue() { return new Queue(Demo04Message.QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Headers Exchange @Bean public HeadersExchange demo04Exchange() { return new HeadersExchange(Demo04Message.EXCHANGE, true, // durable: 是否持久化
false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo04Message.EXCHANGE // Queue:Demo04Message.QUEUE // Headers: Demo04Message.HEADER_KEY + Demo04Message.HEADER_VALUE @Bean public Binding demo4Binding() { return BindingBuilder.bind(demo04Queue()).to(demo04Exchange()) .where(Demo04Message.HEADER_KEY).matches(Demo04Message.HEADER_VALUE); // 配置 Headers 匹配 } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public void configurePolymorphicTypeValidator(BasicPolymorphicTypeValidator.Builder builder) { } @Override public void setupModule(SetupContext context) { context.setMixIn(Bytes.class, BytesMixin.class); context.setMixIn(AttestationConveyancePreference.class, AttestationConveyancePreferenceMixin.class); context.setMixIn(AuthenticationExtensionsClientInput.class, AuthenticationExtensionsClientInputMixin.class); context.setMixIn(AuthenticationExtensionsClientInputs.class, AuthenticationExtensionsClientInputsMixin.class); context.setMixIn(AuthenticationExtensionsClientOutputs.class, AuthenticationExtensionsClientOutputsMixin.class); context.setMixIn(AuthenticatorAssertionResponse.AuthenticatorAssertionResponseBuilder.class, AuthenticatorAssertionResponseMixin.AuthenticatorAssertionResponseBuilderMixin.class); context.setMixIn(AuthenticatorAssertionResponse.class, AuthenticatorAssertionResponseMixin.class); context.setMixIn(AuthenticatorAttachment.class, AuthenticatorAttachmentMixin.class); context.setMixIn(AuthenticatorAttestationResponse.class, AuthenticatorAttestationResponseMixin.class); context.setMixIn(AuthenticatorAttestationResponse.AuthenticatorAttestationResponseBuilder.class, AuthenticatorAttestationResponseMixin.AuthenticatorAttestationResponseBuilderMixin.class); context.setMixIn(AuthenticatorSelectionCriteria.class, AuthenticatorSelectionCriteriaMixin.class); context.setMixIn(AuthenticatorTransport.class, AuthenticatorTransportMixin.class);
context.setMixIn(COSEAlgorithmIdentifier.class, COSEAlgorithmIdentifierMixin.class); context.setMixIn(CredentialPropertiesOutput.class, CredentialPropertiesOutputMixin.class); context.setMixIn(CredProtectAuthenticationExtensionsClientInput.class, CredProtectAuthenticationExtensionsClientInputMixin.class); context.setMixIn(PublicKeyCredential.PublicKeyCredentialBuilder.class, PublicKeyCredentialMixin.PublicKeyCredentialBuilderMixin.class); context.setMixIn(PublicKeyCredential.class, PublicKeyCredentialMixin.class); context.setMixIn(PublicKeyCredentialCreationOptions.class, PublicKeyCredentialCreationOptionsMixin.class); context.setMixIn(PublicKeyCredentialRequestOptions.class, PublicKeyCredentialRequestOptionsMixin.class); context.setMixIn(PublicKeyCredentialType.class, PublicKeyCredentialTypeMixin.class); context.setMixIn(RelyingPartyPublicKey.class, RelyingPartyPublicKeyMixin.class); context.setMixIn(ResidentKeyRequirement.class, ResidentKeyRequirementMixin.class); context.setMixIn(UserVerificationRequirement.class, UserVerificationRequirementMixin.class); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\jackson\WebauthnJacksonModule.java
1
请完成以下Java代码
public LocalDateTime increment(final LocalDateTime date) { if (date.getDayOfWeek().getValue() >= dayOfWeek.getValue()) { return date.with(TemporalAdjusters.previousOrSame(dayOfWeek)).plusWeeks(weeksToAdd); } else { return date.with(TemporalAdjusters.next(dayOfWeek)); } } @Override public LocalDateTime decrement(final LocalDateTime date) {
if (weeksToAdd > 1) { throw new UnsupportedOperationException("Decrementing using a step greater than one is not supported"); } if (date.getDayOfWeek().getValue() <= dayOfWeek.getValue()) { return date.with(TemporalAdjusters.nextOrSame(dayOfWeek)).minusWeeks(weeksToAdd); } else { return date.with(TemporalAdjusters.previous(dayOfWeek)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\WeekDayCalendarIncrementor.java
1
请在Spring Boot框架中完成以下Java代码
public class S3ClientConfiguration { @Bean public S3AsyncClient s3client(S3ClientConfigurarionProperties s3props, AwsCredentialsProvider credentialsProvider) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() .writeTimeout(Duration.ZERO) .maxConcurrency(64) .build(); S3Configuration serviceConfiguration = S3Configuration.builder() .checksumValidationEnabled(false) .chunkedEncodingEnabled(true) .build(); S3AsyncClientBuilder b = S3AsyncClient.builder() .httpClient(httpClient) .region(s3props.getRegion()) .credentialsProvider(credentialsProvider) .serviceConfiguration(serviceConfiguration); if (s3props.getEndpoint() != null) { b = b.endpointOverride(s3props.getEndpoint()); } return b.build(); }
@Bean public AwsCredentialsProvider awsCredentialsProvider(S3ClientConfigurarionProperties s3props) { if (StringUtils.isBlank(s3props.getAccessKeyId())) { // Return default provider return DefaultCredentialsProvider.create(); } else { // Return custom credentials provider return () -> { AwsCredentials creds = AwsBasicCredentials.create(s3props.getAccessKeyId(), s3props.getSecretAccessKey()); return creds; }; } } }
repos\tutorials-master\aws-modules\aws-reactive\src\main\java\com\baeldung\aws\reactive\s3\S3ClientConfiguration.java
2
请完成以下Java代码
public class MigratingTimerJobInstance extends MigratingJobInstance { protected ScopeImpl timerTriggerTargetScope; protected TimerDeclarationImpl targetJobDeclaration; protected boolean updateEvent; public MigratingTimerJobInstance(JobEntity jobEntity) { super(jobEntity); } public MigratingTimerJobInstance(JobEntity jobEntity, JobDefinitionEntity jobDefinitionEntity, ScopeImpl targetScope, boolean updateEvent, TimerDeclarationImpl targetTimerDeclaration) { super(jobEntity, jobDefinitionEntity, targetScope); timerTriggerTargetScope = determineTimerTriggerTargetScope(jobEntity, targetScope); this.updateEvent = updateEvent; this.targetJobDeclaration = targetTimerDeclaration; } protected ScopeImpl determineTimerTriggerTargetScope(JobEntity jobEntity, ScopeImpl targetScope) {
if (TimerStartEventSubprocessJobHandler.TYPE.equals(jobEntity.getJobHandlerType())) { // for event subprocess start jobs, the job handler configuration references the subprocess while // the job references the start event return targetScope.getFlowScope(); } else { return targetScope; } } @Override protected void migrateJobHandlerConfiguration() { TimerJobConfiguration configuration = (TimerJobConfiguration) jobEntity.getJobHandlerConfiguration(); configuration.setTimerElementKey(timerTriggerTargetScope.getId()); jobEntity.setJobHandlerConfiguration(configuration); if (updateEvent) { targetJobDeclaration.updateJob((TimerEntity) jobEntity); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingTimerJobInstance.java
1
请完成以下Java代码
/* package */final class InvocationContext implements IInvocationContext { private final Method method; private final Object[] methodArgs; private final Object target; public InvocationContext(final Method method, final Object[] methodArgs, final Object target) { super(); this.method = method; this.methodArgs = methodArgs; this.target = target; } @Override public String toString() { return "InvocationContext [" + "method=" + method + ", args=" + Arrays.toString(methodArgs) + ", target=" + target + "]"; } @Override public Object proceed() throws Throwable { if (!method.isAccessible()) { method.setAccessible(true); } try { return method.invoke(target, methodArgs); } catch (InvocationTargetException ite) { // unwrap the target implementation's exception to that it can be caught throw ite.getTargetException();
} } @Override public Object call() throws Exception { try { final Object result = proceed(); return result == null ? NullResult : result; } catch (Exception e) { throw e; } catch (Throwable e) { Throwables.propagateIfPossible(e); throw Throwables.propagate(e); } } @Override public Object getTarget() { return target; } @Override public Object[] getParameters() { return methodArgs; } @Override public Method getMethod() { return method; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\InvocationContext.java
1
请完成以下Java代码
public void setStatusLine(final String text) { if (text == null) { setStatusLine("", false); } else { setStatusLine(text, false); } } // setStatusLine /** * Set Status Line * * @param text text * @param error error */ @Override public void setStatusLine(final String text, final boolean error) { mt_error = error; mt_text = text; if (mt_error) { statusLine.setForeground(AdempierePLAF.getTextColor_Issue()); } else { statusLine.setForeground(AdempierePLAF.getTextColor_OK()); } if (mt_text == null || mt_text.length() == 0) { statusLine.setText(""); } else { statusLine.setText(" " + mt_text); } // Thread.yield(); } // setStatusLine /** * Get Status Line text * * @return StatusLine text */ public String getStatusLine() { return statusLine.getText().trim(); } // setStatusLine /** * Set ToolTip of StatusLine * * @param tip tip */ public void setStatusToolTip(final String tip) { statusLine.setToolTipText(tip); } // setStatusToolTip /** * Set Status DB Info * * @param text text * @param dse data status event */ @Override public void setStatusDB(final String text, final DataStatusEvent dse) { // log.info( "StatusBar.setStatusDB - " + text + " - " + created + "/" + createdBy); if (text == null || text.length() == 0) { statusDB.setText(""); statusDB.setVisible(false); } else { final StringBuilder sb = new StringBuilder(" "); sb.append(text).append(" "); statusDB.setText(sb.toString()); if (!statusDB.isVisible()) { statusDB.setVisible(true); } } // Save // m_text = text; m_dse = dse; } // setStatusDB /** * Set Status DB Info * * @param text text */ @Override public void setStatusDB(final String text) { setStatusDB(text, null); } // setStatusDB /** * Set Status DB Info * * @param no no */
public void setStatusDB(final int no) { setStatusDB(String.valueOf(no), null); } // setStatusDB /** * Set Info Line * * @param text text */ @Override public void setInfo(final String text) { infoLine.setVisible(true); infoLine.setText(text); } // setInfo /** * Show {@link RecordInfo} dialog */ private void showRecordInfo() { if (m_dse == null) { return; } final int adTableId = m_dse.getAdTableId(); final ComposedRecordId recordId = m_dse.getRecordId(); if (adTableId <= 0 || recordId == null) { return; } if (!Env.getUserRolePermissions().isShowPreference()) { return; } // final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId); AEnv.showCenterScreen(info); } public void removeBorders() { statusLine.setBorder(BorderFactory.createEmptyBorder()); statusDB.setBorder(BorderFactory.createEmptyBorder()); infoLine.setBorder(BorderFactory.createEmptyBorder()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java
1
请完成以下Java代码
public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public font addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public font addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the Element. @param element adds and Element to the Element. */ public font addElement(Element element)
{ addElementToRegistry(element); return(this); } /** Adds an Element to the Element. @param element adds and Element to the Element. */ public font addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public font removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\font.java
1
请完成以下Java代码
public Builder singleRowDetailLayout(final boolean singleRowDetailLayout) { this.singleRowDetailLayout = singleRowDetailLayout; return this; } /* package */ boolean isEmpty() { return (gridLayout == null || !gridLayout.hasElements()) && (singleRowLayout == null || singleRowLayout.isEmpty()); } public Builder queryOnActivate(final boolean queryOnActivate) { this.queryOnActivate = queryOnActivate; return this; } public Builder quickInputSupport(@Nullable final QuickInputSupportDescriptor quickInputSupport) { this.quickInputSupport = quickInputSupport; return this; } @Nullable public QuickInputSupportDescriptor getQuickInputSupport() { return quickInputSupport; } public Builder caption(@NonNull final ITranslatableString caption) { this.caption = caption; return this;
} public Builder description(@NonNull final ITranslatableString description) { this.description = description; return this; } public Builder addSubTabLayout(@NonNull final DocumentLayoutDetailDescriptor subTabLayout) { this.subTabLayouts.add(subTabLayout); return this; } public Builder addAllSubTabLayouts(@NonNull final List<DocumentLayoutDetailDescriptor> subTabLayouts) { this.subTabLayouts.addAll(subTabLayouts); return this; } public Builder newRecordInputMode(@NonNull final IncludedTabNewRecordInputMode newRecordInputMode) { this.newRecordInputMode = newRecordInputMode; return this; } private IncludedTabNewRecordInputMode getNewRecordInputModeEffective() { final boolean hasQuickInputSupport = getQuickInputSupport() != null; return newRecordInputMode.orCompatibleIfAllowQuickInputIs(hasQuickInputSupport); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDetailDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class AppDeploymentResourceResponse { private String id; private String url; private String contentUrl; private String mediaType; private String type; public AppDeploymentResourceResponse(String resourceId, String url, String contentUrl, String mediaType, String type) { setId(resourceId); setUrl(url); setContentUrl(contentUrl); setMediaType(mediaType); this.type = type; if (type == null) { this.type = "resource"; } } @ApiModelProperty(example = "oneApp.app") public String getId() { return id; } public void setId(String id) { this.id = id; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resources/oneApp.app") public String getUrl() { return url; } public void setContentUrl(String contentUrl) { this.contentUrl = contentUrl; } @ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/app-repository/deployments/10/resourcedata/oneApp.app") public String getContentUrl() { return contentUrl;
} public void setMediaType(String mimeType) { this.mediaType = mimeType; } @ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.") public String getMediaType() { return mediaType; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "appDefinition", value = "Type of resource", allowableValues = "resource,appDefinition") public String getType() { return type; } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResourceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String getClientIp() { return clientIp; } /** * @param clientIp The clientIp to set. */ public void setClientIp(String clientIp) { this.clientIp = clientIp; } public NameValuePair[] getParameters() { return parameters; } public void setParameters(NameValuePair[] parameters) { this.parameters = parameters; } public String getQueryString() { return queryString; } public void setQueryString(String queryString) { this.queryString = queryString; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public int getConnectionTimeout() { return connectionTimeout; }
public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the charset. */ public String getCharset() { return charset; } /** * @param charset The charset to set. */ public void setCharset(String charset) { this.charset = charset; } public HttpResultType getResultType() { return resultType; } public void setResultType(HttpResultType resultType) { this.resultType = resultType; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\httpClient\HttpRequest.java
2
请完成以下Java代码
public class User { private String firstName; private String lastName; private String email; private String username; private Long id; public String name() { return firstName + " " + lastName; } public User(String firstName, String lastName, String email, String username, Long id) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.username = username; this.id = id; } public static Builder builder() { return new Builder(); } public static class Builder { private String firstName; private String lastName; private String email; private String username; private Long id; private Builder() {
} public Builder firstName(String firstName) { this.firstName = firstName; return this; } public Builder lastName(String lastName) { this.lastName = lastName; return this; } public Builder email(String email) { this.email = email; return this; } public Builder username(String username) { this.username = username; return this; } public Builder id(Long id) { this.id = id; return this; } public User build() { return new User(firstName, lastName, email, username, id); } } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\fluentinterface\User.java
1
请完成以下Java代码
public static EventRegistryEngineConfiguration getEventRegistryConfiguration(CommandContext commandContext) { if (commandContext != null) { return (EventRegistryEngineConfiguration) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_EVENT_REGISTRY_CONFIG); } return null; } public static EventRepositoryService getEventRepositoryService() { return getEventRegistryConfiguration().getEventRepositoryService(); } public static DbSqlSession getDbSqlSession() { return getDbSqlSession(getCommandContext()); } public static DbSqlSession getDbSqlSession(CommandContext commandContext) { return commandContext.getSession(DbSqlSession.class); } public static EventResourceEntityManager getResourceEntityManager() { return getResourceEntityManager(getCommandContext()); } public static EventResourceEntityManager getResourceEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getResourceEntityManager(); } public static EventDeploymentEntityManager getDeploymentEntityManager() { return getDeploymentEntityManager(getCommandContext()); } public static EventDeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getDeploymentEntityManager(); } public static EventDefinitionEntityManager getEventDefinitionEntityManager() { return getEventDefinitionEntityManager(getCommandContext()); } public static EventDefinitionEntityManager getEventDefinitionEntityManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getEventDefinitionEntityManager(); } public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager() { return getChannelDefinitionEntityManager(getCommandContext()); } public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getChannelDefinitionEntityManager(); } public static TableDataManager getTableDataManager() { return getTableDataManager(getCommandContext()); } public static TableDataManager getTableDataManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getTableDataManager(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public String getProfileInfo () { return (String)get_Value(COLUMNNAME_ProfileInfo); } /** Set Issue System. @param R_IssueSystem_ID System creating the issue */ public void setR_IssueSystem_ID (int R_IssueSystem_ID) { if (R_IssueSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, Integer.valueOf(R_IssueSystem_ID)); } /** Get Issue System. @return System creating the issue */ public int getR_IssueSystem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueSystem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Statistics. @param StatisticsInfo Information to help profiling the system for solving support issues */ public void setStatisticsInfo (String StatisticsInfo) { set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo); }
/** Get Statistics. @return Information to help profiling the system for solving support issues */ public String getStatisticsInfo () { return (String)get_Value(COLUMNNAME_StatisticsInfo); } /** SystemStatus AD_Reference_ID=374 */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E"; /** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I"; /** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; /** Set System Status. @param SystemStatus Status of the system - Support priority depends on system status */ public void setSystemStatus (String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } /** Get System Status. @return Status of the system - Support priority depends on system status */ public String getSystemStatus () { return (String)get_Value(COLUMNNAME_SystemStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueSystem.java
1
请完成以下Java代码
boolean isEndOfLine() { return this.character == -1 || (!this.escaped && this.character == '\n'); } boolean isListDelimiter() { return !this.escaped && this.character == ','; } boolean isPropertyDelimiter() { return !this.escaped && (this.character == '=' || this.character == ':'); } char getCharacter() { return (char) this.character; } Location getLocation() { return new Location(this.reader.getLineNumber(), this.columnNumber); } boolean isSameLastLineCommentPrefix() { return this.lastLineCommentPrefixCharacter == this.character; } boolean isCommentPrefixCharacter() { return this.character == '#' || this.character == '!'; } boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) { this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请在Spring Boot框架中完成以下Java代码
public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getTransientVariables() { return transientVariables; } public void setTransientVariables(List<RestVariable> transientVariables) { this.transientVariables = transientVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getStartFormVariables() { return startFormVariables; }
public void setStartFormVariables(List<RestVariable> startFormVariables) { this.startFormVariables = startFormVariables; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } @JsonIgnore public boolean isTenantSet() { return tenantId != null && !StringUtils.isEmpty(tenantId); } public boolean getReturnVariables() { return returnVariables; } public void setReturnVariables(boolean returnVariables) { this.returnVariables = returnVariables; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceCreateRequest.java
2
请完成以下Java代码
private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetail from) { record.setIsActive(true); updateRecord(record, from.getOrderLineInfo()); record.setCostAmount(from.getCostAmount().toBigDecimal()); record.setQtyReceived(from.getInoutQty().toBigDecimal()); record.setCostAmountReceived(from.getInoutCostAmount().toBigDecimal()); } private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetailOrderLinePart from) { record.setC_OrderLine_ID(from.getOrderLineId().getRepoId()); record.setM_Product_ID(from.getProductId().getRepoId()); record.setC_UOM_ID(from.getUomId().getRepoId()); record.setQtyOrdered(from.getQtyOrdered().toBigDecimal()); record.setC_Currency_ID(from.getCurrencyId().getRepoId()); record.setLineNetAmt(from.getOrderLineNetAmt().toBigDecimal());
} public void changeByOrderLineId( @NonNull final OrderLineId orderLineId, @NonNull Consumer<OrderCost> consumer) { final List<OrderCost> orderCosts = getByOrderLineIds(ImmutableSet.of(orderLineId)); orderCosts.forEach(orderCost -> { consumer.accept(orderCost); saveUsingCache(orderCost); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepositorySession.java
1
请完成以下Java代码
public String getSourceProcessDefinitionId() { return sourceProcessDefinitionId; } public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetProcessDefinitionId() { return targetProcessDefinitionId; } @Override public VariableMap getVariables() { return variables; } public void setVariables(VariableMap variables) { this.variables = variables; } public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; }
public List<MigrationInstruction> getInstructions() { return instructions; } public void setInstructions(List<MigrationInstruction> instructions) { this.instructions = instructions; } public String toString() { return "MigrationPlan[" + "sourceProcessDefinitionId='" + sourceProcessDefinitionId + '\'' + ", targetProcessDefinitionId='" + targetProcessDefinitionId + '\'' + ", instructions=" + instructions + ']'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationPlanImpl.java
1
请完成以下Java代码
public void keyPressed(KeyEvent e) { // sequence: pressed - typed(no KeyCode) - released char input = e.getKeyChar(); int code = e.getKeyCode(); e.consume(); // does not work on JTextField if (code == KeyEvent.VK_DELETE) { input = 'A'; } else if (code == KeyEvent.VK_BACK_SPACE) { input = 'C'; } else if (code == KeyEvent.VK_ENTER) { input = '='; } else if (code == KeyEvent.VK_CANCEL || code == KeyEvent.VK_ESCAPE) { m_abort = true;
dispose(); return; } handleInput(input); } /** * KeyTyped Listener (nop) * @param e event */ @Override public void keyTyped(KeyEvent e) {} /** * KeyReleased Listener (nop) * @param e event */ @Override public void keyReleased(KeyEvent e) {} } // Calculator
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Calculator.java
1
请完成以下Java代码
public final class CurrentDirectoryFetcher { public static void main(String[] args) { System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties()); System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile()); System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems()); System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths()); } public static String currentDirectoryUsingSystemProperties() { return System.getProperty("user.dir"); } public static String currentDirectoryUsingPaths() {
return Paths.get("") .toAbsolutePath() .toString(); } public static String currentDirectoryUsingFileSystems() { return FileSystems.getDefault() .getPath("") .toAbsolutePath() .toString(); } public static String currentDirectoryUsingFile() { return new File("").getAbsolutePath(); } }
repos\tutorials-master\core-java-modules\core-java-os\src\main\java\com\baeldung\core\pwd\CurrentDirectoryFetcher.java
1
请完成以下Java代码
public class Message { private Long id; @ApiModelProperty(value = "消息体") private String text; @ApiModelProperty(value = "消息总结") private String summary; private Date createDate; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public String getSummary() { return this.summary;
} public void setSummary(String summary) { this.summary = summary; } @Override public String toString() { return "Message{" + "id=" + id + ", text='" + text + '\'' + ", summary='" + summary + '\'' + ", createDate=" + createDate + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\model\Message.java
1
请完成以下Java代码
public static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++){ resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) { n += 256; } int d1 = n / 16; int d2 = n % 16; return HEXDIGITS[d1] + HEXDIGITS[d2]; }
public static String md5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) { resultString = byteArrayToHexString(md.digest(resultString.getBytes())); } else { resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname))); } } catch (Exception exception) { } return resultString; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\Md5Util.java
1
请完成以下Java代码
public BPartnerLocationId retrieveOrgBPartnerLocationId(@NonNull final OrgId orgId) { final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class); return bpartnerOrgBL.retrieveOrgBPLocationId(orgId); } /** * @param productPlanningData may be {@code null} as of gh #1635 * @param networkLine may also be {@code null} as of gh #1635 */ public int calculateDurationDays( @Nullable final ProductPlanning productPlanningData, @Nullable final DistributionNetworkLine networkLine) { // // Leadtime final int leadtimeDays; if (productPlanningData != null) { leadtimeDays = productPlanningData.getLeadTimeDays(); Check.assume(leadtimeDays >= 0, "leadtimeDays >= 0"); } else { leadtimeDays = 0; } // // Transfer time final int transferTimeFromNetworkLine; if (networkLine != null) { transferTimeFromNetworkLine = (int)networkLine.getTransferDuration().toDays(); } else { transferTimeFromNetworkLine = 0; }
final int transferTime; if (transferTimeFromNetworkLine > 0) { transferTime = transferTimeFromNetworkLine; } else if (productPlanningData != null) { transferTime = productPlanningData.getTransferTimeDays(); Check.assume(transferTime >= 0, "transferTime >= 0"); } else { transferTime = 0; } return leadtimeDays + transferTime; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ddorder\DDOrderUtil.java
1
请在Spring Boot框架中完成以下Java代码
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) { FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); return registration; } @Bean public OAuth2RestTemplate restTemplate() { return new OAuth2RestTemplate(githubClient(), oauth2ClientContext); } @Bean @ConfigurationProperties("github.client") public AuthorizationCodeResourceDetails githubClient() { return new AuthorizationCodeResourceDetails(); } private Filter oauth2ClientFilter() {
OAuth2ClientAuthenticationProcessingFilter oauth2ClientFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github"); OAuth2RestTemplate restTemplate = restTemplate(); oauth2ClientFilter.setRestTemplate(restTemplate); UserInfoTokenServices tokenServices = new UserInfoTokenServices(githubResource().getUserInfoUri(), githubClient().getClientId()); tokenServices.setRestTemplate(restTemplate); oauth2ClientFilter.setTokenServices(tokenServices); return oauth2ClientFilter; } @Bean @ConfigurationProperties("github.resource") public ResourceServerProperties githubResource() { return new ResourceServerProperties(); } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2resttemplate\SecurityConfig.java
2
请完成以下Java代码
public col setVAlign(String valign) { addAttribute("valign",valign); return(this); } /** Sets the char="" attribute. @param character the character to use for alignment. */ public col setChar(String character) { addAttribute("char",character); return(this); } /** Sets the charoff="" attribute. @param char_off When present this attribute specifies the offset of the first occurrence of the alignment character on each line. */ public col setCharOff(int char_off) { addAttribute("charoff",Integer.toString(char_off)); return(this); } /** Sets the charoff="" attribute. @param char_off When present this attribute specifies the offset of the first occurrence of the alignment character on each line. */ public col setCharOff(String char_off) { addAttribute("charoff",char_off); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /**
Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public col addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public col addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public col addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public col addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public col removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\col.java
1
请在Spring Boot框架中完成以下Java代码
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) { Map<String, String> params = new HashMap<>(2); params.put("handlerType", jobHandlerType); params.put("processDefinitionKey", processDefinitionKey); return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyNoTenantId", params); } @Override @SuppressWarnings("unchecked") public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) { Map<String, String> params = new HashMap<>(3); params.put("handlerType", jobHandlerType); params.put("processDefinitionKey", processDefinitionKey); params.put("tenantId", tenantId); return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyAndTenantId", params); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateTimerJobTenantIdForDeployment", params); }
@Override public void bulkUpdateJobLockWithoutRevisionCheck(List<TimerJobEntity> timerJobEntities, String lockOwner, Date lockExpirationTime) { Map<String, Object> params = new HashMap<>(3); params.put("lockOwner", lockOwner); params.put("lockExpirationTime", lockExpirationTime); bulkUpdateEntities("updateTimerJobLocks", params, "timerJobs", timerJobEntities); } @Override public void bulkDeleteWithoutRevision(List<TimerJobEntity> timerJobEntities) { bulkDeleteEntities("deleteTimerJobs", timerJobEntities); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisTimerJobDataManager.java
2
请完成以下Java代码
public boolean isEmpty() { return rates.isEmpty(); } public ImmutableSet<UomId> getCatchUomIds() { if (rates.isEmpty()) { return ImmutableSet.of(); } return rates.values() .stream() .filter(UOMConversionRate::isCatchUOMForProduct) .map(UOMConversionRate::getToUomId) .collect(ImmutableSet.toImmutableSet()); } private static FromAndToUomIds toFromAndToUomIds(final UOMConversionRate conversion) {
return FromAndToUomIds.builder() .fromUomId(conversion.getFromUomId()) .toUomId(conversion.getToUomId()) .build(); } @Value @Builder public static class FromAndToUomIds { @NonNull UomId fromUomId; @NonNull UomId toUomId; public FromAndToUomIds invert() { return builder().fromUomId(toUomId).toUomId(fromUomId).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionsMap.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Process getProcess() { return processRefAttribute.getReferenceTargetElement(this); } public void setProcess(Process process) { processRefAttribute.setReferenceTargetElement(this, process); }
public Collection<Interface> getInterfaces() { return interfaceRefCollection.getReferenceTargetElements(this); } public Collection<EndPoint> getEndPoints() { return endPointRefCollection.getReferenceTargetElements(this); } public ParticipantMultiplicity getParticipantMultiplicity() { return participantMultiplicityChild.getChild(this); } public void setParticipantMultiplicity(ParticipantMultiplicity participantMultiplicity) { participantMultiplicityChild.setChild(this, participantMultiplicity); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParticipantImpl.java
1
请完成以下Java代码
public String getUserAgent () { return (String)get_Value(COLUMNNAME_UserAgent); } public I_W_CounterCount getW_CounterCount() throws RuntimeException { return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name) .getPO(getW_CounterCount_ID(), get_TrxName()); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Web Counter. @param W_Counter_ID Individual Count hit */ public void setW_Counter_ID (int W_Counter_ID) { if (W_Counter_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID)); } /** Get Web Counter. @return Individual Count hit */ public int getW_Counter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_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_W_Counter.java
1
请完成以下Java代码
public IMigrationExecutor newMigrationExecutor(final IMigrationExecutorContext migrationCtx, final int migrationId) { return new MigrationExecutor(migrationCtx, migrationId); } @Override public void registerMigrationStepExecutor(final String stepType, final Class<? extends IMigrationStepExecutor> executorClass) { stepExecutorsByType.put(stepType, executorClass); } @Override public IMigrationStepExecutor newMigrationStepExecutor(final IMigrationExecutorContext migrationCtx, final I_AD_MigrationStep step) { final String stepType = step.getStepType(); final Class<? extends IMigrationStepExecutor> executorClass = stepExecutorsByType.get(stepType);
if (executorClass == null) { throw new AdempiereException("Step type not supported: " + stepType); } try { return executorClass .getConstructor(IMigrationExecutorContext.class, I_AD_MigrationStep.class) .newInstance(migrationCtx, step); } catch (Exception e) { throw new AdempiereException("Cannot not load step executor for class " + executorClass, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorProvider.java
1
请在Spring Boot框架中完成以下Java代码
private static void addEnclosingClassesForClass(Set<Class<?>> enclosingClasses, @Nullable Class<?> clazz) { if (clazz == null) { return; } Class<?> enclosing = clazz.getEnclosingClass(); if (enclosing != null) { enclosingClasses.add(enclosing); addEnclosingClassesForClass(enclosingClasses, enclosing); } } private static Set<Class<?>> getClassesToAdd(String packageName) { Set<Class<?>> classesToAdd = new HashSet<>(); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(Object.class)); provider.addExcludeFilter(new AssignableTypeFilter(FilterAutoConfiguration.class)); provider.addExcludeFilter(new AssignableTypeFilter(PredicateAutoConfiguration.class)); Set<BeanDefinition> components = provider.findCandidateComponents(packageName); for (BeanDefinition component : components) { Class<?> clazz; try { clazz = Class.forName(component.getBeanClassName()); if (shouldRegisterClass(clazz)) { classesToAdd.add(clazz); } } catch (NoClassDefFoundError | ClassNotFoundException exception) { if (LOG.isDebugEnabled()) { LOG.debug(exception); } } } return classesToAdd; } private static void addGenericsForClass(Set<Class<?>> genericsToAdd, ResolvableType resolvableType) { if (resolvableType.getSuperType().hasGenerics()) { genericsToAdd.addAll(Arrays.stream(resolvableType.getSuperType().getGenerics()) .map(ResolvableType::toClass) .collect(Collectors.toSet())); } } private static void addSuperTypesForClass(ResolvableType resolvableType, Set<Class<?>> supertypesToAdd, Set<Class<?>> genericsToAdd) { ResolvableType superType = resolvableType.getSuperType();
if (!ResolvableType.NONE.equals(superType)) { addGenericsForClass(genericsToAdd, superType); supertypesToAdd.add(superType.toClass()); addSuperTypesForClass(superType, supertypesToAdd, genericsToAdd); } } private static boolean shouldRegisterClass(Class<?> clazz) { Set<String> conditionClasses = beansConditionalOnClasses.getOrDefault(clazz.getName(), Collections.emptySet()); for (String conditionClass : conditionClasses) { try { GatewayMvcRuntimeHintsProcessor.class.getClassLoader().loadClass(conditionClass); } catch (ClassNotFoundException e) { return false; } } return true; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcRuntimeHintsProcessor.java
2
请完成以下Java代码
public class LanguageBL implements ILanguageBL { @Override public ADLanguageList getAvailableLanguages() { return Services.get(ILanguageDAO.class).retrieveAvailableLanguages(); } @Override public String getOrgAD_Language(final Properties ctx) throws OrgHasNoBPartnerLinkException { final int orgId = Env.getAD_Org_ID(ctx); return getOrgAD_Language(ctx, orgId); } @Override public String getOrgAD_Language(final Properties ctx, final int orgRepoId) throws OrgHasNoBPartnerLinkException { final OrgId orgId = OrgId.ofRepoIdOrAny(orgRepoId); // // Check organization Language (if found); if (orgId.isRegular()) { final I_C_BPartner bpOrg = Services.get(IBPartnerDAO.class).retrieveOrgBPartner(ctx, orgId.getRepoId(), I_C_BPartner.class, ITrx.TRXNAME_None); final String orgAD_Language = bpOrg.getAD_Language(); if (orgAD_Language != null) { return orgAD_Language; } } // // Check client language (if found) final ClientId clientId; if (orgId.isRegular()) { clientId = Services.get(IOrgDAO.class).getClientIdByOrgId(orgId); } else // AD_Org_ID <= 0 { clientId = Env.getClientId(ctx); } final String clientAD_Language = getClientAD_Language(ctx, clientId.getRepoId()); return clientAD_Language; } @Override
public Language getOrgLanguage(final Properties ctx, final int AD_Org_ID) throws OrgHasNoBPartnerLinkException { final String adLanguage = getOrgAD_Language(ctx, AD_Org_ID); if (!Check.isEmpty(adLanguage, true)) { return Language.getLanguage(adLanguage); } return null; } public String getClientAD_Language(final Properties ctx, final int clientId) { // // Check AD_Client Language if (clientId >= 0) { final I_AD_Client client = Services.get(IClientDAO.class).retriveClient(ctx, clientId); final String clientAD_Language = client.getAD_Language(); if (clientAD_Language != null) { return clientAD_Language; } } // If none of the above was found, return the base language final String baseAD_Language = Language.getBaseAD_Language(); return baseAD_Language; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\LanguageBL.java
1
请完成以下Java代码
public PRTCPrintJobInstructionsConfirmType createPRTADPrintPackageResponse(final PrintJobInstructionsConfirm response, final int sessionId) { final PRTCPrintJobInstructionsConfirmType convertedResponse = new PRTCPrintJobInstructionsConfirmType(); convertedResponse.setADSessionIDAttr(BigInteger.valueOf(sessionId)); if (response.getPrintJobInstructionsID() == null) { logger.log(Level.SEVERE, "Print job Instructions ID cannot be null!"); throw new IllegalArgumentException("Print job Instructions ID cannot be null!"); } convertedResponse.setCPrintJobInstructionsID(BigInteger.valueOf(Long.valueOf(response.getPrintJobInstructionsID()))); switch (response.getStatus()) { case Gedruckt: convertedResponse.setStatus(CPrintJobInstructionsStatusEnum.Done); convertedResponse.setErrorMsg(null); break; case Druckfehler: convertedResponse.setStatus(CPrintJobInstructionsStatusEnum.Error); convertedResponse.setErrorMsg(response.getErrorMsg());
break; default: throw new IllegalArgumentException("Invalid original response status: " + response.getStatus()); } // ADempiere Specific Data convertedResponse.setReplicationEventAttr(ReplicationEventEnum.AfterChange); convertedResponse.setReplicationModeAttr(ReplicationModeEnum.Table); convertedResponse.setReplicationTypeAttr(ReplicationTypeEnum.Merge); convertedResponse.setVersionAttr(JAXBConstants.PRT_C_PRINT_JOB_INSTRUCTIONS_CONFIRM_FORMAT_VERSION); return convertedResponse; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\inout\bean\PRTCPrintJobInstructionsConfirmTypeConverter.java
1
请完成以下Java代码
public DmnTransformException decisionTableOutputIdIsMissing(DmnDecision dmnDecision, DmnDecisionTableOutputImpl dmnDecisionTableOutput) { return new DmnTransformException(exceptionMessage( "012", "The decision table output '{}' of decision '{}' must have a 'id' attribute set.", dmnDecisionTableOutput, dmnDecision) ); } public DmnTransformException decisionTableRuleIdIsMissing(DmnDecision dmnDecision, DmnDecisionTableRuleImpl dmnDecisionTableRule) { return new DmnTransformException(exceptionMessage( "013", "The decision table rule '{}' of decision '{}' must have a 'id' attribute set.", dmnDecisionTableRule, dmnDecision) ); } public void decisionWithoutExpression(Decision decision) { logInfo( "014", "The decision '{}' has no expression and will be ignored.", decision.getName() ); } public DmnTransformException requiredDecisionLoopDetected(String decisionId) { return new DmnTransformException(exceptionMessage( "015", "The decision '{}' has a loop.", decisionId)
); } public DmnTransformException errorWhileTransformingDefinitions(Throwable cause) { return new DmnTransformException(exceptionMessage( "016", "Error while transforming decision requirements graph: " + cause.getMessage()), cause ); } public DmnTransformException drdIdIsMissing(DmnDecisionRequirementsGraph drd) { return new DmnTransformException(exceptionMessage( "017", "The decision requirements graph '{}' must have an 'id' attribute set.", drd) ); } public DmnTransformException decisionVariableIsMissing(String decisionId) { return new DmnTransformException(exceptionMessage( "018", "The decision '{}' must have an 'variable' element if it contains a literal expression.", decisionId)); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnTransformLogger.java
1
请完成以下Java代码
public class Book { @DatabaseField(generatedId = true) private long bookId; @DatabaseField private String title; @DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true) private Library library; public Book() { } public Book(String title) { this.title = title; } public long getBookId() { return bookId; } public void setBookId(long bookId) { this.bookId = bookId; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Library getLibrary() { return library; } public void setLibrary(Library library) { this.library = library; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ormlite\Book.java
1
请完成以下Java代码
public void delete(VariableInstanceEntity entity, boolean fireDeleteEvent) { super.delete(entity, false); ByteArrayRef byteArrayRef = entity.getByteArrayRef(); if (byteArrayRef != null) { byteArrayRef.delete(); } entity.setDeleted(true); if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( entity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setVariableCount(executionEntity.getVariableCount() - 1); } } ActivitiEventDispatcher eventDispatcher = getEventDispatcher(); if (fireDeleteEvent && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, entity) ); eventDispatcher.dispatchEvent(createVariableDeleteEvent(entity)); } } protected ActivitiVariableEvent createVariableDeleteEvent(VariableInstanceEntity variableInstance) { String processDefinitionId = null; if (variableInstance.getProcessInstanceId() != null) { ExecutionEntity executionEntity = getExecutionEntityManager().findById( variableInstance.getProcessInstanceId() ); if (executionEntity != null) { processDefinitionId = executionEntity.getProcessDefinitionId(); } } Object variableValue = null; boolean getValue = true; if (variableInstance.getType().getTypeName().equals("jpa-entity")) { getValue = false; } if (getValue) variableValue = variableInstance.getValue(); return ActivitiEventBuilder.createVariableEvent( ActivitiEventType.VARIABLE_DELETED, variableInstance.getName(),
variableValue, variableInstance.getType(), variableInstance.getTaskId(), variableInstance.getExecutionId(), variableInstance.getProcessInstanceId(), processDefinitionId ); } @Override public void deleteVariableInstanceByTask(TaskEntity task) { Map<String, VariableInstanceEntity> variableInstances = task.getVariableInstanceEntities(); if (variableInstances != null) { for (VariableInstanceEntity variableInstance : variableInstances.values()) { delete(variableInstance); } } } public VariableInstanceDataManager getVariableInstanceDataManager() { return variableInstanceDataManager; } public void setVariableInstanceDataManager(VariableInstanceDataManager variableInstanceDataManager) { this.variableInstanceDataManager = variableInstanceDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableInstanceEntityManagerImpl.java
1
请完成以下Java代码
public class JPAEntityVariableType implements VariableType, CacheableVariable { public static final String TYPE_NAME = "jpa-entity"; private JPAEntityMappings mappings; private boolean forceCacheable; public JPAEntityVariableType() { mappings = new JPAEntityMappings(); } public String getTypeName() { return TYPE_NAME; } public boolean isCachable() { return forceCacheable; } public boolean isAbleToStore(Object value) { if (value == null) { return true; } return mappings.isJPAEntity(value); } public void setValue(Object value, ValueFields valueFields) { EntityManagerSession entityManagerSession = Context.getCommandContext().getSession(EntityManagerSession.class); if (entityManagerSession == null) { throw new ActivitiException("Cannot set JPA variable: " + EntityManagerSession.class + " not configured"); } else {
// Before we set the value we must flush all pending changes from // the entitymanager // If we don't do this, in some cases the primary key will not yet // be set in the object // which will cause exceptions down the road. entityManagerSession.flush(); } if (value != null) { String className = mappings.getJPAClassString(value); String idString = mappings.getJPAIdString(value); valueFields.setTextValue(className); valueFields.setTextValue2(idString); } else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } public Object getValue(ValueFields valueFields) { if (valueFields.getTextValue() != null && valueFields.getTextValue2() != null) { return mappings.getJPAEntity(valueFields.getTextValue(), valueFields.getTextValue2()); } return null; } /** * Force the value to be cacheable. */ public void setForceCacheable(boolean forceCachedValue) { this.forceCacheable = forceCachedValue; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JPAEntityVariableType.java
1
请完成以下Java代码
public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID) { if (PP_Cost_Collector_ID < 1) set_Value (COLUMNNAME_PP_Cost_Collector_ID, null); else set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID)); } /** Get Manufacturing Cost Collector. @return Manufacturing Cost Collector */ @Override public int getPP_Cost_Collector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } /** Set Produktionsauftrag. @param PP_Order_ID Produktionsauftrag */ @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } /** Get Produktionsauftrag. @return Produktionsauftrag */ @Override public int getPP_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID); if (ii == null) return 0; return ii.intValue(); } /** Set PP_Order_ProductAttribute. @param PP_Order_ProductAttribute_ID PP_Order_ProductAttribute */ @Override public void setPP_Order_ProductAttribute_ID (int PP_Order_ProductAttribute_ID) { if (PP_Order_ProductAttribute_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ProductAttribute_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ProductAttribute_ID, Integer.valueOf(PP_Order_ProductAttribute_ID));
} /** Get PP_Order_ProductAttribute. @return PP_Order_ProductAttribute */ @Override public int getPP_Order_ProductAttribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ProductAttribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Zahlwert. @param ValueNumber Numeric Value */ @Override public void setValueNumber (java.math.BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } /** Get Zahlwert. @return Numeric Value */ @Override public java.math.BigDecimal getValueNumber () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ValueNumber); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_ProductAttribute.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderPayScheduleRepository { @NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); private OrderPayScheduleLoaderAndSaver newLoaderAndSaver() { return OrderPayScheduleLoaderAndSaver.builder() .queryBL(queryBL) .trxManager(trxManager) .build(); } public void create(@NonNull final OrderPayScheduleCreateRequest request) { final SeqNoProvider seqNoProvider = SeqNoProvider.ofInt(10); request.getLines() .forEach(line -> createLine(line, request.getOrderId(), seqNoProvider.getAndIncrement())); } private static void createLine(@NonNull final OrderPayScheduleCreateRequest.Line request, @NonNull final OrderId orderId, @NonNull final SeqNo seqNo) { final I_C_OrderPaySchedule record = newInstance(I_C_OrderPaySchedule.class); record.setC_Order_ID(orderId.getRepoId()); record.setC_PaymentTerm_ID(request.getPaymentTermBreakId().getPaymentTermId().getRepoId()); record.setC_PaymentTerm_Break_ID(request.getPaymentTermBreakId().getRepoId()); record.setDueAmt(request.getDueAmount().toBigDecimal()); record.setC_Currency_ID(request.getDueAmount().getCurrencyId().getRepoId()); record.setDueDate(TimeUtil.asTimestamp(request.getDueDate())); record.setPercent(request.getPercent().toInt()); record.setReferenceDateType(request.getReferenceDateType().getCode()); record.setOffsetDays(request.getOffsetDays()); record.setSeqNo(seqNo.toInt()); record.setStatus(OrderPayScheduleStatus.toCodeOrNull(request.getOrderPayScheduleStatus())); saveRecord(record); }
@NonNull public Optional<OrderPaySchedule> getByOrderId(@NonNull final OrderId orderId) { return newLoaderAndSaver().loadByOrderId(orderId); } public void deleteByOrderId(@NonNull final OrderId orderId) { queryBL.createQueryBuilder(I_C_OrderPaySchedule.class) .addEqualsFilter(I_C_OrderPaySchedule.COLUMNNAME_C_Order_ID, orderId) .create() .delete(); } public void save(final OrderPaySchedule orderPaySchedule) {newLoaderAndSaver().save(orderPaySchedule);} public void updateById(@NonNull final OrderId orderId, @NonNull final Consumer<OrderPaySchedule> updater) { newLoaderAndSaver().updateById(orderId, updater); } public void updateByIds(@NonNull final Set<OrderId> orderIds, @NonNull final Consumer<OrderPaySchedule> updater) { newLoaderAndSaver().updateByIds(orderIds, updater); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\repository\OrderPayScheduleRepository.java
2
请完成以下Java代码
public class MAchievement extends X_PA_Achievement { /** * */ private static final long serialVersionUID = -1438593600498523664L; /** * Get achieved Achievements Of Measure * @param measure Measure * @return array of Achievements */ public static MAchievement[] get (MMeasure measure) { return getOfMeasure(measure.getCtx(), measure.getPA_Measure_ID()); } // get /** * Get achieved Achievements Of Measure * @param ctx context * @param PA_Measure_ID measure id * @return array of Achievements */ public static MAchievement[] getOfMeasure (Properties ctx, int PA_Measure_ID) { String whereClause ="PA_Measure_ID=? AND IsAchieved='Y'"; List <MAchievement> list = new Query(ctx,MAchievement.Table_Name, whereClause, null) .setParameters(new Object[]{PA_Measure_ID}).setOrderBy("SeqNo, DateDoc").list(MAchievement.class); MAchievement[] retValue = new MAchievement[list.size ()]; retValue = list.toArray (retValue); return retValue; } // getOfMeasure /** Logger */ private static Logger s_log = LogManager.getLogger(MAchievement.class); /************************************************************************** * Standard Constructor * @param ctx context * @param PA_Achievement_ID id * @param trxName trx */ public MAchievement (Properties ctx, int PA_Achievement_ID, String trxName) { super (ctx, PA_Achievement_ID, trxName); } // MAchievement /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MAchievement (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MAchievement /** * String Representation * @return info */ @Override public String toString () { StringBuffer sb = new StringBuffer ("MAchievement["); sb.append (get_ID()).append ("-").append (getName()).append ("]"); return sb.toString (); } // toString
/** * Before Save * @param newRecord new * @return true */ @Override protected boolean beforeSave (boolean newRecord) { if (isAchieved()) { if (getManualActual().signum() == 0) setManualActual(Env.ONE); if (getDateDoc() == null) setDateDoc(new Timestamp(System.currentTimeMillis())); } return true; } // beforeSave /** * After Save * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave (boolean newRecord, boolean success) { if (success) updateAchievementGoals(); return success; } // afterSave /** * After Delete * @param success success * @return success */ @Override protected boolean afterDelete (boolean success) { if (success) updateAchievementGoals(); return success; } // afterDelete /** * Update Goals with Achievement */ private void updateAchievementGoals() { MMeasure measure = MMeasure.get (getCtx(), getPA_Measure_ID()); measure.updateGoals(); } // updateAchievementGoals } // MAchievement
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAchievement.java
1