conflict_resolution
stringlengths
27
16k
<<<<<<< private final RaftLog log; private final Fiber scheduler; ======= private final ScheduledExecutorService scheduler; >>>>>>> private final Fiber scheduler; <<<<<<< private void stepDown(RaftStateContext ctx) { heartbeatTask.dispose(); ======= @Override public void destroy(RaftStateContext ctx) { heartbeatTask.cancel(false); >>>>>>> @Override public void destroy(RaftStateContext ctx) { heartbeatTask.dispose(); <<<<<<< ctx.setState(this, FOLLOWER); } @Nonnull @Override public RequestVoteResponse requestVote(@Nonnull RaftStateContext ctx, @Nonnull RequestVote request) { LOGGER.debug("RequestVote received for term {}", request.getTerm()); boolean voteGranted = false; if (request.getTerm() > log.currentTerm()) { log.currentTerm(request.getTerm()); stepDown(ctx); Replica candidate = log.getReplica(request.getCandidateId()); voteGranted = shouldVoteFor(log, request); if (voteGranted) { log.lastVotedFor(Optional.of(candidate)); } } return RequestVoteResponse.newBuilder() .setTerm(log.currentTerm()) .setVoteGranted(voteGranted) .build(); } @Nonnull @Override public AppendEntriesResponse appendEntries(@Nonnull RaftStateContext ctx, @Nonnull AppendEntries request) { boolean success = false; if (request.getTerm() > log.currentTerm()) { log.currentTerm(request.getTerm()); stepDown(ctx); success = log.append(request); } return AppendEntriesResponse.newBuilder() .setTerm(log.currentTerm()) .setSuccess(success) .build(); ======= >>>>>>>
<<<<<<< public String pkToJson(KeyFormat keyFormat) throws IOException { if ( keyFormat == KeyFormat.HASH ) return pkToJsonHash(); else return pkToJsonArray(); } private String pkToJsonHash() throws IOException { ======= public RowMap(String type, String database, String table, Long timestamp, List<String> pkColumns, BinlogPosition nextPosition, List<Pattern> excludeColumns) { this(type, database, table, timestamp, pkColumns, nextPosition); this.excludeColumns = excludeColumns; } public String pkToJson() throws IOException { >>>>>>> public RowMap(String type, String database, String table, Long timestamp, List<String> pkColumns, BinlogPosition nextPosition, List<Pattern> excludeColumns) { this(type, database, table, timestamp, pkColumns, nextPosition); this.excludeColumns = excludeColumns; } public String pkToJson(KeyFormat keyFormat) throws IOException { if ( keyFormat == KeyFormat.HASH ) return pkToJsonHash(); else return pkToJsonArray(); } private String pkToJsonHash() throws IOException {
<<<<<<< assertEquals(config.maxwellMysql.getConnectionURI(), "jdbc:mysql://localhost:3306?useCursorFetch=true&zeroDateTimeBehavior=convertToNull&netTimeoutForStreamingResults=123&profileSQL=true"); assertEquals(config.replicationMysql.getConnectionURI(), "jdbc:mysql://localhost:3306?useCursorFetch=true&zeroDateTimeBehavior=convertToNull&netTimeoutForStreamingResults=123&profileSQL=true"); ======= assertEquals(config.maxwellMysql.getConnectionURI(), "jdbc:mysql://no-soup-spoons:3306?useCursorFetch=true&zeroDateTimeBehavior=convertToNull&netTimeoutForStreamingResults=123&profileSQL=true"); >>>>>>> assertEquals(config.maxwellMysql.getConnectionURI(), "jdbc:mysql://no-soup-spoons:3306?useCursorFetch=true&zeroDateTimeBehavior=convertToNull&netTimeoutForStreamingResults=123&profileSQL=true"); assertEquals(config.replicationMysql.getConnectionURI(), "jdbc:mysql://no-soup-spoons:3306?useCursorFetch=true&zeroDateTimeBehavior=convertToNull&netTimeoutForStreamingResults=123&profileSQL=true");
<<<<<<< parser.accepts( "output_ddl", "produce DDL records to ddl_kafka_topic [true|false]. default: false" ).withOptionalArg(); parser.accepts( "ddl_kafka_topic", "optionally provide a topic name to push DDL records to. default: kafka_topic").withOptionalArg(); ======= parser.accepts( "output_server_id", "produced records include server_id; [true|false]. default: false" ).withOptionalArg(); parser.accepts( "output_thread_id", "produced records include thread_id; [true|false]. default: false" ).withOptionalArg(); >>>>>>> parser.accepts( "output_ddl", "produce DDL records to ddl_kafka_topic [true|false]. default: false" ).withOptionalArg(); parser.accepts( "ddl_kafka_topic", "optionally provide a topic name to push DDL records to. default: kafka_topic").withOptionalArg(); parser.accepts( "output_server_id", "produced records include server_id; [true|false]. default: false" ).withOptionalArg(); parser.accepts( "output_thread_id", "produced records include thread_id; [true|false]. default: false" ).withOptionalArg(); <<<<<<< this.kafkaTopic = fetchOption("kafka_topic", options, properties, "maxwell"); this.kafkaKeyFormat = fetchOption("kafka_key_format", options, properties, "hash"); this.kafkaPartitionKey = fetchOption("kafka_partition_by", options, properties, "database"); this.kafkaPartitionHash = fetchOption("kafka_partition_hash", options, properties, "default"); this.outputDDL = fetchBooleanOption("output_ddl", options, properties, false); this.ddlKafkaTopic = fetchOption("ddl_kafka_topic", options, properties, this.kafkaTopic); ======= this.kafkaTopic = fetchOption("kafka_topic", options, properties, "maxwell"); this.kafkaKeyFormat = fetchOption("kafka_key_format", options, properties, "hash"); this.kafkaPartitionKey = fetchOption("kafka_partition_by", options, properties, "database"); this.kafkaPartitionColumns = fetchOption("kafka_partition_columns", options, properties, null); this.kafkaPartitionFallback = fetchOption("kafka_partition_by_fallback", options, properties, null); this.kafkaPartitionHash = fetchOption("kafka_partition_hash", options, properties, "default"); >>>>>>> this.kafkaTopic = fetchOption("kafka_topic", options, properties, "maxwell"); this.kafkaKeyFormat = fetchOption("kafka_key_format", options, properties, "hash"); this.kafkaPartitionKey = fetchOption("kafka_partition_by", options, properties, "database"); this.kafkaPartitionColumns = fetchOption("kafka_partition_columns", options, properties, null); this.kafkaPartitionFallback = fetchOption("kafka_partition_by_fallback", options, properties, null); this.kafkaPartitionHash = fetchOption("kafka_partition_hash", options, properties, "default"); this.outputDDL = fetchBooleanOption("output_ddl", options, properties, false); this.ddlKafkaTopic = fetchOption("ddl_kafka_topic", options, properties, this.kafkaTopic);
<<<<<<< if ( options.has("schema_database")) { this.databaseName = (String) options.valueOf("schema_database"); } if ( options.has("client_id") ) { this.clientID = (String) options.valueOf("client_id"); } if ( options.has("producer")) this.producerType = (String) options.valueOf("producer"); if ( options.has("bootstrapper")) this.bootstrapperType = (String) options.valueOf("bootstrapper"); ======= this.databaseName = fetchOption("schema_database", options, properties, "maxwell"); this.producerType = fetchOption("producer", options, properties, "stdout"); this.bootstrapperType = fetchOption("bootstrapper", options, properties, "async"); >>>>>>> this.databaseName = fetchOption("schema_database", options, properties, "maxwell"); this.producerType = fetchOption("producer", options, properties, "stdout"); this.bootstrapperType = fetchOption("bootstrapper", options, properties, "async"); this.clientID = fetchOption("client_id", options, properties, "maxwell"); <<<<<<< this.maxwellMysql.host = p.getProperty("host"); this.maxwellMysql.password = p.getProperty("password"); this.maxwellMysql.user = p.getProperty("user", "maxwell"); this.maxwellMysql.port = Integer.valueOf(p.getProperty("port", "3306")); this.maxwellMysql.parseJDBCOptions(p.getProperty("jdbc_options")); this.replicationMysql.host = p.getProperty("replication_host"); this.replicationMysql.password = p.getProperty("replication_password"); this.replicationMysql.user = p.getProperty("replication_user"); this.replicationMysql.port = Integer.valueOf(p.getProperty("replication_port", "3306")); this.replicationMysql.parseJDBCOptions(p.getProperty("jdbc_options")); this.databaseName = p.getProperty("schema_database", "maxwell"); this.producerType = p.getProperty("producer", "stdout"); this.bootstrapperType = p.getProperty("bootstrapper", "async"); this.clientID = p.getProperty("client_id"); this.outputFile = p.getProperty("output_file"); this.kafkaTopic = p.getProperty("kafka_topic"); this.kafkaPartitionHash = p.getProperty("kafka_partition_hash", "default"); this.kafkaPartitionKey = p.getProperty("kafka_partition_by", "database"); this.kafkaKeyFormat = p.getProperty("kafka_key_format", "hash"); this.includeDatabases = p.getProperty("include_dbs"); this.excludeDatabases = p.getProperty("exclude_dbs"); this.includeTables = p.getProperty("include_tables"); this.excludeTables = p.getProperty("exclude_tables"); this.excludeColumns = p.getProperty("exclude_columns"); this.blacklistDatabases = p.getProperty("blacklist_dbs"); this.blacklistTables = p.getProperty("blacklist_tables"); if ( p.containsKey("log_level") ) this.log_level = parseLogLevel(p.getProperty("log_level")); for ( Enumeration<Object> e = p.keys(); e.hasMoreElements(); ) { String k = (String) e.nextElement(); if ( k.startsWith("kafka.")) { this.kafkaProperties.setProperty(k.replace("kafka.", ""), p.getProperty(k)); } } ======= return p; >>>>>>> return p; <<<<<<< if ( this.databaseName == null) { this.databaseName = "maxwell"; } if ( this.clientID == null ) { this.clientID = "maxwell"; } ======= >>>>>>>
<<<<<<< SchemaScavenger s = new SchemaScavenger(this.connectionPool, this.config.databaseName); ======= SchemaScavenger s = new SchemaScavenger(this.maxwellConnectionPool); >>>>>>> SchemaScavenger s = new SchemaScavenger(this.maxwellConnectionPool, this.config.databaseName); <<<<<<< this.schemaPosition = new ReadOnlySchemaPosition(this.getConnectionPool(), this.getServerID(), this.config.databaseName); ======= this.schemaPosition = new ReadOnlySchemaPosition(this.getMaxwellConnectionPool(), this.getServerID()); >>>>>>> this.schemaPosition = new ReadOnlySchemaPosition(this.getMaxwellConnectionPool(), this.getServerID(), this.config.databaseName); <<<<<<< this.schemaPosition = new SchemaPosition(this.getConnectionPool(), this.getServerID(), this.config.databaseName); ======= this.schemaPosition = new SchemaPosition(this.getMaxwellConnectionPool(), this.getServerID()); >>>>>>> this.schemaPosition = new SchemaPosition(this.getMaxwellConnectionPool(), this.getServerID(), this.config.databaseName);
<<<<<<< import com.zendesk.maxwell.BinlogPosition; import com.zendesk.maxwell.DDLMap; ======= import com.zendesk.maxwell.replication.BinlogPosition; >>>>>>> import com.zendesk.maxwell.replication.BinlogPosition; import com.zendesk.maxwell.DDLMap; <<<<<<< this.partitioner = new MaxwellKafkaPartitioner(hash, partitionKey); this.outputDDL = context.getConfig().outputDDL; this.ddlPartitioner = new MaxwellKafkaPartitioner(hash, "database"); this.ddlTopic = context.getConfig().ddlKafkaTopic; ======= String partitionColumns = context.getConfig().kafkaPartitionColumns; String partitionFallback = context.getConfig().kafkaPartitionFallback; this.partitioner = new MaxwellKafkaPartitioner(hash, partitionKey, partitionColumns, partitionFallback); >>>>>>> String partitionColumns = context.getConfig().kafkaPartitionColumns; String partitionFallback = context.getConfig().kafkaPartitionFallback; this.partitioner = new MaxwellKafkaPartitioner(hash, partitionKey, partitionColumns, partitionFallback); this.outputDDL = context.getConfig().outputDDL; this.ddlPartitioner = new MaxwellKafkaPartitioner(hash, "database"); this.ddlTopic = context.getConfig().ddlKafkaTopic;
<<<<<<< public String mysqlHost; public Integer mysqlPort; public String mysqlUser; public String mysqlPassword; public String databaseName; ======= public MaxwellMysqlConfig replicationMysql; public MaxwellMysqlConfig maxwellMysql; >>>>>>> public MaxwellMysqlConfig replicationMysql; public MaxwellMysqlConfig maxwellMysql; public String databaseName; <<<<<<< if ( options.has("host")) this.mysqlHost = (String) options.valueOf("host"); if ( options.has("password")) this.mysqlPassword = (String) options.valueOf("password"); if ( options.has("user")) this.mysqlUser = (String) options.valueOf("user"); if ( options.has("port")) this.mysqlPort = Integer.valueOf((String) options.valueOf("port")); if ( options.has("database")) { this.databaseName = (String) options.valueOf("database"); } ======= this.maxwellMysql.parseOptions("", options); this.replicationMysql.parseOptions("replication_", options); >>>>>>> this.maxwellMysql.parseOptions("", options); this.replicationMysql.parseOptions("replication_", options); if ( options.has("database")) { this.databaseName = (String) options.valueOf("database"); } <<<<<<< this.mysqlHost = p.getProperty("host", "127.0.0.1"); this.mysqlPassword = p.getProperty("password"); this.mysqlUser = p.getProperty("user"); this.mysqlPort = Integer.valueOf(p.getProperty("port", "3306")); this.databaseName = p.getProperty("database"); ======= this.maxwellMysql.host = p.getProperty("host", "127.0.0.1"); this.maxwellMysql.password = p.getProperty("password"); this.maxwellMysql.user = p.getProperty("user"); this.maxwellMysql.port = Integer.valueOf(p.getProperty("port", "3306")); this.replicationMysql.host = p.getProperty("replication_host"); this.replicationMysql.password = p.getProperty("replication_password"); this.replicationMysql.user = p.getProperty("replication_user"); this.replicationMysql.port = Integer.valueOf(p.getProperty("replication_port", "3306")); >>>>>>> this.maxwellMysql.host = p.getProperty("host", "127.0.0.1"); this.maxwellMysql.password = p.getProperty("password"); this.maxwellMysql.user = p.getProperty("user"); this.maxwellMysql.port = Integer.valueOf(p.getProperty("port", "3306")); this.replicationMysql.host = p.getProperty("replication_host"); this.replicationMysql.password = p.getProperty("replication_password"); this.replicationMysql.user = p.getProperty("replication_user"); this.replicationMysql.port = Integer.valueOf(p.getProperty("replication_port", "3306")); this.databaseName = p.getProperty("database");
<<<<<<< import java.awt.Color; import java.text.NumberFormat; ======= >>>>>>> import java.awt.Color; import java.text.NumberFormat; <<<<<<< import java.util.Set; import java.util.logging.Logger; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.cdk.interfaces.IMolecularFormula; import org.openscience.cdk.silent.SilentChemObjectBuilder; import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; import com.google.common.collect.Range; import org.postgresql.translation.messages_bg; ======= import java.util.Vector; import java.util.logging.Logger; >>>>>>> import java.util.Set; import java.util.logging.Logger; import org.openscience.cdk.interfaces.IIsotope; import org.openscience.cdk.interfaces.IMolecularFormula; import org.openscience.cdk.silent.SilentChemObjectBuilder; import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator; import com.google.common.collect.Range; import org.postgresql.translation.messages_bg; <<<<<<< private double mergeWidth; private final double minAbundance = 0.01; private Range<Double> mzrange; private boolean displayResults; private int maxCharge; ======= >>>>>>> private double mergeWidth; private final double minAbundance = 0.01; private Range<Double> mzrange; private int maxCharge; <<<<<<< mzrange = parameterSet.getParameter(DPPIsotopeGrouperParameters.mzRange).getValue(); maxCharge = parameterSet.getParameter(DPPIsotopeGrouperParameters.maximumCharge).getValue(); displayResults = parameterSet.getParameter(DPPIsotopeGrouperParameters.displayResults).getValue(); format = MZmineCore.getConfiguration().getMZFormat(); ======= setDisplayResults( parameterSet.getParameter(DPPIsotopeGrouperParameters.displayResults).getValue()); setColor(parameterSet.getParameter(DPPIsotopeGrouperParameters.datasetColor).getValue()); >>>>>>> mzrange = parameterSet.getParameter(DPPIsotopeGrouperParameters.mzRange).getValue(); maxCharge = parameterSet.getParameter(DPPIsotopeGrouperParameters.maximumCharge).getValue(); setDisplayResults( parameterSet.getParameter(DPPIsotopeGrouperParameters.displayResults).getValue()); setColor(parameterSet.getParameter(DPPIsotopeGrouperParameters.datasetColor).getValue()); format = MZmineCore.getConfiguration().getMZFormat(); <<<<<<< ======= if(!checkParameterSet() || !checkValues()) { setStatus(TaskStatus.ERROR); return; } if (!FormulaUtils.checkMolecularFormula(element)) { setStatus(TaskStatus.ERROR); logger.warning("Data point/Spectra processing: Invalid element parameter in " + getTaskDescription()); } if (getDataPoints().length == 0) { logger.info("Data point/Spectra processing: 0 data points were passed to " + getTaskDescription() + " Please check the parameters."); setStatus(TaskStatus.CANCELED); return; } >>>>>>> if(!checkParameterSet() || !checkValues()) { setStatus(TaskStatus.ERROR); return; } // check formula if (elements == null || elements.equals("") || !FormulaUtils.checkMolecularFormula(elements)) { setErrorMessage("Invalid element parameter in " + getTaskDescription()); setStatus(TaskStatus.ERROR); logger.warning("Invalid element parameter in " + getTaskDescription()); return; } <<<<<<< // check formula if (elements == null || elements.equals("") || !FormulaUtils.checkMolecularFormula(elements)) { setErrorMessage("Invalid element parameter in " + this.getClass().getName()); setStatus(TaskStatus.ERROR); logger.warning("Invalid element parameter in " + this.getClass().getName()); return; } ======= setStatus(TaskStatus.PROCESSING); >>>>>>> <<<<<<< if (displayResults || getController().isLastTaskRunning()) { // getTargetPlot().addDataSet(compressIsotopeDataSets(getResults()), Color.GREEN, false); int i = 0; for (ProcessedDataPoint result : getResults()) if (result.resultTypeExists(ResultType.ISOTOPEPATTERN)) i++; if (i == 0) i = 1; List<Color> clr = generateRainbowColors(i); int j = 0; for (ProcessedDataPoint result : getResults()) if (result.resultTypeExists(ResultType.ISOTOPEPATTERN)) { getTargetPlot().addDataSet(new IsotopesDataSet( (IsotopePattern) result.getFirstResultByType(ResultType.ISOTOPEPATTERN).getValue()), clr.get(j), false); j++; } // getTargetPlot().addDataSet(new DPPResultsDataSet("Isotopes (" + getResults().length + ")", getResults()), color, false); ======= if (isDisplayResults() || getController().isLastTaskRunning()) { getTargetPlot().addDataSet( new DPPResultsDataSet("Isotopes (" + getResults().length + ")", getResults()), getColor(), false); >>>>>>> if (displayResults || getController().isLastTaskRunning()) { // getTargetPlot().addDataSet(compressIsotopeDataSets(getResults()), Color.GREEN, false); int i = 0; for (ProcessedDataPoint result : getResults()) if (result.resultTypeExists(ResultType.ISOTOPEPATTERN)) i++; if (i == 0) i = 1; List<Color> clr = generateRainbowColors(i); int j = 0; for (ProcessedDataPoint result : getResults()) if (result.resultTypeExists(ResultType.ISOTOPEPATTERN)) { getTargetPlot().addDataSet(new IsotopesDataSet( (IsotopePattern) result.getFirstResultByType(ResultType.ISOTOPEPATTERN).getValue()), clr.get(j), false); j++; } // getTargetPlot().addDataSet(new DPPResultsDataSet("Isotopes (" + getResults().length + ")", getResults()), color, false);
<<<<<<< /* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * Original author: Yann Richet - https://github.com/yannrichet/rsession */ ======= /* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * Original author: Yann Richet */ >>>>>>> <<<<<<< import net.sf.mzmine.util.R.Rsession.Logger; import net.sf.mzmine.util.R.Rsession.Logger.Level; /** * @author richet */ ======= >>>>>>>
<<<<<<< /* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * Original author: Yann Richet - https://github.com/yannrichet/rsession */ ======= /* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * Original author: Yann Richet */ >>>>>>> <<<<<<< @SuppressWarnings("serial") ======= >>>>>>>
<<<<<<< // has identity of MS/MS database match PeakIdentity pi = clickedPeakListRow.getPreferredPeakIdentity(); showMSMSMirrorMatchDBItem.setEnabled(pi != null && pi instanceof SpectralDBPeakIdentity); ======= // open id url if available PeakIdentity pi = clickedPeakListRow.getPreferredPeakIdentity(); String url = null; if (pi != null) url = pi.getPropertyValue(PeakIdentity.PROPERTY_URL); openCompoundIdUrl.setEnabled(url != null && !url.isEmpty()); >>>>>>> // has identity of MS/MS database match PeakIdentity pi = clickedPeakListRow.getPreferredPeakIdentity(); showMSMSMirrorMatchDBItem.setEnabled(pi != null && pi instanceof SpectralDBPeakIdentity); // open id url if available String url = null; if (pi != null) url = pi.getPropertyValue(PeakIdentity.PROPERTY_URL); openCompoundIdUrl.setEnabled(url != null && !url.isEmpty());
<<<<<<< RawDataImportModule.class, RawDataExportModule.class, MassDetectionModule.class, ShoulderPeaksFilterModule.class, ChromatogramBuilderModule.class, ADAPChromatogramBuilderModule.class, // Not ready for prime time: ADAP3DModule.class, GridMassModule.class, ManualPeakPickerModule.class, MsMsPeakPickerModule.class, ScanFiltersModule.class, CropFilterModule.class, BaselineCorrectionModule.class, AlignScansModule.class, ScanSmoothingModule.class, OrderDataFilesModule.class, ======= RawDataImportModule.class, RawDataExportModule.class, ExtractScansModule.class, MassDetectionModule.class, ShoulderPeaksFilterModule.class, ChromatogramBuilderModule.class, ADAPChromatogramBuilderModule.class, // Not ready for prime time: ADAP3DModule.class, GridMassModule.class, ManualPeakPickerModule.class, MsMsPeakPickerModule.class, ScanFiltersModule.class, CropFilterModule.class, BaselineCorrectionModule.class, AlignScansModule.class, ScanSmoothingModule.class, OrderDataFilesModule.class, >>>>>>> RawDataImportModule.class, RawDataExportModule.class, ExtractScansModule.class, MassDetectionModule.class, ShoulderPeaksFilterModule.class, ChromatogramBuilderModule.class, ADAPChromatogramBuilderModule.class, // Not ready for prime time: ADAP3DModule.class, GridMassModule.class, ManualPeakPickerModule.class, MsMsPeakPickerModule.class, ScanFiltersModule.class, CropFilterModule.class, BaselineCorrectionModule.class, AlignScansModule.class, ScanSmoothingModule.class, OrderDataFilesModule.class, <<<<<<< GPLipidSearchModule.class, LipidSearchModule.class, CameraSearchModule.class, NistMsSearchModule.class, FormulaPredictionPeakListModule.class, Ms2SearchModule.class, ======= GPLipidSearchModule.class, CameraSearchModule.class, NistMsSearchModule.class, FormulaPredictionPeakListModule.class, Ms2SearchModule.class, SiriusProcessingModule.class, >>>>>>> GPLipidSearchModule.class, LipidSearchModule.class, CameraSearchModule.class, NistMsSearchModule.class, FormulaPredictionPeakListModule.class, Ms2SearchModule.class, SiriusProcessingModule.class, <<<<<<< PeakListTableModule.class, IsotopePatternExportModule.class, MSMSExportModule.class, ScatterPlotVisualizerModule.class, HistogramVisualizerModule.class, InfoVisualizerModule.class, IntensityPlotModule.class, KendrickMassPlotModule.class, VanKrevelenDiagramModule.class, ======= MZDistributionHistoModule.class, PeakListTableModule.class, IsotopePatternExportModule.class, MSMSExportModule.class, ScatterPlotVisualizerModule.class, HistogramVisualizerModule.class, InfoVisualizerModule.class, IntensityPlotModule.class, KendrickMassPlotModule.class, VanKrevelenDiagramModule.class, >>>>>>> MZDistributionHistoModule.class, PeakListTableModule.class, IsotopePatternExportModule.class, MSMSExportModule.class, ScatterPlotVisualizerModule.class, HistogramVisualizerModule.class, InfoVisualizerModule.class, IntensityPlotModule.class, KendrickMassPlotModule.class, VanKrevelenDiagramModule.class,
<<<<<<< public synchronized void addResult(DPPResult<?> result) { if (result == null) return; ======= public void addResult(@Nonnull DPPResult<?> result) { >>>>>>> public synchronized void addResult(@Nonnull PPResult<?> result) { if (result == null) return; <<<<<<< public synchronized void addAllResults(Collection<DPPResult<?>> results) { if (results == null) return; ======= public void addAllResults(@Nonnull Collection<DPPResult<?>> results) { >>>>>>> public synchronized void addAllResults(@Nonnull Collection<DPPResult<?>> results) { if (results == null) return; <<<<<<< public synchronized void addAllResults(DPPResult<?>[] result) { if (result == null) return; ======= public void addAllResults(@Nonnull DPPResult<?>[] result) { >>>>>>> public synchronized void addAllResults(@Nonnull DPPResult<?>[] result) { if (result == null) return; <<<<<<< public DPPResult<?> getFirstResultByType(DPPResult.ResultType type) { ======= public @Nullable DPPResult<?> getFirstResultByType(DPPResult.ResultType type) { >>>>>>> public @Nullable DPPResult<?> getFirstResultByType(DPPResult.ResultType type) {
<<<<<<< ElasticTestUtils.configure(elasticsearchConfig, nodeInfo.port, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig)); ======= ElasticTestUtils.configure( elasticsearchConfig, nodeInfo.hostname, nodeInfo.port, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig, notesMigration)); >>>>>>> ElasticTestUtils.configure( elasticsearchConfig, nodeInfo.hostname, nodeInfo.port, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig));
<<<<<<< @RequestMapping(value="/facilities/getListInRequisitionGroup/{id}",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getFacilityListInARequisitionGroup(@PathVariable("id") Long id, HttpServletRequest request){ RequisitionGroup requisitionGroup = requisitionGroupService.loadRequisitionGroupById(id); List<RequisitionGroup> requisitionGroups= new ArrayList<RequisitionGroup>(); requisitionGroups.add(requisitionGroup); return OpenLmisResponse.response("facilities",facilityService.getCompleteListInRequisitionGroups(requisitionGroups)); } @RequestMapping(value = "/facilities/facilityType/{facilityTypeId}", method = GET, headers = ACCEPT_JSON) //@PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getFacilityListForAFacilityType(@PathVariable("facilityTypeId") Long facilityTypeId) { return OpenLmisResponse.response("facilities",facilityService.getFacilitiesListForAFacilityType(facilityTypeId)); } @RequestMapping(value = "/facility/supplyingFacilities", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getSupplyingFacilitiesCompleteList() { return OpenLmisResponse.response("facilities",facilityService.getSupplyingFacilitiesCompleteList()); } ======= >>>>>>> @RequestMapping(value="/facilities/getListInRequisitionGroup/{id}",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getFacilityListInARequisitionGroup(@PathVariable("id") Long id, HttpServletRequest request){ RequisitionGroup requisitionGroup = requisitionGroupService.loadRequisitionGroupById(id); List<RequisitionGroup> requisitionGroups= new ArrayList<RequisitionGroup>(); requisitionGroups.add(requisitionGroup); return OpenLmisResponse.response("facilities",facilityService.getCompleteListInRequisitionGroups(requisitionGroups)); } @RequestMapping(value = "/facilities/facilityType/{facilityTypeId}", method = GET, headers = ACCEPT_JSON) //@PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getFacilityListForAFacilityType(@PathVariable("facilityTypeId") Long facilityTypeId) { return OpenLmisResponse.response("facilities",facilityService.getFacilitiesListForAFacilityType(facilityTypeId)); } @RequestMapping(value = "/facility/supplyingFacilities", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getSupplyingFacilitiesCompleteList() { return OpenLmisResponse.response("facilities",facilityService.getSupplyingFacilitiesCompleteList()); }
<<<<<<< @Select("SELECT * " + " FROM (SELECT sn.*, " + " snParent.name AS supervisoryNodeParentName," + " concat(f.code,' - ',f.name) AS facilityName," + " ft.name AS facilityTypeName " + " FROM supervisory_nodes sn " + " LEFT JOIN supervisory_nodes snParent " + " ON sn.parentId = snParent.id" + " LEFT JOIN facilities f" + " ON sn.facilityId=f.ID" + " LEFT JOIN facility_types ft " + " ON f.typeid=ft.id) AS y " + " LEFT JOIN (SELECT supervisorynodeid AS id, " + " Count(DISTINCT userId) supervisorCount " + " FROM role_assignments ra " + " GROUP BY supervisorynodeid) AS x " + " ON y.id = x.id " + " ORDER BY y.supervisoryNodeParentName, y.name, y.facilityName") @Results(value={ @Result(property = "parent.name", column = "supervisoryNodeParentName"), @Result(property = "parent.id", column = "parentid"), @Result(property = "facility.id",column="facilityid"), @Result(property = "facility.name",column="facilityName"), @Result(property = "facility.facilityType.name",column = "facilityTypeName"), @Result(property = "supervisorCount", column = "supervisorCount") }) List<SupervisoryNode> getCompleteList(); @Select("SELECT * " + " FROM (SELECT sn.*, " + " snParent.name AS supervisoryNodeParentName," + " concat(f.code,' - ',f.name) AS facilityName," + " ft.name AS facilityTypeName " + " FROM supervisory_nodes sn " + " LEFT JOIN supervisory_nodes snParent " + " ON sn.parentId = snParent.id" + " LEFT JOIN facilities f" + " ON sn.facilityId=f.ID" + " LEFT JOIN facility_types ft " + " ON f.typeid=ft.id " + " WHERE sn.ID = #{id}) AS y " + " LEFT JOIN (SELECT supervisorynodeid AS id, " + " Count(DISTINCT userId) supervisorCount " + " FROM role_assignments ra " + " GROUP BY supervisorynodeid) AS x " + " ON y.id = x.id") @Results(value={ @Result(property = "parent.name", column = "supervisoryNodeParentName"), @Result(property = "parent.id", column = "parentid"), @Result(property = "facility.id",column="facilityid"), @Result(property = "facility.name",column="facilityName"), @Result(property = "facility.facilityType.name",column = "facilityTypeName"), @Result(property = "supervisorCount", column = "supervisorCount") }) SupervisoryNode getSupervisoryNodeById(@Param(value="id") Long id); @Delete("DELETE FROM supervisory_nodes WHERE ID = #{id}") void removeSupervisoryNode(@Param(value="id") Long id); @Select("select count(id) AS total_unassigned from supervisory_nodes where id not in \n" + " (select id from vw_user_supervisorynodes where userid = #{userId} and programid = #{programId} )") Long getTotalUnassignedSupervisoryNodeOfUserBy( @Param(value="userId") Long userId, @Param(value="programId") Long programId ); @Select({"WITH recursive supervisoryNodesRec AS ", " (", " SELECT *", " FROM supervisory_nodes ", " WHERE id in (SELECT DISTINCT s.id FROM ", " supervisory_nodes s ", " INNER JOIN role_assignments ra ON s.id = ra.supervisoryNodeId ", " INNER JOIN role_rights rr ON ra.roleId = rr.roleId ", " WHERE ra.userId = #{userId} ) ", " UNION ", " SELECT sn.* ", " FROM supervisory_nodes sn ", " JOIN supervisoryNodesRec ", " ON sn.parentId = supervisoryNodesRec.id ", " )", "SELECT * FROM supervisoryNodesRec"}) List<SupervisoryNode> getAllSupervisoryNodesInHierarchyByUser(@Param("userId") Long userId); ======= @Select({"SELECT * FROM supervisory_nodes SN INNER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SNP.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%' order by LOWER(SNP.name), LOWER(SN.name) NULLS LAST"}) @Results(value = { @Result(property = "parent", column = "parentId", javaType = SupervisoryNode.class, one = @One(select = "getById")), @Result(property = "facility", column = "facilityId", javaType = Facility.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityMapper.getById")) }) List<SupervisoryNode> getSupervisoryNodesByParent(@Param(value = "nameSearchCriteria") String nameSearchCriteria, RowBounds rowBounds); @Select({"SELECT * FROM supervisory_nodes SN LEFT OUTER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SN.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%' ORDER BY LOWER(SNP.name), LOWER(SN.name) NULLS LAST"}) @Results(value = { @Result(property = "parent", column = "parentId", javaType = SupervisoryNode.class, one = @One(select = "getById")), @Result(property = "facility", column = "facilityId", javaType = Facility.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityMapper.getById")) }) List<SupervisoryNode> getSupervisoryNodesBy(@Param(value = "nameSearchCriteria") String nameSearchCriteria, RowBounds rowBounds); @Select({"SELECT COUNT(*) FROM supervisory_nodes SN LEFT OUTER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SN.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%'"}) Integer getTotalSearchResultCount(String param); @Select({"SELECT COUNT(*) FROM supervisory_nodes SN INNER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SNP.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%'"}) Integer getTotalParentSearchResultCount(String param); @Select("SELECT * FROM supervisory_nodes WHERE LOWER(name) LIKE '%' || LOWER(#{param}) || '%' ORDER BY LOWER(name)") List<SupervisoryNode> getFilteredSupervisoryNodesByName(String param); @Select({"SELECT * FROM supervisory_nodes WHERE parentId IS NULL AND LOWER(name) LIKE '%' || LOWER(#{param}) || '%' ORDER BY LOWER(name)"}) List<SupervisoryNode> searchTopLevelSupervisoryNodesByName(String param); >>>>>>> @Select({"SELECT * FROM supervisory_nodes SN INNER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SNP.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%' order by LOWER(SNP.name), LOWER(SN.name) NULLS LAST"}) @Results(value = { @Result(property = "parent", column = "parentId", javaType = SupervisoryNode.class, one = @One(select = "getById")), @Result(property = "facility", column = "facilityId", javaType = Facility.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityMapper.getById")) }) List<SupervisoryNode> getSupervisoryNodesByParent(@Param(value = "nameSearchCriteria") String nameSearchCriteria, RowBounds rowBounds); @Select({"SELECT * FROM supervisory_nodes SN LEFT OUTER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SN.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%' ORDER BY LOWER(SNP.name), LOWER(SN.name) NULLS LAST"}) @Results(value = { @Result(property = "parent", column = "parentId", javaType = SupervisoryNode.class, one = @One(select = "getById")), @Result(property = "facility", column = "facilityId", javaType = Facility.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityMapper.getById")) }) List<SupervisoryNode> getSupervisoryNodesBy(@Param(value = "nameSearchCriteria") String nameSearchCriteria, RowBounds rowBounds); @Select({"SELECT COUNT(*) FROM supervisory_nodes SN LEFT OUTER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SN.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%'"}) Integer getTotalSearchResultCount(String param); @Select({"SELECT COUNT(*) FROM supervisory_nodes SN INNER JOIN supervisory_nodes SNP ON SN.parentId = SNP.id WHERE LOWER(SNP.name)" + " LIKE '%'|| LOWER(#{nameSearchCriteria}) ||'%'"}) Integer getTotalParentSearchResultCount(String param); @Select("SELECT * FROM supervisory_nodes WHERE LOWER(name) LIKE '%' || LOWER(#{param}) || '%' ORDER BY LOWER(name)") List<SupervisoryNode> getFilteredSupervisoryNodesByName(String param); @Select({"SELECT * FROM supervisory_nodes WHERE parentId IS NULL AND LOWER(name) LIKE '%' || LOWER(#{param}) || '%' ORDER BY LOWER(name)"}) List<SupervisoryNode> searchTopLevelSupervisoryNodesByName(String param); @Select("select count(id) AS total_unassigned from supervisory_nodes where id not in \n" + " (select id from vw_user_supervisorynodes where userid = #{userId} and programid = #{programId} )") Long getTotalUnassignedSupervisoryNodeOfUserBy( @Param(value="userId") Long userId, @Param(value="programId") Long programId );
<<<<<<< import org.openlmis.rnr.dto.RnrFeedDTO; import org.openlmis.rnr.service.NotificationServices; import org.springframework.beans.factory.annotation.Autowired; ======= import org.openlmis.rnr.dto.RequisitionStatusFeedDTO; >>>>>>> import org.openlmis.rnr.dto.RequisitionStatusFeedDTO; import org.openlmis.rnr.dto.RnrFeedDTO; import org.openlmis.rnr.service.NotificationServices; import org.springframework.beans.factory.annotation.Autowired; <<<<<<< new RnrFeedDTO(requisition).getSerializedContents(), FEED_CATEGORY); if(requisition != null) { notificationService = nServices; notificationService.notifyStatusChange(requisition); } ======= new RequisitionStatusFeedDTO(requisition).getSerializedContents(), FEED_CATEGORY); >>>>>>> new RequisitionStatusFeedDTO(requisition).getSerializedContents(), FEED_CATEGORY); new RnrFeedDTO(requisition).getSerializedContents(), FEED_CATEGORY); if(requisition != null) { notificationService = nServices; notificationService.notifyStatusChange(requisition); }
<<<<<<< ======= public void navigateRnr() throws IOException { testWebDriver.waitForElementToAppear(requisitionsLink); testWebDriver.keyPress(requisitionsLink); testWebDriver.waitForElementToAppear(createLink); testWebDriver.sleep(2000); testWebDriver.keyPress(createLink); testWebDriver.sleep(2000); testWebDriver.waitForElementToAppear(myFacilityRadioButton); } public boolean isHomeMenuTabDisplayed(){ return homeMenuItem.isDisplayed(); } public boolean isRequisitionsMenuTabDisplayed(){ return requisitionMenuItem.isDisplayed(); } >>>>>>> public void navigateRnr() throws IOException { testWebDriver.waitForElementToAppear(requisitionsLink); testWebDriver.keyPress(requisitionsLink); testWebDriver.waitForElementToAppear(createLink); testWebDriver.sleep(2000); testWebDriver.keyPress(createLink); testWebDriver.sleep(2000); testWebDriver.waitForElementToAppear(myFacilityRadioButton); } public boolean isHomeMenuTabDisplayed(){ return homeMenuItem.isDisplayed(); } public boolean isRequisitionsMenuTabDisplayed(){ return requisitionMenuItem.isDisplayed(); }
<<<<<<< @Select("SELECT * FROM dosage_units") List<DosageUnit> getAll(); ======= @Select("SELECT * FROM dosage_units WHERE LOWER(code) = LOWER(#{code})") DosageUnit getByCode(String code); >>>>>>> @Select("SELECT * FROM dosage_units") List<DosageUnit> getAll(); @Select("SELECT * FROM dosage_units WHERE LOWER(code) = LOWER(#{code})") DosageUnit getByCode(String code);
<<<<<<< @Select("SELECT id from products where code = #{code}") Integer getIdByCode(String code); @Select("SELECT * FROM products") List<Product> getAll(); ======= @Update({"UPDATE products SET alternateItemCode=#{alternateItemCode}, ", "manufacturer =#{manufacturer},manufacturerCode=#{manufacturerCode},manufacturerBarcode=#{manufacturerBarCode}, mohBarcode=#{mohBarCode}, ", "gtin=#{gtin},type=#{type}, ", "displayOrder=#{displayOrder}, ", "primaryName=#{primaryName},fullName=#{fullName}, genericName=#{genericName},alternateName=#{alternateName},description=#{description}, ", "strength=#{strength}, formId=#{form.id}, ", "dosageUnitId=#{dosageUnit.id}, dispensingUnit=#{dispensingUnit}, dosesPerDispensingUnit=#{dosesPerDispensingUnit}, ", "packSize=#{packSize},alternatePackSize=#{alternatePackSize}, ", "storeRefrigerated=#{storeRefrigerated},storeRoomTemperature=#{storeRoomTemperature}, ", "hazardous=#{hazardous},flammable=#{flammable},controlledSubstance=#{controlledSubstance},lightSensitive=#{lightSensitive},approvedByWHO=#{approvedByWHO}, ", "contraceptiveCYP=#{contraceptiveCYP},", "packLength=#{packLength},packWidth=#{packWidth},packHeight=#{packHeight},packWeight=#{packWeight},packsPerCarton=#{packsPerCarton},", "cartonLength=#{cartonLength},cartonWidth=#{cartonWidth},cartonHeight=#{cartonHeight},cartonsPerPallet=#{cartonsPerPallet},", "expectedShelfLife=#{expectedShelfLife},", "specialStorageInstructions=#{specialStorageInstructions},specialTransportInstructions=#{specialTransportInstructions},", "active=#{active},fullSupply=#{fullSupply},tracer=#{tracer},roundToZero=#{roundToZero},archived=#{archived},", "packRoundingThreshold=#{packRoundingThreshold}, categoryId=#{category.id},", "modifiedBy=#{modifiedBy}, modifiedDate=#{modifiedDate} WHERE id=#{id}"}) void update(Product product); >>>>>>> @Update({"UPDATE products SET alternateItemCode=#{alternateItemCode}, ", "manufacturer =#{manufacturer},manufacturerCode=#{manufacturerCode},manufacturerBarcode=#{manufacturerBarCode}, mohBarcode=#{mohBarCode}, ", "gtin=#{gtin},type=#{type}, ", "displayOrder=#{displayOrder}, ", "primaryName=#{primaryName},fullName=#{fullName}, genericName=#{genericName},alternateName=#{alternateName},description=#{description}, ", "strength=#{strength}, formId=#{form.id}, ", "dosageUnitId=#{dosageUnit.id}, dispensingUnit=#{dispensingUnit}, dosesPerDispensingUnit=#{dosesPerDispensingUnit}, ", "packSize=#{packSize},alternatePackSize=#{alternatePackSize}, ", "storeRefrigerated=#{storeRefrigerated},storeRoomTemperature=#{storeRoomTemperature}, ", "hazardous=#{hazardous},flammable=#{flammable},controlledSubstance=#{controlledSubstance},lightSensitive=#{lightSensitive},approvedByWHO=#{approvedByWHO}, ", "contraceptiveCYP=#{contraceptiveCYP},", "packLength=#{packLength},packWidth=#{packWidth},packHeight=#{packHeight},packWeight=#{packWeight},packsPerCarton=#{packsPerCarton},", "cartonLength=#{cartonLength},cartonWidth=#{cartonWidth},cartonHeight=#{cartonHeight},cartonsPerPallet=#{cartonsPerPallet},", "expectedShelfLife=#{expectedShelfLife},", "specialStorageInstructions=#{specialStorageInstructions},specialTransportInstructions=#{specialTransportInstructions},", "active=#{active},fullSupply=#{fullSupply},tracer=#{tracer},roundToZero=#{roundToZero},archived=#{archived},", "packRoundingThreshold=#{packRoundingThreshold}, categoryId=#{category.id},", "modifiedBy=#{modifiedBy}, modifiedDate=#{modifiedDate} WHERE id=#{id}"}) void update(Product product); @Select("SELECT * FROM products") List<Product> getAll();
<<<<<<< // assertThat(periods.get(0), is(processingPeriod1)); // assertThat(periods.get(1), is(processingPeriod2)); ======= assertThat(periods.get(0), is(processingPeriod1)); assertThat(periods.get(1), is(processingPeriod2)); } @Test public void shouldThrowExceptionIfLastPostSubmitRequisitionIsOfCurrentPeriod() throws Exception { DateTime currentDate = new DateTime(); ProcessingPeriod currentPeriod = createProcessingPeriod(10L, currentDate); Rnr currentRnr = createRequisition(currentPeriod.getId(), AUTHORIZED); expectedException.expect(DataException.class); expectedException.expectMessage("error.current.rnr.already.post.submit"); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(currentDate.toDate()); when(requisitionRepository.getLastRegularRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(currentRnr); when( processingScheduleService.getCurrentPeriod(FACILITY.getId(), PROGRAM.getId(), currentDate.toDate())).thenReturn( currentPeriod); requisitionService.getAllPeriodsForInitiatingRequisition(FACILITY.getId(), PROGRAM.getId()); verify(processingScheduleService, never()).getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), currentDate.toDate(), null); >>>>>>> // assertThat(periods.get(0), is(processingPeriod1)); // assertThat(periods.get(1), is(processingPeriod2)); } @Test public void shouldThrowExceptionIfLastPostSubmitRequisitionIsOfCurrentPeriod() throws Exception { DateTime currentDate = new DateTime(); ProcessingPeriod currentPeriod = createProcessingPeriod(10L, currentDate); Rnr currentRnr = createRequisition(currentPeriod.getId(), AUTHORIZED); expectedException.expect(DataException.class); expectedException.expectMessage("error.current.rnr.already.post.submit"); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(currentDate.toDate()); when(requisitionRepository.getLastRegularRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(currentRnr); when( processingScheduleService.getCurrentPeriod(FACILITY.getId(), PROGRAM.getId(), currentDate.toDate())).thenReturn( currentPeriod); requisitionService.getAllPeriodsForInitiatingRequisition(FACILITY.getId(), PROGRAM.getId()); verify(processingScheduleService, never()).getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), currentDate.toDate(), null); <<<<<<< // verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), submittedRnr.getFacility(), submittedRnr.getProgram(), submittedRnr.getPeriod(), "AUTHORIZED"); ======= verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), submittedRnr.getFacility(), submittedRnr.getProgram(), submittedRnr.getPeriod(), "AUTHORIZED"); >>>>>>> verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), submittedRnr.getFacility(), submittedRnr.getProgram(), submittedRnr.getPeriod(), "AUTHORIZED"); <<<<<<< //verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), savedRnr.getFacility(), savedRnr.getProgram(), savedRnr.getPeriod(), "SUBMITTED"); ======= verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), savedRnr.getFacility(), savedRnr.getProgram(), savedRnr.getPeriod(), "SUBMITTED"); >>>>>>> verify(statusChangeEventService).notifyUsers(emptyList, savedRnr.getId(), savedRnr.getFacility(), savedRnr.getProgram(), savedRnr.getPeriod(), "SUBMITTED");
<<<<<<< @RequestMapping(value="/productProgramCategoryTree/{programId}", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getProductCategoryProductByProgramId(@PathVariable("programId") int programId){ List<ProductCategoryProductTree> categoryProductTree = reportLookupService.getProductCategoryProductByProgramId(programId); return OpenLmisResponse.response("productCategoryTree", categoryProductTree); } @RequestMapping(value="/yearSchedulePeriod", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getScheduleYearPeriod(){ List<YearSchedulePeriodTree> yearSchedulePeriodTree = reportLookupService.getYearSchedulePeriodTree(); return OpenLmisResponse.response("yearSchedulePeriod", yearSchedulePeriodTree); } ======= @RequestMapping(value = "/OrderFillRateSummary/program/{programId}/period/{periodId}/schedule/{scheduleId}/facilityTypeId/{facilityTypeId}/zone/{zoneId}/status/{status}/orderFillRateSummary", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getOrderFillRateSummaryData(@PathVariable("programId") Long programId, @PathVariable("periodId") Long periodId, @PathVariable("scheduleId") Long scheduleId, @PathVariable("facilityTypeId") Long facilityTypeId, @PathVariable("zoneId") Long zoneId, @PathVariable("status") String status, HttpServletRequest request) { List<OrderFillRateSummaryReport> orderFillRateReportSummaryList = reportLookupService.getOrderFillRateSummary(programId, periodId, scheduleId, facilityTypeId, loggedInUserId(request), zoneId, status); return OpenLmisResponse.response("orderFillRateSummary", orderFillRateReportSummaryList); } >>>>>>> @RequestMapping(value="/productProgramCategoryTree/{programId}", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getProductCategoryProductByProgramId(@PathVariable("programId") int programId){ List<ProductCategoryProductTree> categoryProductTree = reportLookupService.getProductCategoryProductByProgramId(programId); return OpenLmisResponse.response("productCategoryTree", categoryProductTree); } @RequestMapping(value="/yearSchedulePeriod", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getScheduleYearPeriod(){ List<YearSchedulePeriodTree> yearSchedulePeriodTree = reportLookupService.getYearSchedulePeriodTree(); return OpenLmisResponse.response("yearSchedulePeriod", yearSchedulePeriodTree); } @RequestMapping(value = "/OrderFillRateSummary/program/{programId}/period/{periodId}/schedule/{scheduleId}/facilityTypeId/{facilityTypeId}/zone/{zoneId}/status/{status}/orderFillRateSummary", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getOrderFillRateSummaryData(@PathVariable("programId") Long programId, @PathVariable("periodId") Long periodId, @PathVariable("scheduleId") Long scheduleId, @PathVariable("facilityTypeId") Long facilityTypeId, @PathVariable("zoneId") Long zoneId, @PathVariable("status") String status, HttpServletRequest request) { List<OrderFillRateSummaryReport> orderFillRateReportSummaryList = reportLookupService.getOrderFillRateSummary(programId, periodId, scheduleId, facilityTypeId, loggedInUserId(request), zoneId, status); return OpenLmisResponse.response("orderFillRateSummary", orderFillRateReportSummaryList); }
<<<<<<< public void calculateMaxStockQuantity( ProgramRnrTemplate template) { RnrColumn column = template.getRnrColumnsMap().get("maxStockQuantity"); String columnOption = "DEFAULT"; if(column != null){ columnOption = column.getCalculationOption(); } if(columnOption.equalsIgnoreCase( "CONSUMPTION_X_2")){ maxStockQuantity = this.normalizedConsumption * 2; }else if(columnOption.equalsIgnoreCase("DISPENSED_X_2")){ maxStockQuantity = this.quantityDispensed * 2; } else{ // apply the default calculation if there was no other calculation that works here maxStockQuantity = maxMonthsOfStock * amc; } ======= public void calculateMaxStockQuantity() { maxStockQuantity = (int) round(maxMonthsOfStock * amc); >>>>>>> public void calculateMaxStockQuantity( ProgramRnrTemplate template) { RnrColumn column = template.getRnrColumnsMap().get("maxStockQuantity"); String columnOption = "DEFAULT"; if(column != null){ columnOption = column.getCalculationOption(); } if(columnOption.equalsIgnoreCase( "CONSUMPTION_X_2")){ maxStockQuantity = this.normalizedConsumption * 2; }else if(columnOption.equalsIgnoreCase("DISPENSED_X_2")){ maxStockQuantity = this.quantityDispensed * 2; } else{ // apply the default calculation if there was no other calculation that works here maxStockQuantity = (int) round(maxMonthsOfStock * amc); }
<<<<<<< private String programName; // this section is added to make the product editing form work. private List<ProgramProduct> programProducts; ======= @JsonIgnore public String getName() { return (getPrimaryName() == null ? "" : getPrimaryName()) + " " + (getForm().getCode() == null ? "" : getForm().getCode()) + " " + (getStrength() == null ? "" : getStrength()) + " " + (getDosageUnit().getCode() == null ? "" : getDosageUnit().getCode()); } >>>>>>> @JsonIgnore public String getName() { return (getPrimaryName() == null ? "" : getPrimaryName()) + " " + (getForm().getCode() == null ? "" : getForm().getCode()) + " " + (getStrength() == null ? "" : getStrength()) + " " + (getDosageUnit().getCode() == null ? "" : getDosageUnit().getCode()); } private String programName; // this section is added to make the product editing form work. private List<ProgramProduct> programProducts;
<<<<<<< public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); } ======= public Facility getVirtualFacilityByCode(String facilityCode) { Facility facility = facilityRepository.getByCode(facilityCode); if (facility == null) { throw new DataException(ERROR_FACILITY_CODE_INVALID); } Facility parentFacility = null; if (facility.getVirtualFacility()) { parentFacility = facilityRepository.getById(facility.getParentFacilityId()); } if (!facility.isValid(parentFacility)) { throw new DataException("error.facility.inoperative"); } return facility; } >>>>>>> public Facility getVirtualFacilityByCode(String facilityCode) { Facility facility = facilityRepository.getByCode(facilityCode); if (facility == null) { throw new DataException(ERROR_FACILITY_CODE_INVALID); } Facility parentFacility = null; if (facility.getVirtualFacility()) { parentFacility = facilityRepository.getById(facility.getParentFacilityId()); } if (!facility.isValid(parentFacility)) { throw new DataException("error.facility.inoperative"); } return facility; } public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); }
<<<<<<< import org.openlmis.rnr.calculation.RegularRnrCalcStrategy; import org.openlmis.rnr.calculation.RnrCalculationStrategy; ======= >>>>>>> import org.openlmis.rnr.calculation.RegularRnrCalcStrategy; import org.openlmis.rnr.calculation.RnrCalculationStrategy; <<<<<<< import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.when; ======= >>>>>>> <<<<<<< @Mock RnrColumn column; private RnrCalculationStrategy calcStrategy; ======= >>>>>>> @Mock RnrColumn column; <<<<<<< lossesAndAdjustmentsList = asList( new LossesAndAdjustmentsType[]{additive1, additive2, subtractive1, subtractive2}); calcStrategy = mock(RegularRnrCalcStrategy.class); } private void addVisibleColumns(List<RnrColumn> templateColumns) { addColumnToTemplate(templateColumns, ProgramRnrTemplate.BEGINNING_BALANCE, true, true); addColumnToTemplate(templateColumns, ProgramRnrTemplate.QUANTITY_DISPENSED, true, null); addColumnToTemplate(templateColumns, ProgramRnrTemplate.QUANTITY_RECEIVED, true, null); addColumnToTemplate(templateColumns, ProgramRnrTemplate.NEW_PATIENT_COUNT, true, null); addColumnToTemplate(templateColumns, ProgramRnrTemplate.STOCK_OUT_DAYS, true, null); addColumnToTemplate(templateColumns, ProgramRnrTemplate.QUANTITY_REQUESTED, true, null); addColumnToTemplate(templateColumns, ProgramRnrTemplate.REASON_FOR_REQUESTED_QUANTITY, true, null); } private void addColumnToTemplate(List<RnrColumn> templateColumns, String columnName, Boolean visible, Boolean formulaValidation) { RnrColumn rnrColumn = new RnrColumn(); rnrColumn.setName(columnName); rnrColumn.setVisible(visible); if (formulaValidation != null) rnrColumn.setFormulaValidationRequired(formulaValidation); templateColumns.add(rnrColumn); } @Test public void shouldCalculateAMC() throws Exception { lineItem.calculateAmc(calcStrategy); verify(calcStrategy).calculateAmc(lineItem.getNormalizedConsumption(), lineItem.getPreviousNormalizedConsumptions()); } @Test public void shouldCalculatePacksToShip() throws Exception { lineItem.calculatePacksToShip(calcStrategy); verify(calcStrategy).calculatePacksToShip(lineItem.getQuantityApproved(), lineItem.getPackSize(), lineItem.getPackRoundingThreshold(), lineItem.getRoundToZero()); } @Test public void shouldCalculateMaxStockQuantity() throws Exception { lineItem.calculateMaxStockQuantity(calcStrategy,template); verify(calcStrategy).calculateMaxStockQuantity(lineItem.getMaxMonthsOfStock(), lineItem.getAmc()); } @Test public void shouldCalculateOrderQuantity() throws Exception { lineItem.calculateOrderQuantity(calcStrategy); verify(calcStrategy).calculateOrderQuantity(lineItem.getMaxStockQuantity(), lineItem.getStockInHand()); } @Test public void shouldCalculateNormalizedConsumption() throws Exception { lineItem.calculateNormalizedConsumption(calcStrategy,template); verify(calcStrategy).calculateNormalizedConsumption(lineItem.getStockOutDays(), lineItem.getQuantityDispensed(), lineItem.getNewPatientCount(), lineItem.getDosesPerMonth(), lineItem.getDosesPerDispensingUnit(), null); } @Test public void shouldCalculateLossesAndAdjustments() throws Exception { lineItem.calculateTotalLossesAndAdjustments(calcStrategy, lossesAndAdjustmentsList); verify(calcStrategy).calculateTotalLossesAndAdjustments(lineItem.getLossesAndAdjustments(), lossesAndAdjustmentsList); } @Test public void shouldCalculateQuantityDispensed() throws Exception { lineItem.calculateQuantityDispensed(calcStrategy); verify(calcStrategy).calculateQuantityDispensed(lineItem.getBeginningBalance(), lineItem.getQuantityReceived(), lineItem.getTotalLossesAndAdjustments(), lineItem.getStockInHand()); } @Test public void shouldCalculateStockInHand() throws Exception { lineItem.calculateStockInHand(calcStrategy); verify(calcStrategy).calculateStockInHand(lineItem.getBeginningBalance(), lineItem.getQuantityReceived(), lineItem.getTotalLossesAndAdjustments(), lineItem.getQuantityDispensed()); } @Test public void shouldCalculateDefaultApprovedQuantity() { lineItem.setFieldsForApproval(calcStrategy); verify(calcStrategy).calculateDefaultApprovedQuantity(lineItem.getFullSupply(), lineItem.getCalculatedOrderQuantity(), lineItem.getQuantityRequested()); ======= lossesAndAdjustmentsList = asList(additive1, additive2, subtractive1, subtractive2); >>>>>>> lossesAndAdjustmentsList = asList(additive1, additive2, subtractive1, subtractive2); <<<<<<< doNothing().when(spyLineItem, "calculateNormalizedConsumption", calcStrategy, template); ======= doNothing().when(spyLineItem, "calculateNormalizedConsumption"); >>>>>>> doNothing().when(spyLineItem, "calculateNormalizedConsumption"); <<<<<<< verify(spyLineItem).calculateAmc(calcStrategy); verify(spyLineItem).calculateMaxStockQuantity(calcStrategy, template); verify(spyLineItem).calculateOrderQuantity(calcStrategy); ======= verify(spyLineItem).calculateAmc(); verify(spyLineItem).calculateMaxStockQuantity(); verify(spyLineItem).calculateOrderQuantity(); >>>>>>> verify(spyLineItem).calculateAmc(); verify(spyLineItem).calculateMaxStockQuantity(); verify(spyLineItem).calculateOrderQuantity();
<<<<<<< @ImportField(name = "Display Order", type = "int") private Integer displayOrder; ======= >>>>>>> <<<<<<< private Long formId; @ImportField(mandatory = true, type = "String", name = "Product Category", nested = "code") private ProductCategory category; private Long categoryId; ======= >>>>>>> private Long formId;
<<<<<<< @Select("SELECT * FROM processing_periods WHERE scheduleId = #{scheduleId} AND extract('year' from startdate) = #{year} ORDER BY startDate DESC") List<ProcessingPeriod> getAllPeriodsForScheduleAndYear(@Param("scheduleId")Long scheduleId, @Param("year") Long year); ======= @Select({"SELECT * FROM processing_periods WHERE scheduleId = #{currentPeriod.scheduleId}", "AND startDate < #{currentPeriod.startDate}", "ORDER BY startDate DESC LIMIT #{n}"}) List<ProcessingPeriod> getNPreviousPeriods(@Param("currentPeriod") ProcessingPeriod currentPeriod, @Param("n") Integer n); >>>>>>> @Select({"SELECT * FROM processing_periods WHERE scheduleId = #{currentPeriod.scheduleId}", "AND startDate < #{currentPeriod.startDate}", "ORDER BY startDate DESC LIMIT #{n}"}) List<ProcessingPeriod> getNPreviousPeriods(@Param("currentPeriod") ProcessingPeriod currentPeriod, @Param("n") Integer n); @Select("SELECT * FROM processing_periods WHERE scheduleId = #{scheduleId} AND extract('year' from startdate) = #{year} ORDER BY startDate DESC") List<ProcessingPeriod> getAllPeriodsForScheduleAndYear(@Param("scheduleId")Long scheduleId, @Param("year") Long year);
<<<<<<< @Select("select userPreferenceKey as key, value from user_preferences where userId = #{userId} " + "UNION " + "select key, defaultValue as value from user_preference_master " + " where key not in (select userPreferenceKey from user_preferences where userId = #{userId})") List<LinkedHashMap> getPreferences(@Param(value = "userId") Long userId); ======= @Select({"SELECT id, userName, facilityId, firstName, lastName, employeeId, restrictLogin, jobTitle, primaryNotificationMethod,", "officePhone, cellPhone, email, supervisorId, verified, active from users inner join role_assignments on users.id = role_assignments.userId ", "INNER JOIN role_rights ON role_rights.roleId = role_assignments.roleId ", "where supervisoryNodeId IN (WITH RECURSIVE supervisoryNodesRec(id, parentId) ", "AS (SELECT sn.id, sn.parentId FROM supervisory_nodes AS sn WHERE sn.id = #{nodeId}", "UNION ALL ", "SELECT c.id, c.parentId FROM supervisoryNodesRec AS p, supervisory_nodes AS c WHERE p.parentId = c.id)", "SELECT id FROM supervisoryNodesRec) ", "AND programId = #{programId} AND role_rights.rightName = #{rightName}"}) List<User> getUsersWithRightInHierarchyUsingBaseNode(@Param(value = "nodeId") Long nodeId, @Param(value = "programId") Long programId, @Param(value = "rightName") Right right); @Select({"SELECT id, userName, u.facilityId, firstName, lastName, employeeId, restrictLogin, jobTitle, primaryNotificationMethod," + "officePhone, cellPhone, email, supervisorId, verified, active FROM users u INNER JOIN fulfillment_role_assignments f ON u.id = f.userId " + "INNER JOIN role_rights rr ON f.roleId = rr.roleId", "WHERE f.facilityId = #{facilityId} AND rr.rightName = #{rightName}"}) List<User> getUsersWithRightOnWarehouse(@Param("facilityId") Long facilityId, @Param("rightName") Right right); >>>>>>> @Select("select userPreferenceKey as key, value from user_preferences where userId = #{userId} " + "UNION " + "select key, defaultValue as value from user_preference_master " + " where key not in (select userPreferenceKey from user_preferences where userId = #{userId})") List<LinkedHashMap> getPreferences(@Param(value = "userId") Long userId); @Select({"SELECT id, userName, facilityId, firstName, lastName, employeeId, restrictLogin, jobTitle, primaryNotificationMethod,", "officePhone, cellPhone, email, supervisorId, verified, active from users inner join role_assignments on users.id = role_assignments.userId ", "INNER JOIN role_rights ON role_rights.roleId = role_assignments.roleId ", "where supervisoryNodeId IN (WITH RECURSIVE supervisoryNodesRec(id, parentId) ", "AS (SELECT sn.id, sn.parentId FROM supervisory_nodes AS sn WHERE sn.id = #{nodeId}", "UNION ALL ", "SELECT c.id, c.parentId FROM supervisoryNodesRec AS p, supervisory_nodes AS c WHERE p.parentId = c.id)", "SELECT id FROM supervisoryNodesRec) ", "AND programId = #{programId} AND role_rights.rightName = #{rightName}"}) List<User> getUsersWithRightInHierarchyUsingBaseNode(@Param(value = "nodeId") Long nodeId, @Param(value = "programId") Long programId, @Param(value = "rightName") Right right); @Select({"SELECT id, userName, u.facilityId, firstName, lastName, employeeId, restrictLogin, jobTitle, primaryNotificationMethod," + "officePhone, cellPhone, email, supervisorId, verified, active FROM users u INNER JOIN fulfillment_role_assignments f ON u.id = f.userId " + "INNER JOIN role_rights rr ON f.roleId = rr.roleId", "WHERE f.facilityId = #{facilityId} AND rr.rightName = #{rightName}"}) List<User> getUsersWithRightOnWarehouse(@Param("facilityId") Long facilityId, @Param("rightName") Right right);
<<<<<<< //NOTE: this rule has been removed because a supply line can be at any point //this change was made to accommodate the vaccine supply chain. // @Test // public void shouldThrowErrorIfSupervisoryNodeIsNotTheParentNode() { // when(supervisoryNodeRepository.getSupervisoryNodeParentId(supplyLine.getSupervisoryNode().getId())).thenThrow(new DataException("Supervising Node is not the Top node")); // expectedEx.expect(DataException.class); // expectedEx.expectMessage("Supervising Node is not the Top node"); // supplyLineService.save(supplyLine); // } ======= @Test public void shouldThrowErrorIfSupervisoryNodeIsNotTheParentNode() { when(supervisoryNodeRepository.getSupervisoryNodeParentId(supplyLine.getSupervisoryNode().getId())).thenThrow(new DataException("Supervising Node is not the Top node")); expectedEx.expect(DataException.class); expectedEx.expectMessage("Supervising Node is not the Top node"); service.save(supplyLine); } >>>>>>> // @Test // public void shouldThrowErrorIfSupervisoryNodeIsNotTheParentNode() { // when(supervisoryNodeRepository.getSupervisoryNodeParentId(supplyLine.getSupervisoryNode().getId())).thenThrow(new DataException("Supervising Node is not the Top node")); // expectedEx.expect(DataException.class); // expectedEx.expectMessage("Supervising Node is not the Top node"); // service.save(supplyLine); // }
<<<<<<< import org.joda.time.DateTime; import org.openlmis.core.domain.Product; import org.openlmis.core.domain.FacilityType; import org.openlmis.core.domain.Program; import org.openlmis.core.domain.ProgramProduct; import org.openlmis.core.domain.ProgramProductPrice; ======= import org.openlmis.core.domain.*; >>>>>>> import org.openlmis.core.domain.*; <<<<<<< public List<ProgramProduct> getActiveByProgram(Long programId) { return programProductRepository.getActiveByProgram(programId); } ======= private void validateAndSetProductCategory(ProgramProduct programProduct) { ProductCategory category = programProduct.getProductCategory(); if (category == null) return; String categoryCode = category.getCode(); if (categoryCode == null || categoryCode.isEmpty()) return; Long categoryId = categoryService.getProductCategoryIdByCode(category.getCode()); if (categoryId == null) { throw new DataException("error.reference.data.invalid.product"); } category.setId(categoryId); } >>>>>>> private void validateAndSetProductCategory(ProgramProduct programProduct) { ProductCategory category = programProduct.getProductCategory(); if (category == null) return; String categoryCode = category.getCode(); if (categoryCode == null || categoryCode.isEmpty()) return; Long categoryId = categoryService.getProductCategoryIdByCode(category.getCode()); if (categoryId == null) { throw new DataException("error.reference.data.invalid.product"); } category.setId(categoryId); } public List<ProgramProduct> getActiveByProgram(Long programId) { return programProductRepository.getActiveByProgram(programId); }
<<<<<<< @RequestMapping(value = "/reportdata/replacementPlanSummary", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementPlanSummaryReport(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("replacement_plan_summary"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> reportList = (List<ReplacementPlanSummary>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportList); } @RequestMapping(value = "/reportdata/equipmentsInNeedForReplacement", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementToBeReplaced(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("equipment_replacement_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> SummaryList = (List<ReplacementPlanSummary>)report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, SummaryList); } ======= @RequestMapping(value = "/reportdata/coldChainEquipment", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_COLD_CHAIN_EQUIPMENT_LIST_REPORT')") public Pages getColdChainEquipment(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request ) { Report report = reportManager.getReportByKey("cold_chain_equipment"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<CCEInventoryReportDatum> reportData = (List<CCEInventoryReportDatum>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportData); } >>>>>>> @RequestMapping(value = "/reportdata/replacementPlanSummary", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementPlanSummaryReport(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("replacement_plan_summary"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> reportList = (List<ReplacementPlanSummary>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportList); } @RequestMapping(value = "/reportdata/equipmentsInNeedForReplacement", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementToBeReplaced(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("equipment_replacement_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> SummaryList = (List<ReplacementPlanSummary>)report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, SummaryList); } @RequestMapping(value = "/reportdata/coldChainEquipment", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_COLD_CHAIN_EQUIPMENT_LIST_REPORT')") public Pages getColdChainEquipment(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request ) { Report report = reportManager.getReportByKey("cold_chain_equipment"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<CCEInventoryReportDatum> reportData = (List<CCEInventoryReportDatum>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportData); }
<<<<<<< public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); } ======= public List<Facility> getChildFacilities(Facility facility) { return facilityRepository.getChildFacilities(facility); } >>>>>>> public List<Facility> getChildFacilities(Facility facility) { return facilityRepository.getChildFacilities(facility); } public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); }
<<<<<<< ======= Task commandProgress = progress.beginSubTask("refs", UNKNOWN); commands = commands.stream().map(c -> wrapReceiveCommand(c, commandProgress)).collect(toList()); processCommandsUnsafe(commands, progress); rejectRemaining(commands, INTERNAL_SERVER_ERROR); // This sends error messages before the 'done' string of the progress monitor is sent. // Currently, the test framework relies on this ordering to understand if pushes completed // successfully. sendErrorMessages(); commandProgress.end(); progress.end(); } // Process as many commands as possible, but may leave some commands in state NOT_ATTEMPTED. private void processCommandsUnsafe( Collection<ReceiveCommand> commands, MultiProgressMonitor progress) { >>>>>>> <<<<<<< ======= logger.atFine().log("Added %d additional ref updates", added); bu.execute(); } catch (UpdateException | RestApiException e) { rejectRemaining(cmds, INTERNAL_SERVER_ERROR); logger.atFine().withCause(e).log("update failed:"); } >>>>>>> <<<<<<< ======= } } catch (ResourceConflictException e) { addError(e.getMessage()); reject(magicBranchCmd, "conflict"); } catch (BadRequestException | UnprocessableEntityException | AuthException e) { logger.atFine().withCause(e).log("Rejecting due to client error"); reject(magicBranchCmd, e.getMessage()); } catch (RestApiException | IOException e) { logger.atSevere().withCause(e).log("Can't insert change/patch set for %s", project.getName()); reject(magicBranchCmd, String.format("%s: %s", INTERNAL_SERVER_ERROR, e.getMessage())); } >>>>>>> <<<<<<< } if (!walk.isMergedInto(tip, branchTip)) { reject(cmd, "not merged into branch"); ======= } catch (IOException e) { logger.atWarning().withCause(e).log( "Project %s cannot read %s", project.getName(), id.name()); reject(cmd, INTERNAL_SERVER_ERROR); >>>>>>> } if (!walk.isMergedInto(tip, branchTip)) { reject(cmd, "not merged into branch"); <<<<<<< } catch (StorageException err) { logger.atSevere().withCause(err).log( "Cannot read database before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), "internal server error"); } catch (IOException | PermissionBackendException err) { logger.atSevere().withCause(err).log( "Cannot read repository before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), "internal server error"); } logger.atFine().log("Read %d changes to replace", replaceByChange.size()); if (magicBranch != null && magicBranch.cmd.getResult() != NOT_ATTEMPTED) { // Cancel creations tied to refs/for/ command. for (ReplaceRequest req : replaceByChange.values()) { if (req.inputCommand == magicBranch.cmd && req.cmd != null) { req.cmd.setResult(Result.REJECTED_OTHER_REASON, "aborted"); } } for (CreateRequest req : newChanges) { ======= } } catch (StorageException err) { logger.atSevere().withCause(err).log( "Cannot read database before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), INTERNAL_SERVER_ERROR); } catch (IOException | PermissionBackendException err) { logger.atSevere().withCause(err).log( "Cannot read repository before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), INTERNAL_SERVER_ERROR); } logger.atFine().log("Read %d changes to replace", replaceByChange.size()); if (magicBranch != null && magicBranch.cmd.getResult() != NOT_ATTEMPTED) { // Cancel creations tied to refs/for/ or refs/drafts/ command. for (ReplaceRequest req : replaceByChange.values()) { if (req.inputCommand == magicBranch.cmd && req.cmd != null) { >>>>>>> } catch (StorageException err) { logger.atSevere().withCause(err).log( "Cannot read database before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), INTERNAL_SERVER_ERROR); } catch (IOException | PermissionBackendException err) { logger.atSevere().withCause(err).log( "Cannot read repository before replacement for project %s", project.getName()); rejectRemainingRequests(replaceByChange.values(), INTERNAL_SERVER_ERROR); } logger.atFine().log("Read %d changes to replace", replaceByChange.size()); if (magicBranch != null && magicBranch.cmd.getResult() != NOT_ATTEMPTED) { // Cancel creations tied to refs/for/ command. for (ReplaceRequest req : replaceByChange.values()) { if (req.inputCommand == magicBranch.cmd && req.cmd != null) { req.cmd.setResult(Result.REJECTED_OTHER_REASON, "aborted"); } } for (CreateRequest req : newChanges) {
<<<<<<< import org.joda.time.DateTime; import org.openlmis.core.domain.Product; ======= import org.openlmis.core.domain.FacilityType; >>>>>>> import org.joda.time.DateTime; import org.openlmis.core.domain.Product; import org.openlmis.core.domain.FacilityType; <<<<<<< ======= @Autowired private ProgramRepository programRepository; @Autowired private FacilityRepository facilityRepository; >>>>>>> @Autowired private ProgramRepository programRepository; @Autowired private FacilityRepository facilityRepository;
<<<<<<< import org.openlmis.core.domain.FacilityOperator; import org.openlmis.core.domain.FacilityType; import org.openlmis.core.domain.PriceSchedule; import org.openlmis.core.dto.FacilityContact; import org.openlmis.core.dto.FacilityGeoTreeDto; import org.openlmis.core.dto.FacilityImages; import org.openlmis.core.dto.FacilitySupervisor; ======= >>>>>>> import org.openlmis.core.domain.PriceSchedule; import org.openlmis.core.dto.FacilityContact; import org.openlmis.core.dto.FacilityGeoTreeDto; import org.openlmis.core.dto.FacilityImages; import org.openlmis.core.dto.FacilitySupervisor; <<<<<<< one = @One(select = "getFacilityOperatorById")), @Result(property = "priceSchedule", column = "priceScheduleId", javaType = PriceSchedule.class, one = @One(select = "org.openlmis.core.repository.mapper.PriceScheduleMapper.getById")), ======= one = @One(select = "org.openlmis.core.repository.mapper.FacilityOperatorMapper.getById")) >>>>>>> one = @One(select = "org.openlmis.core.repository.mapper.FacilityOperatorMapper.getById")), @Result(property = "priceSchedule", column = "priceScheduleId", javaType = PriceSchedule.class, one = @One(select = "org.openlmis.core.repository.mapper.PriceScheduleMapper.getById")), <<<<<<< ======= @Results(value = { @Result(property = "geographicZone.id", column = "geographicZoneId"), @Result(property = "facilityType", column = "typeId", javaType = Long.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityTypeMapper.getById")), @Result(property = "operatedBy", column = "operatedById", javaType = Long.class, one = @One(select = "org.openlmis.core.repository.mapper.FacilityOperatorMapper.getById")) }) >>>>>>>
<<<<<<< ElasticTestUtils.configure( elasticsearchConfig, nodeInfo.hostname, nodeInfo.port, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig)); ======= ElasticTestUtils.configure(elasticsearchConfig, container, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig, notesMigration)); >>>>>>> ElasticTestUtils.configure(elasticsearchConfig, container, indicesPrefix); return Guice.createInjector(new InMemoryModule(elasticsearchConfig));
<<<<<<< public void updateRequisitionStatus(String status) throws IOException, SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions ;"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = 'Admin123'), (select id from users where username = 'Admin123'));"); } update("update requisitions set supervisorynodeid=(select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = 'Admin123') , modifiedBy= (select id from users where username = 'Admin123');"); } ======= public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws IOException, SQLException { update("update requisitions set status='" + status + "' where id=" + rnrId +";"); update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } >>>>>>> public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws IOException, SQLException { update("update requisitions set status='" + status + "' where id=" + rnrId +";"); update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " + "(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));"); update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');"); } public void updateRequisitionStatus(String status) throws IOException, SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions ;"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = 'Admin123'), (select id from users where username = 'Admin123'));"); } update("update requisitions set supervisorynodeid=(select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = 'Admin123') , modifiedBy= (select id from users where username = 'Admin123');"); }
<<<<<<< CONFIGURE_RNR("right.configure.rnr", TRUE, "Permission to create and edit r&r template for any program", 1), MANAGE_FACILITY("right.manage.facility", TRUE, "Permission to manage facility(crud)", 2), MANAGE_ROLE("right.manage.role", TRUE, "Permission to create and edit roles in the system", 5), MANAGE_SCHEDULE("right.manage.schedule", TRUE, "Permission to create and edit schedules in the system", 6), MANAGE_USERS("right.manage.user", TRUE, "Permission to manage users(crud)", 7), UPLOADS("right.upload", TRUE, "Permission to upload", 8), VIEW_REPORTS("right.view.report", TRUE, "Permission to view reports", 11), MANAGE_REPORTS("right.manage.report", TRUE, "Permission to manage reports", 10, VIEW_REPORTS), VIEW_REQUISITION("right.view.requisition", FALSE, "Permission to view requisitions", 16), CREATE_REQUISITION("right.create.requisition", FALSE, "Permission to create, edit, submit and recall requisitions", 15, VIEW_REQUISITION), AUTHORIZE_REQUISITION("right.authorize.requisition", FALSE, "Permission to edit, authorize and recall requisitions", 13, VIEW_REQUISITION), APPROVE_REQUISITION("right.approve.requisition", FALSE, "Permission to approve requisitions", 12, VIEW_REQUISITION), CONVERT_TO_ORDER("right.convert.to.order", TRUE, "Permission to convert requisitions to order", 14), VIEW_ORDER("right.view.order", TRUE, "Permission to view orders", 17), MANAGE_PROGRAM_PRODUCT("right.manage.program.product", TRUE, "Permission to manage program products", 3), MANAGE_DISTRIBUTION("right.manage.distribution", FALSE, "Permission to manage an distribution", 9), MANAGE_REGIMEN_TEMPLATE("right.manage.regimen.template", TRUE, "Permission to manage a regimen template", 4), ======= CONFIGURE_RNR("right.configure.rnr", ADMIN, "Permission to create and edit r&r template for any program", 1), MANAGE_FACILITY("right.manage.facility", ADMIN, "Permission to manage facility(crud)", 2), MANAGE_ROLE("right.manage.role", ADMIN, "Permission to create and edit roles in the system", 5), MANAGE_SCHEDULE("right.manage.schedule", ADMIN, "Permission to create and edit schedules in the system", 6), MANAGE_USER("right.manage.user", ADMIN, "Permission to manage users(crud)", 7), UPLOADS("right.upload", ADMIN, "Permission to upload", 8), VIEW_REPORT("right.view.report", ADMIN, "Permission to view reports", 11), MANAGE_REPORT("right.manage.report", ADMIN, "Permission to manage reports", 10, VIEW_REPORT), VIEW_REQUISITION("right.view.requisition", REQUISITION, "Permission to view requisitions", 16), CREATE_REQUISITION("right.create.requisition", REQUISITION, "Permission to create, edit, submit and recall requisitions", 15, VIEW_REQUISITION), AUTHORIZE_REQUISITION("right.authorize.requisition", REQUISITION, "Permission to edit, authorize and recall requisitions", 13, VIEW_REQUISITION), APPROVE_REQUISITION("right.approve.requisition", REQUISITION, "Permission to approve requisitions", 12, VIEW_REQUISITION), CONVERT_TO_ORDER("right.convert.to.order", ADMIN, "Permission to convert requisitions to order", 14), VIEW_ORDER("right.view.order", ADMIN, "Permission to view orders", 17), MANAGE_PROGRAM_PRODUCT("right.manage.program.product", ADMIN, "Permission to manage program products", 3), MANAGE_DISTRIBUTION("right.manage.distribution", ALLOCATION, "Permission to manage an distribution", 9), MANAGE_REGIMEN_TEMPLATE("right.manage.regimen.template", ADMIN, "Permission to manage a regimen template", 4); >>>>>>> CONFIGURE_RNR("right.configure.rnr", ADMIN, "Permission to create and edit r&r template for any program", 1), MANAGE_FACILITY("right.manage.facility", ADMIN, "Permission to manage facility(crud)", 2), MANAGE_ROLE("right.manage.role", ADMIN, "Permission to create and edit roles in the system", 5), MANAGE_SCHEDULE("right.manage.schedule", ADMIN, "Permission to create and edit schedules in the system", 6), MANAGE_USER("right.manage.user", ADMIN, "Permission to manage users(crud)", 7), UPLOADS("right.upload", ADMIN, "Permission to upload", 8), VIEW_REPORT("right.view.report", ADMIN, "Permission to view reports", 11), MANAGE_REPORT("right.manage.report", ADMIN, "Permission to manage reports", 10, VIEW_REPORT), VIEW_REQUISITION("right.view.requisition", REQUISITION, "Permission to view requisitions", 16), CREATE_REQUISITION("right.create.requisition", REQUISITION, "Permission to create, edit, submit and recall requisitions", 15, VIEW_REQUISITION), AUTHORIZE_REQUISITION("right.authorize.requisition", REQUISITION, "Permission to edit, authorize and recall requisitions", 13, VIEW_REQUISITION), APPROVE_REQUISITION("right.approve.requisition", REQUISITION, "Permission to approve requisitions", 12, VIEW_REQUISITION), CONVERT_TO_ORDER("right.convert.to.order", ADMIN, "Permission to convert requisitions to order", 14), VIEW_ORDER("right.view.order", ADMIN, "Permission to view orders", 17), MANAGE_PROGRAM_PRODUCT("right.manage.program.product", ADMIN, "Permission to manage program products", 3), MANAGE_DISTRIBUTION("right.manage.distribution", ALLOCATION, "Permission to manage an distribution", 9), MANAGE_REGIMEN_TEMPLATE("right.manage.regimen.template", ADMIN, "Permission to manage a regimen template", 4), <<<<<<< private Boolean adminRight; ======= private RightType type; >>>>>>> private RightType type;
<<<<<<< @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id "+ "ORDER BY facilities.name,facilities.code") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesCompleteList(); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id and facilities.typeid = #{facilityTypeId}"+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeId = facility_types.id and facilities.suppliesOthers = 't' "+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getSupplyingFacilitiesCompleteList(); @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingFacilityId FROM supply_lines) AND enabled = true"}) ======= @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingFacilityId FROM supply_lines) AND enabled = TRUE"}) >>>>>>> @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id "+ "ORDER BY facilities.name,facilities.code") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesCompleteList(); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id and facilities.typeid = #{facilityTypeId}"+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeId = facility_types.id and facilities.suppliesOthers = 't' "+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getSupplyingFacilitiesCompleteList(); @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingFacilityId FROM supply_lines) AND enabled = TRUE"})
<<<<<<< @RequestMapping(value = "/facility/{facilityId}/program/{programId}/isa", method = PUT, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public void overrideIsa(@PathVariable Long facilityId, @RequestBody FacilityProgramProductList products) { service.saveOverriddenIsa(facilityId, products); } @RequestMapping(value = "/facility/{facilityId}/program/{programId}/programProductList", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PROGRAM_PRODUCT')") public ResponseEntity<OpenLmisResponse> getByFacilityAndProgram(@PathVariable Long programId, @PathVariable Long facilityId) { List<FacilityProgramProduct> programProductsByProgram = service.getActiveProductsForProgramAndFacility(facilityId,programId); return OpenLmisResponse.response(PROGRAM_PRODUCT_LIST, programProductsByProgram); } ======= >>>>>>> @RequestMapping(value = "/facility/{facilityId}/program/{programId}/programProductList", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PROGRAM_PRODUCT')") public ResponseEntity<OpenLmisResponse> getByFacilityAndProgram(@PathVariable Long programId, @PathVariable Long facilityId) { List<FacilityProgramProduct> programProductsByProgram = service.getActiveProductsForProgramAndFacility(facilityId,programId); return OpenLmisResponse.response(PROGRAM_PRODUCT_LIST, programProductsByProgram); }
<<<<<<< public List<Product> getAllProducts() { return repository.getAll(); } ======= public Product getByCode(String code) { return repository.getByCode(code); } >>>>>>> public Product getByCode(String code) { return repository.getByCode(code); } public List<Product> getAllProducts() { return repository.getAll(); }
<<<<<<< public List<SupervisoryNode> getCompleteList(){ return supervisoryNodeRepository.getCompleteList(); } public SupervisoryNode loadSupervisoryNodeById(Long id){ return supervisoryNodeRepository.loadSupervisoryNodeById(id); } public void save_Ext(SupervisoryNode supervisoryNode) { if (supervisoryNode.getId() == null) supervisoryNodeRepository.insert(supervisoryNode); else supervisoryNodeRepository.update(supervisoryNode); } public void removeSupervisoryNode(long id){ supervisoryNodeRepository.removeSupervisoryNode(id); } public Long getTotalUnassignedSupervisoryNodeOfUserBy(Long userId, Long programId){ return supervisoryNodeRepository.getTotalUnassignedSupervisoryNodeOfUserBy(userId, programId); } public List<SupervisoryNode> getAllSupervisoryNodesInHierarchyBy(Long userId) { return supervisoryNodeRepository.getAllSupervisoryNodesInHierarchyBy(userId); } ======= public Pagination getPagination(Integer page) { return new Pagination(page, pageSize); } public Integer getTotalSearchResultCount(String param, Boolean parent) { if(parent) { return supervisoryNodeRepository.getTotalParentSearchResultCount(param); } return supervisoryNodeRepository.getTotalSearchResultCount(param); } public SupervisoryNode getSupervisoryNode(Long id) { return supervisoryNodeRepository.getSupervisoryNode(id); } public List<SupervisoryNode> getFilteredSupervisoryNodesByName(String param) { return supervisoryNodeRepository.getFilteredSupervisoryNodesByName(param); } public List<SupervisoryNode> searchTopLevelSupervisoryNodesByName(String param) { return supervisoryNodeRepository.searchTopLevelSupervisoryNodesByName(param); } >>>>>>> public Pagination getPagination(Integer page) { return new Pagination(page, pageSize); } public Integer getTotalSearchResultCount(String param, Boolean parent) { if(parent) { return supervisoryNodeRepository.getTotalParentSearchResultCount(param); } return supervisoryNodeRepository.getTotalSearchResultCount(param); } public SupervisoryNode getSupervisoryNode(Long id) { return supervisoryNodeRepository.getSupervisoryNode(id); } public List<SupervisoryNode> getFilteredSupervisoryNodesByName(String param) { return supervisoryNodeRepository.getFilteredSupervisoryNodesByName(param); } public List<SupervisoryNode> searchTopLevelSupervisoryNodesByName(String param) { return supervisoryNodeRepository.searchTopLevelSupervisoryNodesByName(param); } public Long getTotalUnassignedSupervisoryNodeOfUserBy(Long userId, Long programId){ return supervisoryNodeRepository.getTotalUnassignedSupervisoryNodeOfUserBy(userId, programId); }
<<<<<<< import com.google.gerrit.common.UsedAt; ======= import com.google.common.flogger.FluentLogger; import com.google.gerrit.common.errors.EmailException; >>>>>>> import com.google.common.flogger.FluentLogger; import com.google.gerrit.common.UsedAt; import com.google.gerrit.exceptions.EmailException; <<<<<<< return Strings.isNullOrEmpty(newPassword) ? Response.none() : Response.ok(newPassword); ======= try { httpPasswordUpdateSenderFactory .create(user, newPassword == null ? "deleted" : "added or updated") .send(); } catch (EmailException e) { logger.atSevere().withCause(e).log( "Cannot send HttpPassword update message to %s", user.getAccount().getPreferredEmail()); } return Strings.isNullOrEmpty(newPassword) ? Response.<String>none() : Response.ok(newPassword); >>>>>>> try { httpPasswordUpdateSenderFactory .create(user, newPassword == null ? "deleted" : "added or updated") .send(); } catch (EmailException e) { logger.atSevere().withCause(e).log( "Cannot send HttpPassword update message to %s", user.getAccount().getPreferredEmail()); } return Strings.isNullOrEmpty(newPassword) ? Response.none() : Response.ok(newPassword);
<<<<<<< whenNew(RequisitionStatusChangeEvent.class).withArguments(requisition, vendor, notificationServices).thenReturn(event); ======= whenNew(RequisitionStatusChangeEvent.class).withArguments(requisition).thenReturn(event); >>>>>>> whenNew(RequisitionStatusChangeEvent.class).withArguments(requisition).thenReturn(event); whenNew(RequisitionStatusChangeEvent.class).withArguments(requisition, vendor, notificationServices).thenReturn(event);
<<<<<<< import com.google.gerrit.extensions.api.changes.StarsInput; ======= import com.google.gerrit.extensions.api.groups.GroupApi; >>>>>>> import com.google.gerrit.extensions.api.changes.StarsInput; import com.google.gerrit.extensions.api.groups.GroupApi;
<<<<<<< private String quantityOrdered; ======= private String replacedProductCode; >>>>>>> private String quantityOrdered; private String replacedProductCode;
<<<<<<< public void goBack(){ TestWebDriver.getDriver().navigate().back(); } public String getErrorMessage() { testWebDriver.waitForElementToAppear(errorMsg); return errorMsg.getText().trim(); } ======= public String getErrorMessage() { testWebDriver.waitForElementToAppear(errorMsg); return errorMsg.getText().trim(); } >>>>>>> public String getErrorMessage() { testWebDriver.waitForElementToAppear(errorMsg); return errorMsg.getText().trim(); } public void goBack(){ TestWebDriver.getDriver().navigate().back(); } public String getErrorMessage() { testWebDriver.waitForElementToAppear(errorMsg); return errorMsg.getText().trim(); }
<<<<<<< @RequestMapping(value = "/reportdata/repairManagementEquipmentList", method = GET, headers = BaseController.ACCEPT_JSON) public Pages getRepairManagementEquipmentList( @RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request ) { Report report = reportManager.getReportByKey("repair_management_equipment_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<RepairManagementEquipmentList> repairManagementEquipmentList = (List<RepairManagementEquipmentList>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, repairManagementEquipmentList); } ======= @RequestMapping(value = "/reportdata/replacementPlanSummary", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementPlanSummaryReport(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("replacement_plan_summary"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> reportList = (List<ReplacementPlanSummary>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportList); } @RequestMapping(value = "/reportdata/equipmentsInNeedForReplacement", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementToBeReplaced(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("equipment_replacement_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> SummaryList = (List<ReplacementPlanSummary>)report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, SummaryList); } >>>>>>> @RequestMapping(value = "/reportdata/repairManagementEquipmentList", method = GET, headers = BaseController.ACCEPT_JSON) public Pages getRepairManagementEquipmentList( @RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request ) { Report report = reportManager.getReportByKey("repair_management_equipment_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<RepairManagementEquipmentList> repairManagementEquipmentList = (List<RepairManagementEquipmentList>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, repairManagementEquipmentList); } @RequestMapping(value = "/reportdata/replacementPlanSummary", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementPlanSummaryReport(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("replacement_plan_summary"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> reportList = (List<ReplacementPlanSummary>) report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, reportList); } @RequestMapping(value = "/reportdata/equipmentsInNeedForReplacement", method = GET, headers = BaseController.ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'VIEW_VACCINE_REPLACEMENT_PLAN_SUMMARY')") public Pages getReplacementToBeReplaced(@RequestParam(value = "page", required = false, defaultValue = "1") int page, @RequestParam(value = "max", required = false, defaultValue = "10") int max, HttpServletRequest request) { Report report = reportManager.getReportByKey("equipment_replacement_list"); report.getReportDataProvider().setUserId(loggedInUserId(request)); List<ReplacementPlanSummary> SummaryList = (List<ReplacementPlanSummary>)report.getReportDataProvider().getMainReportData(request.getParameterMap(), request.getParameterMap(), page, max); return new Pages(page, max, SummaryList); }
<<<<<<< private String orderId; private String concatenatedOrderId; private String facilityCode; private String programCode; ======= private String orderNumber; >>>>>>> private String orderNumber; private String orderId; private String concatenatedOrderId; private String facilityCode; private String programCode;
<<<<<<< user.setReportRoles(roleAssignmentService.getReportRole(id)); ======= user.setShipmentRoleAssignments(shipmentRoleService.getRolesForUser(id)); >>>>>>> user.setShipmentRoleAssignments(shipmentRoleService.getRolesForUser(id)); user.setReportRoles(roleAssignmentService.getReportRole(id));
<<<<<<< user.setShipmentRoleAssignments(shipmentRoleService.getRolesForUser(id)); user.setReportRoles(roleAssignmentService.getReportRole(id)); ======= user.setFulfillmentRoles(fulfillmentRoleService.getRolesForUser(id)); >>>>>>> user.setFulfillmentRoles(fulfillmentRoleService.getRolesForUser(id)); user.setReportRoles(roleAssignmentService.getReportRole(id));
<<<<<<< private ProgramProductPriceListDataProvider programPriceService; @Autowired private ProgramProductService service; ======= ProgramProductService service; >>>>>>> ProgramProductService service; private ProgramProductPriceListDataProvider programPriceService; <<<<<<< // All product cost @RequestMapping(value = "/allproductcost", method = RequestMethod.GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PRODUCT')") public ResponseEntity<OpenLmisResponse> getAllPrices(Long id) { return OpenLmisResponse.response("AllProgramCosts", programPriceService.getAllPrices()); } // product cost history for this product @RequestMapping(value = "/priceHistory/{productId}", method = RequestMethod.GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PRODUCT')") public ResponseEntity<OpenLmisResponse> getProductPriceHistory(@PathVariable("productId") Long productId) { return OpenLmisResponse.response("priceHistory", programPriceService.getByProductId( productId ) ); } @RequestMapping(value = "/program/{programId}/active-products", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getActiveProgramProductsByProgram(@PathVariable Long programId) { List<ProgramProduct> programProductsByProgram = service.getActiveByProgram(programId); return response(PROGRAM_PRODUCT_LIST, programProductsByProgram); } ======= >>>>>>> // All product cost @RequestMapping(value = "/allproductcost", method = RequestMethod.GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PRODUCT')") public ResponseEntity<OpenLmisResponse> getAllPrices(Long id) { return OpenLmisResponse.response("AllProgramCosts", programPriceService.getAllPrices()); } // product cost history for this product @RequestMapping(value = "/priceHistory/{productId}", method = RequestMethod.GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_PRODUCT')") public ResponseEntity<OpenLmisResponse> getProductPriceHistory(@PathVariable("productId") Long productId) { return OpenLmisResponse.response("priceHistory", programPriceService.getByProductId( productId ) ); } @RequestMapping(value = "/program/{programId}/active-products", method = GET, headers = BaseController.ACCEPT_JSON) public ResponseEntity<OpenLmisResponse> getActiveProgramProductsByProgram(@PathVariable Long programId) { List<ProgramProduct> programProductsByProgram = service.getActiveByProgram(programId); return response(PROGRAM_PRODUCT_LIST, programProductsByProgram); }
<<<<<<< public FacilityMailingListReportPage navigateViewFacilityMailingListReport() throws IOException { SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(FacilityMailingListReportMenu); testWebDriver.keyPress(FacilityMailingListReportMenu); testWebDriver.waitForElementToAppear(facilityListingReportPageHeader); return new FacilityMailingListReportPage(testWebDriver); } public FacilityListingReportPage navigateViewFacilityListingReport() throws IOException { SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(FacilityListingReportMenu); testWebDriver.keyPress(FacilityListingReportMenu); return new FacilityListingReportPage(testWebDriver); } public SummaryReportPage navigateViewSummaryReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(SummaryReportMenu); testWebDriver.keyPress(SummaryReportMenu); return new SummaryReportPage(testWebDriver); } public NonReportingFacilityReportPage navigateViewNonReportingFacilityReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(NonReportingFacilityReportMenu); testWebDriver.keyPress(NonReportingFacilityReportMenu); return new NonReportingFacilityReportPage(testWebDriver); } public AverageConsumptionReportPage navigateViewAverageConsumptionReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(AverageConsumptionReportMenu); testWebDriver.keyPress(AverageConsumptionReportMenu); return new AverageConsumptionReportPage(testWebDriver); } public AdjustmentSummaryReportPage navigateViewAdjustmentSummaryReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ProductReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ProductReportsMenuItem); testWebDriver.keyPress(ProductReportsMenuItem); testWebDriver.waitForElementToAppear(AdjustmentSummaryReportMenu); testWebDriver.keyPress(AdjustmentSummaryReportMenu); return new AdjustmentSummaryReportPage(testWebDriver); } public StockedOutReportPage navigateViewStockedOutReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ProductReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ProductReportsMenuItem); testWebDriver.keyPress(ProductReportsMenuItem); testWebDriver.waitForElementToAppear(StockedOutReportMenu); testWebDriver.keyPress(StockedOutReportMenu); return new StockedOutReportPage(testWebDriver); } public void goBack(){ TestWebDriver.getDriver().navigate().back(); } ======= public void verifyLoggedInUser(String Username) { testWebDriver.waitForElementToAppear(loggedInUserLabel); SeleneseTestNgHelper.assertEquals(loggedInUserLabel.getText(), Username); } >>>>>>> public FacilityMailingListReportPage navigateViewFacilityMailingListReport() throws IOException { SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(FacilityMailingListReportMenu); testWebDriver.keyPress(FacilityMailingListReportMenu); testWebDriver.waitForElementToAppear(facilityListingReportPageHeader); return new FacilityMailingListReportPage(testWebDriver); } public FacilityListingReportPage navigateViewFacilityListingReport() throws IOException { SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(FacilityListingReportMenu); testWebDriver.keyPress(FacilityListingReportMenu); return new FacilityListingReportPage(testWebDriver); } public SummaryReportPage navigateViewSummaryReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(SummaryReportMenu); testWebDriver.keyPress(SummaryReportMenu); return new SummaryReportPage(testWebDriver); } public NonReportingFacilityReportPage navigateViewNonReportingFacilityReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(NonReportingFacilityReportMenu); testWebDriver.keyPress(NonReportingFacilityReportMenu); return new NonReportingFacilityReportPage(testWebDriver); } public AverageConsumptionReportPage navigateViewAverageConsumptionReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ReportsMenuItem); testWebDriver.keyPress(ReportsMenuItem); testWebDriver.waitForElementToAppear(AverageConsumptionReportMenu); testWebDriver.keyPress(AverageConsumptionReportMenu); return new AverageConsumptionReportPage(testWebDriver); } public AdjustmentSummaryReportPage navigateViewAdjustmentSummaryReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ProductReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ProductReportsMenuItem); testWebDriver.keyPress(ProductReportsMenuItem); testWebDriver.waitForElementToAppear(AdjustmentSummaryReportMenu); testWebDriver.keyPress(AdjustmentSummaryReportMenu); return new AdjustmentSummaryReportPage(testWebDriver); } public StockedOutReportPage navigateViewStockedOutReport() throws IOException{ SeleneseTestNgHelper.assertTrue(ProductReportsMenuItem.isDisplayed()); testWebDriver.waitForElementToAppear(ProductReportsMenuItem); testWebDriver.keyPress(ProductReportsMenuItem); testWebDriver.waitForElementToAppear(StockedOutReportMenu); testWebDriver.keyPress(StockedOutReportMenu); return new StockedOutReportPage(testWebDriver); } public void goBack(){ TestWebDriver.getDriver().navigate().back(); } public void verifyLoggedInUser(String Username) { testWebDriver.waitForElementToAppear(loggedInUserLabel); SeleneseTestNgHelper.assertEquals(loggedInUserLabel.getText(), Username); }
<<<<<<< @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id "+ "ORDER BY facilities.name,facilities.code") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesCompleteList(); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id and facilities.typeid = #{facilityTypeId}"+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeId = facility_types.id and facilities.suppliesOthers = 't' "+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getSupplyingFacilitiesCompleteList(); @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingfacilityid FROM supply_lines) AND enabled = true"}) ======= @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingFacilityId FROM supply_lines) AND enabled = true"}) >>>>>>> @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id "+ "ORDER BY facilities.name,facilities.code") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesCompleteList(); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeid = facility_types.id and facilities.typeid = #{facilityTypeId}"+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId); @Select("SELECT facilities.*, facility_types.name as facilityType "+ "FROM facilities, facility_types "+ "WHERE facilities.typeId = facility_types.id and facilities.suppliesOthers = 't' "+ "ORDER BY facilities.code, facilities.name") @Results(value = { @Result(property = "geographicZone", column = "geographicZoneId", javaType = Integer.class, one = @One(select = "org.openlmis.core.repository.mapper.GeographicZoneMapperExtension.getGeographicZoneById_Ext")), @Result(property = "facilityType", column = "typeId", javaType = Integer.class, one = @One(select = "getFacilityTypeById")), @Result(property = "operatedBy", column = "operatedById", javaType = Integer.class, one = @One(select = "getFacilityOperatorById")) }) List<Facility> getSupplyingFacilitiesCompleteList(); @Select({"SELECT * FROM facilities WHERE id IN (SELECT supplyingFacilityId FROM supply_lines) AND enabled = true"})
<<<<<<< public void updateRequisitionStatus(String status) throws IOException, SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions ;"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = 'Admin123'), (select id from users where username = 'Admin123'));"); } update("update requisitions set supervisorynodeid=(select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = 'Admin123') , modifiedBy= (select id from users where username = 'Admin123');"); } public String getSupplyFacilityName(String supervisoryNode, String programCode) throws IOException, SQLException { ======= public String getSupplyFacilityName(String supervisoryNode, String programCode) throws SQLException { >>>>>>> public void updateRequisitionStatus(String status) throws IOException, SQLException { update("update requisitions set status='" + status + "';"); ResultSet rs = query("select id from requisitions ;"); while (rs.next()) { update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " + "(select id from users where username = 'Admin123'), (select id from users where username = 'Admin123'));"); } update("update requisitions set supervisorynodeid=(select id from supervisory_nodes where code='N1');"); update("update requisitions set createdBy= (select id from users where username = 'Admin123') , modifiedBy= (select id from users where username = 'Admin123');"); } public String getSupplyFacilityName(String supervisoryNode, String programCode) throws IOException, SQLException { public String getSupplyFacilityName(String supervisoryNode, String programCode) throws SQLException {
<<<<<<< @RequestMapping(value="/facilities/getListInRequisitionGroup/{id}",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getFacilityListInARequisitionGroup(@PathVariable("id") Long id, HttpServletRequest request){ RequisitionGroup requisitionGroup = requisitionGroupService.loadRequisitionGroupById(id); List<RequisitionGroup> requisitionGroups= new ArrayList<RequisitionGroup>(); requisitionGroups.add(requisitionGroup); return OpenLmisResponse.response("facilities",facilityService.getCompleteListInRequisitionGroups(requisitionGroups)); } @RequestMapping(value="/facilities/getFacilityCompleteList",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getAllFacilityDetail(HttpServletRequest request){ return OpenLmisResponse.response("facilities",facilityService.getFacilitiesCompleteList()); } @RequestMapping(value = "/facilities/facilityType/{facilityTypeId}", method = GET, headers = ACCEPT_JSON) //@PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getFacilityListForAFacilityType(@PathVariable("facilityTypeId") Long facilityTypeId) { return OpenLmisResponse.response("facilities",facilityService.getFacilitiesListForAFacilityType(facilityTypeId)); } @RequestMapping(value = "/facility/supplyingFacilities", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getSupplyingFacilitiesCompleteList() { return OpenLmisResponse.response("facilities",facilityService.getSupplyingFacilitiesCompleteList()); } ======= >>>>>>> @RequestMapping(value="/facilities/getListInRequisitionGroup/{id}",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getFacilityListInARequisitionGroup(@PathVariable("id") Long id, HttpServletRequest request){ RequisitionGroup requisitionGroup = requisitionGroupService.loadRequisitionGroupById(id); List<RequisitionGroup> requisitionGroups= new ArrayList<RequisitionGroup>(); requisitionGroups.add(requisitionGroup); return OpenLmisResponse.response("facilities",facilityService.getCompleteListInRequisitionGroups(requisitionGroups)); } @RequestMapping(value="/facilities/getFacilityCompleteList",method= GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_REQUISITION_GROUP')") public ResponseEntity<OpenLmisResponse> getAllFacilityDetail(HttpServletRequest request){ return OpenLmisResponse.response("facilities",facilityService.getFacilitiesCompleteList()); } @RequestMapping(value = "/facilities/facilityType/{facilityTypeId}", method = GET, headers = ACCEPT_JSON) //@PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getFacilityListForAFacilityType(@PathVariable("facilityTypeId") Long facilityTypeId) { return OpenLmisResponse.response("facilities",facilityService.getFacilitiesListForAFacilityType(facilityTypeId)); } @RequestMapping(value = "/facility/supplyingFacilities", method = GET, headers = ACCEPT_JSON) @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_FACILITY')") public ResponseEntity<OpenLmisResponse> getSupplyingFacilitiesCompleteList() { return OpenLmisResponse.response("facilities",facilityService.getSupplyingFacilitiesCompleteList()); }
<<<<<<< ======= @RequestMapping(value = "/users/supervisory/rights.json", method= GET) public ResponseEntity<OpenLmisResponse> getRights(HttpServletRequest request){ return response("rights", userService.getSupervisoryRights(loggedInUserId(request))); } >>>>>>> @RequestMapping(value = "/users/supervisory/rights.json", method= GET) public ResponseEntity<OpenLmisResponse> getRights(HttpServletRequest request){ return response("rights", userService.getSupervisoryRights(loggedInUserId(request))); }
<<<<<<< RevCommit priorCommit = revisions.inverse().get(priorPatchSet); replaceOp = replaceOpFactory .create( projectState, notes.getChange().getDest(), checkMergedInto, priorPatchSet, priorCommit, psId, newCommit, info, groups, magicBranch, receivePack.getPushCertificate()) .setRequestScopePropagator(requestScopePropagator); bu.addOp(notes.getChangeId(), replaceOp); if (progress != null) { bu.addOp(notes.getChangeId(), new ChangeProgressOp(progress)); } ======= RevCommit priorCommit = revisions.inverse().get(priorPatchSet); replaceOp = replaceOpFactory .create( projectState, notes.getChange().getDest(), checkMergedInto, checkMergedInto ? inputCommand.getNewId().name() : null, priorPatchSet, priorCommit, psId, newCommit, info, groups, magicBranch, receivePack.getPushCertificate()) .setRequestScopePropagator(requestScopePropagator); bu.addOp(notes.getChangeId(), replaceOp); if (progress != null) { bu.addOp(notes.getChangeId(), new ChangeProgressOp(progress)); >>>>>>> RevCommit priorCommit = revisions.inverse().get(priorPatchSet); replaceOp = replaceOpFactory .create( projectState, notes.getChange().getDest(), checkMergedInto, checkMergedInto ? inputCommand.getNewId().name() : null, priorPatchSet, priorCommit, psId, newCommit, info, groups, magicBranch, receivePack.getPushCertificate()) .setRequestScopePropagator(requestScopePropagator); bu.addOp(notes.getChangeId(), replaceOp); if (progress != null) { bu.addOp(notes.getChangeId(), new ChangeProgressOp(progress)); } <<<<<<< BranchCommitValidator validator = commitValidatorFactory.create(projectState, branch, user); RevWalk walk = receivePack.getRevWalk(); walk.reset(); walk.sort(RevSort.NONE); try { RevObject parsedObject = walk.parseAny(cmd.getNewId()); if (!(parsedObject instanceof RevCommit)) { ======= BranchCommitValidator validator = commitValidatorFactory.create(projectState, branch, user); RevWalk walk = receivePack.getRevWalk(); walk.reset(); walk.sort(RevSort.NONE); try { RevObject parsedObject = walk.parseAny(cmd.getNewId()); if (!(parsedObject instanceof RevCommit)) { return; } ListMultimap<ObjectId, Ref> existing = changeRefsById(); walk.markStart((RevCommit) parsedObject); markHeadsAsUninteresting(walk, cmd.getRefName()); int limit = receiveConfig.maxBatchCommits; int n = 0; for (RevCommit c; (c = walk.next()) != null; ) { // Even if skipValidation is set, we still get here when at least one plugin // commit validator requires to validate all commits. In this case, however, // we don't need to check the commit limit. if (++n > limit && !skipValidation) { logger.atFine().log("Number of new commits exceeds limit of %d", limit); reject( cmd, String.format( "more than %d commits, and %s not set", limit, PUSH_OPTION_SKIP_VALIDATION)); >>>>>>> BranchCommitValidator validator = commitValidatorFactory.create(projectState, branch, user); RevWalk walk = receivePack.getRevWalk(); walk.reset(); walk.sort(RevSort.NONE); try { RevObject parsedObject = walk.parseAny(cmd.getNewId()); if (!(parsedObject instanceof RevCommit)) { <<<<<<< // TODO(dborowitz): Combine this BatchUpdate with the main one in // handleRegularCommands try { retryHelper.execute( updateFactory -> { try (BatchUpdate bu = updateFactory.create(projectState.getNameKey(), user, TimeUtil.nowTs()); ObjectInserter ins = repo.newObjectInserter(); ObjectReader reader = ins.newReader(); RevWalk rw = new RevWalk(reader)) { bu.setRepository(repo, rw, ins); // TODO(dborowitz): Teach BatchUpdate to ignore missing changes. RevCommit newTip = rw.parseCommit(cmd.getNewId()); BranchNameKey branch = BranchNameKey.create(project.getNameKey(), refName); rw.reset(); rw.sort(RevSort.REVERSE); rw.markStart(newTip); if (!ObjectId.zeroId().equals(cmd.getOldId())) { rw.markUninteresting(rw.parseCommit(cmd.getOldId())); ======= ListMultimap<ObjectId, Ref> byCommit = changeRefsById(); Map<Change.Key, ChangeNotes> byKey = null; List<ReplaceRequest> replaceAndClose = new ArrayList<>(); int existingPatchSets = 0; int newPatchSets = 0; COMMIT: for (RevCommit c; (c = rw.next()) != null; ) { rw.parseBody(c); for (Ref ref : byCommit.get(c.copy())) { PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName()); Optional<ChangeNotes> notes = getChangeNotes(psId.getParentKey()); if (notes.isPresent() && notes.get().getChange().getDest().equals(branch)) { existingPatchSets++; bu.addOp(notes.get().getChangeId(), setPrivateOpFactory.create(false, null)); bu.addOp( psId.getParentKey(), mergedByPushOpFactory.create( requestScopePropagator, psId, refName, newTip.getId().getName())); continue COMMIT; } >>>>>>> // TODO(dborowitz): Combine this BatchUpdate with the main one in // handleRegularCommands try { retryHelper.execute( updateFactory -> { try (BatchUpdate bu = updateFactory.create(projectState.getNameKey(), user, TimeUtil.nowTs()); ObjectInserter ins = repo.newObjectInserter(); ObjectReader reader = ins.newReader(); RevWalk rw = new RevWalk(reader)) { bu.setRepository(repo, rw, ins); // TODO(dborowitz): Teach BatchUpdate to ignore missing changes. RevCommit newTip = rw.parseCommit(cmd.getNewId()); BranchNameKey branch = BranchNameKey.create(project.getNameKey(), refName); rw.reset(); rw.sort(RevSort.REVERSE); rw.markStart(newTip); if (!ObjectId.zeroId().equals(cmd.getOldId())) { rw.markUninteresting(rw.parseCommit(cmd.getOldId())); <<<<<<< logger.atFine().log( "Auto-closing %s changes with existing patch sets and %s with new patch sets", existingPatchSets, newPatchSets); bu.execute(); } catch (IOException | StorageException | PermissionBackendException e) { logger.atSevere().withCause(e).log("Failed to auto-close changes"); return null; ======= req.addOps(bu, null); bu.addOp(id, setPrivateOpFactory.create(false, null)); bu.addOp( id, mergedByPushOpFactory .create(requestScopePropagator, req.psId, refName, newTip.getId().getName()) .setPatchSetProvider(req.replaceOp::getPatchSet)); bu.addOp(id, new ChangeProgressOp(progress)); ids.add(id); >>>>>>> logger.atFine().log( "Auto-closing %s changes with existing patch sets and %s with new patch sets", existingPatchSets, newPatchSets); bu.execute(); } catch (IOException | StorageException | PermissionBackendException e) { logger.atSevere().withCause(e).log("Failed to auto-close changes"); return null;
<<<<<<< public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); } ======= public List<Facility> getAllByRequisitionGroupMemberModifiedDate(Date modifiedDate) { return facilityRepository.getAllByRequisitionGroupMemberModifiedDate(modifiedDate); } >>>>>>> public List<Facility> getAllByRequisitionGroupMemberModifiedDate(Date modifiedDate) { return facilityRepository.getAllByRequisitionGroupMemberModifiedDate(modifiedDate); } public List<Facility> getAllFacilitiesDetail(){ return facilityRepository.getAllFacilitiesDetail(); } public List<Facility> getCompleteListInRequisitionGroups(List<RequisitionGroup> requisitionGroups){ return facilityRepository.getAllInRequisitionGroups(requisitionGroups); } public List<Facility> getFacilitiesCompleteList(){ return facilityRepository.getFacilitiesCompleteList(); } public List<Facility> getFacilitiesListForAFacilityType(Long facilityTypeId){ return facilityRepository.getFacilitiesForAFacilityType(facilityTypeId); } public List<Facility> getSupplyingFacilitiesCompleteList() { return facilityRepository.getSupplyingFacilitiesCompleteList(); }
<<<<<<< ======= totalTicks++; >>>>>>> totalTicks++; <<<<<<< ======= boolean completedWithErrors = false; >>>>>>> boolean completedWithErrors = false; <<<<<<< hook.start(currentMissionInit(), videoProducer, envServer); ======= frameProduced(); hook.start(currentMissionInit(), videoProducer, this); >>>>>>> frameProduced(); hook.start(currentMissionInit(), videoProducer, this, envServer);
<<<<<<< /* * Copyright (C) 2012-2019 52°North Initiative for Geospatial Open Source ======= /** * Copyright (C) 2012-2020 52°North Initiative for Geospatial Open Source >>>>>>> /* * Copyright (C) 2012-2020 52°North Initiative for Geospatial Open Source
<<<<<<< assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); StringWriter w = new StringWriter(); assertEquals(3, p.getText(w)); assertEquals("num", w.toString()); ======= assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); >>>>>>> assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("num", p.getCurrentName()); StringWriter w = new StringWriter(); assertEquals(3, p.getText(w)); assertEquals("num", w.toString()); <<<<<<< assertToken(JsonToken.VALUE_STRING, p.nextToken()); w = new StringWriter(); assertEquals(IP.length(), p.getText(w)); assertEquals(IP, w.toString()); assertEquals(IP, p.getText()); p.close(); ======= assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals(IP, p.getText()); p.close(); >>>>>>> assertToken(JsonToken.VALUE_STRING, p.nextToken()); w = new StringWriter(); assertEquals(IP.length(), p.getText(w)); assertEquals(IP, w.toString()); assertEquals(IP, p.getText()); p.close(); <<<<<<< String YAML = "nulls: [~ ]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("nulls", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); ======= final String YAML = "nulls: [~ ]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("nulls", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } // for [dataformat-yaml#69] public void testTimeLikeValues() throws Exception { final String YAML = "value: 3:00\n"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("3:00", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); >>>>>>> String YAML = "nulls: [~ ]"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("nulls", p.getCurrentName()); assertToken(JsonToken.START_ARRAY, p.nextToken()); assertToken(JsonToken.VALUE_NULL, p.nextToken()); assertToken(JsonToken.END_ARRAY, p.nextToken()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } // for [dataformat-yaml#69] public void testTimeLikeValues() throws Exception { final String YAML = "value: 3:00\n"; JsonParser p = YAML_F.createParser(YAML); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("value", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("3:00", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close();
<<<<<<< @Test public void testClass3() throws IOException, CopperParserException { String input = "class Hello\n" + " class def create():Hello = new\n" + " def foo():Int = 7\n" + " val bar:Int = 19\n" + "Hello.create().foo()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(7)"); } @Test public void testClassMutual() throws IOException, CopperParserException { String input = "class Foo\n" + " class def create():Foo = new\n" + " def hello():Hello = Hello.create()\n" + "class Hello\n" + " class def create():Hello = new\n" + " def foo():Foo = Foo.create()\n" + " val bar:Int = 19\n" + "Hello.create().bar"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals("IntegerConstant(19)", res.evaluate(Globals.getStandardEnv()).toString()); } ======= @Test public void parseSimpleClass() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void parseClassWithNew() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():C\n" + " new\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void testSimpleClass() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():C\n" + " new\n" + "C.create().bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } @Test public void parseSimpleType() throws IOException, CopperParserException { String input = "type T\n" + " def bar():Int\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void testSimpleType() throws IOException, CopperParserException { String input = "type T\n" + " def bar():Int\n" + "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():T\n" + " new\n" + "C.create().bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } @Test public void testSimpleMetadata() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():T\n" + " new\n" + "type T\n" + " def foo():Int\n" + " metadata = C.create()\n" + "T.bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } // admittedly this is only a starting point.... @Test public void testTrivialDSL() throws IOException, CopperParserException { String input = "val myNumMetadata = /* write me somehow or import from Java */\n" + "type MyNum\n" + " def getValue():Int\n" + " metadata = myNumMetadata\n" + "val n:MyNum = { 5 }" + "n.getValue()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } >>>>>>> @Test public void testClass3() throws IOException, CopperParserException { String input = "class Hello\n" + " class def create():Hello = new\n" + " def foo():Int = 7\n" + " val bar:Int = 19\n" + "Hello.create().foo()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(7)"); } @Test public void testClassMutual() throws IOException, CopperParserException { String input = "class Foo\n" + " class def create():Foo = new\n" + " def hello():Hello = Hello.create()\n" + "class Hello\n" + " class def create():Hello = new\n" + " def foo():Foo = Foo.create()\n" + " val bar:Int = 19\n" + "Hello.create().bar"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals("IntegerConstant(19)", res.evaluate(Globals.getStandardEnv()).toString()); } @Test public void parseSimpleClass() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void parseClassWithNew() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():C\n" + " new\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void testSimpleClass() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():C\n" + " new\n" + "C.create().bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } @Test public void parseSimpleType() throws IOException, CopperParserException { String input = "type T\n" + " def bar():Int\n" + "5"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); } @Test public void testSimpleType() throws IOException, CopperParserException { String input = "type T\n" + " def bar():Int\n" + "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():T\n" + " new\n" + "C.create().bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } @Test public void testSimpleMetadata() throws IOException, CopperParserException { String input = "class C\n" + " def bar():Int\n" + " 9\n" + " class def create():T\n" + " new\n" + "type T\n" + " def foo():Int\n" + " metadata = C.create()\n" + "T.bar()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(9)"); } // admittedly this is only a starting point.... @Test public void testTrivialDSL() throws IOException, CopperParserException { String input = "val myNumMetadata = /* write me somehow or import from Java */\n" + "type MyNum\n" + " def getValue():Int\n" + " metadata = myNumMetadata\n" + "val n:MyNum = { 5 }" + "n.getValue()"; TypedAST res = (TypedAST)new Wyvern().parse(new StringReader(input), "test input"); Assert.assertEquals(res.typecheck(Globals.getStandardEnv()), Int.getInstance()); Assert.assertEquals(res.evaluate(Globals.getStandardEnv()).toString(), "IntegerConstant(5)"); }
<<<<<<< import wyvern.target.corewyvernIL.FormalArg; ======= import wyvern.target.corewyvernIL.decl.Declaration; >>>>>>> <<<<<<< import wyvern.target.corewyvernIL.decltype.DefDeclType; import wyvern.target.corewyvernIL.decltype.ValDeclType; import wyvern.target.corewyvernIL.type.IntegerType; ======= import wyvern.target.corewyvernIL.expression.ObjectValue; import wyvern.target.corewyvernIL.expression.Value; >>>>>>> import wyvern.target.corewyvernIL.decl.Declaration; import wyvern.target.corewyvernIL.expression.ObjectValue; import wyvern.target.corewyvernIL.expression.Value; <<<<<<< public static ValueType listType() { /* jLinkedList<DeclType> listDecls = new LinkedList<DeclType>(); listDecls.add(new ValDeclType("length", new IntegerType())); listDecls.add(new DefDeclType("getVal", theEmptyType, new LinkedList<FormalArg>())); listDecls.add(new DefDeclType("getVal", new NominalType("system", "List"), new LinkedList<FormalArg>())); return new StructuralType("list", listDecls); */ return new NominalType ("Lists", "List"); } ======= public static Value unitValue() { return new ObjectValue(new LinkedList<Declaration>(), "unitSelf", theUnitType, null, EvalContext.empty()); } >>>>>>> public static ValueType listType() { /* jLinkedList<DeclType> listDecls = new LinkedList<DeclType>(); listDecls.add(new ValDeclType("length", new IntegerType())); listDecls.add(new DefDeclType("getVal", theEmptyType, new LinkedList<FormalArg>())); listDecls.add(new DefDeclType("getVal", new NominalType("system", "List"), new LinkedList<FormalArg>())); return new StructuralType("list", listDecls); */ return new NominalType ("Lists", "List"); public static Value unitValue() { return new ObjectValue(new LinkedList<Declaration>(), "unitSelf", theUnitType, null, EvalContext.empty()); }
<<<<<<< ======= import wyvern.tools.tests.TestUtil; >>>>>>> import wyvern.tools.tests.TestUtil; <<<<<<< ======= @Test @Deprecated public void testHello() throws ParseException { String program = TestUtil.readFile(PATH + "hello.wyv"); /* String input = "requires stdout\n\n" // or stdio, or io, or stdres, but these are not least privilege + "stdout.print(\"Hello, World\")\n"; String altInput = "requires ffi\n" // more explicit version; but resources can be available w/o explicit ffi + "instantiate stdout(ffi)\n\n" + "stdout.print(\"Hello, World\")\n"; // a standard bag of resources is a map from type to resource module impl String stdoutInput = "module stdout.java : stdout\n\n" // the java version + "requires ffi.java as ffi\n\n" // this is the version for the Java platform; others linked in transparently + "instantiate java(ffi)\n\n" // a particular FFI that needs the FFI meta-permission + "import java:java.lang.System\n\n" + "java.lang.System.out\n"; // result of the stdout module - of course could also be wrapped String stdoutSig = "type stdout\n" // type sig for stdout; part of std prelude, so this is always in scope + " def print(String text):void"; */ TypedAST ast = TestUtil.getNewAST(program, "test input"); //Type resultType = ast.typecheck(Globals.getStandardEnv(), Optional.<Type>empty()); TestUtil.evaluateNew(ast); //Assert.assertEquals(resultType, new Int()); //Value out = testAST.evaluate(Globals.getStandardEvalEnv()); //int finalRes = ((IntegerConstant)out).getValue(); //Assert.assertEquals(3, finalRes); } >>>>>>> <<<<<<< ======= private static final String OLD_PATH = BASE_PATH + "rosetta-old/"; @Test public void testNewHello() throws ParseException { TestUtil.doTestScriptModularly("rosetta.hello", null, null); } >>>>>>>
<<<<<<< @Override public Expression generateIL(GenContext ctx) { // TODO Auto-generated method stub return null; } @Override public DeclType genILType(GenContext ctx) { // TODO Auto-generated method stub return null; } @Override public wyvern.target.corewyvernIL.decl.Declaration generateDecl(GenContext ctx, GenContext thisContext) { // TODO Auto-generated method stub return null; } ======= public boolean isResource() { return this.resourceFlag; } >>>>>>> @Override public Expression generateIL(GenContext ctx) { // TODO Auto-generated method stub return null; } @Override public DeclType genILType(GenContext ctx) { // TODO Auto-generated method stub return null; } @Override public wyvern.target.corewyvernIL.decl.Declaration generateDecl(GenContext ctx, GenContext thisContext) { // TODO Auto-generated method stub return null; public boolean isResource() { return this.resourceFlag; }
<<<<<<< public boolean equalsByName(EffectSet other) { HashSet<String> thisEffectSet = new HashSet<String>(); for (Effect e : effectSet) { thisEffectSet.add(e.getName()); } HashSet<String> otherEffectSet = new HashSet<String>(); for (Effect e : other.effectSet) { otherEffectSet.add(e.getName()); } return thisEffectSet.equals(otherEffectSet); } ======= public EffectSet contextualize(GenContext ctx) { if (effectSet.isEmpty()) { return this; } final Set<Effect> newSet = new HashSet<Effect>(); for (final Effect e:effectSet) { newSet.add(e.adaptVariables(ctx)); } return new EffectSet(newSet); } >>>>>>> public boolean equalsByName(EffectSet other) { HashSet<String> thisEffectSet = new HashSet<String>(); for (Effect e : effectSet) { thisEffectSet.add(e.getName()); } HashSet<String> otherEffectSet = new HashSet<String>(); for (Effect e : other.effectSet) { otherEffectSet.add(e.getName()); } return thisEffectSet.equals(otherEffectSet); } public EffectSet contextualize(GenContext ctx) { if (effectSet.isEmpty()) { return this; } final Set<Effect> newSet = new HashSet<Effect>(); for (final Effect e:effectSet) { newSet.add(e.adaptVariables(ctx)); } return new EffectSet(newSet); }
<<<<<<< @Test @Category(CurrentlyBroken.class) public void testType() throws ParseException { String input = "type IntResult\n" + " def getResult():system.Int\n\n" + "val r : IntResult = new\n" + " def getResult():system.Int = 5\n\n" + "r.getResult()\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } @Test @Category(CurrentlyBroken.class) public void testTypeAbbrev() throws ParseException { String input = "type Int = system.Int\n\n" + "val i : Int = 5\n\n" + "i\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } @Test @Category(CurrentlyBroken.class) public void testSimpleDelegation() throws ParseException { String input = "type IntResult\n" + " def getResult():system.Int\n\n" + "val r : IntResult = new\n" + " def getResult():system.Int = 5\n\n" + "val r2 : IntResult = new\n" + " delegate IntResult to r\n\n" + "r2.getResult()\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } ======= @Test public void testSingleModule() throws ParseException { String source = TestUtil.readFile(PATH + "example.wyv"); TypedAST ast = TestUtil.getNewAST(source); GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")).extend("D", new Variable("D"), new NominalType("", "D")); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); } */ @Test public void testMultipleModules() throws ParseException { String[] fileList = {"A.wyt", "B.wyt", "D.wyt", "A.wyv", "D.wyv", "B.wyv", "main.wyv"}; GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")); genCtx = new TypeGenContext("Int", "system", genCtx); for(String fileName : fileList) { System.out.println(fileName); String source = TestUtil.readFile(PATH + fileName); TypedAST ast = TestUtil.getNewAST(source); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); genCtx = GenUtil.link(genCtx, decl); } } /* @Test public void testRecursiveMethod() throws ParseException { String source = TestUtil.readFile(PATH + "recursive.wyv"); TypedAST ast = TestUtil.getNewAST(source); GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")).extend("D", new Variable("D"), new NominalType("", "D")); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); } */ >>>>>>> @Test @Category(CurrentlyBroken.class) public void testType() throws ParseException { String input = "type IntResult\n" + " def getResult():system.Int\n\n" + "val r : IntResult = new\n" + " def getResult():system.Int = 5\n\n" + "r.getResult()\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } @Test @Category(CurrentlyBroken.class) public void testTypeAbbrev() throws ParseException { String input = "type Int = system.Int\n\n" + "val i : Int = 5\n\n" + "i\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } @Test @Category(CurrentlyBroken.class) public void testSimpleDelegation() throws ParseException { String input = "type IntResult\n" + " def getResult():system.Int\n\n" + "val r : IntResult = new\n" + " def getResult():system.Int = 5\n\n" + "val r2 : IntResult = new\n" + " delegate IntResult to r\n\n" + "r2.getResult()\n" ; TypedAST ast = TestUtil.getNewAST(input); // bogus "system" entry, but makes the text work for now GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), null); Expression program = ast.generateIL(genCtx); TypeContext ctx = TypeContext.empty(); ValueType t = program.typeCheck(ctx); Assert.assertEquals(Util.intType(), t); Value v = program.interpret(EvalContext.empty()); IntegerLiteral five = new IntegerLiteral(5); Assert.assertEquals(five, v); } @Test public void testSingleModule() throws ParseException { String source = TestUtil.readFile(PATH + "example.wyv"); TypedAST ast = TestUtil.getNewAST(source); GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")).extend("D", new Variable("D"), new NominalType("", "D")); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); } @Test public void testMultipleModules() throws ParseException { String[] fileList = {"A.wyt", "B.wyt", "D.wyt", "A.wyv", "D.wyv", "B.wyv", "main.wyv"}; GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")); genCtx = new TypeGenContext("Int", "system", genCtx); for(String fileName : fileList) { System.out.println(fileName); String source = TestUtil.readFile(PATH + fileName); TypedAST ast = TestUtil.getNewAST(source); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); genCtx = GenUtil.link(genCtx, decl); } } @Test public void testRecursiveMethod() throws ParseException { String source = TestUtil.readFile(PATH + "recursive.wyv"); TypedAST ast = TestUtil.getNewAST(source); GenContext genCtx = GenContext.empty().extend("system", new Variable("system"), new NominalType("", "system")).extend("D", new Variable("D"), new NominalType("", "D")); wyvern.target.corewyvernIL.decl.Declaration decl = ((Declaration) ast).topLevelGen(genCtx); }
<<<<<<< import wyvern.tools.typedAST.core.expressions.TaggedInfo; ======= import wyvern.tools.typedAST.core.binding.compiler.MetadataInnerBinding; import wyvern.tools.typedAST.core.binding.evaluation.ValueBinding; import wyvern.tools.typedAST.core.binding.objects.TypeDeclBinding; import wyvern.tools.typedAST.core.binding.typechecking.TypeBinding; >>>>>>> import wyvern.tools.typedAST.core.expressions.TaggedInfo; import wyvern.tools.typedAST.core.binding.compiler.MetadataInnerBinding; import wyvern.tools.typedAST.core.binding.evaluation.ValueBinding; import wyvern.tools.typedAST.core.binding.objects.TypeDeclBinding; import wyvern.tools.typedAST.core.binding.typechecking.TypeBinding;
<<<<<<< import com.google.gerrit.reviewdb.client.AccountSshKey; ======= import com.google.gerrit.reviewdb.client.AccountGroupName; >>>>>>> import com.google.gerrit.reviewdb.client.AccountGroupName; import com.google.gerrit.reviewdb.client.AccountSshKey;
<<<<<<< GraphTraversal iter = g.V().order().by(outE().count(), Order.decr); printTraversalForm(iter); ======= GraphTraversal iter = g.V().drop(); >>>>>>> GraphTraversal iter = g.V().drop(); printTraversalForm(iter);
<<<<<<< ======= else if (predicate instanceof Compare) { String predicateString = predicate.toString(); switch (predicateString) { case ("eq"): boolFilterBuilder.must(FilterBuilders.termFilter(key, value)); break; case ("neq"): boolFilterBuilder.mustNot(FilterBuilders.termFilter(key, value)); break; case ("gt"): boolFilterBuilder.must(FilterBuilders.rangeFilter(key).gt(value)); break; case ("gte"): boolFilterBuilder.must(FilterBuilders.rangeFilter(key).gte(value)); break; case ("lt"): boolFilterBuilder.must(FilterBuilders.rangeFilter(key).lt(value)); break; case ("lte"): boolFilterBuilder.must(FilterBuilders.rangeFilter(key).lte(value)); break; case("inside"): List items =(List) value; Object firstItem = items.get(0); Object secondItem = items.get(1); boolFilterBuilder.must(FilterBuilders.rangeFilter(key).from(firstItem).to(secondItem)); break; default: throw new IllegalArgumentException("predicate not supported in has step: " + predicate.toString()); } } else if (predicate instanceof Contains) { if (predicate == Contains.without) boolFilterBuilder.must(FilterBuilders.missingFilter(key)); else if (predicate == Contains.within){ if(value == null) boolFilterBuilder.must(FilterBuilders.existsFilter(key)); else if(value instanceof Iterable) boolFilterBuilder.must(FilterBuilders.termsFilter (key, (Iterable)value)); else boolFilterBuilder.must(FilterBuilders.termsFilter (key, value)); } } else if (predicate instanceof Geo) boolFilterBuilder.must(new GeoShapeFilterBuilder(key, GetShapeBuilder(value), ((Geo) predicate).getRelation())); else throw new IllegalArgumentException("predicate not supported by unipop: " + predicate.toString()); >>>>>>>
<<<<<<< String setting = Files.toString(new File(TCP_BACKLOG_SETTING_LOCATION), Charsets.UTF_8); return Integer.parseInt(setting.trim()); ======= String setting = Files.toString(new File(TCP_BACKLOG_SETTING_LOCATION), StandardCharsets.UTF_8); somaxconn = Integer.parseInt(setting.trim()); >>>>>>> String setting = Files.toString(new File(TCP_BACKLOG_SETTING_LOCATION), StandardCharsets.UTF_8); return Integer.parseInt(setting.trim());
<<<<<<< import org.apache.http.client.config.RequestConfig; import org.apache.http.config.SocketConfig; ======= import org.apache.http.client.params.AllClientPNames; import org.apache.http.client.params.CookiePolicy; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.scheme.SchemeRegistry; >>>>>>> import org.apache.http.client.config.RequestConfig; import org.apache.http.config.SocketConfig; <<<<<<< ======= private final MetricRegistry metricRegistry; private String environmentName; private HttpClientConfiguration configuration = new HttpClientConfiguration(); private DnsResolver resolver = new SystemDefaultDnsResolver(); private HttpRequestRetryHandler httpRequestRetryHandler; private SchemeRegistry registry = SchemeRegistryFactory.createSystemDefault(); private CredentialsProvider credentialsProvider = null; private HttpRoutePlanner routePlanner = null; >>>>>>> <<<<<<< super(environment, new HttpClientConfiguration()); ======= this (environment.metrics()); name(environment.getName()); } /** * Use the given environment name. This is used in the user agent. * * @param environmentName an environment name to use in the user agent. * @return {@code this} */ public HttpClientBuilder name(String environmentName) { this.environmentName = environmentName; return this; } /** * Use the given {@link HttpClientConfiguration} instance. * * @param configuration a {@link HttpClientConfiguration} instance * @return {@code this} */ public HttpClientBuilder using(HttpClientConfiguration configuration) { this.configuration = configuration; return this; } /** * Use the given {@link DnsResolver} instance. * * @param resolver a {@link DnsResolver} instance * @return {@code this} */ public HttpClientBuilder using(DnsResolver resolver) { this.resolver = resolver; return this; } /** * Uses the {@link HttpRequestRetryHandler} for handling request retries. * * @param httpRequestRetryHandler an httpRequestRetryHandler * @return {@code this} */ public HttpClientBuilder using(HttpRequestRetryHandler httpRequestRetryHandler) { this.httpRequestRetryHandler = httpRequestRetryHandler; return this; } /** * Use the given {@link SchemeRegistry} instance. * * @param registry a {@link SchemeRegistry} instance * @return {@code this} */ public HttpClientBuilder using(SchemeRegistry registry) { this.registry = registry; return this; } /** * Use the given {@link HttpRoutePlanner} instance. * * @param routePlanner a {@link HttpRoutePlanner} instance * @return {@code this} */ public HttpClientBuilder using(HttpRoutePlanner routePlanner) { this.routePlanner = routePlanner; return this; } /** * Use the given {@link CredentialsProvider} instance. * * @param credentialsProvider a {@link CredentialsProvider} instance * @return {@code this} */ public HttpClientBuilder using(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; >>>>>>> super(environment, new HttpClientConfiguration()); <<<<<<< builder.setDefaultCredentialsProvider(credentialsProvider); ======= client.setCredentialsProvider(credentialsProvider); } if (routePlanner != null) { client.setRoutePlanner(routePlanner); } } /** * Map the parameters in HttpClientConfiguration to a BasicHttpParams object * * @return a BasicHttpParams object from the HttpClientConfiguration */ protected BasicHttpParams createHttpParams(String name) { final BasicHttpParams params = new BasicHttpParams(); if (configuration.isCookiesEnabled()) { params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } else { params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); >>>>>>> builder.setDefaultCredentialsProvider(credentialsProvider); } if (routePlanner != null) { builder.setRoutePlanner(routePlanner);
<<<<<<< pageable.getPageSize(), Math.toIntExact(pageable.getOffset()))); ======= isLeft, pageable.getPageSize(), pageable.getOffset())); >>>>>>> isLeft, pageable.getPageSize(), Math.toIntExact(pageable.getOffset())));
<<<<<<< ======= import com.fasterxml.jackson.annotation.JsonIgnore; >>>>>>> <<<<<<< public static final String DEFAULT_ACCESS_CONDITIONS = "defaultAccessConditions"; public static final String HARVEST = "harvester"; public static final String LICENSE = "license"; public static final String LOGO = "logo"; public static final String MAPPED_ITEMS = "mappedItems"; ======= public BitstreamRest getLogo() { return logo; } public void setLogo(BitstreamRest logo) { this.logo = logo; } >>>>>>> public static final String HARVEST = "harvester"; public static final String LICENSE = "license"; public static final String LOGO = "logo"; public static final String MAPPED_ITEMS = "mappedItems"; <<<<<<< ======= >>>>>>>
<<<<<<< import org.dspace.app.rest.model.RestModel; import org.springframework.hateoas.ResourceSupport; ======= import org.dspace.app.rest.model.hateoas.HALResource; >>>>>>> import org.dspace.app.rest.model.RestModel; import org.springframework.hateoas.ResourceSupport; import org.dspace.app.rest.model.hateoas.HALResource; <<<<<<< public interface LinkRestRepository<L extends RestModel> { public abstract ResourceSupport wrapResource(L model, String... rels); ======= public interface LinkRestRepository<L extends Serializable> { public abstract HALResource wrapResource(L model, String... rels); >>>>>>> public interface LinkRestRepository<L extends RestModel> { public abstract HALResource wrapResource(L model, String... rels);
<<<<<<< /** * This method retrieves a list of MetadataValue objects that get constructed from processing * the given Item's Relationships through the config given to the {@link VirtualMetadataPopulator} * @param item The Item that will be processed through it's Relationships * @param enableVirtualMetadata This parameter will determine whether the list of Relationship metadata * should be populated with metadata that is being generated through the * VirtualMetadataPopulator functionality or not * @return The list of MetadataValue objects constructed through the Relationships */ public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata); /** * Get metadata for the DSpace Object in a chosen schema. * See <code>MetadataSchema</code> for more information about schemas. * Passing in a <code>null</code> value for <code>qualifier</code> * or <code>lang</code> only matches metadata fields where that * qualifier or languages is actually <code>null</code>. * Passing in <code>DSpaceObject.ANY</code> * retrieves all metadata fields with any value for the qualifier or * language, including <code>null</code> * <P> * Examples: * <P> * Return values of the unqualified "title" field, in any language. * Qualified title fields (e.g. "title.uniform") are NOT returned: * <P> * <code>dspaceobject.getMetadataByMetadataString("dc", "title", null, DSpaceObject.ANY );</code> * <P> * Return all US English values of the "title" element, with any qualifier * (including unqualified): * <P> * <code>dspaceobject.getMetadataByMetadataString("dc, "title", DSpaceObject.ANY, "en_US" );</code> * <P> * The ordering of values of a particular element/qualifier/language * combination is significant. When retrieving with wildcards, values of a * particular element/qualifier/language combinations will be adjacent, but * the overall ordering of the combinations is indeterminate. * * If enableVirtualMetadata is set to false, the virtual metadata will not be included * * @param item Item * @param schema the schema for the metadata field. <em>Must</em> match * the <code>name</code> of an existing metadata schema. * @param element the element name. <code>DSpaceObject.ANY</code> matches any * element. <code>null</code> doesn't really make sense as all * metadata must have an element. * @param qualifier the qualifier. <code>null</code> means unqualified, and * <code>DSpaceObject.ANY</code> means any qualifier (including * unqualified.) * @param lang the ISO639 language code, optionally followed by an underscore * and the ISO3166 country code. <code>null</code> means only * values with no language are returned, and * <code>DSpaceObject.ANY</code> means values with any country code or * no country code are returned. * @param enableVirtualMetadata * Enables virtual metadata calculation and inclusion from the * relationships. * @return metadata fields that match the parameters */ public List<MetadataValue> getMetadata(Item item, String schema, String element, String qualifier, String lang, boolean enableVirtualMetadata); ======= >>>>>>> /** * This method retrieves a list of MetadataValue objects that get constructed from processing * the given Item's Relationships through the config given to the {@link VirtualMetadataPopulator} * @param item The Item that will be processed through it's Relationships * @param enableVirtualMetadata This parameter will determine whether the list of Relationship metadata * should be populated with metadata that is being generated through the * VirtualMetadataPopulator functionality or not * @return The list of MetadataValue objects constructed through the Relationships */ public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata); /** * Get metadata for the DSpace Object in a chosen schema. * See <code>MetadataSchema</code> for more information about schemas. * Passing in a <code>null</code> value for <code>qualifier</code> * or <code>lang</code> only matches metadata fields where that * qualifier or languages is actually <code>null</code>. * Passing in <code>DSpaceObject.ANY</code> * retrieves all metadata fields with any value for the qualifier or * language, including <code>null</code> * <P> * Examples: * <P> * Return values of the unqualified "title" field, in any language. * Qualified title fields (e.g. "title.uniform") are NOT returned: * <P> * <code>dspaceobject.getMetadataByMetadataString("dc", "title", null, DSpaceObject.ANY );</code> * <P> * Return all US English values of the "title" element, with any qualifier * (including unqualified): * <P> * <code>dspaceobject.getMetadataByMetadataString("dc, "title", DSpaceObject.ANY, "en_US" );</code> * <P> * The ordering of values of a particular element/qualifier/language * combination is significant. When retrieving with wildcards, values of a * particular element/qualifier/language combinations will be adjacent, but * the overall ordering of the combinations is indeterminate. * * If enableVirtualMetadata is set to false, the virtual metadata will not be included * * @param item Item * @param schema the schema for the metadata field. <em>Must</em> match * the <code>name</code> of an existing metadata schema. * @param element the element name. <code>DSpaceObject.ANY</code> matches any * element. <code>null</code> doesn't really make sense as all * metadata must have an element. * @param qualifier the qualifier. <code>null</code> means unqualified, and * <code>DSpaceObject.ANY</code> means any qualifier (including * unqualified.) * @param lang the ISO639 language code, optionally followed by an underscore * and the ISO3166 country code. <code>null</code> means only * values with no language are returned, and * <code>DSpaceObject.ANY</code> means values with any country code or * no country code are returned. * @param enableVirtualMetadata * Enables virtual metadata calculation and inclusion from the * relationships. * @return metadata fields that match the parameters */ public List<MetadataValue> getMetadata(Item item, String schema, String element, String qualifier, String lang, boolean enableVirtualMetadata);
<<<<<<< @Autowired(required=true) protected ConfigurationService configurationService; ======= @Autowired(required=true) protected WorkspaceItemService workspaceItemService; @Autowired(required=true) protected WorkflowItemService workflowItemService; >>>>>>> @Autowired(required=true) protected ConfigurationService configurationService; @Autowired(required=true) protected WorkspaceItemService workspaceItemService; @Autowired(required=true) protected WorkflowItemService workflowItemService; <<<<<<< @Override public boolean canCreateNewVersion(Context context, Item item) throws SQLException{ if (authorizeService.isAdmin(context, item)) { return true; } ======= /** * Check if the item is an inprogress submission * @param context * @param item * @return <code>true</code> if the item is an inprogress submission, i.e. a WorkspaceItem or WorkflowItem * @throws SQLException */ public boolean isInProgressSubmission(Context context, Item item) throws SQLException { return workspaceItemService.findByItem(context, item) != null || workflowItemService.findByItem(context, item) != null; } /* With every finished submission a bunch of resource policy entries with have null value for the dspace_object column are generated in the database. prevent the generation of resource policy entry values with null dspace_object as value >>>>>>> /** * Check if the item is an inprogress submission * @param context * @param item * @return <code>true</code> if the item is an inprogress submission, i.e. a WorkspaceItem or WorkflowItem * @throws SQLException */ public boolean isInProgressSubmission(Context context, Item item) throws SQLException { return workspaceItemService.findByItem(context, item) != null || workflowItemService.findByItem(context, item) != null; } /* With every finished submission a bunch of resource policy entries with have null value for the dspace_object column are generated in the database. prevent the generation of resource policy entry values with null dspace_object as value */ @Override /** * Add the default policies, which have not been already added to the given DSpace object * * @param context * @param dso * @param defaultCollectionPolicies * @throws SQLException * @throws AuthorizeException */ protected void addDefaultPoliciesNotInPlace(Context context, DSpaceObject dso, List<ResourcePolicy> defaultCollectionPolicies) throws SQLException, AuthorizeException { for (ResourcePolicy defaultPolicy : defaultCollectionPolicies) { if (!authorizeService.isAnIdenticalPolicyAlreadyInPlace(context, dso, defaultPolicy.getGroup(), Constants.READ, defaultPolicy.getID())) { ResourcePolicy newPolicy = resourcePolicyService.clone(context, defaultPolicy); newPolicy.setdSpaceObject(dso); newPolicy.setAction(Constants.READ); newPolicy.setRpType(ResourcePolicy.TYPE_INHERITED); resourcePolicyService.update(context, newPolicy); } } } /** * Returns an iterator of Items possessing the passed metadata field, or only * those matching the passed value, if value is not Item.ANY * * @param context DSpace context object * @param schema metadata field schema * @param element metadata field element * @param qualifier metadata field qualifier * @param value field value or Item.ANY to match any value * @return an iterator over the items matching that authority value * @throws SQLException if database error * @throws AuthorizeException if authorization error * @throws IOException if IO error * */ @Override public Iterator<Item> findByMetadataField(Context context, String schema, String element, String qualifier, String value) throws SQLException, AuthorizeException, IOException { MetadataSchema mds = metadataSchemaService.find(context, schema); if (mds == null) { throw new IllegalArgumentException("No such metadata schema: " + schema); } MetadataField mdf = metadataFieldService.findByElement(context, mds, element, qualifier); if (mdf == null) { throw new IllegalArgumentException( "No such metadata field: schema=" + schema + ", element=" + element + ", qualifier=" + qualifier); } if (Item.ANY.equals(value)) { return itemDAO.findByMetadataField(context, mdf, null, true); } else { return itemDAO.findByMetadataField(context, mdf, value, true); } } @Override public Iterator<Item> findByMetadataQuery(Context context, List<List<MetadataField>> listFieldList, List<String> query_op, List<String> query_val, List<UUID> collectionUuids, String regexClause, int offset, int limit) throws SQLException, AuthorizeException, IOException { return itemDAO.findByMetadataQuery(context, listFieldList, query_op, query_val, collectionUuids, regexClause, offset, limit); } @Override public DSpaceObject getAdminObject(Context context, Item item, int action) throws SQLException { DSpaceObject adminObject = null; //Items are always owned by collections Collection collection = (Collection) getParentObject(context, item); Community community = null; if (collection != null) { if(CollectionUtils.isNotEmpty(collection.getCommunities())) { community = collection.getCommunities().get(0); } } switch (action) { case Constants.ADD: // ADD a cc license is less general than add a bitstream but we can't/won't // add complex logic here to know if the ADD action on the item is required by a cc or // a generic bitstream so simply we ignore it.. UI need to enforce the requirements. if (AuthorizeConfiguration.canItemAdminPerformBitstreamCreation()) { adminObject = item; } else if (AuthorizeConfiguration.canCollectionAdminPerformBitstreamCreation()) { adminObject = collection; } else if (AuthorizeConfiguration.canCommunityAdminPerformBitstreamCreation()) { adminObject = community; } break; case Constants.REMOVE: // see comments on ADD action, same things... if (AuthorizeConfiguration.canItemAdminPerformBitstreamDeletion()) { adminObject = item; } else if (AuthorizeConfiguration.canCollectionAdminPerformBitstreamDeletion()) { adminObject = collection; } else if (AuthorizeConfiguration.canCommunityAdminPerformBitstreamDeletion()) { adminObject = community; } break; case Constants.DELETE: if (item.getOwningCollection() != null) { if (AuthorizeConfiguration.canCollectionAdminPerformItemDeletion()) { adminObject = collection; } else if (AuthorizeConfiguration.canCommunityAdminPerformItemDeletion()) { adminObject = community; } } else { if (AuthorizeConfiguration.canCollectionAdminManageTemplateItem()) { adminObject = collection; } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionTemplateItem()) { adminObject = community; } } break; case Constants.WRITE: // if it is a template item we need to check the // collection/community admin configuration if (item.getOwningCollection() == null) { if (AuthorizeConfiguration.canCollectionAdminManageTemplateItem()) { adminObject = collection; } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionTemplateItem()) { adminObject = community; } } else { adminObject = item; } break; default: adminObject = item; break; } return adminObject; } @Override public DSpaceObject getParentObject(Context context, Item item) throws SQLException { Collection ownCollection = item.getOwningCollection(); if (ownCollection != null) { return ownCollection; } else { // is a template item? return item.getTemplateItemOf(); } } @Override public Iterator<Item> findByAuthorityValue(Context context, String schema, String element, String qualifier, String value) throws SQLException, AuthorizeException { MetadataSchema mds = metadataSchemaService.find(context, schema); if (mds == null) { throw new IllegalArgumentException("No such metadata schema: " + schema); } MetadataField mdf = metadataFieldService.findByElement(context, mds, element, qualifier); if (mdf == null) { throw new IllegalArgumentException("No such metadata field: schema=" + schema + ", element=" + element + ", qualifier=" + qualifier); } return itemDAO.findByAuthorityValue(context, mdf, value, true); } @Override public Iterator<Item> findByMetadataFieldAuthority(Context context, String mdString, String authority) throws SQLException, AuthorizeException { String[] elements = getElementsFilled(mdString); String schema = elements[0], element = elements[1], qualifier = elements[2]; MetadataSchema mds = metadataSchemaService.find(context, schema); if (mds == null) { throw new IllegalArgumentException("No such metadata schema: " + schema); } MetadataField mdf = metadataFieldService.findByElement(context, mds, element, qualifier); if (mdf == null) { throw new IllegalArgumentException( "No such metadata field: schema=" + schema + ", element=" + element + ", qualifier=" + qualifier); } return findByAuthorityValue(context, mds.getName(), mdf.getElement(), mdf.getQualifier(), authority); } @Override public boolean isItemListedForUser(Context context, Item item) { try { if (authorizeService.isAdmin(context)) { return true; } if (authorizeService.authorizeActionBoolean(context, item, org.dspace.core.Constants.READ)) { if(item.isDiscoverable()) { return true; } } log.debug("item(" + item.getID() + ") " + item.getName() + " is unlisted."); return false; } catch (SQLException e) { log.error(e.getMessage()); return false; } } @Override public int countItems(Context context, Collection collection) throws SQLException { return itemDAO.countItems(context, collection, true, false); } @Override public int countItems(Context context, Community community) throws SQLException { // First we need a list of all collections under this community in the hierarchy List<Collection> collections = communityService.getAllCollections(context, community); // Now, lets count unique items across that list of collections return itemDAO.countItems(context, collections, true, false); } @Override protected void getAuthoritiesAndConfidences(String fieldKey, Collection collection, List<String> values, List<String> authorities, List<Integer> confidences, int i) { Choices c = choiceAuthorityService.getBestMatch(fieldKey, values.get(i), collection, null); authorities.add(c.values.length > 0 ? c.values[0].authority : null); confidences.add(c.confidence); } @Override public Item findByIdOrLegacyId(Context context, String id) throws SQLException { if(StringUtils.isNumeric(id)) { return findByLegacyId(context, Integer.parseInt(id)); } else { return find(context, UUID.fromString(id)); } } @Override public Item findByLegacyId(Context context, int id) throws SQLException { return itemDAO.findByLegacyId(context, id, Item.class); } @Override public Iterator<Item> findByLastModifiedSince(Context context, Date last) throws SQLException { return itemDAO.findByLastModifiedSince(context, last); } @Override public int countTotal(Context context) throws SQLException { return itemDAO.countRows(context); } @Override public int countNotArchivedItems(Context context) throws SQLException { // return count of items not in archive and also not withdrawn return itemDAO.countItems(context, false, false); } @Override public int countWithdrawnItems(Context context) throws SQLException { // return count of items that are not in archive and withdrawn return itemDAO.countItems(context, false, true); } public boolean canCreateNewVersion(Context context, Item item) throws SQLException{ if (authorizeService.isAdmin(context, item)) { return true; }
<<<<<<< import org.dspace.content.Collection; ======= import org.dspace.authorize.service.ResourcePolicyService; >>>>>>> import org.dspace.authorize.service.ResourcePolicyService; import org.dspace.content.Collection;
<<<<<<< import org.dspace.app.rest.builder.CollectionBuilder; import org.dspace.app.rest.builder.CommunityBuilder; import org.dspace.app.rest.builder.EPersonBuilder; import org.dspace.app.rest.builder.ItemBuilder; import org.dspace.app.rest.builder.MetadataFieldBuilder; import org.dspace.app.rest.builder.RelationshipBuilder; ======= >>>>>>>
<<<<<<< ======= import org.dspace.app.rest.exception.UnprocessableEntityException; import org.dspace.app.rest.model.ItemRest; >>>>>>> import org.dspace.app.rest.exception.UnprocessableEntityException; <<<<<<< if (supports(object, operation)) { Item item = (Item) object; item.setDiscoverable(discoverable); return object; } else { throw new DSpaceBadRequestException("ItemDiscoverableReplaceOperation does not support this operation"); ======= if (discoverable) { if (item.getTemplateItemOf() != null) { throw new UnprocessableEntityException("A template item cannot be discoverable."); } } item.setDiscoverable(discoverable); return item; } @Override void checkModelForExistingValue(ItemRest resource, Operation operation) { if ((Object) resource.getDiscoverable() == null) { throw new DSpaceBadRequestException("Attempting to replace a non-existent value."); >>>>>>> if (supports(object, operation)) { Item item = (Item) object; if (discoverable) { if (item.getTemplateItemOf() != null) { throw new UnprocessableEntityException("A template item cannot be discoverable."); } } item.setDiscoverable(discoverable); return object; } else { throw new DSpaceBadRequestException("ItemDiscoverableReplaceOperation does not support this operation");
<<<<<<< private static final Logger log = Logger.getLogger(AbstractDSpaceRestRepository.class); ======= >>>>>>>
<<<<<<< import org.apache.commons.lang.StringUtils; import org.dspace.content.MetadataSchemaEnum; ======= import org.apache.commons.lang3.StringUtils; import org.dspace.content.MetadataSchema; >>>>>>> import org.apache.commons.lang3.StringUtils; import org.dspace.content.MetadataSchemaEnum;
<<<<<<< import org.dspace.app.util.SubmissionStepConfig; import org.dspace.browse.IndexableObject; import org.dspace.content.Collection; import org.dspace.content.Item; import org.dspace.content.WorkspaceItem; import org.dspace.eperson.EPerson; import org.springframework.beans.factory.annotation.Autowired; ======= import org.dspace.browse.BrowsableObject; import org.dspace.content.WorkspaceItem; >>>>>>> import org.dspace.browse.IndexableObject; import org.dspace.content.WorkspaceItem; <<<<<<< implements IndexableDSpaceObjectConverter<org.dspace.content.WorkspaceItem, org.dspace.app.rest.model.WorkspaceItemRest> { private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(WorkspaceItemConverter.class); @Autowired private EPersonConverter epersonConverter; @Autowired private ItemConverter itemConverter; @Autowired private CollectionConverter collectionConverter; private SubmissionConfigReader submissionConfigReader; @Autowired private SubmissionDefinitionConverter submissionDefinitionConverter; @Autowired private SubmissionSectionConverter submissionSectionConverter; @Autowired SubmissionService submissionService; ======= extends AInprogressItemConverter<WorkspaceItem, WorkspaceItemRest, Integer> { >>>>>>> extends AInprogressItemConverter<WorkspaceItem, WorkspaceItemRest, Integer> {
<<<<<<< ======= import org.dspace.app.rest.converter.BitstreamConverter; import org.dspace.app.rest.converter.CommunityConverter; import org.dspace.app.rest.converter.MetadataConverter; >>>>>>> <<<<<<< public CommunityRestRepository(CommunityService dsoService) { super(dsoService, new DSpaceObjectPatch<CommunityRest>() {}); this.cs = dsoService; ======= @Autowired private CommunityService cs; @Autowired private BitstreamService bitstreamService; public CommunityRestRepository(CommunityService dsoService, CommunityConverter dsoConverter) { super(dsoService, dsoConverter, new DSpaceObjectPatch<CommunityRest>() {}); >>>>>>> public CommunityRestRepository(CommunityService dsoService) { super(dsoService, new DSpaceObjectPatch<CommunityRest>() {}); this.cs = dsoService;
<<<<<<< public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean extra); ======= public List<MetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata); >>>>>>> public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata);
<<<<<<< List<RelationshipType> findByLeftOrRightLabel(Context context, String label) throws SQLException; ======= List<RelationshipType> findByEntityType(Context context, EntityType entityType) throws SQLException; >>>>>>> List<RelationshipType> findByLeftOrRightLabel(Context context, String label) throws SQLException; List<RelationshipType> findByEntityType(Context context, EntityType entityType) throws SQLException;
<<<<<<< if (supports(object, operation)) { Item item = (Item) object; // This is a request to withdraw the item. try { if (withdraw) { // The item is currently not withdrawn and also not archived. Is this a possible situation? if (!item.isWithdrawn() && !item.isArchived()) { throw new UnprocessableEntityException("Cannot withdraw item when it is not in archive."); } // Item is already withdrawn. No-op, 200 response. // (The operation is not idempotent since it results in a provenance note in the record.) if (item.isWithdrawn()) { return object; } itemService.withdraw(context, item); return object; ======= // This is a request to withdraw the item. if (withdraw) { if (item.getTemplateItemOf() != null) { throw new UnprocessableEntityException("A template item cannot be withdrawn."); } // The item is currently not withdrawn and also not archived. Is this a possible situation? if (!item.getWithdrawn() && !item.getInArchive()) { throw new UnprocessableEntityException("Cannot withdraw item when it is not in archive."); } // Item is already withdrawn. No-op, 200 response. // (The operation is not idempotent since it results in a provenance note in the record.) if (item.getWithdrawn()) { return item; } item.setWithdrawn(true); return item; >>>>>>> if (supports(object, operation)) { Item item = (Item) object; // This is a request to withdraw the item. try { if (withdraw) { if (item.getTemplateItemOf() != null) { throw new UnprocessableEntityException("A template item cannot be withdrawn."); } // The item is currently not withdrawn and also not archived. Is this a possible situation? if (!item.isWithdrawn() && !item.isArchived()) { throw new UnprocessableEntityException("Cannot withdraw item when it is not in archive."); } // Item is already withdrawn. No-op, 200 response. // (The operation is not idempotent since it results in a provenance note in the record.) if (item.isWithdrawn()) { return object; } itemService.withdraw(context, item); return object;
<<<<<<< ======= import org.dspace.workflow.WorkflowException; import org.dspace.xmlworkflow.Role; >>>>>>> import org.dspace.xmlworkflow.Role; <<<<<<< private static final String SUBMIT_CANCEL = "submit_cancel"; private static final String SUBMIT_SEARCH = "submit_search"; private static final String SUBMIT_SELECT_REVIEWER = "submit_select_reviewer_"; private String roleId; ======= private Role role; >>>>>>> private static final String SUBMIT_CANCEL = "submit_cancel"; private static final String SUBMIT_SEARCH = "submit_search"; private static final String SUBMIT_SELECT_REVIEWER = "submit_select_reviewer_"; private Role role; <<<<<<< @Override public List<String> getOptions() { List<String> options = new ArrayList<>(); options.add(SUBMIT_SEARCH); options.add(SUBMIT_SELECT_REVIEWER); return options; } public String getRoleId() { return roleId; ======= public Role getRole() { return role; >>>>>>> @Override public List<String> getOptions() { List<String> options = new ArrayList<>(); options.add(SUBMIT_SEARCH); options.add(SUBMIT_SELECT_REVIEWER); return options; } public Role getRole() { return role;
<<<<<<< @Autowired SearchService searchService; @Autowired AuthorizeService authorizeService; ======= @Autowired private CommunityService cs; >>>>>>> @Autowired SearchService searchService; @Autowired AuthorizeService authorizeService; private CommunityService cs;
<<<<<<< import org.dspace.content.service.ItemService; ======= import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.DSpaceObjectService; import org.dspace.core.ConfigurationManager; >>>>>>> import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.DSpaceObjectService;
<<<<<<< import java.util.ArrayList; ======= import java.sql.SQLException; import java.util.LinkedList; >>>>>>> <<<<<<< ======= import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; >>>>>>> import java.util.stream.Collectors; <<<<<<< import org.dspace.app.rest.model.MetadataValueList; import org.dspace.app.rest.projection.Projection; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; ======= import org.dspace.app.rest.model.RelationshipRest; import org.dspace.app.rest.utils.ContextUtil; >>>>>>> import org.dspace.app.rest.model.MetadataValueList; import org.dspace.app.rest.projection.Projection; <<<<<<< ======= @Autowired(required = true) private CollectionConverter collectionConverter; @Autowired(required = true) private BundleConverter bundleConverter; >>>>>>> <<<<<<< List<BitstreamRest> bitstreams = new ArrayList<>(); for (Bundle bun : obj.getBundles()) { for (Bitstream bit : bun.getBitstreams()) { bitstreams.add(converter.toRest(bit, projection)); } } item.setBitstreams(bitstreams); ======= item.setBundles(obj.getBundles() .stream() .map(x -> bundleConverter.fromModel(x)) .collect(Collectors.toList())); List<Relationship> relationships = new LinkedList<>(); try { Context context; Request currentRequest = requestService.getCurrentRequest(); if (currentRequest != null) { HttpServletRequest request = currentRequest.getHttpServletRequest(); context = ContextUtil.obtainContext(request); } else { context = new Context(); } relationships = relationshipService.findByItem(context, obj); } catch (SQLException e) { log.error("Error retrieving relationships for item " + item.getHandle(), e); } List<RelationshipRest> relationshipRestList = new LinkedList<>(); for (Relationship relationship : relationships) { RelationshipRest relationshipRest = relationshipConverter.fromModel(relationship); relationshipRestList.add(relationshipRest); } item.setRelationships(relationshipRestList); List<MetadataValue> fullList = new LinkedList<>(); fullList = itemService.getMetadata(obj, Item.ANY, Item.ANY, Item.ANY, Item.ANY, true); item.setMetadata(metadataConverter.convert(fullList)); >>>>>>> item.setBundles(obj.getBundles() .stream() .map(x -> (BundleRest) converter.toRest(x, projection)) .collect(Collectors.toList()));
<<<<<<< String getValue(Context context, Item item) throws SQLException; /** * Generic setter for the useForPlace property * @param useForPlace The boolean value that the useForPlace property will be set to */ void setUseForPlace(boolean useForPlace); /** * Generic getter for the useForPlace property * @return The useForPlace to be used by this bean */ boolean getUseForPlace(); ======= List<String> getValues(Context context, Item item) throws SQLException; >>>>>>> List<String> getValues(Context context, Item item) throws SQLException; /** * Generic setter for the useForPlace property * @param useForPlace The boolean value that the useForPlace property will be set to */ void setUseForPlace(boolean useForPlace); /** * Generic getter for the useForPlace property * @return The useForPlace to be used by this bean */ boolean getUseForPlace();
<<<<<<< import org.dspace.content.DSpaceObject; ======= import org.dspace.content.service.MetadataFieldService; >>>>>>> import org.dspace.content.DSpaceObject; import org.dspace.content.service.MetadataFieldService; <<<<<<< /** * Apply an update to the REST object via JSON PUT * * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object */ public T put(HttpServletRequest request, String apiCategory, String model, ID id, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, id, jsonNode); context.commit(); } catch (SQLException | AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } return findOne(id); } /** * Method to support updating a DSpace instance. * * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param dSpaceObjects The list of DSpaceObjects that will be used as data for the put * @return the updated REST object */ public T put(HttpServletRequest request, String apiCategory, String model, ID id, List<DSpaceObject> dSpaceObjects) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, id, dSpaceObjects); context.commit(); } catch (SQLException | AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } return findOne(id); } /** * Implement this method in the subclass to support updating a REST object. * * @param context the dspace context * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object * @throws AuthorizeException if the context user is not authorized to perform this operation * @throws SQLException when the database returns an error * @throws RepositoryMethodNotImplementedException * returned by the default implementation when the operation is not supported for the entity */ protected T put(Context context, HttpServletRequest request, String apiCategory, String model, ID id, JsonNode jsonNode) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException { throw new RepositoryMethodNotImplementedException(apiCategory, model); } /** * Implement this method in the subclass to support updating a DSpace instance. * * @param context the dspace context * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param dSpaceObjects The list of DSpaceObjects that will be used as data for the put * @return the updated REST object * @throws AuthorizeException if the context user is not authorized to perform this operation * @throws SQLException when the database returns an error * @throws RepositoryMethodNotImplementedException * returned by the default implementation when the operation is not supported for the entity */ protected T put(Context context, HttpServletRequest request, String apiCategory, String model, ID id, List<DSpaceObject> dSpaceObjects) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException { throw new RepositoryMethodNotImplementedException(apiCategory, model); } ======= /** * This method will fully replace the REST object with the given UUID with the REST object that is described * in the JsonNode parameter * * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param uuid the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object */ public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException e) { throw new RuntimeException("Unable to update DSpace object " + model + " with id=" + uuid, e); } catch (AuthorizeException e) { throw new RuntimeException("Unable to perform PUT request as the " + "current user does not have sufficient rights", e); } return findOne(uuid); } /** * Implement this method in the subclass to support the PUT functionality for a REST object. * This PUT functionality will fully replace the REST object with the given UUID with the REST object that is * described in the JsonNode parameter * * @param context the dspace context * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object * @throws AuthorizeException if the context user is not authorized to perform this operation * @throws SQLException when the database returns an error * @throws RepositoryMethodNotImplementedException * returned by the default implementation when the operation is not supported for the entity */ protected T put(Context context, HttpServletRequest request, String apiCategory, String model, ID id, JsonNode jsonNode) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException { throw new RepositoryMethodNotImplementedException(apiCategory, model); } >>>>>>> /** * This method will fully replace the REST object with the given UUID with the REST object that is described * in the JsonNode parameter * * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param uuid the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object */ public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException e) { throw new RuntimeException("Unable to update DSpace object " + model + " with id=" + uuid, e); } catch (AuthorizeException e) { throw new RuntimeException("Unable to perform PUT request as the " + "current user does not have sufficient rights", e); } return findOne(uuid); } /** * Method to support updating a DSpace instance. * * @param request the http request * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param dSpaceObjects The list of DSpaceObjects that will be used as data for the put * @return the updated REST object */ public T put(HttpServletRequest request, String apiCategory, String model, ID id, List<DSpaceObject> dSpaceObjects) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, id, dSpaceObjects); context.commit(); } catch (SQLException | AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } return findOne(id); } /** * Implement this method in the subclass to support updating a REST object. * * @param context the dspace context * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param jsonNode the part of the request body representing the updated rest object * @return the updated REST object * @throws AuthorizeException if the context user is not authorized to perform this operation * @throws SQLException when the database returns an error * @throws RepositoryMethodNotImplementedException * returned by the default implementation when the operation is not supported for the entity */ protected T put(Context context, HttpServletRequest request, String apiCategory, String model, ID id, JsonNode jsonNode) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException { throw new RepositoryMethodNotImplementedException(apiCategory, model); } /** * Implement this method in the subclass to support updating a DSpace instance. * * @param context the dspace context * @param apiCategory the API category e.g. "api" * @param model the DSpace model e.g. "metadatafield" * @param id the ID of the target REST object * @param dSpaceObjects The list of DSpaceObjects that will be used as data for the put * @return the updated REST object * @throws AuthorizeException if the context user is not authorized to perform this operation * @throws SQLException when the database returns an error * @throws RepositoryMethodNotImplementedException * returned by the default implementation when the operation is not supported for the entity */ protected T put(Context context, HttpServletRequest request, String apiCategory, String model, ID id, List<DSpaceObject> dSpaceObjects) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException { throw new RepositoryMethodNotImplementedException(apiCategory, model); }
<<<<<<< /** * Boolean indicating whether the parameter is mandatory or not */ private boolean mandatory; ======= /** * The long name of the parameter */ private String nameLong; /** * Boolean indicating whether the parameter is mandatory or not */ private boolean mandatory; >>>>>>> /** * Boolean indicating whether the parameter is mandatory or not */ private boolean mandatory; /** * The long name of the parameter */ private String nameLong; <<<<<<< /** * Generic getter for the mandatory * @return the mandatory value of this ParameterRest */ public boolean isMandatory() { return mandatory; } /** * Generic setter for the mandatory * @param mandatory The mandatory to be set on this ParameterRest */ public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } ======= /** * Generic getter for the nameLong * @return the nameLong value of this ParameterRest */ public String getNameLong() { return nameLong; } /** * Generic setter for the nameLong * @param nameLong The nameLong to be set on this ParameterRest */ public void setNameLong(String nameLong) { this.nameLong = nameLong; } /** * Generic getter for the mandatory * @return the mandatory value of this ParameterRest */ public boolean isMandatory() { return mandatory; } /** * Generic setter for the mandatory * @param mandatory The mandatory to be set on this ParameterRest */ public void setMandatory(boolean mandatory) { this.mandatory = mandatory; } >>>>>>> /** * Generic getter for the nameLong * @return the nameLong value of this ParameterRest */ public String getNameLong() { return nameLong; } /** * Generic setter for the nameLong * @param nameLong The nameLong to be set on this ParameterRest */ public void setNameLong(String nameLong) { this.nameLong = nameLong; } /** * Generic getter for the mandatory * @return the mandatory value of this ParameterRest */ public boolean isMandatory() { return mandatory; } /** * Generic setter for the mandatory * @param mandatory The mandatory to be set on this ParameterRest */ public void setMandatory(boolean mandatory) { this.mandatory = mandatory; }
<<<<<<< DirectlyAddressableRestModel data = r.getData(); ======= RestModel data = r.getContent(); >>>>>>> DirectlyAddressableRestModel data = r.getContent(); <<<<<<< public Link linkToSingleResource(DirectlyAddressableRestModel data, String rel) { return linkTo(data.getController(), data.getCategory(), English.plural(data.getType())).slash(data) ======= public Link linkToSingleResource(RestModel data, String rel) { return linkTo(data.getController(), data.getCategory(), data.getTypePlural()).slash(data) >>>>>>> public Link linkToSingleResource(DirectlyAddressableRestModel data, String rel) { return linkTo(data.getController(), data.getCategory(), data.getTypePlural()).slash(data) <<<<<<< public Link linkToSubResource(DirectlyAddressableRestModel data, String rel, String path) { return linkTo(data.getController(), data.getCategory(), English.plural(data.getType())).slash(data).slash(path) ======= public Link linkToSubResource(RestModel data, String rel, String path) { return linkTo(data.getController(), data.getCategory(), data.getTypePlural()).slash(data).slash(path) >>>>>>> public Link linkToSubResource(DirectlyAddressableRestModel data, String rel, String path) { return linkTo(data.getController(), data.getCategory(), data.getTypePlural()).slash(data).slash(path) <<<<<<< ======= /** * Build the canonical representation of a metadata key in DSpace. ie * <schema>.<element>[.<qualifier>] * * @param schema * @param element * @param object * @return */ public String getMetadataKey(String schema, String element, String qualifier) { return schema + "." + element + (StringUtils.isNotBlank(qualifier) ? "." + qualifier : ""); } >>>>>>> /** * Build the canonical representation of a metadata key in DSpace. ie * <schema>.<element>[.<qualifier>] * * @param schema * @param element * @param object * @return */ public String getMetadataKey(String schema, String element, String qualifier) { return org.dspace.core.Utils.standardize(schema, element, qualifier, "."); }
<<<<<<< @Override public List<Process> search(Context context, ProcessQueryParameterContainer processQueryParameterContainer, int limit, int offset) throws SQLException { return processDAO.search(context, processQueryParameterContainer, limit, offset); } @Override public int countSearch(Context context, ProcessQueryParameterContainer processQueryParameterContainer) throws SQLException { return processDAO.countTotalWithParameters(context, processQueryParameterContainer); } ======= @Override public void appendLog(int processId, String scriptName, String output, ProcessLogLevel processLogLevel) throws IOException { File tmpDir = FileUtils.getTempDirectory(); File tempFile = new File(tmpDir, scriptName + processId + ".log"); FileWriter out = new FileWriter(tempFile, true); try { try (BufferedWriter writer = new BufferedWriter(out)) { writer.append(formatLogLine(processId, scriptName, output, processLogLevel)); writer.newLine(); } } finally { out.close(); } } @Override public void createLogBitstream(Context context, Process process) throws IOException, SQLException, AuthorizeException { File tmpDir = FileUtils.getTempDirectory(); File tempFile = new File(tmpDir, process.getName() + process.getID() + ".log"); FileInputStream inputStream = FileUtils.openInputStream(tempFile); appendFile(context, process, inputStream, Process.OUTPUT_TYPE, process.getName() + process.getID() + ".log"); inputStream.close(); tempFile.delete(); } private String formatLogLine(int processId, String scriptName, String output, ProcessLogLevel processLogLevel) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); StringBuilder sb = new StringBuilder(); sb.append(sdf.format(new Date())); sb.append(" "); sb.append(processLogLevel); sb.append(" "); sb.append(scriptName); sb.append(" - "); sb.append(processId); sb.append(" @ "); sb.append(output); return sb.toString(); } >>>>>>> @Override public List<Process> search(Context context, ProcessQueryParameterContainer processQueryParameterContainer, int limit, int offset) throws SQLException { return processDAO.search(context, processQueryParameterContainer, limit, offset); } @Override public int countSearch(Context context, ProcessQueryParameterContainer processQueryParameterContainer) throws SQLException { return processDAO.countTotalWithParameters(context, processQueryParameterContainer); } @Override public void appendLog(int processId, String scriptName, String output, ProcessLogLevel processLogLevel) throws IOException { File tmpDir = FileUtils.getTempDirectory(); File tempFile = new File(tmpDir, scriptName + processId + ".log"); FileWriter out = new FileWriter(tempFile, true); try { try (BufferedWriter writer = new BufferedWriter(out)) { writer.append(formatLogLine(processId, scriptName, output, processLogLevel)); writer.newLine(); } } finally { out.close(); } } @Override public void createLogBitstream(Context context, Process process) throws IOException, SQLException, AuthorizeException { File tmpDir = FileUtils.getTempDirectory(); File tempFile = new File(tmpDir, process.getName() + process.getID() + ".log"); FileInputStream inputStream = FileUtils.openInputStream(tempFile); appendFile(context, process, inputStream, Process.OUTPUT_TYPE, process.getName() + process.getID() + ".log"); inputStream.close(); tempFile.delete(); } private String formatLogLine(int processId, String scriptName, String output, ProcessLogLevel processLogLevel) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); StringBuilder sb = new StringBuilder(); sb.append(sdf.format(new Date())); sb.append(" "); sb.append(processLogLevel); sb.append(" "); sb.append(scriptName); sb.append(" - "); sb.append(processId); sb.append(" @ "); sb.append(output); return sb.toString(); }