instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Optional<JsonReverseInvoiceResponse> reverseInvoice(@NonNull final InvoiceId invoiceId) { final I_C_Invoice documentRecord = invoiceDAO.getByIdInTrx(invoiceId); if (documentRecord == null) { return Optional.empty(); } documentBL.processEx(documentRecord, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); final JsonReverseInvoiceResponse.JsonReverseInvoiceResponseBuilder responseBuilder = JsonReverseInvoiceResponse.builder(); invoiceCandDAO .retrieveInvoiceCandidates(invoiceId) .stream() .map(this::buildJSONItem)
.forEach(responseBuilder::affectedInvoiceCandidate); return Optional.of(responseBuilder.build()); } private JsonInvoiceCandidatesResponseItem buildJSONItem(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { return JsonInvoiceCandidatesResponseItem .builder() .externalHeaderId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalHeaderId())) .externalLineId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalLineId())) .metasfreshId(MetasfreshId.of(invoiceCandidate.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\InvoiceService.java
1
请完成以下Java代码
public java.lang.String getJSPURL () { return (java.lang.String)get_Value(COLUMNNAME_JSPURL); } /** Set Is Modal. @param Modal Is Modal */ @Override public void setModal (boolean Modal) { set_Value (COLUMNNAME_Modal, Boolean.valueOf(Modal)); } /** Get Is Modal. @return Is Modal */ @Override public boolean isModal () { Object oo = get_Value(COLUMNNAME_Modal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */
@Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form.java
1
请完成以下Java代码
public I_C_Calendar getDefaultCalendar(@NonNull final OrgId orgId) { final I_C_Calendar calendar = queryBL.createQueryBuilder(I_C_Calendar.class) .addEqualsFilter(I_C_Calendar.COLUMNNAME_IsDefault, true) .addInArrayFilter(I_C_Calendar.COLUMNNAME_AD_Org_ID, ImmutableList.of(orgId, OrgId.ANY)) .orderByDescending(I_C_Calendar.COLUMNNAME_AD_Org_ID) .create() .first(); if (calendar == null) { throw new AdempiereException(CalendarBL.MSG_SET_DEFAULT_OR_ORG_CALENDAR); } return calendar; } @Nullable @Override public String getName(final CalendarId calendarId)
{ final List<String> calendarNames = queryBL.createQueryBuilder(I_C_Calendar.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Calendar.COLUMNNAME_C_Calendar_ID, calendarId) .create() .listDistinct(I_C_Calendar.COLUMNNAME_Name, String.class); if (calendarNames.isEmpty()) { return null; } return calendarNames.get(0); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\AbstractCalendarDAO.java
1
请在Spring Boot框架中完成以下Java代码
public String scanTable(String tableName, String rowKeyFilter) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Scan scan = new Scan(); if (!StringUtils.isEmpty(rowKeyFilter)) { RowFilter rowFilter = new RowFilter(CompareOperator.EQUAL, new SubstringComparator(rowKeyFilter)); scan.setFilter(rowFilter); } ResultScanner scanner = table.getScanner(scan); try { for (Result result : scanner) { System.out.println(Bytes.toString(result.getRow())); for (Cell cell : result.rawCells()) { System.out.println(cell); } } } finally { if (scanner != null) { scanner.close(); } } return null; } /** * 判断表是否已经存在,这里使用间接的方式来实现
* * admin.tableExists() 会报NoSuchColumnFamilyException, 有人说是hbase-client版本问题 * @param tableName * @return * @throws IOException */ public boolean tableExists(String tableName) throws IOException { TableName[] tableNames = admin.listTableNames(); if (tableNames != null && tableNames.length > 0) { for (int i = 0; i < tableNames.length; i++) { if (tableName.equals(tableNames[i].getNameAsString())) { return true; } } } return false; } }
repos\spring-boot-quick-master\quick-hbase\src\main\java\com\quick\hbase\config\HBaseClient.java
2
请完成以下Java代码
protected void initializeConnectors(ClassLoader classLoader) { Map<String, Connector<?>> connectors = new HashMap<>(); if (classLoader == null) { classLoader = Connectors.class.getClassLoader(); } // discover available custom connector providers on the classpath registerConnectors(connectors, classLoader); // discover and apply connector configurators on the classpath applyConfigurators(connectors, classLoader); this.availableConnectors = connectors; } protected void registerConnectors(Map<String, Connector<?>> connectors, ClassLoader classLoader) { ServiceLoader<ConnectorProvider> providers = ServiceLoader.load(ConnectorProvider.class, classLoader); for (ConnectorProvider provider : providers) { registerProvider(connectors, provider); } } protected void registerProvider(Map<String, Connector<?>> connectors, ConnectorProvider provider) { String connectorId = provider.getConnectorId(); if (connectors.containsKey(connectorId)) { throw LOG.multipleConnectorProvidersFound(connectorId); } else { Connector<?> connectorInstance = provider.createConnectorInstance(); LOG.connectorProviderDiscovered(provider, connectorId, connectorInstance); connectors.put(connectorId, connectorInstance); } } protected void registerConnectorInstance(String connectorId, Connector<?> connector) { ensureConnectorProvidersInitialized(); synchronized (Connectors.class) { availableConnectors.put(connectorId, connector); } }
protected void unregisterConnectorInstance(String connectorId) { ensureConnectorProvidersInitialized(); synchronized (Connectors.class) { availableConnectors.remove(connectorId); } } @SuppressWarnings("rawtypes") protected void applyConfigurators(Map<String, Connector<?>> connectors, ClassLoader classLoader) { ServiceLoader<ConnectorConfigurator> configurators = ServiceLoader.load(ConnectorConfigurator.class, classLoader); for (ConnectorConfigurator configurator : configurators) { LOG.connectorConfiguratorDiscovered(configurator); applyConfigurator(connectors, configurator); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyConfigurator(Map<String, Connector<?>> connectors, ConnectorConfigurator configurator) { for (Connector<?> connector : connectors.values()) { if (configurator.getConnectorClass().isAssignableFrom(connector.getClass())) { configurator.configure(connector); } } } }
repos\camunda-bpm-platform-master\connect\core\src\main\java\org\camunda\connect\Connectors.java
1
请完成以下Java代码
protected MigrationBatchConfiguration createJobConfiguration(MigrationBatchConfiguration configuration, List<String> processIdsForJob) { return new MigrationBatchConfiguration( processIdsForJob, configuration.getMigrationPlan(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.getBatchId() ); } @Override protected void postProcessJob(MigrationBatchConfiguration configuration, JobEntity job, MigrationBatchConfiguration jobConfiguration) { if (job.getDeploymentId() == null) { CommandContext commandContext = Context.getCommandContext(); String sourceProcessDefinitionId = configuration.getMigrationPlan().getSourceProcessDefinitionId(); ProcessDefinitionEntity processDefinition = getProcessDefinition(commandContext, sourceProcessDefinitionId); job.setDeploymentId(processDefinition.getDeploymentId()); } } @Override public void executeHandler(MigrationBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { MigrationPlanImpl migrationPlan = (MigrationPlanImpl) batchConfiguration.getMigrationPlan(); String batchId = batchConfiguration.getBatchId(); setVariables(batchId, migrationPlan, commandContext); MigrationPlanExecutionBuilder executionBuilder = commandContext.getProcessEngineConfiguration() .getRuntimeService() .newMigration(migrationPlan) .processInstanceIds(batchConfiguration.getIds()); if (batchConfiguration.isSkipCustomListeners()) { executionBuilder.skipCustomListeners(); } if (batchConfiguration.isSkipIoMappings()) { executionBuilder.skipIoMappings(); }
commandContext.executeWithOperationLogPrevented( new MigrateProcessInstanceCmd((MigrationPlanExecutionBuilderImpl)executionBuilder, true)); } protected void setVariables(String batchId, MigrationPlanImpl migrationPlan, CommandContext commandContext) { Map<String, ?> variables = null; if (batchId != null) { variables = VariableUtil.findBatchVariablesSerialized(batchId, commandContext); if (variables != null) { migrationPlan.setVariables(new VariableMapImpl(new HashMap<>(variables))); } } } protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) { return commandContext.getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\batch\MigrationBatchJobHandler.java
1
请完成以下Java代码
private ChartOfAccountsService chartOfAccountsService() { ChartOfAccountsService chartOfAccountsService = this._chartOfAccountsService; if (chartOfAccountsService == null) { chartOfAccountsService = this._chartOfAccountsService = SpringContextHolder.instance.getBean(ChartOfAccountsService.class); } return chartOfAccountsService; } @Override public String getWhereClause(final MTree_Base tree) { final ChartOfAccountsId chartOfAccountsId = getChartOfAccountsId(tree).orElse(null); if (chartOfAccountsId == null) { // the tree is not yet referenced from any C_Element record. maybe it was just created
return "0=1"; } else { return I_C_ElementValue.COLUMNNAME_C_Element_ID + "=" + chartOfAccountsId.getRepoId(); } } private Optional<ChartOfAccountsId> getChartOfAccountsId(final MTree_Base tree) { return chartOfAccountsService() .getByTreeId(AdTreeId.ofRepoId(tree.getAD_Tree_ID())) .map(ChartOfAccounts::getId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\MElementValueTreeSupport.java
1
请完成以下Java代码
private I_C_Commission_Share getCommissionShareRecord(@NonNull final I_C_Invoice_Candidate ic) { return TableRecordReference .ofReferenced(ic) .getModel(I_C_Commission_Share.class); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Commission_Share commissionShareRecord = getCommissionShareRecord(ic); final SOTrx soTrx = SOTrx.ofBoolean(commissionShareRecord.isSOTrx()); ic.setBill_BPartner_ID(soTrx.isSales() ? commissionShareRecord.getC_BPartner_Payer_ID() : commissionShareRecord.getC_BPartner_SalesRep_ID()); } @Override public String toString() { return "CommissionShareHandler"; } @NonNull private DocTypeId getDoctypeId(@NonNull final I_C_Commission_Share shareRecord) { final CommissionConstants.CommissionDocType commissionDocType = getCommissionDocType(shareRecord); return docTypeDAO.getDocTypeId( DocTypeQuery.builder() .docBaseType(commissionDocType.getDocBaseType()) .docSubType(DocSubType.ofCode(commissionDocType.getDocSubType())) .adClientId(shareRecord.getAD_Client_ID()) .adOrgId(shareRecord.getAD_Org_ID()) .build()); } @NonNull private CommissionConstants.CommissionDocType getCommissionDocType(@NonNull final I_C_Commission_Share shareRecord) { if (!shareRecord.isSOTrx()) {
// note that SOTrx is about the share record's settlement. // I.e. if the sales-rep receives money from the commission, then it's a purchase order trx return CommissionConstants.CommissionDocType.COMMISSION; } else if (shareRecord.getC_LicenseFeeSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.LICENSE_COMMISSION; } else if (shareRecord.getC_MediatedCommissionSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.MEDIATED_COMMISSION; } throw new AdempiereException("Unhandled commission type! ") .appendParametersToMessage() .setParameter("C_CommissionShare_ID", shareRecord.getC_Commission_Share_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\invoicecandidate\CommissionShareHandler.java
1
请完成以下Java代码
public class ZKGetData { private static ZooKeeper zk; private static ZooKeeperConnection conn; public static Stat znode_exists(String path) throws KeeperException, InterruptedException { return zk.exists(path, true); } public static void main(String[] args) throws InterruptedException, KeeperException { String path = ZKConstants.ZK_FIRST_PATH; final CountDownLatch connectedSignal = new CountDownLatch(1); try { conn = new ZooKeeperConnection(); zk = conn.connect(ZKConstants.ZK_HOST); Stat stat = znode_exists(path); if (stat != null) { byte[] b = zk.getData(path, new Watcher() { public void process(WatchedEvent we) { if (we.getType() == Event.EventType.None) { switch (we.getState()) { case Expired: connectedSignal.countDown(); break; } } else { String path = ZKConstants.ZK_FIRST_PATH; try { byte[] bn = zk.getData(path, false, null); String data = new String(bn, "UTF-8"); System.out.println(data); connectedSignal.countDown();
} catch (Exception ex) { System.out.println(ex.getMessage()); } } } }, null); String data = new String(b, "UTF-8"); System.out.println(data); connectedSignal.await(); } else { System.out.println("Node does not exists"); } } catch (Exception e) { System.out.println(e.getMessage()); } } }
repos\spring-boot-quick-master\quick-zookeeper\src\main\java\com\quick\zookeeper\client\ZKGetData.java
1
请在Spring Boot框架中完成以下Java代码
public class CompletePickingWFActivityHandler implements WFActivityHandler, UserConfirmationSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("picking.completePicking"); private static final AdMessageKey NOT_ALL_LINES_ARE_COMPLETED_WARNING = AdMessageKey .of("de.metas.picking.workflow.handlers.activity_handlers.NOT_ALL_LINES_ARE_COMPLETED_WARNING"); private final IMsgBL msgBL = Services.get(IMsgBL.class); private final PickingJobRestService pickingJobRestService; public CompletePickingWFActivityHandler( @NonNull final PickingJobRestService pickingJobRestService) { this.pickingJobRestService = pickingJobRestService; } @Override public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(getQuestion(wfProcess, jsonOpts.getAdLanguage())) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completePickingWFActivity) { final PickingJob pickingJob = getPickingJob(wfProcess);
return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getDocStatus().isCompleted() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.getWfActivity().getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJobRestService::complete ); } private String getQuestion(@NonNull final WFProcess wfProcess, @NonNull final String language) { final PickingJob pickingJob = wfProcess.getDocumentAs(PickingJob.class); if (pickingJob.getProgress().isDone()) { return msgBL.getMsg(language, ARE_YOU_SURE); } final PickingJobOptions options = pickingJobRestService.getPickingJobOptions(pickingJob.getCustomerId()); if (!options.isAllowCompletingPartialPickingJob()) { return msgBL.getMsg(language, ARE_YOU_SURE); } return msgBL.getMsg(language, NOT_ALL_LINES_ARE_COMPLETED_WARNING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\CompletePickingWFActivityHandler.java
2
请完成以下Java代码
public void setRoundToPrecision(final Integer roundToPrecision) { this.roundToPrecision = roundToPrecision == null ? -1 : roundToPrecision; } @Override public IDeviceResponseGetConfigParams getRequiredConfigParams() { final List<IDeviceConfigParam> params = new ArrayList<IDeviceConfigParam>(); // params.add(new DeviceConfigParamPojo("DeviceClass", "DeviceClass", "")); // if we can query this device for its params, then we already know the device class. params.add(new DeviceConfigParam(PARAM_ENDPOINT_CLASS, "Endpoint.Class", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_IP, "Endpoint.IP", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_PORT, "Endpoint.Port", "")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_RETURN_LAST_LINE, PARAM_ENDPOINT_RETURN_LAST_LINE, "N")); params.add(new DeviceConfigParam(PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, PARAM_ENDPOINT_READ_TIMEOUT_MILLIS, "500")); params.add(new DeviceConfigParam(PARAM_ROUND_TO_PRECISION, "RoundToPrecision", "-1")); return new IDeviceResponseGetConfigParams() { @Override public List<IDeviceConfigParam> getParams() { return params; }
}; } @Override public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler() { return new ConfigureDeviceHandler(this); } @Override public String toString() { return getClass().getSimpleName() + " with Endpoint " + endPoint.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\AbstractTcpScales.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isPrSingleHopEnabled() { return this.prSingleHopEnabled; } public void setPrSingleHopEnabled(boolean prSingleHopEnabled) { this.prSingleHopEnabled = prSingleHopEnabled; } public int getReadTimeout() { return this.readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public boolean isReadyForEvents() { return this.readyForEvents; } public void setReadyForEvents(boolean readyForEvents) { this.readyForEvents = readyForEvents; } public int getRetryAttempts() { return this.retryAttempts; } public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } public String getServerGroup() { return this.serverGroup; } public void setServerGroup(String serverGroup) { this.serverGroup = serverGroup; } public String[] getServers() { return this.servers; } public void setServers(String[] servers) { this.servers = servers; } public int getSocketBufferSize() { return this.socketBufferSize; } public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; }
public int getStatisticInterval() { return this.statisticInterval; } public void setStatisticInterval(int statisticInterval) { this.statisticInterval = statisticInterval; } public int getSubscriptionAckInterval() { return this.subscriptionAckInterval; } public void setSubscriptionAckInterval(int subscriptionAckInterval) { this.subscriptionAckInterval = subscriptionAckInterval; } public boolean isSubscriptionEnabled() { return this.subscriptionEnabled; } public void setSubscriptionEnabled(boolean subscriptionEnabled) { this.subscriptionEnabled = subscriptionEnabled; } public int getSubscriptionMessageTrackingTimeout() { return this.subscriptionMessageTrackingTimeout; } public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) { this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout; } public int getSubscriptionRedundancy() { return this.subscriptionRedundancy; } public void setSubscriptionRedundancy(int subscriptionRedundancy) { this.subscriptionRedundancy = subscriptionRedundancy; } public boolean isThreadLocalConnections() { return this.threadLocalConnections; } public void setThreadLocalConnections(boolean threadLocalConnections) { this.threadLocalConnections = threadLocalConnections; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PoolProperties.java
2
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getMessageName() { return messageName; } public String getProcessInstanceName() { return processInstanceName; } public String getBusinessKey() {
return businessKey; } public String getTenantId() { return tenantId; } public Map<String, Object> getVariables() { return variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java
1
请完成以下Java代码
public static class MyState { private Set<Employee> employeeSet1 = new HashSet<>(); private List<Employee> employeeList1 = new ArrayList<>(); private Set<Employee> employeeSet2 = new HashSet<>(); private List<Employee> employeeList2 = new ArrayList<>(); private Set<Employee> employeeSet3 = new HashSet<>(); private Set<Employee> employeeSet4 = new HashSet<>(); private long set1Size = 60000; private long list1Size = 50000; private long set2Size = 50000; private long list2Size = 60000; private long set3Size = 50000; private long set4Size = 60000; @Setup(Level.Trial) public void setUp() { for (long i = 0; i < set1Size; i++) { employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < list1Size; i++) { employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set2Size; i++) { employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < list2Size; i++) { employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set3Size; i++) { employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false))); } for (long i = 0; i < set4Size; i++) { employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false))); }
} } @Benchmark public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) { return state.employeeSet1.removeAll(state.employeeList1); } @Benchmark public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) { return state.employeeSet2.removeAll(state.employeeList2); } @Benchmark public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) { return state.employeeSet3.removeAll(state.employeeSet4); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName()) .threads(1) .forks(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server") .build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-3\src\main\java\com\baeldung\collections\removeallperformance\HashSetBenchmark.java
1
请完成以下Java代码
public String getBom() { return this.bom; } public void setBom(String bom) { this.bom = bom; } public String getRepository() { return this.repository; } public void setRepository(String repository) { this.repository = repository; } public VersionRange getRange() { return this.range; } public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange;
} public static Mapping create(String range, String groupId, String artifactId, String version, Boolean starter, String bom, String repository) { Mapping mapping = new Mapping(); mapping.compatibilityRange = range; mapping.groupId = groupId; mapping.artifactId = artifactId; mapping.version = version; mapping.starter = starter; mapping.bom = bom; mapping.repository = repository; return mapping; } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Dependency.java
1
请在Spring Boot框架中完成以下Java代码
public final class PPOrderHandlerUtils { public static CandidateType extractCandidateType(final PPOrderLine ppOrderLine) { return ppOrderLine.getPpOrderLineData().isReceipt() ? CandidateType.SUPPLY : CandidateType.DEMAND; } /** * Creates and returns a {@link DemandDetail} for the given {@code supplyRequiredDescriptor}, * if the respective candidate should have one. * Supply candidates that are about *another* product that the required one (i.e. co- and by-products) may not have that demand detail. * (Otherwise, their stock candidate would be connected to the resp. demand record) */ @NonNull public static Optional<DemandDetail> computeDemandDetail( @NonNull final CandidateType lineCandidateType, @Nullable final SupplyRequiredDescriptor supplyRequiredDescriptor, @NonNull final MaterialDescriptor materialDescriptor) { if (supplyRequiredDescriptor == null) { return Optional.empty(); } if (lineCandidateType == CandidateType.DEMAND) {
return Optional.of(DemandDetail.forSupplyRequiredDescriptor(supplyRequiredDescriptor)); } if (lineCandidateType == CandidateType.SUPPLY && supplyRequiredDescriptor.getProductId() == materialDescriptor.getProductId() && supplyRequiredDescriptor.getStorageAttributesKey().equals(materialDescriptor.getStorageAttributesKey())) { return Optional.of(DemandDetail.forSupplyRequiredDescriptor(supplyRequiredDescriptor)); } return Optional.empty(); } public static MaterialDescriptorQuery createMaterialDescriptorQuery(@NonNull final ProductDescriptor productDescriptor) { return MaterialDescriptorQuery.builder() .productId(productDescriptor.getProductId()) .storageAttributesKey(productDescriptor.getStorageAttributesKey()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderHandlerUtils.java
2
请完成以下Java代码
public static UomId ofRepoId(final int repoId) { if (repoId == EACH.repoId) { return EACH; } else { return new UomId(repoId); } } @Nullable public static UomId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final UomId uomId) { return uomId != null ? uomId.getRepoId() : -1; } public static Optional<UomId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } int repoId; private UomId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_UOM_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final UomId id1, @Nullable final UomId id2) { return Objects.equals(id1, id2); } @NonNull @SafeVarargs public static <T> UomId getCommonUomIdOfAll( @NonNull final Function<T, UomId> getUomId, @NonNull final String name, @Nullable final T... objects) { if (objects == null || objects.length == 0) { throw new AdempiereException("No " + name + " provided"); } else if (objects.length == 1 && objects[0] != null) { return getUomId.apply(objects[0]); } else {
UomId commonUomId = null; for (final T object : objects) { if (object == null) { continue; } final UomId uomId = getUomId.apply(object); if (commonUomId == null) { commonUomId = uomId; } else if (!UomId.equals(commonUomId, uomId)) { throw new AdempiereException("All given " + name + "(s) shall have the same UOM: " + Arrays.asList(objects)); } } if (commonUomId == null) { throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects)); } return commonUomId; } } public boolean isEach() {return EACH.equals(this);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UomId.java
1
请完成以下Java代码
public class HistoricFormPropertyEventEntity extends HistoricDetailEventEntity { private static final long serialVersionUID = 1L; protected String propertyId; protected String propertyValue; public HistoricFormPropertyEventEntity() { } public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } public Object getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } public Date getTime() { return timestamp; }
@Override public String toString() { return this.getClass().getSimpleName() + "[propertyId=" + propertyId + ", propertyValue=" + propertyValue + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricFormPropertyEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
private CandidateQtyDetails fromDB(@NonNull final I_MD_Candidate_QtyDetails candQtyDetails) { return CandidateQtyDetails.builder() .id(CandidateQtyDetailsId.ofRepoId(candQtyDetails.getMD_Candidate_QtyDetails_ID())) .candidateId(CandidateId.ofRepoId(candQtyDetails.getMD_Candidate_ID())) .stockCandidateId(CandidateId.ofRepoIdOrNull(candQtyDetails.getStock_MD_Candidate_ID())) .detailCandidateId(CandidateId.ofRepoIdOrNull(candQtyDetails.getDetail_MD_Candidate_ID())) .qtyInStockUOM(candQtyDetails.getQty()) .build(); } public void save(@NonNull final CandidateQtyDetailsPersistMultiRequest saveRequest) { deleteByCandidateId(saveRequest.getCandidateId()); final List<I_MD_Candidate_QtyDetails> qtyDetails = saveRequest .getDetails() .stream() .map(request -> create(saveRequest.getCandidateId(), saveRequest.getStockCandidateId(), request)) .collect(Collectors.toList()); saveAll(qtyDetails); } private void deleteByCandidateId(@NonNull final CandidateId candidateId) {
query.createQueryBuilder(I_MD_Candidate_QtyDetails.class) .addEqualsFilter(I_MD_Candidate_QtyDetails.COLUMNNAME_MD_Candidate_ID, candidateId) .create() .delete(); } private I_MD_Candidate_QtyDetails create(final @NonNull CandidateId candidateId, @Nullable final CandidateId stockCandidateId, final CandidateQtyDetailsPersistRequest request) { final I_MD_Candidate_QtyDetails po = InterfaceWrapperHelper.newInstance(I_MD_Candidate_QtyDetails.class); po.setMD_Candidate_ID(candidateId.getRepoId()); po.setStock_MD_Candidate_ID(CandidateId.toRepoId(stockCandidateId)); po.setDetail_MD_Candidate_ID(CandidateId.toRepoId(request.getDetailCandidateId())); po.setQty(request.getQtyInStockUom()); return po; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateQtyDetailsRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class UploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public Result upload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResultGenerator.genFailResult("请选择文件"); } String fileName = file.getOriginalFilename(); String suffixName = fileName.substring(fileName.lastIndexOf(".")); //生成文件名称通用方法 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); Random r = new Random(); StringBuilder tempName = new StringBuilder(); tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
String newFileName = tempName.toString(); try { // 保存文件 byte[] bytes = file.getBytes(); Path path = Paths.get(Constants.FILE_UPLOAD_PATH + newFileName); Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); } Result result = ResultGenerator.genSuccessResult(); result.setData("files/" + newFileName); return result; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\UploadController.java
2
请在Spring Boot框架中完成以下Java代码
private void auditBPartnerLocation( @NonNull final JsonResponseLocation jsonResponseLocation, @Nullable final DataExportAuditId dataExportParentId, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { final Action exportAction = dataExportParentId != null ? Action.AlongWithParent : Action.Standalone; final int bPartnerLocId = jsonResponseLocation.getMetasfreshId().getValue(); final I_C_BPartner_Location bpartnerLocationRecord = InterfaceWrapperHelper.load(bPartnerLocId, I_C_BPartner_Location.class); final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerLocationRecord.getC_BPartner_ID(), bpartnerLocationRecord.getC_BPartner_Location_ID()); final DataExportAuditRequest bpLocationRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_C_BPartner_Location.Table_Name, bPartnerLocationId.getRepoId())) .action(exportAction) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(dataExportParentId) .build(); final DataExportAuditId bpartnerLocationExportAuditId = dataExportAuditService.createExportAudit(bpLocationRequest); final LocationId locationId = bpartnerDAO.getLocationId(bPartnerLocationId); final DataExportAuditRequest locationRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_C_Location.Table_Name, locationId.getRepoId())) .action(Action.AlongWithParent) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(bpartnerLocationExportAuditId) .build();
dataExportAuditService.createExportAudit(locationRequest); } private void auditAdUser( @NonNull final JsonResponseContact jsonResponseContact, @Nullable final DataExportAuditId dataExportParentId, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { final Action exportAction = dataExportParentId != null ? Action.AlongWithParent : Action.Standalone; final DataExportAuditRequest adUserRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_AD_User.Table_Name, jsonResponseContact.getMetasfreshId().getValue())) .action(exportAction) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .parentExportAuditId(dataExportParentId) .build(); dataExportAuditService.createExportAudit(adUserRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\data\service\BPartnerCompositeAuditService.java
2
请在Spring Boot框架中完成以下Java代码
public JmxManagedThreadPool getValue() { return this; } public void setCorePoolSize(int corePoolSize) { threadPoolExecutor.setCorePoolSize(corePoolSize); } public void setMaximumPoolSize(int maximumPoolSize) { threadPoolExecutor.setMaximumPoolSize(maximumPoolSize); } public int getMaximumPoolSize() { return threadPoolExecutor.getMaximumPoolSize(); } public void setKeepAliveTime(long time, TimeUnit unit) { threadPoolExecutor.setKeepAliveTime(time, unit); } public void purgeThreadPool() { threadPoolExecutor.purge(); } public int getPoolSize() { return threadPoolExecutor.getPoolSize(); } public int getActiveCount() { return threadPoolExecutor.getActiveCount();
} public int getLargestPoolSize() { return threadPoolExecutor.getLargestPoolSize(); } public long getTaskCount() { return threadPoolExecutor.getTaskCount(); } public long getCompletedTaskCount() { return threadPoolExecutor.getCompletedTaskCount(); } public int getQueueCount() { return threadPoolQueue.size(); } public int getQueueAddlCapacity() { return threadPoolQueue.remainingCapacity(); } public ThreadPoolExecutor getThreadPoolExecutor() { return threadPoolExecutor; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedThreadPool.java
2
请在Spring Boot框架中完成以下Java代码
public void undoDecommissionProductsByInventoryId(final InventoryId inventoryId) { final Set<SecurPharmProductId> productIds = actionsRepo.getProductIdsByInventoryId(inventoryId); final Collection<SecurPharmProduct> products = productsRepo.getProductsByIds(productIds); if (products.isEmpty()) { return; } for (final SecurPharmProduct product : products) { undoDecommissionProductIfEligible(product, inventoryId); } } public Optional<UndoDecommissionResponse> undoDecommissionProductIfEligible( @NonNull final SecurPharmProductId productId, @Nullable final InventoryId inventoryId) { final SecurPharmProduct product = productsRepo.getProductById(productId); return undoDecommissionProductIfEligible(product, inventoryId); } public Optional<UndoDecommissionResponse> undoDecommissionProductIfEligible( @NonNull final SecurPharmProduct product, @Nullable final InventoryId inventoryId) { if (!isEligibleForUndoDecommission(product)) { return Optional.empty(); } final SecurPharmClient client = createClient(); final UndoDecommissionClientResponse clientResponse = client.undoDecommission( product.getProductDetails(), product.getDecommissionServerTransactionId()); final UndoDecommissionResponse response = UndoDecommissionResponse.builder() .error(clientResponse.isError()) .inventoryId(inventoryId) .productId(product.getId()) .serverTransactionId(clientResponse.getServerTransactionId()) .build(); actionsRepo.save(response); logsRepo.saveActionLog( clientResponse.getLog(), response.getProductId(),
response.getId()); if (!response.isError()) { product.productDecommissionUndo(clientResponse.getServerTransactionId()); productsRepo.save(product); } else { userNotifications.notifyUndoDecommissionFailed(client.getSupportUserId(), response); } return Optional.of(response); } public boolean isEligibleForUndoDecommission(@NonNull final SecurPharmProduct product) { return product.isDecommissioned() // was already decommissioned && !product.isError() // no errors ; } public SecurPharmHUAttributesScanner newHUScanner() { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final IHandlingUnitsDAO handlingUnitsRepo = Services.get(IHandlingUnitsDAO.class); return SecurPharmHUAttributesScanner.builder() .securPharmService(this) .handlingUnitsBL(handlingUnitsBL) .handlingUnitsRepo(handlingUnitsRepo) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmService.java
2
请在Spring Boot框架中完成以下Java代码
public int getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(int maxBucketCount) { this.maxBucketCount = maxBucketCount; } public TimeUnit getBaseTimeUnit() { return this.baseTimeUnit; } public void setBaseTimeUnit(TimeUnit baseTimeUnit) { this.baseTimeUnit = baseTimeUnit; } public Map<String, Meter> getMeter() { return this.meter; } /** * Per-meter settings. */ public static class Meter { /** * Maximum number of buckets to be used for exponential histograms, if configured. * This has no effect on explicit bucket histograms. */ private @Nullable Integer maxBucketCount; /** * Histogram type when histogram publishing is enabled. */ private @Nullable HistogramFlavor histogramFlavor;
public @Nullable Integer getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(@Nullable Integer maxBucketCount) { this.maxBucketCount = maxBucketCount; } public @Nullable HistogramFlavor getHistogramFlavor() { return this.histogramFlavor; } public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java
2
请在Spring Boot框架中完成以下Java代码
public ApiResponse<File> getSingleDocumentWithHttpInfo(String apiKey, String id) throws ApiException { com.squareup.okhttp.Call call = getSingleDocumentValidateBeforeCall(apiKey, id, null, null); Type localVarReturnType = new TypeToken<File>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Einzelnes Dokument abrufen (asynchronously) * Szenario - das WaWi fragt ein bestimmtes Dokument im PDF-Format an * @param apiKey (required) * @param id (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getSingleDocumentAsync(String apiKey, String id, final ApiCallback<File> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() {
@Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getSingleDocumentValidateBeforeCall(apiKey, id, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<File>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\api\DocumentApi.java
2
请完成以下Java代码
public BigDecimal getQtyIssued() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyIssued); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReject (final @Nullable BigDecimal QtyReject) { set_Value (COLUMNNAME_QtyReject, QtyReject); } @Override public BigDecimal getQtyReject() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToIssue (final BigDecimal QtyToIssue) { set_ValueNoCheck (COLUMNNAME_QtyToIssue, QtyToIssue); } @Override public BigDecimal getQtyToIssue() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToIssue); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_ValueNoCheck (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_IssueSchedule.java
1
请完成以下Java代码
public Properties getCtx(final Object model, final boolean useClientOrgFromModel) { return POJOWrapper.getCtx(model, useClientOrgFromModel); } @Override public String getTrxName(final Object model, final boolean ignoreIfNotHandled) { return POJOWrapper.getTrxName(model); } @Override public void setTrxName(final Object model, final String trxName, final boolean ignoreIfNotHandled) { POJOWrapper.setTrxName(model, trxName); } @Override public int getId(final Object model) { return POJOWrapper.getWrapper(model).getId(); } @Override public String getModelTableNameOrNull(final Object model) { return POJOWrapper.getWrapper(model).getTableName(); } @Override public boolean isNew(final Object model) { return POJOWrapper.isNew(model); } @Override public <T> T getValue(final Object model, final String columnName, final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable) { final POJOWrapper wrapper = POJOWrapper.getWrapper(model); if (useOverrideColumnIfAvailable) { final IModelInternalAccessor modelAccessor = wrapper.getModelInternalAccessor(); final T value = getValueOverrideOrNull(modelAccessor, columnName); if (value != null) { return value; } } // if (!wrapper.hasColumnName(columnName)) { if (throwExIfColumnNotFound) { throw new AdempiereException("No columnName " + columnName + " found for " + model); } else { return null; } } @SuppressWarnings("unchecked") final T value = (T)wrapper.getValuesMap().get(columnName); return value;
} @Override public boolean isValueChanged(final Object model, final String columnName) { return POJOWrapper.isValueChanged(model, columnName); } @Override public boolean isValueChanged(final Object model, final Set<String> columnNames) { return POJOWrapper.isValueChanged(model, columnNames); } @Override public boolean isNull(final Object model, final String columnName) { return POJOWrapper.isNull(model, columnName); } @Override public <T> T getDynAttribute(final Object model, final String attributeName) { final T value = POJOWrapper.getDynAttribute(model, attributeName); return value; } @Override public Object setDynAttribute(final Object model, final String attributeName, final Object value) { return POJOWrapper.setDynAttribute(model, attributeName, value); } @Override public <T extends PO> T getPO(final Object model, final boolean strict) { throw new UnsupportedOperationException("Getting PO from '" + model + "' is not supported in JUnit testing mode"); } @Override public Evaluatee getEvaluatee(final Object model) { return POJOWrapper.getWrapper(model).asEvaluatee(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOInterfaceWrapperHelper.java
1
请完成以下Java代码
public class MyBookContainer<T> implements Collection<T> { private static final long serialVersionUID = 1L; private T[] elements; public MyBookContainer(T[] elements) { this.elements = elements; } @Override public Spliterator<T> spliterator() { return new BookSpliterator(elements, 0); } @Override public Stream<T> parallelStream() { return StreamSupport.stream(spliterator(), false); } // standard overridden methods of Collection Interface @Override public int size() { return elements.length; } @Override public boolean isEmpty() { return elements.length == 0; } @Override public boolean contains(Object o) { return false; } @Override public Iterator<T> iterator() { return null; } @Override public Object[] toArray() { return new Object[0]; } @Override public <T1> T1[] toArray(T1[] a) { return null; }
@Override public boolean add(T t) { return false; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends T> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } }
repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\MyBookContainer.java
1
请完成以下Java代码
public String getReceiveNote() { return receiveNote; } public void setReceiveNote(String receiveNote) { this.receiveNote = receiveNote; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", orderId=").append(orderId); sb.append(", companyAddressId=").append(companyAddressId); sb.append(", productId=").append(productId); sb.append(", orderSn=").append(orderSn); sb.append(", createTime=").append(createTime); sb.append(", memberUsername=").append(memberUsername); sb.append(", returnAmount=").append(returnAmount); sb.append(", returnName=").append(returnName); sb.append(", returnPhone=").append(returnPhone);
sb.append(", status=").append(status); sb.append(", handleTime=").append(handleTime); sb.append(", productPic=").append(productPic); sb.append(", productName=").append(productName); sb.append(", productBrand=").append(productBrand); sb.append(", productAttr=").append(productAttr); sb.append(", productCount=").append(productCount); sb.append(", productPrice=").append(productPrice); sb.append(", productRealPrice=").append(productRealPrice); sb.append(", reason=").append(reason); sb.append(", description=").append(description); sb.append(", proofPics=").append(proofPics); sb.append(", handleNote=").append(handleNote); sb.append(", handleMan=").append(handleMan); sb.append(", receiveMan=").append(receiveMan); sb.append(", receiveTime=").append(receiveTime); sb.append(", receiveNote=").append(receiveNote); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderReturnApply.java
1
请完成以下Java代码
public void createMobileApplicationAccess(@NonNull final CreateMobileApplicationAccessRequest request) { mobileApplicationPermissionsRepository.createMobileApplicationAccess(request); resetCacheAfterTrxCommit(); } @Override public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId) { mobileApplicationPermissionsRepository.deleteMobileApplicationAccess(applicationId); } @Override public void deleteUserOrgAccessByUserId(final UserId userId) { queryBL.createQueryBuilder(I_AD_User_OrgAccess.class) .addEqualsFilter(I_AD_User_OrgAccess.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } @Override public void deleteUserOrgAssignmentByUserId(final UserId userId) { queryBL.createQueryBuilder(I_C_OrgAssignment.class) .addEqualsFilter(I_C_OrgAssignment.COLUMNNAME_AD_User_ID, userId) .create() .delete();
} @Value(staticConstructor = "of") private static class RoleOrgPermissionsCacheKey { RoleId roleId; AdTreeId adTreeOrgId; } @Value(staticConstructor = "of") private static class UserOrgPermissionsCacheKey { UserId userId; AdTreeId adTreeOrgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsDAO.java
1
请完成以下Java代码
private static void runRules(String rulesURI, RuleServiceProvider ruleServiceProvider) throws ConfigurationException, RuleSessionTypeUnsupportedException, RuleSessionCreateException, RuleExecutionSetNotFoundException, RemoteException, InvalidRuleSessionException { // Get a RuleRuntime and invoke the rule engine. RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime(); //Create a statelessRuleSession. StatelessRuleSession statelessRuleSession = (StatelessRuleSession) ruleRuntime.createRuleSession(rulesURI, new HashMap(), RuleRuntime.STATELESS_SESSION_TYPE); calculateResults(statelessRuleSession); statelessRuleSession.release(); } private static void calculateResults(StatelessRuleSession statelessRuleSession) throws InvalidRuleSessionException, RemoteException { List data = prepareData(); // execute the rules List results = statelessRuleSession.executeRules(data); checkResults(results); } private static List prepareData() { List data = new ArrayList(); data.add(new Question("Can I have a bonus?", -5)); return data; } private static void checkResults(List results) { Iterator itr = results.iterator(); while (itr.hasNext()) {
Object obj = itr.next(); if (obj instanceof Answer) { log.info(obj.toString()); } } } private static void registerRules(String rulesFile, String rulesURI, RuleServiceProvider serviceProvider) throws ConfigurationException, RuleExecutionSetCreateException, IOException, RuleExecutionSetRegisterException { // Get the rule administrator. RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator(); // load the rules InputStream ruleInput = JessWithJsr94.class.getResourceAsStream(rulesFile); HashMap vendorProperties = new HashMap(); // Create the RuleExecutionSet RuleExecutionSet ruleExecutionSet = ruleAdministrator .getLocalRuleExecutionSetProvider(vendorProperties) .createRuleExecutionSet(ruleInput, vendorProperties); // Register the rule execution set. ruleAdministrator.registerRuleExecutionSet(rulesURI, ruleExecutionSet, vendorProperties); } }
repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\JessWithJsr94.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHostKey (final @Nullable java.lang.String HostKey) { set_Value (COLUMNNAME_HostKey, HostKey); } @Override public java.lang.String getHostKey() { return get_ValueAsString(COLUMNNAME_HostKey); } @Override public void setIsLoginIncorrect (final boolean IsLoginIncorrect) { set_Value (COLUMNNAME_IsLoginIncorrect, IsLoginIncorrect); } @Override public boolean isLoginIncorrect() { return get_ValueAsBoolean(COLUMNNAME_IsLoginIncorrect); } @Override public void setLoginDate (final @Nullable java.sql.Timestamp LoginDate) { set_Value (COLUMNNAME_LoginDate, LoginDate); } @Override public java.sql.Timestamp getLoginDate() { return get_ValueAsTimestamp(COLUMNNAME_LoginDate); } @Override public void setLoginUsername (final @Nullable java.lang.String LoginUsername) { set_Value (COLUMNNAME_LoginUsername, LoginUsername); } @Override public java.lang.String getLoginUsername() { return get_ValueAsString(COLUMNNAME_LoginUsername); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override
public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setRemote_Addr (final @Nullable java.lang.String Remote_Addr) { set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr); } @Override public java.lang.String getRemote_Addr() { return get_ValueAsString(COLUMNNAME_Remote_Addr); } @Override public void setRemote_Host (final @Nullable java.lang.String Remote_Host) { set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host); } @Override public java.lang.String getRemote_Host() { return get_ValueAsString(COLUMNNAME_Remote_Host); } @Override public void setWebSession (final @Nullable java.lang.String WebSession) { set_ValueNoCheck (COLUMNNAME_WebSession, WebSession); } @Override public java.lang.String getWebSession() { return get_ValueAsString(COLUMNNAME_WebSession); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Session.java
1
请完成以下Java代码
public class EscalationImpl extends RootElementImpl implements Escalation { protected static Attribute<String> nameAttribute; protected static Attribute<String> escalationCodeAttribute; protected static AttributeReference<ItemDefinition> structureRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Escalation.class, BPMN_ELEMENT_ESCALATION) .namespaceUri(BPMN20_NS) .extendsType(RootElement.class) .instanceProvider(new ModelTypeInstanceProvider<Escalation>() { public Escalation newInstance(ModelTypeInstanceContext instanceContext) { return new EscalationImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); escalationCodeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ESCALATION_CODE) .build(); structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF) .qNameAttributeReference(ItemDefinition.class) .build(); typeBuilder.build(); } public EscalationImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name);
} public String getEscalationCode() { return escalationCodeAttribute.getValue(this); } public void setEscalationCode(String escalationCode) { escalationCodeAttribute.setValue(this, escalationCode); } public ItemDefinition getStructure() { return structureRefAttribute.getReferenceTargetElement(this); } public void setStructure(ItemDefinition structure) { structureRefAttribute.setReferenceTargetElement(this, structure); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\EscalationImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class CurrencyRepository { final ICurrencyDAO currencyDAO = Services.get(ICurrencyDAO.class); @NonNull public Currency getById(@NonNull final CurrencyId currencyId) { return currencyDAO.getById(currencyId); } @NonNull public Currency getById(final int currencyId) { return getById(CurrencyId.ofRepoId(currencyId)); } public CurrencyId getCurrencyIdByCurrencyCode(@NonNull final CurrencyCode currencyCode) { final Currency currency = currencyDAO.getByCurrencyCode(currencyCode); return currency.getId(); }
public CurrencyCode getCurrencyCodeById(@NonNull final CurrencyId currencyId) { return getById(currencyId).getCurrencyCode(); } public CurrencyPrecision getStdPrecision(@NonNull final CurrencyId currencyId) { return getById(currencyId).getPrecision(); } public CurrencyPrecision getStdPrecision(@NonNull final CurrencyCode currencyCode) { final CurrencyId currencyId = getCurrencyIdByCurrencyCode(currencyCode); return getStdPrecision(currencyId); } public CurrencyPrecision getCostingPrecision(@NonNull final CurrencyId currencyId) { return getById(currencyId).getCostingPrecision(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyRepository.java
2
请完成以下Java代码
public List<AttachmentEntity> findAttachmentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return attachmentDataManager.findAttachmentsByProcessInstanceId(processInstanceId); } @Override public List<AttachmentEntity> findAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); return attachmentDataManager.findAttachmentsByTaskId(taskId); } @Override public void deleteAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); List<AttachmentEntity> attachments = findAttachmentsByTaskId(taskId); boolean dispatchEvents = getEventDispatcher().isEnabled(); String processInstanceId = null; String processDefinitionId = null; String executionId = null; if (dispatchEvents && attachments != null && !attachments.isEmpty()) { // Forced to fetch the task to get hold of the process definition // for event-dispatching, if available Task task = getTaskEntityManager().findById(taskId); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); processInstanceId = task.getProcessInstanceId(); executionId = task.getExecutionId(); } } for (Attachment attachment : attachments) { String contentId = attachment.getContentId();
if (contentId != null) { getByteArrayEntityManager().deleteByteArrayById(contentId); } attachmentDataManager.delete((AttachmentEntity) attachment); if (dispatchEvents) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent( ActivitiEventType.ENTITY_DELETED, attachment, executionId, processInstanceId, processDefinitionId ) ); } } } protected void checkHistoryEnabled() { if (!getHistoryManager().isHistoryEnabled()) { throw new ActivitiException("In order to use attachments, history should be enabled"); } } public AttachmentDataManager getAttachmentDataManager() { return attachmentDataManager; } public void setAttachmentDataManager(AttachmentDataManager attachmentDataManager) { this.attachmentDataManager = attachmentDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityManagerImpl.java
1
请完成以下Java代码
public class QtyDemand_QtySupply_V_to_ShipmentSchedule extends JavaProcess implements IProcessPrecondition { private final QtyDemandSupplyRepository demandSupplyRepository = SpringContextHolder.instance.getBean(QtyDemandSupplyRepository.class); private final ShipmentScheduleRepository shipmentScheduleRepository = SpringContextHolder.instance.getBean(ShipmentScheduleRepository.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID()));
final ShipmentScheduleQuery shipmentScheduleQuery = ShipmentScheduleQuery.builder() .warehouseId(currentRow.getWarehouseId()) .orgId(currentRow.getOrgId()) .productId(currentRow.getProductId()) .attributesKey(currentRow.getAttributesKey()) .onlyNonZeroReservedQty(true) .build(); final List<TableRecordReference> recordReferences = shipmentScheduleRepository.getIdsByQuery(shipmentScheduleQuery) .stream() .map(id -> TableRecordReference.of(I_M_ShipmentSchedule.Table_Name, id)) .collect(Collectors.toList()); getResult().setRecordsToOpen(recordReferences); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_ShipmentSchedule.java
1
请在Spring Boot框架中完成以下Java代码
public int getRule() { return rule; } /** * Sets the value of the rule property. * */ public void setRule(int value) { this.rule = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language;
} /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProactiveNotification.java
2
请在Spring Boot框架中完成以下Java代码
public class JsonAuthResponse { @JsonPOJOBuilder(withPrefix = "") public static class JsonAuthResponseBuilder {} @JsonInclude(JsonInclude.Include.NON_EMPTY) String token; @JsonInclude(JsonInclude.Include.NON_EMPTY) String language; @JsonInclude(JsonInclude.Include.NON_EMPTY) Integer userId; @JsonInclude(JsonInclude.Include.NON_EMPTY) String username; @JsonInclude(JsonInclude.Include.NON_NULL) String userFullname; @JsonInclude(JsonInclude.Include.NON_EMPTY)
String error; @JsonInclude(JsonInclude.Include.NON_EMPTY) Map<String, Object> messages; public static JsonAuthResponse.JsonAuthResponseBuilder ok(@NonNull final String token) { return builder().token(token); } public static JsonAuthResponse error(@NonNull final String error) { return builder().error(error).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\authentication\JsonAuthResponse.java
2
请完成以下Java代码
public InventoryLineAggregationKey createAggregationKey(@NonNull final HuForInventoryLine huForInventoryLine) { return new SingleHUInventoryLineInventoryLineAggregationKey(huForInventoryLine.getHuId(), huForInventoryLine.getHuQRCode(), huForInventoryLine.getProductId()); } @Override public InventoryLineAggregationKey createAggregationKey(@NonNull final InventoryLine inventoryLine) { final InventoryLineHU singleLineHU = inventoryLine.getSingleLineHU(); return new SingleHUInventoryLineInventoryLineAggregationKey(singleLineHU.getHuId(), singleLineHU.getHuQRCode(), inventoryLine.getProductId()); } @Override public AggregationType getAggregationType() { return AggregationType.SINGLE_HU; } @Value private static class SingleHUInventoryLineInventoryLineAggregationKey implements InventoryLineAggregationKey
{ @Nullable HuId huId; @Nullable HUQRCode huQRCode; @NonNull ProductId productId; SingleHUInventoryLineInventoryLineAggregationKey( @Nullable final HuId huId, @Nullable final HUQRCode huQRCode, @NonNull final ProductId productId) { if (huId == null && huQRCode == null) { throw new AdempiereException("At least huId or huQRCode must be set"); } this.huId = huId; this.huQRCode = huQRCode; this.productId = productId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\SingleHUInventoryLineAggregator.java
1
请在Spring Boot框架中完成以下Java代码
public String getSuppliersOrderingPartyID() { return suppliersOrderingPartyID; } /** * Sets the value of the suppliersOrderingPartyID property. * * @param value * allowed object is * {@link String } * */ public void setSuppliersOrderingPartyID(String value) { this.suppliersOrderingPartyID = value; } /** * Gets the value of the orderingPartyExtension property. * * @return
* possible object is * {@link OrderingPartyExtensionType } * */ public OrderingPartyExtensionType getOrderingPartyExtension() { return orderingPartyExtension; } /** * Sets the value of the orderingPartyExtension property. * * @param value * allowed object is * {@link OrderingPartyExtensionType } * */ public void setOrderingPartyExtension(OrderingPartyExtensionType value) { this.orderingPartyExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\OrderingPartyType.java
2
请完成以下Java代码
public class X_C_Workplace_User_Assign extends org.compiere.model.PO implements I_C_Workplace_User_Assign, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1619807920L; /** Standard Constructor */ public X_C_Workplace_User_Assign (final Properties ctx, final int C_Workplace_User_Assign_ID, @Nullable final String trxName) { super (ctx, C_Workplace_User_Assign_ID, trxName); } /** Load Constructor */ public X_C_Workplace_User_Assign (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public org.compiere.model.I_C_Workplace getC_Workplace() { return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class); } @Override public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace) { set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace); } @Override
public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); } @Override public void setC_Workplace_User_Assign_ID (final int C_Workplace_User_Assign_ID) { if (C_Workplace_User_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Workplace_User_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Workplace_User_Assign_ID, C_Workplace_User_Assign_ID); } @Override public int getC_Workplace_User_Assign_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_User_Assign_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_User_Assign.java
1
请完成以下Java代码
public List<String> getImageUrls() { return imageUrls; } public void setImageUrls(List<String> imageUrls) { this.imageUrls = imageUrls; } public List<String> getVideoUrls() { return videoUrls; } public void setVideoUrls(List<String> videoUrls) { this.videoUrls = videoUrls; } public Integer getStock() {
return stock; } public void setStock(Integer stock) { this.stock = stock; } public Float getAverageRating() { return averageRating; } public void setAverageRating(Float averageRating) { this.averageRating = averageRating; } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\entity\Product.java
1
请在Spring Boot框架中完成以下Java代码
public User getUser(UUID id) { return userRepository.findById(id).orElseThrow(() -> new NoSuchElementException("user not found.")); } /** * Get user by username. * * @return Returns user */ public User getUser(String username) { return userRepository.findByUsername(username).orElseThrow(() -> new NoSuchElementException("user not found.")); } /** * Register a new user in the system. * * @param registry User registration information * @return Returns the registered user */ @SuppressWarnings("UnusedReturnValue") public User signup(UserRegistry registry) { if (userRepository.existsBy(registry.email(), registry.username())) { throw new IllegalArgumentException("email or username is already exists."); } var requester = new User(registry); requester.encryptPassword(passwordEncoder, registry.password()); return userRepository.save(requester); } /** * Login to the system. * * @param email users email * @param password users password * @return Returns the logged-in user */ public User login(String email, String password) { if (email == null || email.isBlank()) { throw new IllegalArgumentException("email is required."); }
if (password == null || password.isBlank()) { throw new IllegalArgumentException("password is required."); } return userRepository .findByEmail(email) .filter(user -> passwordEncoder.matches(password, user.getPassword())) .orElseThrow(() -> new IllegalArgumentException("invalid email or password.")); } /** * Update user information. * * @param userId The user who requested the update * @param email users email * @param username users username * @param password users password * @param bio users bio * @param imageUrl users imageUrl * @return Returns the updated user */ public User updateUserDetails( UUID userId, String email, String username, String password, String bio, String imageUrl) { if (userId == null) { throw new IllegalArgumentException("user id is required."); } return userRepository.updateUserDetails(userId, passwordEncoder, email, username, password, bio, imageUrl); } }
repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public class OmsOrderReturnApplyController { @Autowired private OmsOrderReturnApplyService returnApplyService; @ApiOperation("分页查询退货申请") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrderReturnApply>> list(OmsReturnApplyQueryParam queryParam, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<OmsOrderReturnApply> returnApplyList = returnApplyService.list(queryParam, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(returnApplyList)); } @ApiOperation("批量删除退货申请") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = returnApplyService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取退货申请详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody
public CommonResult getItem(@PathVariable Long id) { OmsOrderReturnApplyResult result = returnApplyService.getItem(id); return CommonResult.success(result); } @ApiOperation("修改退货申请状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, @RequestBody OmsUpdateStatusParam statusParam) { int count = returnApplyService.updateStatus(id, statusParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderReturnApplyController.java
2
请在Spring Boot框架中完成以下Java代码
public class CommentEntity implements Serializable { private String id; private String comment; private String articleId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getArticleId() { return articleId;
} public void setArticleId(String articleId) { this.articleId = articleId; } @Override public String toString() { return "CommentEntity{" + "id='" + id + '\'' + ", comment='" + comment + '\'' + ", articleId='" + articleId + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\CommentEntity.java
2
请完成以下Java代码
public void setIsAutoSendWhenCreatedByUserGroup (final boolean IsAutoSendWhenCreatedByUserGroup) { set_Value (COLUMNNAME_IsAutoSendWhenCreatedByUserGroup, IsAutoSendWhenCreatedByUserGroup); } @Override public boolean isAutoSendWhenCreatedByUserGroup() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendWhenCreatedByUserGroup); } @Override public void setIsSyncBPartnersToRabbitMQ (final boolean IsSyncBPartnersToRabbitMQ) { set_Value (COLUMNNAME_IsSyncBPartnersToRabbitMQ, IsSyncBPartnersToRabbitMQ); } @Override public boolean isSyncBPartnersToRabbitMQ() { return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRabbitMQ); } @Override public void setIsSyncExternalReferencesToRabbitMQ (final boolean IsSyncExternalReferencesToRabbitMQ) { set_Value (COLUMNNAME_IsSyncExternalReferencesToRabbitMQ, IsSyncExternalReferencesToRabbitMQ); } @Override public boolean isSyncExternalReferencesToRabbitMQ() { return get_ValueAsBoolean(COLUMNNAME_IsSyncExternalReferencesToRabbitMQ); } @Override public void setRemoteURL (final java.lang.String RemoteURL) { set_Value (COLUMNNAME_RemoteURL, RemoteURL); }
@Override public String getRemoteURL() { return get_ValueAsString(COLUMNNAME_RemoteURL); } @Override public void setRouting_Key (final String Routing_Key) { set_Value (COLUMNNAME_Routing_Key, Routing_Key); } @Override public String getRouting_Key() { return get_ValueAsString(COLUMNNAME_Routing_Key); } @Override public void setAuthToken (final String AuthToken) { set_Value (COLUMNNAME_AuthToken, AuthToken); } @Override public String getAuthToken() { return get_ValueAsString(COLUMNNAME_AuthToken); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_RabbitMQ_HTTP.java
1
请在Spring Boot框架中完成以下Java代码
public JsonRequestProductUpsert run() { return JsonRequestProductUpsert.builder() .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .requestItems(getProductItems()) .build(); } @NonNull private List<JsonRequestProductUpsertItem> getProductItems() { return mapProductToProductRequestItem() .map(ImmutableList::of) .orElseGet(ImmutableList::of); } @NonNull private Optional<JsonRequestProductUpsertItem> mapProductToProductRequestItem() { if (product.getName() == null) { return Optional.empty(); } routeContext.setNextImportStartingTimestamp(product.getUpdatedAtNonNull().toInstant()); final String productIdentifier = formatExternalId(product.getId()); final JsonRequestProduct jsonRequestProduct = new JsonRequestProduct(); jsonRequestProduct.setCode(product.getProductNumber()); jsonRequestProduct.setEan(product.getEan()); jsonRequestProduct.setName(product.getName()); jsonRequestProduct.setType(JsonRequestProduct.Type.ITEM); jsonRequestProduct.setUomCode(getUOMCode(product.getUnitId())); return Optional.of(JsonRequestProductUpsertItem.builder() .productIdentifier(productIdentifier) .requestProduct(jsonRequestProduct) .externalSystemConfigId(routeContext.getExternalSystemRequest().getExternalSystemConfigId()) .build());
} @NonNull private String getUOMCode(@Nullable final String unitId) { if (unitId == null) { processLogger.logMessage("Shopware unit id is null, fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } if (routeContext.getUomMappings().isEmpty()) { processLogger.logMessage("No UOM mappings found in the route context, fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } final String externalCode = routeContext.getShopwareUomInfoProvider().getCode(unitId); if (externalCode == null) { processLogger.logMessage("No externalCode found for unit id: " + unitId + ", fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } final JsonUOM jsonUOM = routeContext.getUomMappings().get(externalCode); if (jsonUOM == null) { processLogger.logMessage("No UOM mapping found for externalCode: " + externalCode + " ! fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } return jsonUOM.getCode(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\ProductUpsertRequestProducer.java
2
请完成以下Java代码
public static BPartnerDepartmentId none(@NonNull final BPartnerId bpartnerId) { return new BPartnerDepartmentId(bpartnerId); } public static BPartnerDepartmentId ofRepoId(@NonNull final BPartnerId bpartnerId, final int bpartnerDepartmentId) { return new BPartnerDepartmentId(bpartnerId, bpartnerDepartmentId); } public static BPartnerDepartmentId ofRepoId(final int bpartnerId, final int bpartnerDepartmentId) { return new BPartnerDepartmentId(BPartnerId.ofRepoId(bpartnerId), bpartnerDepartmentId); } @NonNull public static BPartnerDepartmentId ofRepoIdOrNone( @NonNull final BPartnerId bpartnerId, @Nullable final Integer bpartnerDepartmentId) { return bpartnerDepartmentId != null && bpartnerDepartmentId > 0 ? ofRepoId(bpartnerId, bpartnerDepartmentId) : none(bpartnerId); } private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId, final int bpartnerDepartmentId) { this.repoId = Check.assumeGreaterThanZero(bpartnerDepartmentId, "bpartnerDepartmentId"); this.bpartnerId = bpartnerId;
} private BPartnerDepartmentId(@NonNull final BPartnerId bpartnerId) { this.repoId = -1; this.bpartnerId = bpartnerId; } public static int toRepoId(@Nullable final BPartnerDepartmentId bpartnerDepartmentId) { return bpartnerDepartmentId != null && !bpartnerDepartmentId.isNone() ? bpartnerDepartmentId.getRepoId() : -1; } public boolean isNone() { return repoId <= 0; } @Nullable public static Integer toRepoIdOrNull(@Nullable final BPartnerDepartmentId bPartnerDepartmentId) { return bPartnerDepartmentId != null && !bPartnerDepartmentId.isNone() ? bPartnerDepartmentId.getRepoId() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\department\BPartnerDepartmentId.java
1
请完成以下Java代码
public int getExternalSystem_Config_Shopware6_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_ID); } @Override public void setExternalSystem_Config_Shopware6_UOM_ID (final int ExternalSystem_Config_Shopware6_UOM_ID) { if (ExternalSystem_Config_Shopware6_UOM_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, ExternalSystem_Config_Shopware6_UOM_ID); } @Override public int getExternalSystem_Config_Shopware6_UOM_ID()
{ return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID); } @Override public void setShopwareCode (final String ShopwareCode) { set_Value (COLUMNNAME_ShopwareCode, ShopwareCode); } @Override public String getShopwareCode() { return get_ValueAsString(COLUMNNAME_ShopwareCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6_UOM.java
1
请完成以下Java代码
public class DocActionOptionsBL implements IDocActionOptionsBL { private static final Logger logger = LogManager.getLogger(DocActionOptionsBL.class); private final Supplier<Map<String, IDocActionOptionsCustomizer>> _docActionOptionsCustomizerByTableName = Suppliers.memoize(DocActionOptionsBL::retrieveDocActionOptionsCustomizer); @Override public Set<String> getRequiredParameters(@Nullable final String contextTableName) { final HashSet<String> requiredParameters = new HashSet<>(DefaultDocActionOptionsCustomizer.instance.getParameters()); if (contextTableName != null) { final IDocActionOptionsCustomizer tableSpecificCustomizer = _docActionOptionsCustomizerByTableName.get().get(contextTableName); if (tableSpecificCustomizer != null) { requiredParameters.addAll(tableSpecificCustomizer.getParameters()); } } else { // NOTE: in case contextTableName is not provided // then we shall consider all params as (possibly) required. _docActionOptionsCustomizerByTableName.get() .values() .forEach(tableSpecificCustomizer -> requiredParameters.addAll(tableSpecificCustomizer.getParameters())); } return requiredParameters; } @Override public void updateDocActions(final DocActionOptionsContext optionsCtx) { final IDocActionOptionsCustomizer customizers = getDocActionOptionsCustomizers(optionsCtx.getTableName()); customizers.customizeValidActions(optionsCtx); // // Apply role access final DocTypeId docTypeId = optionsCtx.getDocTypeId(); if (docTypeId != null) { final UserRolePermissionsKey permissionsKey = optionsCtx.getUserRolePermissionsKey(); final IUserRolePermissions role = Services.get(IUserRolePermissionsDAO.class).getUserRolePermissions(permissionsKey);
role.applyActionAccess(optionsCtx); } } private IDocActionOptionsCustomizer getDocActionOptionsCustomizers(@Nullable final String contextTableName) { final ArrayList<IDocActionOptionsCustomizer> customizers = new ArrayList<>(2); customizers.add(DefaultDocActionOptionsCustomizer.instance); if (contextTableName != null) { final IDocActionOptionsCustomizer tableSpecificCustomizer = _docActionOptionsCustomizerByTableName.get().get(contextTableName); if (tableSpecificCustomizer != null) { customizers.add(tableSpecificCustomizer); } } return CompositeDocActionOptionsCustomizer.ofList(customizers); } private static ImmutableMap<String, IDocActionOptionsCustomizer> retrieveDocActionOptionsCustomizer() { final ImmutableMap<String, IDocActionOptionsCustomizer> customizers = SpringContextHolder.instance.getBeansOfType(IDocActionOptionsCustomizer.class) .stream() .collect(ImmutableMap.toImmutableMap(IDocActionOptionsCustomizer::getAppliesToTableName, Function.identity())); logger.info("Loaded {}(s): {}", IDocActionOptionsCustomizer.class, customizers); return customizers; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocActionOptionsBL.java
1
请完成以下Java代码
public class ScriptExecutionListener implements ExecutionListener { private static final long serialVersionUID = 1L; protected Expression script; protected Expression language; protected Expression resultVariable; @Override public void notify(DelegateExecution execution) { validateParameters(); ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); Object result = scriptingEngines.evaluate(script.getExpressionText(), language.getExpressionText(), execution); if (resultVariable != null) { execution.setVariable(resultVariable.getExpressionText(), result); } } protected void validateParameters() { if (script == null) { throw new IllegalArgumentException("The field 'script' should be set on the ExecutionListener"); } if (language == null) { throw new IllegalArgumentException("The field 'language' should be set on the ExecutionListener");
} } public void setScript(Expression script) { this.script = script; } public void setLanguage(Expression language) { this.language = language; } public void setResultVariable(Expression resultVariable) { this.resultVariable = resultVariable; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ScriptExecutionListener.java
1
请完成以下Java代码
public class AlarmCommentNotificationInfo implements RuleOriginatedNotificationInfo { private String comment; private String action; private String userEmail; private String userFirstName; private String userLastName; private String alarmType; private UUID alarmId; private EntityId alarmOriginator; private String alarmOriginatorName; private String alarmOriginatorLabel; private AlarmSeverity alarmSeverity; private AlarmStatus alarmStatus; private CustomerId alarmCustomerId; private DashboardId dashboardId; @Override public Map<String, String> getTemplateData() { return mapOf( "comment", comment, "action", action, "userTitle", User.getTitle(userEmail, userFirstName, userLastName), "userEmail", userEmail, "userFirstName", userFirstName, "userLastName", userLastName, "alarmType", alarmType,
"alarmId", alarmId.toString(), "alarmSeverity", alarmSeverity.name().toLowerCase(), "alarmStatus", alarmStatus.toString(), "alarmOriginatorEntityType", alarmOriginator.getEntityType().getNormalName(), "alarmOriginatorId", alarmOriginator.getId().toString(), "alarmOriginatorName", alarmOriginatorName, "alarmOriginatorLabel", alarmOriginatorLabel ); } @Override public CustomerId getAffectedCustomerId() { return alarmCustomerId; } @Override public EntityId getStateEntityId() { return alarmOriginator; } @Override public DashboardId getDashboardId() { return dashboardId; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\AlarmCommentNotificationInfo.java
1
请完成以下Java代码
public abstract class AuthenticationException extends RuntimeException { @Serial private static final long serialVersionUID = 2018827803361503060L; private @Nullable Authentication authenticationRequest; /** * Constructs an {@code AuthenticationException} with the specified message and root * cause. * @param msg the detail message * @param cause the root cause */ public AuthenticationException(@Nullable String msg, Throwable cause) { super(msg, cause); } /** * Constructs an {@code AuthenticationException} with the specified message and no * root cause. * @param msg the detail message */ public AuthenticationException(@Nullable String msg) { super(msg); } /** * Get the {@link Authentication} object representing the failed authentication * attempt. * <p> * This field captures the authentication request that was attempted but ultimately * failed, providing critical information for diagnosing the failure and facilitating * debugging
* @since 6.5 */ public @Nullable Authentication getAuthenticationRequest() { return this.authenticationRequest; } /** * Set the {@link Authentication} object representing the failed authentication * attempt. * <p> * The provided {@code authenticationRequest} should not be null * @param authenticationRequest the authentication request associated with the failed * authentication attempt * @since 6.5 */ public void setAuthenticationRequest(@Nullable Authentication authenticationRequest) { Assert.notNull(authenticationRequest, "authenticationRequest cannot be null"); this.authenticationRequest = authenticationRequest; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\AuthenticationException.java
1
请完成以下Spring Boot application配置
server.port=8001 logging.config=classpath:log4j2.xml #multipart.maxFileSize=2Mb #multipart.maxRequestSize=2Mb #upload.file.path=/mnt/data/txt2img #upload.file.path=/mnt/data/img2txt error.file.path=/mnt/data/img2txt/error.txt ## Freemarker 配置 ## 文件配置路径 spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.cache=false spring.freemarker.charset=UTF-8 spring.freemarker.check-template-location=true spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=true spring.freemarker.expose-session-attributes=true spring.freemarker.request-context-attribute=request spring.
freemarker.suffix=.ftl ##thymeleaf start #spring.thymeleaf.prefix=classpath:/templates/ #spring.thymeleaf.suffix=.html #spring.thymeleaf.mode=HTML5 #spring.thymeleaf.encoding=UTF-8 #spring.thymeleaf.content-type=text/html #spring.thymeleaf.cache=false ##thymeleaf end
repos\spring-boot-quick-master\quick-img2txt\src\main\resources\application.properties
2
请完成以下Java代码
public class X_C_Flatrate_Data extends org.compiere.model.PO implements I_C_Flatrate_Data, org.compiere.model.I_Persistent { private static final long serialVersionUID = -691275621L; /** Standard Constructor */ public X_C_Flatrate_Data (final Properties ctx, final int C_Flatrate_Data_ID, @Nullable final String trxName) { super (ctx, C_Flatrate_Data_ID, trxName); } /** Load Constructor */ public X_C_Flatrate_Data (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_Flatrate_DataEntry_IncludedT (final @Nullable java.lang.String C_Flatrate_DataEntry_IncludedT) { set_Value (COLUMNNAME_C_Flatrate_DataEntry_IncludedT, C_Flatrate_DataEntry_IncludedT); } @Override
public java.lang.String getC_Flatrate_DataEntry_IncludedT() { return get_ValueAsString(COLUMNNAME_C_Flatrate_DataEntry_IncludedT); } @Override public void setC_Flatrate_Data_ID (final int C_Flatrate_Data_ID) { if (C_Flatrate_Data_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, C_Flatrate_Data_ID); } @Override public int getC_Flatrate_Data_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_Data_ID); } @Override public void setHasContracts (final boolean HasContracts) { set_Value (COLUMNNAME_HasContracts, HasContracts); } @Override public boolean isHasContracts() { return get_ValueAsBoolean(COLUMNNAME_HasContracts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Data.java
1
请在Spring Boot框架中完成以下Java代码
public class TradeController { @Autowired private RpTradePaymentQueryService rpTradePaymentQueryService; @RequiresPermissions("trade:order:view") @RequestMapping(value = "/listPaymentOrder", method ={RequestMethod.POST, RequestMethod.GET}) public String listPaymentOrder(HttpServletRequest request, PaymentOrderQueryParam paymentOrderQueryParam, PageParam pageParam, Model model) { PageBean pageBean = rpTradePaymentQueryService.listPaymentOrderPage(pageParam, paymentOrderQueryParam); model.addAttribute("pageBean", pageBean); model.addAttribute("pageParam", pageParam); model.addAttribute("paymentOrderQueryParam", paymentOrderQueryParam);//查询条件 model.addAttribute("statusEnums", TradeStatusEnum.toMap());//状态 model.addAttribute("payWayNameEnums", PayWayEnum.toMap());//支付方式 model.addAttribute("payTypeNameEnums", PayTypeEnum.toMap());//支付类型 model.addAttribute("fundIntoTypeEnums", FundInfoTypeEnum.toMap());//支付类型 return "trade/listPaymentOrder"; }
@RequiresPermissions("trade:record:view") @RequestMapping(value = "/listPaymentRecord", method ={RequestMethod.POST, RequestMethod.GET}) public String listPaymentRecord(HttpServletRequest request, PaymentOrderQueryParam paymentOrderQueryParam, PageParam pageParam, Model model) { PageBean pageBean = rpTradePaymentQueryService.listPaymentRecordPage(pageParam, paymentOrderQueryParam); model.addAttribute("pageBean", pageBean); model.addAttribute("pageParam", pageParam); model.addAttribute("paymentOrderQueryParam", paymentOrderQueryParam); model.addAttribute("statusEnums", TradeStatusEnum.toMap());//状态 model.addAttribute("payWayNameEnums", PayWayEnum.toMap());//支付方式 model.addAttribute("payTypeNameEnums", PayTypeEnum.toMap());//支付类型 model.addAttribute("fundIntoTypeEnums", FundInfoTypeEnum.toMap());//支付类型 model.addAttribute("trxTypeEnums", TrxTypeEnum.toMap());//支付类型 return "trade/listPaymentRecord"; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\trade\TradeController.java
2
请完成以下Java代码
public int hashCode(Salary x) { return x.hashCode(); } @Override public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Salary salary = new Salary(); String salaryValue = rs.getString(position); salary.setAmount(Long.parseLong(salaryValue.split(" ")[1])); salary.setCurrency(salaryValue.split(" ")[0]); return salary; } @Override public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException { if (Objects.isNull(value)) st.setNull(index, Types.VARCHAR); else { Long salaryValue = SalaryCurrencyConvertor.convert(value.getAmount(), value.getCurrency(), localCurrency); st.setString(index, value.getCurrency() + " " + salaryValue); } } @Override public Salary deepCopy(Salary value) { if (Objects.isNull(value)) return null; Salary newSal = new Salary(); newSal.setAmount(value.getAmount()); newSal.setCurrency(value.getCurrency()); return newSal; } @Override public boolean isMutable() {
return true; } @Override public Serializable disassemble(Salary value) { return deepCopy(value); } @Override public Salary assemble(Serializable cached, Object owner) { return deepCopy((Salary) cached); } @Override public Salary replace(Salary detached, Salary managed, Object owner) { return detached; } @Override public void setParameterValues(Properties parameters) { this.localCurrency = parameters.getProperty("currency"); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\SalaryType.java
1
请完成以下Java代码
public void deleteComment(String commentId) { ensureHistoryEnabled(Status.FORBIDDEN); ensureProcessInstanceExists(Status.NOT_FOUND); TaskService taskService = engine.getTaskService(); try { taskService.deleteProcessInstanceComment(processInstanceId, commentId); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } /** * Updates message for a given processInstanceId and commentId */ @Override public void updateComment(CommentDto comment) { ensureHistoryEnabled(Status.FORBIDDEN); ensureProcessInstanceExists(Status.NOT_FOUND); TaskService taskService = engine.getTaskService(); try { taskService.updateProcessInstanceComment(processInstanceId, comment.getId(), comment.getMessage()); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } /** * Deletes all comments by a given processInstanceId */ @Override public void deleteComments() { ensureHistoryEnabled(Status.FORBIDDEN); ensureProcessInstanceExists(Status.NOT_FOUND); TaskService taskService = engine.getTaskService();
try { taskService.deleteProcessInstanceComments(processInstanceId); } catch (AuthorizationException e) { throw e; } catch (NullValueException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } } private void ensureHistoryEnabled(Status status) { if (!isHistoryEnabled()) { throw new InvalidRequestException(status, "History is not enabled"); } } private boolean isHistoryEnabled() { IdentityService identityService = engine.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); try { identityService.clearAuthentication(); int historyLevel = engine.getManagementService().getHistoryLevel(); return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; } finally { identityService.setAuthentication(currentAuthentication); } } private void ensureProcessInstanceExists(Status status) { HistoricProcessInstance historicProcessInstance = engine.getHistoryService().createHistoricProcessInstanceQuery() .processInstanceId(processInstanceId).singleResult(); if (historicProcessInstance == null) { throw new InvalidRequestException(status, "No process instance found for id " + processInstanceId); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ProcessInstanceCommentResourceImpl.java
1
请完成以下Java代码
public void setSalesDefault(final Boolean salesDefault) { this.salesDefault = salesDefault; this.salesDefaultSet = true; } public void setPurchase(final Boolean purchase) { this.purchase = purchase; this.purchaseSet = true; } public void setPurchaseDefault(final Boolean purchaseDefault) { this.purchaseDefault = purchaseDefault; this.purchaseDefaultSet = true; } public void setSubjectMatter(final Boolean subjectMatter) { this.subjectMatter = subjectMatter; this.subjectMatterSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setMetasfreshBPartnerId(final JsonMetasfreshId metasfreshBPartnerId) { this.metasfreshBPartnerId = metasfreshBPartnerId; this.metasfreshBPartnerIdSet = true; } public void setBirthday(final LocalDate birthday) { this.birthday = birthday;
this.birthdaySet = true; } public void setInvoiceEmailEnabled(@Nullable final Boolean invoiceEmailEnabled) { this.invoiceEmailEnabled = invoiceEmailEnabled; invoiceEmailEnabledSet = true; } public void setTitle(final String title) { this.title = title; this.titleSet = true; } public void setPhone2(final String phone2) { this.phone2 = phone2; this.phone2Set = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestContact.java
1
请完成以下Java代码
public java.math.BigDecimal getMargin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Offer Amount. @param OfferAmt Amount of the Offer */ @Override public void setOfferAmt (java.math.BigDecimal OfferAmt) { set_Value (COLUMNNAME_OfferAmt, OfferAmt); } /** Get Offer Amount. @return Amount of the Offer */ @Override public java.math.BigDecimal getOfferAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt); if (bd == null)
return BigDecimal.ZERO; return bd; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonStatusRequest { @NonNull @JsonProperty("status") JsonExternalStatus status; @Nullable @JsonProperty("adIssueId") JsonMetasfreshId adIssueId; @Nullable @JsonProperty("adPInstanceId") JsonMetasfreshId pInstanceId; @Nullable @JsonProperty("message") String message;
@Builder @JsonCreator private JsonStatusRequest( @JsonProperty("status") @NonNull final JsonExternalStatus status, @JsonProperty("adIssueId") @Nullable final JsonMetasfreshId adIssueId, @JsonProperty("adPInstanceId") @Nullable final JsonMetasfreshId pInstanceId, @JsonProperty("message") @Nullable final String message) { this.status = status; this.adIssueId = adIssueId; this.pInstanceId = pInstanceId; this.message = message; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalsystem\src\main\java\de\metas\common\externalsystem\status\JsonStatusRequest.java
2
请完成以下Java代码
public class GlobalExceptionInterceptor implements ServerInterceptor { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionInterceptor.class); @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata headers, ServerCallHandler<ReqT, RespT> next) { ServerCall.Listener<ReqT> delegate = null; logger.info("In the interceptor, going to call the target RPC"); try { delegate = next.startCall(serverCall, headers); } catch(Exception ex) { logger.error("Exception caught in a subsequent interceptor", ex.getMessage()); return handleInterceptorException(ex, serverCall); } return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(delegate) { @Override public void onHalfClose() { try { super.onHalfClose(); } catch (Exception ex) { logger.error("Exception caught in a RPC endpoint", ex.getMessage()); handleEndpointException(ex, serverCall); }
} }; } private static <ReqT, RespT> void handleEndpointException(Exception ex, ServerCall<ReqT, RespT> serverCall) { logger.error("The ex.getMessage() = {}", ex.getMessage()); String ticket = new TicketService().createTicket(ex.getMessage()); //send the response back serverCall.close(Status.INTERNAL .withCause(ex) .withDescription(ex.getMessage() + ", Ticket raised:" + ticket), new Metadata()); } private <ReqT, RespT> ServerCall.Listener<ReqT> handleInterceptorException(Throwable t, ServerCall<ReqT, RespT> serverCall) { String ticket = new TicketService().createTicket(t.getMessage()); serverCall.close(Status.INTERNAL .withCause(t) .withDescription("An exception occurred in a **subsequent** interceptor:" + ", Ticket raised:" + ticket), new Metadata()); return new ServerCall.Listener<ReqT>() { // no-op }; } }
repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\orderprocessing\orderprocessing\GlobalExceptionInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public static class Menu { private String name; private String path; private String title; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "Menu{" + "name='" + name + '\'' + ", path='" + path + '\'' + ", title='" + title + '\'' + '}'; } } public static class Compiler { private String timeout; private String outputFolder; public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getOutputFolder() { return outputFolder; } public void setOutputFolder(String outputFolder) { this.outputFolder = outputFolder; } @Override public String toString() {
return "Compiler{" + "timeout='" + timeout + '\'' + ", outputFolder='" + outputFolder + '\'' + '}'; } } public String getError() { return error; } public void setError(String error) { this.error = error; } public List<Menu> getMenus() { return menus; } public void setMenus(List<Menu> menus) { this.menus = menus; } public Compiler getCompiler() { return compiler; } public void setCompiler(Compiler compiler) { this.compiler = compiler; } @Override public String toString() { return "AppProperties{" + "error='" + error + '\'' + ", menus=" + menus + ", compiler=" + compiler + '}'; } }
repos\spring-boot-master\spring-boot-externalize-config\src\main\java\com\mkyong\global\AppProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionUrl() { return processDefinitionUrl; } public void setProcessDefinitionUrl(String processDefinitionUrl) { this.processDefinitionUrl = processDefinitionUrl; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getExecutionUrl() { return executionUrl; } public void setExecutionUrl(String executionUrl) { this.executionUrl = executionUrl; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; }
public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\EventSubscriptionResponse.java
2
请完成以下Java代码
private Map<String, String> processFieldsMappingPatterns(TbMsg msg) { var mappingsMap = new HashMap<String, String>(); config.getDataMapping().forEach((sourceField, targetKey) -> { String patternProcessedTargetKey = TbNodeUtils.processPattern(targetKey, msg); mappingsMap.put(sourceField, patternProcessedTargetKey); }); return mappingsMap; } private Map<String, String> processKvEntryMappingPatterns(TbMsg msg) { var mappingsMap = new HashMap<String, String>(); config.getDataMapping().forEach((sourceKey, targetKey) -> { String patternProcessedSourceKey = TbNodeUtils.processPattern(sourceKey, msg); String patternProcessedTargetKey = TbNodeUtils.processPattern(targetKey, msg); mappingsMap.put(patternProcessedSourceKey, patternProcessedTargetKey); }); return mappingsMap; } private ListenableFuture<Map<String, String>> getEntityFieldsAsync(TbContext ctx, EntityId entityId, Map<String, String> mappingsMap, boolean ignoreNullStrings) { return Futures.transform(EntitiesFieldsAsyncLoader.findAsync(ctx, entityId), fieldsData -> { var targetKeysToSourceValuesMap = new HashMap<String, String>(); for (var mappingEntry : mappingsMap.entrySet()) { var sourceFieldName = mappingEntry.getKey(); var targetKeyName = mappingEntry.getValue(); var sourceFieldValue = fieldsData.getFieldValue(sourceFieldName, ignoreNullStrings); if (sourceFieldValue != null) { targetKeysToSourceValuesMap.put(targetKeyName, sourceFieldValue); } }
return targetKeysToSourceValuesMap; }, ctx.getDbCallbackExecutor() ); } private ListenableFuture<List<KvEntry>> getAttributesAsync(TbContext ctx, EntityId entityId, List<String> attrKeys) { var latest = ctx.getAttributesService().find(ctx.getTenantId(), entityId, AttributeScope.SERVER_SCOPE, attrKeys); return Futures.transform(latest, l -> l.stream() .map(i -> (KvEntry) i) .collect(Collectors.toList()), ctx.getDbCallbackExecutor()); } private ListenableFuture<List<KvEntry>> getLatestTelemetryAsync(TbContext ctx, EntityId entityId, List<String> timeseriesKeys) { var latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(), entityId, timeseriesKeys); return Futures.transform(latest, l -> l.stream() .map(i -> (KvEntry) i) .collect(Collectors.toList()), ctx.getDbCallbackExecutor()); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractGetMappedDataNode.java
1
请完成以下Java代码
public XtraAmbulatoryType getAmbulatory() { return ambulatory; } /** * Sets the value of the ambulatory property. * * @param value * allowed object is * {@link XtraAmbulatoryType } * */ public void setAmbulatory(XtraAmbulatoryType value) { this.ambulatory = value; } /** * Gets the value of the stationary property. * * @return * possible object is * {@link XtraStationaryType }
* */ public XtraStationaryType getStationary() { return stationary; } /** * Sets the value of the stationary property. * * @param value * allowed object is * {@link XtraStationaryType } * */ public void setStationary(XtraStationaryType value) { this.stationary = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraHospitalType.java
1
请在Spring Boot框架中完成以下Java代码
public UserVO get3(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return user; } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get4") public CommonResult<UserVO> get4(@RequestParam("id") Integer id) { // 查询用户 UserVO user = new UserVO().setId(id).setUsername("username:" + id); // 返回 return CommonResult.success(user); } /** * 测试抛出 NullPointerException 异常 */ @GetMapping("/exception-01") public UserVO exception01() { throw new NullPointerException("没有粗面鱼丸"); }
/** * 测试抛出 ServiceException 异常 */ @GetMapping("/exception-02") public UserVO exception02() { throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND); } // @PostMapping(value = "/add", // // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 // consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, // // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 // produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} // ) @PostMapping(value = "/add", // ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头 consumes = {MediaType.APPLICATION_XML_VALUE}, // ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头 produces = {MediaType.APPLICATION_XML_VALUE} ) // @PostMapping(value = "/add") public Mono<UserVO> add(@RequestBody Mono<UserVO> user) { return user; } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请完成以下Java代码
public class UserAttributeEditor extends PropertyEditorSupport { @Override public void setAsText(String s) throws IllegalArgumentException { if (!StringUtils.hasText(s)) { setValue(null); return; } String[] tokens = StringUtils.commaDelimitedListToStringArray(s); UserAttribute userAttrib = new UserAttribute(); List<String> authoritiesAsStrings = new ArrayList<>(); for (int i = 0; i < tokens.length; i++) { String currentToken = tokens[i].trim(); if (i == 0) { userAttrib.setPassword(currentToken); } else {
if (currentToken.toLowerCase(Locale.ENGLISH).equals("enabled")) { userAttrib.setEnabled(true); } else if (currentToken.toLowerCase(Locale.ENGLISH).equals("disabled")) { userAttrib.setEnabled(false); } else { authoritiesAsStrings.add(currentToken); } } } userAttrib.setAuthoritiesAsString(authoritiesAsStrings); setValue(userAttrib.isValid() ? userAttrib : null); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\memory\UserAttributeEditor.java
1
请完成以下Java代码
protected int getUpdateChunkSize(SetRemovalTimeBatchConfiguration configuration, CommandContext commandContext) { return configuration.getChunkSize() == null ? commandContext.getProcessEngineConfiguration().getRemovalTimeUpdateChunkSize() : configuration.getChunkSize(); } protected TransactionListener createTransactionHandler(SetRemovalTimeBatchConfiguration configuration, Map<Class<? extends DbEntity>, DbOperation> operations, Integer chunkSize, MessageEntity currentJob, CommandExecutor newCommandExecutor) { return new ProcessSetRemovalTimeResultHandler(configuration, chunkSize, newCommandExecutor, this, currentJob.getId(), operations); } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> processInstanceIds) { return new SetRemovalTimeBatchConfiguration(processInstanceIds) .setRemovalTime(configuration.getRemovalTime()) .setHasRemovalTime(configuration.hasRemovalTime()) .setHierarchical(configuration.isHierarchical())
.setUpdateInChunks(configuration.isUpdateInChunks()) .setChunkSize(configuration.getChunkSize()); } @Override protected SetRemovalTimeJsonConverter getJsonConverterInstance() { return SetRemovalTimeJsonConverter.INSTANCE; } @Override public int calculateInvocationsPerBatchJob(String batchType, SetRemovalTimeBatchConfiguration configuration) { if (configuration.isUpdateInChunks()) { return 1; } return super.calculateInvocationsPerBatchJob(batchType, configuration); } @Override public String getType() { return Batch.TYPE_PROCESS_SET_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\ProcessSetRemovalTimeJobHandler.java
1
请完成以下Java代码
private IQueryBuilder<I_AD_Record_Warning> toSqlQuery(@NonNull final RecordWarningQuery query) { final IQueryBuilder<I_AD_Record_Warning> queryBuilder = queryBL.createQueryBuilder(I_AD_Record_Warning.class); if(query.getRootRecordRef() != null) { final TableRecordReference rootRecordRef = query.getRootRecordRef(); queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Root_AD_Table_ID, rootRecordRef.getAD_Table_ID()) .addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Root_Record_ID, rootRecordRef.getRecord_ID()); } if(query.getRecordRef() != null) { final TableRecordReference recordRef = query.getRecordRef(); queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID()) .addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Record_ID, recordRef.getRecord_ID()); } if (query.getBusinessRuleId() != null) { queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_AD_BusinessRule_ID, query.getBusinessRuleId()); }
if(query.getSeverity() != null) { queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Severity, query.getSeverity().getCode()); } return queryBuilder; } public boolean hasErrors(@NonNull final TableRecordReference recordRef) { final RecordWarningQuery query = RecordWarningQuery.builder() .recordRef(recordRef) .severity(Severity.Error) .build(); return toSqlQuery(query) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\record\warning\RecordWarningRepository.java
1
请完成以下Java代码
protected ManagedProcessEngineMetadata transformConfiguration(final OperationContext context, String engineName, final ModelNode model) throws OperationFailedException { return new ManagedProcessEngineMetadata( SubsystemAttributeDefinitons.DEFAULT.resolveModelAttribute(context, model).asBoolean(), engineName, SubsystemAttributeDefinitons.DATASOURCE.resolveModelAttribute(context, model).asString(), SubsystemAttributeDefinitons.HISTORY_LEVEL.resolveModelAttribute(context, model).asString(), SubsystemAttributeDefinitons.CONFIGURATION.resolveModelAttribute(context, model).asString(), getProperties(SubsystemAttributeDefinitons.PROPERTIES.resolveModelAttribute(context, model)), getPlugins(SubsystemAttributeDefinitons.PLUGINS.resolveModelAttribute(context, model)) ); } protected List<ProcessEnginePluginXml> getPlugins(ModelNode plugins) { List<ProcessEnginePluginXml> pluginConfigurations = new ArrayList<>(); if (plugins.isDefined()) { for (final ModelNode plugin : plugins.asList()) { ProcessEnginePluginXml processEnginePluginXml = new ProcessEnginePluginXml() { @Override public String getPluginClass() { return plugin.get(Element.PLUGIN_CLASS.getLocalName()).asString(); } @Override public Map<String, String> getProperties() { return ProcessEngineAdd.this.getProperties(plugin.get(Element.PROPERTIES.getLocalName())); } }; pluginConfigurations.add(processEnginePluginXml); }
} return pluginConfigurations; } protected Map<String, String> getProperties(ModelNode properties) { Map<String, String> propertyMap = new HashMap<>(); if (properties.isDefined()) { for (Property property : properties.asPropertyList()) { propertyMap.put(property.getName(), property.getValue().asString()); } } return propertyMap; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\ProcessEngineAdd.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getDeploymentId() { return deploymentId; }
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DecisionResponse.java
2
请完成以下Java代码
public ExecutionQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public ExecutionQuery withoutTenantId() { this.tenantIds = null; isTenantIdSet = true; return this; } //ordering //////////////////////////////////////////////////// public ExecutionQueryImpl orderByProcessInstanceId() { orderBy(ExecutionQueryProperty.PROCESS_INSTANCE_ID); return this; } public ExecutionQueryImpl orderByProcessDefinitionId() { orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_PROCESS_DEFINITION, ExecutionQueryProperty.PROCESS_DEFINITION_ID)); return this; } public ExecutionQueryImpl orderByProcessDefinitionKey() { orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_PROCESS_DEFINITION, ExecutionQueryProperty.PROCESS_DEFINITION_KEY)); return this; } public ExecutionQuery orderByTenantId() { orderBy(ExecutionQueryProperty.TENANT_ID); return this; } //results //////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getExecutionManager() .findExecutionCountByQueryCriteria(this); } @Override @SuppressWarnings("unchecked") public List<Execution> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return (List) commandContext .getExecutionManager() .findExecutionsByQueryCriteria(this, page); } //getters //////////////////////////////////////////////////// public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getProcessInstanceId() { return processInstanceId;
} public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
protected void closeCallAccessDenied(final ServerCall<?, ?> call, final AccessDeniedException aex) { log.debug(ACCESS_DENIED_DESCRIPTION, aex); call.close(Status.PERMISSION_DENIED.withCause(aex).withDescription(ACCESS_DENIED_DESCRIPTION), new Metadata()); } /** * Server call listener that catches and handles exceptions in {@link #onHalfClose()}. * * @param <ReqT> The type of the request. * @param <RespT> The type of the response. */ private class ExceptionTranslatorServerCallListener<ReqT, RespT> extends SimpleForwardingServerCallListener<ReqT> { private final ServerCall<ReqT, RespT> call; protected ExceptionTranslatorServerCallListener(final Listener<ReqT> delegate, final ServerCall<ReqT, RespT> call) { super(delegate);
this.call = call; } @Override // Unary calls error out here public void onHalfClose() { try { super.onHalfClose(); } catch (final AuthenticationException aex) { closeCallUnauthenticated(this.call, aex); } catch (final AccessDeniedException aex) { closeCallAccessDenied(this.call, aex); } } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\ExceptionTranslatingServerInterceptor.java
1
请完成以下Java代码
public boolean isTransportEnabled() { return !ApiUsageStateValue.DISABLED.equals(transportState); } public boolean isReExecEnabled() { return !ApiUsageStateValue.DISABLED.equals(reExecState); } public boolean isDbStorageEnabled() { return !ApiUsageStateValue.DISABLED.equals(dbStorageState); } public boolean isJsExecEnabled() { return !ApiUsageStateValue.DISABLED.equals(jsExecState); } public boolean isTbelExecEnabled() { return !ApiUsageStateValue.DISABLED.equals(tbelExecState);
} public boolean isEmailSendEnabled() { return !ApiUsageStateValue.DISABLED.equals(emailExecState); } public boolean isSmsSendEnabled() { return !ApiUsageStateValue.DISABLED.equals(smsExecState); } public boolean isAlarmCreationEnabled() { return alarmExecState != ApiUsageStateValue.DISABLED; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ApiUsageState.java
1
请完成以下Java代码
public class CStatementVO implements Serializable { private static final long serialVersionUID = -6778280012583949122L; /** * VO Constructor * * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE */ public CStatementVO(final int resultSetType, final int resultSetConcurrency, final String trxName) { super(); m_resultSetType = resultSetType; m_resultSetConcurrency = resultSetConcurrency; m_sql = null; m_trxName = trxName; } // CStatementVO /** * VO Constructor * * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE * @param sql sql */ public CStatementVO(final int resultSetType, final int resultSetConcurrency, final String sql, final String trxName) { m_resultSetType = resultSetType; m_resultSetConcurrency = resultSetConcurrency; m_sql = sql; m_trxName = trxName; } // CStatementVO /** * Type */ private final int m_resultSetType; /** * Concurrency */ private final int m_resultSetConcurrency; /** * SQL Statement */ private String m_sql; /** * Transaction Name **/ private final String m_trxName; /** * Debugging: collected SQL parameters for this statement */ private Map<Integer, Object> debugSqlParams; /** * String representation * * @return info */ @Override public String toString() { return MoreObjects.toStringHelper("SQL") .omitNullValues() .add("trxName", m_trxName) .addValue(m_sql) .toString(); } public final String getSql() { return m_sql; } public void setSql(final String sql) { m_sql = sql; } /** * Get ResultSet Concurrency * * @return rs concurrency */ public int getResultSetConcurrency() { return m_resultSetConcurrency; } /** * Get ResultSet Type *
* @return rs type */ public int getResultSetType() { return m_resultSetType; } /** * @return transaction name */ public String getTrxName() { return m_trxName; } public final void clearDebugSqlParams() { this.debugSqlParams = null; } public final void setDebugSqlParam(final int parameterIndex, final Object parameterValue) { if (debugSqlParams == null) { debugSqlParams = new TreeMap<>(); } debugSqlParams.put(parameterIndex, parameterValue); } public final Map<Integer, Object> getDebugSqlParams() { final Map<Integer, Object> debugSqlParams = this.debugSqlParams; return debugSqlParams == null ? ImmutableMap.of() : debugSqlParams; } public final Map<Integer, Object> getAndClearDebugSqlParams() { final Map<Integer, Object> debugSqlParams = getDebugSqlParams(); clearDebugSqlParams(); return debugSqlParams; } } // CStatementVO
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\CStatementVO.java
1
请完成以下Java代码
private void writeResponse(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER); ctx.write(response); } private void writeResponse(ChannelHandlerContext ctx, LastHttpContent trailer, StringBuilder responseData) { boolean keepAlive = HttpUtil.isKeepAlive(request); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, ((HttpObject) trailer).decoderResult() .isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(responseData.toString(), CharsetUtil.UTF_8)); httpResponse.headers() .set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { httpResponse.headers() .setInt(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content() .readableBytes()); httpResponse.headers()
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(httpResponse); if (!keepAlive) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\http\server\CustomHttpServerHandler.java
1
请完成以下Java代码
public void destroy() { SpringBeanHolder.clearHolder(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringBeanHolder.applicationContext != null) { log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringBeanHolder.applicationContext); } SpringBeanHolder.applicationContext = applicationContext; if (addCallback) { for (SpringBeanHolder.CallBack callBack : SpringBeanHolder.CALL_BACKS) { callBack.executor(); } CALL_BACKS.clear(); } SpringBeanHolder.addCallback = false; } /** * 获取 @Service 的所有 bean 名称 * @return / */ public static List<String> getAllServiceBeanName() { return new ArrayList<>(Arrays.asList(applicationContext
.getBeanNamesForAnnotation(Service.class))); } interface CallBack { /** * 回调执行方法 */ void executor(); /** * 本回调任务名称 * @return / */ default String getCallBackName() { return Thread.currentThread().getId() + ":" + this.getClass().getName(); } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SpringBeanHolder.java
1
请完成以下Java代码
public RoaringBitmap roaringBitmapUnion() { return RoaringBitmap.or(rb1, rb2); } @Benchmark public BitSet bitSetUnion() { BitSet result = (BitSet) bs1.clone(); result.or(bs2); return result; } @Benchmark public RoaringBitmap roaringBitmapIntersection() { return RoaringBitmap.and(rb1, rb2); } @Benchmark public BitSet bitSetIntersection() { BitSet result = (BitSet) bs1.clone(); result.and(bs2); return result; } @Benchmark public RoaringBitmap roaringBitmapDifference() { return RoaringBitmap.andNot(rb1, rb2); } @Benchmark public BitSet bitSetDifference() { BitSet result = (BitSet) bs1.clone(); result.andNot(bs2);
return result; } @Benchmark public RoaringBitmap roaringBitmapXOR() { return RoaringBitmap.xor(rb1, rb2); } @Benchmark public BitSet bitSetXOR() { BitSet result = (BitSet) bs1.clone(); result.xor(bs2); return result; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\roaringbitmap\BitSetsBenchmark.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new FlowableIllegalArgumentException("Process definition id is null"); } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ProcessDefinitionEntity processDefinition = processEngineConfiguration.getProcessDefinitionEntityManager().findById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("No process definition found for id = '" + processDefinitionId + "'", ProcessDefinition.class); } if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.setProcessDefinitionCategory(processDefinitionId, category); return null; } // Update category processDefinition.setCategory(category); // Remove process definition from cache, it will be refetch later DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = processEngineConfiguration.getProcessDefinitionCache(); if (processDefinitionCache != null) { processDefinitionCache.remove(processDefinitionId); }
FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, processDefinition), processEngineConfiguration.getEngineCfgKey()); } return null; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SetProcessDefinitionCategoryCmd.java
1
请完成以下Java代码
public String adminOnly(HttpServletRequest req, Model model) { addUserAttributes(model); model.addAttribute("adminContent", "only admin can view this"); return "comparison/home"; } private void addUserAttributes(Model model) { Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); if (auth != null && !auth.getClass() .equals(AnonymousAuthenticationToken.class)) { User user = (User) auth.getPrincipal(); model.addAttribute("username", user.getUsername()); Collection<GrantedAuthority> authorities = user.getAuthorities();
for (GrantedAuthority authority : authorities) { if (authority.getAuthority() .contains("USER")) { model.addAttribute("role", "USER"); model.addAttribute("permission", "READ"); } else if (authority.getAuthority() .contains("ADMIN")) { model.addAttribute("role", "ADMIN"); model.addAttribute("permission", "READ WRITE"); } } } } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\comparison\springsecurity\web\SpringController.java
1
请完成以下Java代码
public class SplitStringEveryNthChar { public static List<String> usingSplitMethod(String text, int n) { String[] results = text.split("(?<=\\G.{" + n + "})"); return Arrays.asList(results); } public static List<String> usingSubstringMethod(String text, int n) { List<String> results = new ArrayList<>(); int length = text.length(); for (int i = 0; i < length; i += n) { results.add(text.substring(i, Math.min(length, i + n))); } return results; }
public static List<String> usingPattern(String text, int n) { return Pattern.compile(".{1," + n + "}") .matcher(text) .results() .map(MatchResult::group) .collect(Collectors.toList()); } public static List<String> usingGuava(String text, int n) { Iterable<String> parts = Splitter.fixedLength(n) .split(text); return ImmutableList.copyOf(parts); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-4\src\main\java\com\baeldung\split\SplitStringEveryNthChar.java
1
请完成以下Java代码
public static String getBrowser(HttpServletRequest request) { UserAgent ua = UserAgentUtil.parse(request.getHeader("User-Agent")); String browser = ua.getBrowser().toString() + " " + ua.getVersion(); return browser.replace(".0.0.0",""); } /** * 获得当天是周几 */ public static String getWeekDay() { String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int w = cal.get(Calendar.DAY_OF_WEEK) - 1; if (w < 0) { w = 0; } return weekDays[w]; } /** * 获取当前机器的IP * * @return / */ public static String getLocalIp() { try { InetAddress candidateAddress = null; // 遍历所有的网络接口 for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) { NetworkInterface anInterface = interfaces.nextElement(); // 在所有的接口下再遍历IP for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) { InetAddress inetAddr = inetAddresses.nextElement();
// 排除loopback类型地址 if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr.getHostAddress(); } else if (candidateAddress == null) { // site-local类型的地址未被发现,先记录候选地址 candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress.getHostAddress(); } // 如果没有发现 non-loopback地址.只能用最次选的方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { return ""; } return jdkSuppliedAddress.getHostAddress(); } catch (Exception e) { return ""; } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\StringUtils.java
1
请完成以下Java代码
public class PgSQLDatabaseDriver extends GenericSQLDatabaseDriver { public static final String DBTYPE = "postgresql"; private static final transient Logger logger = LoggerFactory.getLogger(PgSQLDatabaseDriver.class); private final Map<Object, String> configKey2password = new HashMap<Object, String>(); public PgSQLDatabaseDriver() { super(DBTYPE, "org.postgresql.Driver"); } @Override protected String getPasswordToUse(final String hostname, final String port, final String dbName, final String user, final String password) throws SQLException { String passwordToUse = password; final Object configKey = mkKey(hostname, port, dbName, user); // // Password not available: check cached configuration if (IDatabase.PASSWORD_NA == passwordToUse) { if (configKey2password.containsKey(configKey)) { passwordToUse = configKey2password.get(configKey); if (passwordToUse == IDatabase.PASSWORD_NA) { throw new SQLException("No password was found for request: " + "hostname=" + hostname + ", port=" + port + ", dbName=" + dbName + ", user=" + user); } return passwordToUse; } } // // Password not available: check "pgpass" file if available if (IDatabase.PASSWORD_NA == passwordToUse) { final PgPassFile pgPassFile = PgPassFile.instance; passwordToUse = pgPassFile.getPassword(hostname, port, dbName, user);
logger.info("Using config from " + pgPassFile.getConfigFile()); } configKey2password.put(configKey, passwordToUse); if (IDatabase.PASSWORD_NA == passwordToUse) { throw new SQLException("No password was found for request: " + "hostname=" + hostname + ", port=" + port + ", dbName=" + dbName + ", user=" + user); } return passwordToUse; } private Object mkKey(final String hostname, final String port, final String dbName, final String user) { return Arrays.asList(hostname, port, dbName, user); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgSQLDatabaseDriver.java
1
请完成以下Java代码
public void addDiEdge(DmnDiEdge diEdge) { diEdges.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>()); diEdges.get(getCurrentDiDiagram().getId()).add(diEdge); setCurrentDiEdge(diEdge); } public DmnDiDiagram getCurrentDiDiagram() { return currentDiDiagram; } public void setCurrentDiDiagram(DmnDiDiagram currentDiDiagram) { this.currentDiDiagram = currentDiDiagram; } public DmnDiShape getCurrentDiShape() { return currentDiShape; } public void setCurrentDiShape(DmnDiShape currentDiShape) { this.currentDiShape = currentDiShape; } public DiEdge getCurrentDiEdge() { return currentDiEdge; }
public void setCurrentDiEdge(DiEdge currentDiEdge) { this.currentDiEdge = currentDiEdge; } public List<DmnDiDiagram> getDiDiagrams() { return diDiagrams; } public List<DmnDiShape> getDiShapes(String diagramId) { return diShapes.get(diagramId); } public List<DmnDiEdge> getDiEdges(String diagramId) { return diEdges.get(diagramId); } }
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\ConversionHelper.java
1
请完成以下Java代码
public String docValidate(PO po, int timing) { return null; } @Override public int getAD_Client_ID() { return ad_Client_ID; } @Override public final void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { ad_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_M_ProductPrice.Table_Name, this); } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } @Override public String modelChange(final PO po, final int type) throws Exception { if (type != ModelValidator.TYPE_AFTER_CHANGE && type != ModelValidator.TYPE_AFTER_NEW && type != ModelValidator.TYPE_BEFORE_DELETE) { return null; } if (!po.is_ManualUserAction()) { return null; } final I_M_ProductPrice productPrice = create(po, I_M_ProductPrice.class); final String useScalePrice = productPrice.getUseScalePrice(); if (Objects.equals(useScalePrice, X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice)) { return null; } if (type == ModelValidator.TYPE_BEFORE_DELETE) { productPriceDelete(productPrice); } else { final IProductPA productPA = Services.get(IProductPA.class); if (!Objects.equals(useScalePrice, X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice)) { final String trxName = getTrxName(productPrice); final I_M_ProductScalePrice productScalePrice = productPA.retrieveOrCreateScalePrices( productPrice.getM_ProductPrice_ID(), BigDecimal.ONE, // Qty true, // createNew=true => if the scalePrice doesn't exist yet, create a new one trxName); // copy the price from the productPrice productScalePrice.setM_ProductPrice_ID(productPrice.getM_ProductPrice_ID()); productScalePrice.setPriceLimit(productPrice.getPriceLimit()); productScalePrice.setPriceList(productPrice.getPriceList());
productScalePrice.setPriceStd(productPrice.getPriceStd()); save(productScalePrice); } } return null; } private void productPriceDelete(final I_M_ProductPrice productPrice) { if (productPrice.getM_ProductPrice_ID() <= 0) { return; } final String trxName = getTrxName(productPrice); for (final I_M_ProductScalePrice psp : productPA.retrieveScalePrices(productPrice.getM_ProductPrice_ID(), trxName)) { if (psp.getM_ProductPrice_ID() != productPrice.getM_ProductPrice_ID()) { // the psp comes from cache and is stale // NOTE: i think this problem does not apply anymore, so we can safely delete this check continue; } delete(psp); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\modelvalidator\MProductPriceValidator.java
1
请完成以下Java代码
public class RandomizedMap<K, V> extends HashMap<K, V> { private final Map<Integer, K> numberToKey = new HashMap<>(); private final Map<K, Integer> keyToNumber = new HashMap<>(); @Override public V put(K key, V value) { V oldValue = super.put(key, value); if (oldValue == null) { int number = this.size() - 1; numberToKey.put(number, key); keyToNumber.put(key, number); } return oldValue; } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public V remove(Object key) { V removedValue = super.remove(key); if (removedValue != null) { removeFromTrackingMaps(key); } return removedValue; } @Override public boolean remove(Object key, Object value) { boolean removed = super.remove(key, value); if (removed) { removeFromTrackingMaps(key); } return removed; } @Override public void clear() { super.clear(); numberToKey.clear(); keyToNumber.clear(); } public V getRandomValue() {
if (this.isEmpty()) { return null; } int randomNumber = ThreadLocalRandom.current().nextInt(this.size()); K randomKey = numberToKey.get(randomNumber); return this.get(randomKey); } private void removeFromTrackingMaps(Object key) { @SuppressWarnings("unchecked") K keyToRemove = (K) key; Integer numberToRemove = keyToNumber.get(keyToRemove); if (numberToRemove == null) { return; } int mapSize = this.size(); int lastIndex = mapSize; if (numberToRemove == lastIndex) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); } else { K lastKey = numberToKey.get(lastIndex); if (lastKey == null) { numberToKey.remove(numberToRemove); keyToNumber.remove(keyToRemove); return; } numberToKey.put(numberToRemove, lastKey); keyToNumber.put(lastKey, numberToRemove); numberToKey.remove(lastIndex); keyToNumber.remove(keyToRemove); } } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\RandomizedMap.java
1
请完成以下Java代码
protected ServiceName getProcessEngineServiceName(ProcessArchiveXml processArchive) { ServiceName serviceName = null; if(processArchive.getProcessEngineName() == null || processArchive.getProcessEngineName().isEmpty()) { serviceName = ServiceNames.forDefaultProcessEngine(); } else { serviceName = ServiceNames.forManagedProcessEngine(processArchive.getProcessEngineName()); } return serviceName; } protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) { final Module module = deploymentUnit.getAttachment(MODULE); Map<String, byte[]> resources = new HashMap<>(); // first, add all resources listed in the processes.xml List<String> process = processArchive.getProcessResourceNames(); ModuleClassLoader classLoader = module.getClassLoader(); for (String resource : process) { InputStream inputStream = null; try { inputStream = classLoader.getResourceAsStream(resource); resources.put(resource, IoUtil.readInputStream(inputStream, resource)); } finally { IoUtil.closeSilently(inputStream); } }
// scan for process definitions if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) { //always use VFS scanner on JBoss final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner(); String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH); String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR); URL processesXmlUrl = vfsFileAsUrl(processesXmlFile); resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes)); } return resources; } protected URL vfsFileAsUrl(VirtualFile processesXmlFile) { try { return processesXmlFile.toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java
1
请完成以下Java代码
public org.compiere.model.I_C_ConversionType getC_ConversionType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class); } @Override public void setC_ConversionType(org.compiere.model.I_C_ConversionType C_ConversionType) { set_ValueFromPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class, C_ConversionType); } /** Set Kursart. @param C_ConversionType_ID Kursart */ @Override public void setC_ConversionType_ID (int C_ConversionType_ID) { if (C_ConversionType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, Integer.valueOf(C_ConversionType_ID)); } /** Get Kursart. @return Kursart */ @Override public int getC_ConversionType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType_Default.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable TemplateAvailabilityProvider getProvider(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { Assert.notNull(view, "'view' must not be null"); Assert.notNull(environment, "'environment' must not be null"); Assert.notNull(classLoader, "'classLoader' must not be null"); Assert.notNull(resourceLoader, "'resourceLoader' must not be null"); Boolean useCache = environment.getProperty("spring.template.provider.cache", Boolean.class, true); if (!useCache) { return findProvider(view, environment, classLoader, resourceLoader); } TemplateAvailabilityProvider provider = this.resolved.get(view); if (provider == null) { synchronized (this.cache) { provider = findProvider(view, environment, classLoader, resourceLoader); provider = (provider != null) ? provider : NONE; this.resolved.put(view, provider); this.cache.put(view, provider); } } return (provider != NONE) ? provider : null; } private @Nullable TemplateAvailabilityProvider findProvider(String view, Environment environment,
ClassLoader classLoader, ResourceLoader resourceLoader) { for (TemplateAvailabilityProvider candidate : this.providers) { if (candidate.isTemplateAvailable(view, environment, classLoader, resourceLoader)) { return candidate; } } return null; } private static final class NoTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { return false; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\TemplateAvailabilityProviders.java
2
请完成以下Java代码
private static void checkMessageElements(String schemaName, List<MessageElement> messageElementsList, String exceptionPrefix) { if (!messageElementsList.isEmpty()) { messageElementsList.forEach(messageElement -> { checkProtoFileCommonSettings(schemaName, messageElement.getGroups().isEmpty(), " Message definition groups don't support!", exceptionPrefix); checkProtoFileCommonSettings(schemaName, messageElement.getOptions().isEmpty(), " Message definition options don't support!", exceptionPrefix); checkProtoFileCommonSettings(schemaName, messageElement.getExtensions().isEmpty(), " Message definition extensions don't support!", exceptionPrefix); checkProtoFileCommonSettings(schemaName, messageElement.getReserveds().isEmpty(), " Message definition reserved elements don't support!", exceptionPrefix); checkFieldElements(schemaName, messageElement.getFields(), exceptionPrefix); List<OneOfElement> oneOfs = messageElement.getOneOfs(); if (!oneOfs.isEmpty()) { oneOfs.forEach(oneOfElement -> { checkProtoFileCommonSettings(schemaName, oneOfElement.getGroups().isEmpty(), " OneOf definition groups don't support!", exceptionPrefix); checkFieldElements(schemaName, oneOfElement.getFields(), exceptionPrefix); }); } List<TypeElement> nestedTypes = messageElement.getNestedTypes();
if (!nestedTypes.isEmpty()) { List<EnumElement> nestedEnumTypes = getEnumElements(nestedTypes); if (!nestedEnumTypes.isEmpty()) { checkEnumElements(schemaName, nestedEnumTypes, exceptionPrefix); } List<MessageElement> nestedMessageTypes = getMessageTypes(nestedTypes); checkMessageElements(schemaName, nestedMessageTypes, exceptionPrefix); } }); } } public static String invalidSchemaProvidedMessage(String schemaName, String exceptionPrefix) { return exceptionPrefix + " invalid " + schemaName + " provided!"; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\DynamicProtoUtils.java
1
请完成以下Java代码
public void setViewsRepository(@NonNull final IViewsRepository viewsRepository) { // nothing } @Override public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId) { final ViewLayout.Builder layoutBuilder = ViewLayout.builder() .setWindowId(WINDOW_ID) .setCaption(msgBL.translatable("InvoicesToAllocate")) .setAllowOpeningRowDetails(false) .addElementsFromViewRowClass(InvoiceRow.class, viewDataType); if (!isEnablePreparedForAllocationFlag()) { layoutBuilder.removeElementByFieldName(InvoiceRow.FIELD_IsPreparedForAllocation); } return layoutBuilder.build(); } @Override public InvoicesView createView(final @NonNull CreateViewRequest request) { throw new UnsupportedOperationException(); } @Override public WindowId getWindowId() { return WINDOW_ID; } @Override public void put(final IView view) { throw new UnsupportedOperationException(); } @Nullable @Override public InvoicesView getByIdOrNull(final ViewId invoicesViewId)
{ final ViewId paymentsViewId = toPaymentsViewId(invoicesViewId); final PaymentsView paymentsView = paymentsViewFactory.getByIdOrNull(paymentsViewId); return paymentsView != null ? paymentsView.getInvoicesView() : null; } private static ViewId toPaymentsViewId(final ViewId invoicesViewId) { return invoicesViewId.withWindowId(PaymentsViewFactory.WINDOW_ID); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { } @Override public Stream<IView> streamAllViews() { return paymentsViewFactory.streamAllViews() .map(PaymentsView::cast) .map(PaymentsView::getInvoicesView); } @Override public void invalidateView(final ViewId invoicesViewId) { final InvoicesView invoicesView = getByIdOrNull(invoicesViewId); if (invoicesView != null) { invoicesView.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesViewFactory.java
1
请完成以下Java代码
public void exportToXlsx(String fileName, String sheetName) { JRXlsxExporter exporter = new JRXlsxExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName)); SimpleXlsxReportConfiguration reportConfig = new SimpleXlsxReportConfiguration(); reportConfig.setSheetNames(new String[] { sheetName }); exporter.setConfiguration(reportConfig); try { exporter.exportReport(); } catch (JRException ex) { Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex); } } public void exportToCsv(String fileName) { JRCsvExporter exporter = new JRCsvExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fileName)); try { exporter.exportReport(); } catch (JRException ex) { Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex); } } public void exportToHtml(String fileName) { HtmlExporter exporter = new HtmlExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleHtmlExporterOutput(fileName)); try { exporter.exportReport(); } catch (JRException ex) { Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex); } } }
repos\tutorials-master\libraries-reporting\src\main\java\com\baeldung\jasperreports\SimpleReportExporter.java
1
请完成以下Java代码
public ResponseEntity<Object> getDeptSuperior(@RequestBody List<Long> ids, @RequestParam(defaultValue = "false") Boolean exclude) { Set<DeptDto> deptSet = new LinkedHashSet<>(); for (Long id : ids) { DeptDto deptDto = deptService.findById(id); List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>()); if(exclude){ for (DeptDto dept : depts) { if(dept.getId().equals(deptDto.getPid())) { dept.setSubCount(dept.getSubCount() - 1); } } // 编辑部门时不显示自己以及自己下级的数据,避免出现PID数据环形问题 depts = depts.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toList()); } deptSet.addAll(depts); } return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptSet)),HttpStatus.OK); } @Log("新增部门") @ApiOperation("新增部门") @PostMapping @PreAuthorize("@el.check('dept:add')") public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } deptService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改部门") @ApiOperation("修改部门") @PutMapping
@PreAuthorize("@el.check('dept:edit')") public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){ deptService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除部门") @ApiOperation("删除部门") @DeleteMapping @PreAuthorize("@el.check('dept:del')") public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){ Set<DeptDto> deptDtos = new HashSet<>(); for (Long id : ids) { List<Dept> deptList = deptService.findByPid(id); deptDtos.add(deptService.findById(id)); if(CollectionUtil.isNotEmpty(deptList)){ deptDtos = deptService.getDeleteDepts(deptList, deptDtos); } } // 验证是否被角色或用户关联 deptService.verification(deptDtos); deptService.delete(deptDtos); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DeptController.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this).addValue(luPI).toString(); } @Override public I_M_HU_PI getM_LU_HU_PI() { return luPI; } @Override public I_M_HU_PI getM_TU_HU_PI() { return null; } @Override public boolean isInfiniteQtyTUsPerLU() { return true; } @Override public BigDecimal getQtyTUsPerLU() { return null; }
@Override public boolean isInfiniteQtyCUsPerTU() { return true; } @Override public BigDecimal getQtyCUsPerTU() { return null; } @Override public I_C_UOM getQtyCUsPerTU_UOM() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\LUPIPackingInfo.java
1
请完成以下Java代码
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // the cached ServerHttpRequest is used when the ServerWebExchange can not be // mutated, for example, during a predicate where the body is read, but still // needs to be cached. ServerHttpRequest cachedRequest = exchange.getAttribute(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR); if (cachedRequest != null) { exchange.getAttributes().remove(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR); return chain.filter(exchange.mutate().request(cachedRequest).build()); } // DataBuffer body = exchange.getAttribute(CACHED_REQUEST_BODY_ATTR); Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); if (body != null || route == null || !this.routesToCache.containsKey(route.getId())) { return chain.filter(exchange); }
return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> { // don't mutate and build if same request object if (serverHttpRequest == exchange.getRequest()) { return chain.filter(exchange); } return chain.filter(exchange.mutate().request(serverHttpRequest).build()); }); } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1000; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\AdaptCachedBodyGlobalFilter.java
1
请完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return emailId; }
public void setEmail(String email) { this.emailId = email; } public Employee(){ } @Override public String toString() { return "Employee{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + emailId + '\'' + '}'; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringPostgreslq\src\main\java\spring\database\model\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public class DateAndSeqNo { Instant date; /** * Can be less or equal to zero which both means "not specified". */ int seqNo; /** * Can be null if this instance is not used for a range start or end. */ public Operator operator; public static DateAndSeqNo atTimeNoSeqNo(@NonNull final Instant date) { return builder() .date(date) .build(); } public static DateAndSeqNo ofCandidate(@NonNull final Candidate candidate) { return builder() .date(candidate.getDate()) .seqNo(candidate.getSeqNo()) .build(); } public static DateAndSeqNo ofAddToResultGroupRequest(@NonNull final AddToResultGroupRequest addToResultGroupRequest) { return builder() .date(addToResultGroupRequest.getDate()) .seqNo(addToResultGroupRequest.getSeqNo()) .build(); } public enum Operator { INCLUSIVE, EXCLUSIVE } @Builder(toBuilder = true) private DateAndSeqNo( @NonNull final Instant date, final int seqNo, @Nullable final Operator operator) { this.date = date; this.seqNo = seqNo; this.operator = operator; } /** * @return {@code true} if this instances {@code date} is after the {@code other}'s {@code date} * or if this instance's {@code seqNo} is greater than the {@code other}'s {@code seqNo}. */ public boolean isAfter(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isAfter(other.getDate())) { return true; } if (date.isBefore(other.getDate())) { return false; } return seqNo > other.getSeqNo(); } /** * Analog to {@link #isAfter(DateAndSeqNo)}.
*/ public boolean isBefore(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isBefore(other.getDate())) { return true; } if (date.isAfter(other.getDate())) { return false; } return seqNo < other.getSeqNo(); } public DateAndSeqNo min(@Nullable final DateAndSeqNo other) { if (other == null) { return this; } else { return this.isBefore(other) ? this : other; } } public DateAndSeqNo max(@Nullable final DateAndSeqNo other) { if (other == null) { return this; } return this.isAfter(other) ? this : other; } public DateAndSeqNo withOperator(@Nullable final Operator operator) { return this .toBuilder() .operator(operator) .build(); } public static boolean equals(@Nullable final DateAndSeqNo value1, @Nullable final DateAndSeqNo value2) {return Objects.equals(value1, value2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\DateAndSeqNo.java
2
请完成以下Java代码
public class AD_PrinterHW_Calibration { /** * Sets the CalX and CalY columns to the value in pixels of the respective measurements * * @param printerCalibration */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }) public void measurementChange(final I_AD_PrinterHW_Calibration printerCalibration) { if (!printerCalibration.isManualCalibration()) { // negative -> up; positive -> down final BigDecimal calXmm = Printing_Constants.AD_PrinterHW_Calibration_JASPER_REF_X_MM.subtract(printerCalibration.getMeasurementX());
// negative -> up; positive -> down final BigDecimal calYmm = Printing_Constants.AD_PrinterHW_Calibration_JASPER_REF_Y_MM.subtract(printerCalibration.getMeasurementY()); printerCalibration.setCalX(mmToPixels(calXmm)); printerCalibration.setCalY(mmToPixels(calYmm)); } } private int mmToPixels(final BigDecimal mm) { final BigDecimal result = Printing_Constants.AD_PrinterHW_Calibration_JASPER_PIXEL_PER_MM.multiply(mm).setScale(0, RoundingMode.HALF_UP); return result.toBigInteger().intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_PrinterHW_Calibration.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getCleanupCron() { return this.cleanupCron; } public void setCleanupCron(@Nullable String cleanupCron) { this.cleanupCron = cleanupCron; } public ConfigureAction getConfigureAction() { return this.configureAction; } public void setConfigureAction(ConfigureAction configureAction) { this.configureAction = configureAction; } public RepositoryType getRepositoryType() { return this.repositoryType; } public void setRepositoryType(RepositoryType repositoryType) { this.repositoryType = repositoryType; } /** * Strategies for configuring and validating Redis. */ public enum ConfigureAction { /** * Ensure that Redis Keyspace events for Generic commands and Expired events are * enabled. */ NOTIFY_KEYSPACE_EVENTS, /**
* No not attempt to apply any custom Redis configuration. */ NONE } /** * Type of Redis session repository to auto-configure. */ public enum RepositoryType { /** * Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository. */ DEFAULT, /** * Auto-configure a RedisIndexedSessionRepository or * ReactiveRedisIndexedSessionRepository. */ INDEXED } }
repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java
2