Xpages and EL: Syntax for retrieving HashMap Values - xpages

I have a cacheBean written in Java. I am successfully pulling out Vectors using EL, but I have a HashMap and when I try to access a value I throw an error.
My cacheBean is:
package com.scoular.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewNavigator;
public class PCConfig implements Serializable {
private static final long serialVersionUID = 1L;
private Database thisDB;
private Database compDirDB;
public Database PCDataDB;
public HashMap<Integer, String> status = new HashMap<Integer, String>();
public static Vector<Object> geoLocations = new Vector<Object>();
public static Vector<Object> models = new Vector<Object>();
// #SuppressWarnings("unchecked")
private void initConfigData() {
try {
getStatus();
getGeoLocations();
getModels();
} catch (Exception e) {
e.printStackTrace();
}
}
public PCConfig() {
// initialize application config
System.out.println("Starting CacheBean");
initConfigData();
System.out.println("Ending CacheBean");
}
public static void setModels(Vector<Object> models) {
PCConfig.models = models;
}
public void getStatus() {
status.put(1, "In Inventory");
status.put(2, "Being Built");
status.put(3, "In Production");
status.put(4, "Aquiring PC");
status.put(5, "Decommissioning");
}
public Vector<Object> getGeoLocations() {
if (PCConfig.geoLocations == null || PCConfig.geoLocations.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
compDirDB = session.getDatabase(thisDB.getServer(), "compdir.nsf", false);
View geoView = compDirDB.getView("xpGeoLocationsByName");
for (ViewEntry ce : geoView.getAllEntries()) {
Vector<Object> rowVal = ce.getColumnValues();
geoLocations.addElement(rowVal.elementAt(0));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return geoLocations;
}
public Vector<Object> getModels() {
if (PCConfig.models == null || PCConfig.models.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
PCDataDB = session.getDatabase(thisDB.getServer(), "scoApps\\PC\\PCData.nsf", false);
ViewNavigator vn = PCDataDB.getView("dbLookupModels").createViewNav();
ViewEntry entry = vn.getFirstDocument();
while (entry != null) {
Vector<Object> thisCat = entry.getColumnValues();
if (entry.isCategory()) {
String thisCatString = thisCat.elementAt(0).toString();
models.addElement(thisCatString);
}
entry = vn.getNext(entry);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return models;
}
}
and the code to grab the a value is:
<xp:text escape="true" id="computedField2">
<xp:this.value><![CDATA[#{PCConfig.status[0]}]]></xp:this.value></xp:text>

Your method getStatus() has to return the HashMap.
public HashMap<Integer, String> getStatus() {
...
return status;
}
In addition, #{PCConfig.status[0]} tries to read the value for key 0. There is no key 0 in your HashMap status though...

As far I know you should do as follow
#{javascript:PCConfig.status.get(1)}

Related

JAXB not unmarshalling all fields

I am working on a JavaFX application which facilitates all kind of sport related training sessions. Each session consists of multiple exercises, whereas each exercise is repeated multiple times in a few sets. I created some test data and marshalled it. As it turned out, some fields of the Exercise class objects were written but not all of them. By adding the #XmlElement(name="someTagName") tag to each getter of each field I managed that all fields are marshalled and the xml file looks like expected. However, when I unmarshall the xml file, only those fields, which were written without the #XmlElement tag are read and most of the fields only have the default value from the constructor. What am I missing in order to unmarshall all fields?
Here is the class that I want to marshall/unmarshall
package domain;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Exercise extends SelectableDomainObj {
protected StringProperty name;
protected StringProperty mediaFilePath;
protected IntegerProperty repsPerSet;
protected IntegerProperty numOfSets;
protected IntegerProperty breakBetweenSetsInSecs;
protected IntegerProperty displayTimeInSecs;
protected DoubleProperty startSpeed;
protected DoubleProperty endSpeed;
protected BooleanProperty withMetronom;
protected BooleanProperty showIntro;
/**
* Set some reasonable default values from lifting domain
*/
public Exercise() {
mediaFilePath = new SimpleStringProperty();
name = new SimpleStringProperty();
numOfSets = new SimpleIntegerProperty(3);
repsPerSet = new SimpleIntegerProperty(8);
breakBetweenSetsInSecs = new SimpleIntegerProperty(60);
displayTimeInSecs = new SimpleIntegerProperty(-1);
startSpeed = new SimpleDoubleProperty(1.0);
endSpeed = new SimpleDoubleProperty(1.0);
withMetronom = new SimpleBooleanProperty(false);
showIntro = new SimpleBooleanProperty(false);
}
#XmlElement(name="name")
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
#XmlElement(name="mediaFilePath")
public String getMediaFilePath() {
return mediaFilePath.get();
}
public void setMediaFilePath(String mediaFilePath) {
this.mediaFilePath.set(mediaFilePath);
}
public StringProperty mediaFilePathProperty() {
return mediaFilePath;
}
#XmlElement(name="repsPerSet")
public Integer getRepsPerSet() {
return repsPerSet.get();
}
public void setRepsPerSet(int repsPerSet) {
this.repsPerSet.set(repsPerSet);
}
public IntegerProperty repsPerSetProperty() {
return repsPerSet;
}
#XmlElement(name="numOfSets")
public int getNumOfSets() {
return numOfSets.get();
}
public void setNumOfSets(int numOfSets) {
this.numOfSets.set(numOfSets);
}
public IntegerProperty numOfSetsProperty() {
return numOfSets;
}
#XmlElement(name="breakBetweenSetsInSec")
public Integer getBreakBetweenSetsInSecs() {
return breakBetweenSetsInSecs.get();
}
public void setBreakBetweenSetsInSecs(int breakBetweenSetsInSecs) {
this.breakBetweenSetsInSecs.set(breakBetweenSetsInSecs);
}
public IntegerProperty displayTimeInSecsProperty() {
return displayTimeInSecs;
}
#XmlElement(name="displayTimeInSecs")
public Integer getDisplayTimeInSecs() {
return displayTimeInSecs.get();
}
public void setDisplayTimeInSecs(int displayTime) {
this.displayTimeInSecs.set(displayTime);
}
public IntegerProperty breakBetweenSetsInSecsProperty() {
return breakBetweenSetsInSecs;
}
#XmlElement(name="showIntro")
public Boolean isShowIntro() {
return showIntro.getValue();
}
public void setShowIntro(boolean showIntro) {
this.showIntro.set(showIntro);
}
public BooleanProperty showIntroProperty() {
return showIntro;
}
#XmlElement(name="withMetronom")
public Boolean isWithMetronom() {
return withMetronom.getValue();
}
public void setWithMetronom(boolean withMetronom) {
this.withMetronom.set(withMetronom);
}
public BooleanProperty withMetronomProperty() {
return withMetronom;
}
#XmlElement(name="startSpeed")
public Double getStartSpeed() {
return startSpeed.get();
}
public void setStartSpeed(double startDuration) {
this.startSpeed.set(startDuration);
}
public DoubleProperty startSpeedProperty() {
return startSpeed;
}
#XmlElement(name="endSpeed")
public Double getEndSpeed() {
return endSpeed.get();
}
public void setEndSpeed(double endDuration) {
this.endSpeed.set(endDuration);
}
public DoubleProperty endSpeedProperty() {
return endSpeed;
}
public double getSpeed(int rep) {
if(getStartSpeed().equals(getEndSpeed())) {
return getStartSpeed();
}
double min, max;
if(getStartSpeed() > getEndSpeed()) {
max = getStartSpeed();
min = getEndSpeed();
} else {
min = getStartSpeed();
max = getEndSpeed();
}
double diff = max - min;
double increment = diff / (getRepsPerSet()-1);
return min + rep * increment;
}
#Override
public String toString() {
return getName();
}
}
I used this to marshall
public void save(Session session) {
try {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(session, new File(System.getProperty("user.home"), ".sifuSays/sessions/" + session.getName() + ".xml"));
} catch (JAXBException e) {
System.err.println("Cannot save session " + session.getName());
e.printStackTrace();
}
}
which generates the following xml file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Session>
<exerciseList>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>3.0</endSpeed>
<mediaFilePath>Tan Pak Gan.mp4</mediaFilePath>
<name>Solo Tan Pak Gan Drill</name>
<numOfSets>2</numOfSets>
<repsPerSet>3</repsPerSet>
<showIntro>false</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>Chain Punches.mp4</mediaFilePath>
<name>Solo Ein-Arm-Zyklus</name>
<numOfSets>2</numOfSets>
<repsPerSet>4</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>true</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>10</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>birddogs.jpg</mediaFilePath>
<name>Stetching</name>
<numOfSets>1</numOfSets>
<repsPerSet>1</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
</exerciseList>
<breakBetweenExercisesInSec>10</breakBetweenExercisesInSec>
<name>MMA - Solo</name>
</Session>
and this is the unmarshaller code
public ObservableList<Session> loadSessions() {
sessions = FXCollections.observableArrayList();
try {
List<File> xmlSessionFiles = Stream.of(
new File(System.getProperty("user.home"), ".sifuSays/sessions/").listFiles())
.filter(file -> !file.isDirectory())
.filter(file -> file.getName().endsWith("xml"))
.collect(Collectors.toList());
for(File xmlSessionFile: xmlSessionFiles) {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Session session = (Session) unmarshaller.unmarshal(xmlSessionFile);
sessions.add(session);
}
} catch (JAXBException e) {
System.err.println("Cannot load sessions");
e.printStackTrace();
}
return sessions;
}
While numOfSets is marshalled, repsPerset is not. Neither startSpeed or stopSpeed are unmarshalled and neither withMetronom or showIntro. But name and mediaFilePath are marshalled. What's wrong?
You are mixing up boxed (Double, Integer) and unboxed (double, int) types. I recommend sticking to boxed types for marshalling since otherwise you'll end up with things set to 0 that you weren't expecting.

Spring batch multiple excel streams in parallel using partitioning

I would like to use read multiple xlsx sheets in parallel using following combination
com.monitorjbl - xlsx-streamer + spring batch / partitioning
I went through the docs
https://docs.spring.io/spring-batch/4.2.x/reference/html/scalability.html#partitioning
and came up with custom ItemStreamReader implementation
#StepScope
#Component
#Scope("prototype")
public class ExcelItemReader implements ItemStreamReader<List<Object>>, ImportContext {
private Iterator<Row> rowIterator;
private Workbook workbook;
private InputStream inputStream;
private int line = 0;
#Override
public List<Object> read() {
List<Object> row = readSingleRow(this.rowIterator);
if (row != null && row.size() > 0 && row.get(0) != null) {
return row;
}
return null;
}
#Override
public void open(#NotNull ExecutionContext executionContext) throws ItemStreamException {
String fileName = (String) executionContext.get("fileName");
File file = null;
try {
file = ResourceUtils.getFile(this.getClass().getResource(fileName));
} catch (FileNotFoundException e) {
throw new ItemStreamException(e);
}
try (
InputStream inputStream = FileUtils.openInputStream(file);
Workbook workbook = StreamingReader.builder()
.rowCacheSize(5000)
.bufferSize(10000)
.open(inputStream)) {
this.inputStream = inputStream;
this.workbook = workbook;
Sheet sheet = workbook.getSheetAt(0);
this.rowIterator = sheet.rowIterator();
List<String> columns =
readSingleRow(this.rowIterator)
.stream()
.map(Object::toString)
.collect(Collectors.toList());
saveToContext(executionContext, ImportContext.headerKey, String.join(",", columns));
} catch (IOException e) {
throw new ItemStreamException(e);
}
}
#Override
public void update(#NotNull ExecutionContext executionContext) throws ItemStreamException {
}
#Override
public void close() throws ItemStreamException {
try {
this.workbook.close();
this.inputStream.close();
} catch (IOException e) {
throw new ItemStreamException(e);
}
}
private List<Object> readSingleRow(Iterator<Row> rowIterator) {
if (rowIterator.hasNext()) {
List<Object> rowContainer = new LinkedList<>();
int prevCellIndex = 0;
Row sheetRow = rowIterator.next();
for (Cell sheetCell : sheetRow) {
int currentIndex = sheetCell.getColumnIndex();
fillGaps(rowContainer, prevCellIndex, currentIndex);
rowContainer.add(sheetCell.getStringCellValue());
prevCellIndex = currentIndex;
}
line++;
return rowContainer;
}
return null;
}
private void fillGaps(List<Object> row, int prevIndex, int currentIndex) {
for (int i = prevIndex + 1; i < currentIndex; i++) {
row.add(null);
}
}
}
Configuration :
#Configuration
#EnableBatchProcessing
#EnableAutoConfiguration
#ComponentScan
public class ImportJobConfiguration<Fact extends BaseFact> {
private DataSource dataSource;
private StepBuilderFactory stepBuilderFactory;
private ImportPartitioner partitioner;
private JobExecutionListener jobListener;
private ItemWriteListener writeListener;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Autowired
public void setStepBuilderFactory(StepBuilderFactory stepBuilderFactory) {
this.stepBuilderFactory = stepBuilderFactory;
}
#Autowired
public void setPartitioner(ImportPartitioner partitioner) {
this.partitioner = partitioner;
}
#Autowired(required = false)
public void setJobListener(JobExecutionListener jobListener) {
this.jobListener = jobListener;
}
#Autowired(required = false)
public void setItemWriteListener(ItemWriteListener writeListener) {
this.writeListener = writeListener;
}
#Autowired
public void setProcessor(FactItemProcessor<Fact> processor) {
this.processor = processor;
}
public void setFact(Fact fact) {
this.fact = fact;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
#Autowired
private FactItemProcessor<Fact> processor;
#Autowired
#Qualifier("sample")
private Fact fact;
#Autowired
private JdbcTemplate template;
#Bean
JdbcBatchItemWriter<Fact> writer() {
JdbcBatchItemWriter<Fact> writer = null;
try {
writer = new JdbcBatchItemWriterBuilder<Fact>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql(fact.getClass().newInstance().insertSQL())
.dataSource(dataSource)
.build();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return writer;
}
#Bean
public ExcelItemReader reader() {
return new ExcelItemReader();
}
#Bean
public Step partitionStep() {
return stepBuilderFactory.get("partitionStep")
.partitioner("slaveStep", partitioner)
.partitionHandler(partitionHandler())
.build();
}
#Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(5);
taskExecutor.setCorePoolSize(5);
taskExecutor.setQueueCapacity(10);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
#Bean
public PartitionHandler partitionHandler() {
TaskExecutorPartitionHandler retVal = new TaskExecutorPartitionHandler();
retVal.setTaskExecutor(taskExecutor());
retVal.setStep(slaveStep());
retVal.setGridSize(10);
return retVal;
}
#Bean
public Step slaveStep() {
SimpleStepBuilder<List<Object>, Fact> slaveStep = stepBuilderFactory.get("slaveStep")
.<List<Object>, Fact>chunk(100)
.reader(reader())
.processor(processor)
.writer(writer());
if (writeListener != null) {
slaveStep.listener(writeListener);
}
return slaveStep
.build();
}
#Bean
public Job createJob(#Autowired JobBuilderFactory jobBuilderFactory) {
SimpleJobBuilder jobBuilder = jobBuilderFactory.get("importJob")
.incrementer(new RunIdIncrementer())
.start(partitionStep());
if (jobListener != null) {
jobBuilder = jobBuilder
.listener(jobListener);
}
return jobBuilder.build();
}
}
Unfortunately im not able to make it thread safe. I assumed that the TaskExecutorPartitionHandler is 'assigning' Threads per partition aka per file. But it looks that the ExcelItemReader.read() is accessed randomly and i can't rely on state of the private members. Mostly the rowIterator. Any ideas and thoughts appreciated.
Unfortunately im not able to make it thread safe.
Since your item reader implements ItemStreamReader, you can wrap it in a SynchronizedItemStreamReader to make it thread safe:
#Bean
public SynchronizedItemStreamReader reader() throws Exception {
SynchronizedItemStreamReader synchronizedReader = new SynchronizedItemStreamReader();
synchronizedReader.setDelegate(new ExcelItemReader());
synchronizedReader.afterPropertiesSet();
return synchronizedReader;
}
You can find more details about this reader in the Item readers and writers decorators section.
Update:
Actually the solution almost worked. The issue was the 'try with resources' block in open method, which closes the stream somewhat randomly. I dont have explanation for this behaviour but the modified solution works as expected and im able to parse multiple excel files in paralllel and using streams.
Prototype scope on the ExcelItemReader is still important, this ensures that there are as many independent instances of ExcelItemReader how many threads you have.
The updated ExcelItemReader
import com.monitorjbl.xlsx.StreamingReader;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.bmsource.dwh.common.fileManager.FileManager;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
#Component
#StepScope
#Scope("prototype")
public class ExcelItemReader implements ItemStreamReader<List<Object>>, ImportContext {
private Logger logger = LoggerFactory.getLogger(ExcelItemReader.class.getName());
private int rowsCount = -1;
private Iterator<Row> rowIterator;
private Workbook workbook;
private InputStream inputStream;
private ExecutionContext executionContext;
#Value("#{jobParameters['transaction']}")
private String transaction;
#Value("#{stepExecutionContext['fileName']}")
private String fileName;
#Autowired
private FileManager fileManager;
#Override
public List<Object> read() {
List<Object> row = readSingleRow(this.rowIterator);
if (row != null && row.size() > 0 && row.get(0) != null) {
return row;
}
return null;
}
#Override
public void open(#NotNull ExecutionContext executionContext) throws ItemStreamException {
this.executionContext = executionContext;
try {
InputStream inputStream = fileManager.getStream(transaction, fileName);
Workbook workbook = StreamingReader.builder()
.rowCacheSize(5000)
.bufferSize(1024)
.open(inputStream);
this.inputStream = inputStream;
this.workbook = workbook;
logger.debug("Excel file {} opened for reading", this.fileName);
Sheet sheet = workbook.getSheetAt(0);
executionContext.put(ImportContext.totalRowsKey, sheet.getLastRowNum());
executionContext.put(ImportContext.rowsKey, 0);
this.rowIterator = sheet.rowIterator();
List<String> columns =
readSingleRow(this.rowIterator)
.stream()
.map(Object::toString)
.collect(Collectors.toList());
saveToContext(executionContext, ImportContext.headerKey, String.join(",", columns));
} catch (Exception e) {
try {
this.workbook.close();
this.inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
throw new ItemStreamException(e);
}
}
#Override
public void update(#NotNull ExecutionContext executionContext) throws ItemStreamException {
}
#Override
public void close() throws ItemStreamException {
try {
logger.debug("Closing excel file " + this.fileName);
this.workbook.close();
this.inputStream.close();
} catch (IOException e) {
throw new ItemStreamException(e);
}
}
private List<Object> readSingleRow(Iterator<Row> rowIterator) {
if (rowIterator.hasNext()) {
List<Object> row = new LinkedList<>();
int prevCellIndex = 0;
Row sheetRow = rowIterator.next();
for (Cell sheetCell : sheetRow) {
int currentIndex = sheetCell.getColumnIndex();
fillGaps(row, prevCellIndex, currentIndex);
row.add(sheetCell.getStringCellValue());
prevCellIndex = currentIndex;
}
rowsCount++;
return row;
}
return null;
}
private void fillGaps(List<Object> row, int prevIndex, int currentIndex) {
for (int i = prevIndex + 1; i < currentIndex; i++) {
row.add(null);
}
}
}
Job configuation
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.job.builder.SimpleJobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.batch.core.partition.PartitionHandler;
import org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.builder.SimpleStepBuilder;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
#Configuration
#EnableBatchProcessing
#EnableAutoConfiguration
#ComponentScan
public class ImportJobConfiguration<Fact extends BaseFact> {
private Logger logger = LoggerFactory.getLogger(ImportJobConfiguration.class);
private static final int BATCH_SIZE = 5000;
private static final int MAX_CONCURRENT_FILES = 10;
private DataSource dataSource;
private StepBuilderFactory stepBuilderFactory;
private ImportPartitioner excelImportPartitioner;
private JobExecutionListener jobListener;
private ItemWriteListener writeListener;
private ChunkListener chunkListener;
private FactItemProcessor<Fact> processor;
private Fact fact;
#Autowired
AppStateService appStateService;
#Autowired
JobRepository jobRepository;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Autowired
public void setStepBuilderFactory(StepBuilderFactory stepBuilderFactory) {
this.stepBuilderFactory = stepBuilderFactory;
}
#Autowired
public void setExcelImportPartitioner(ImportPartitioner excelImportPartitioner) {
this.excelImportPartitioner = excelImportPartitioner;
}
#Autowired(required = false)
public void setJobListener(JobExecutionListener jobListener) {
this.jobListener = jobListener;
}
#Autowired(required = false)
public void setItemWriteListener(ItemWriteListener writeListener) {
this.writeListener = writeListener;
}
#Autowired(required = false)
public void setChunkListener(ChunkListener chunkListener) {
this.chunkListener = chunkListener;
}
#Autowired
public void setProcessor(FactItemProcessor<Fact> processor) {
this.processor = processor;
}
#Autowired
#Qualifier("fact")
public void setFact(Fact fact) {
this.fact = fact;
}
#Bean
JdbcBatchItemWriter<Fact> writer() {
JdbcBatchItemWriter<Fact> writer = null;
try {
writer = new JdbcBatchItemWriterBuilder<Fact>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql(fact.getClass().newInstance().insertSQL())
.dataSource(dataSource)
.build();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return writer;
}
#Bean
#StepScope
public ExcelItemReader reader() {
return new ExcelItemReader();
}
#Bean
public Step excelReadPartitionStep() {
return stepBuilderFactory.get("excelReadPartitionStep")
.partitioner("excelReadPartitioner", excelImportPartitioner)
.partitionHandler(excelReadPartitioner())
.build();
}
#Bean
public PartitionHandler excelReadPartitioner() {
TaskExecutorPartitionHandler partitionHandler = new TaskExecutorPartitionHandler();
partitionHandler.setTaskExecutor(taskExecutor());
partitionHandler.setStep(excelReadStep());
partitionHandler.setGridSize(MAX_CONCURRENT_FILES);
return partitionHandler;
}
#Bean
public Step excelReadStep() {
SimpleStepBuilder<List<Object>, Fact> step = stepBuilderFactory.get("excelReadStep")
.<List<Object>, Fact>chunk(BATCH_SIZE)
.reader(reader())
.processor(processor)
.writer(writer());
if (writeListener != null) {
step.listener(writeListener);
}
if (chunkListener != null) {
step.listener(chunkListener);
}
return step
.build();
}
#Bean
public Job importJob(#Autowired JobBuilderFactory jobBuilderFactory) {
SimpleJobBuilder jobBuilder = jobBuilderFactory.get("importJob")
//.incrementer(new RunIdIncrementer())
.start(excelReadPartitionStep());
if (jobListener != null) {
jobBuilder = jobBuilder
.listener(jobListener);
}
return jobBuilder.build();
}
#Bean
public JobLauncher simpleJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
#Bean
public JobExecutionListener jobListener() {
JobExecutionListener listener = new JobExecutionListenerSupport() {
#Override
public void beforeJob(JobExecution jobExecution) {
}
#Override
public void afterJob(JobExecution jobExecution) {
}
};
return listener;
}
#Bean
public ChunkListener chunkListener() {
return new ChunkListener() {
#Override
public void beforeChunk(ChunkContext context) {
}
#Override
public void afterChunk(ChunkContext context) {
// some progress indicator
}
#Override
public void afterChunkError(ChunkContext context) {
}
};
}
#Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(MAX_CONCURRENT_FILES);
taskExecutor.setCorePoolSize(MAX_CONCURRENT_FILES / 2);
taskExecutor.setQueueCapacity(MAX_CONCURRENT_FILES / 2);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
}

How to restrict CRUD functions for not logged users?

I followed this tutorial to do a CRUD application: https://www.youtube.com/watch?v=DFFKMq1kh-M&t=339s
Here is my ManagedBean for it:
package model_controller;
import com.sun.net.httpserver.HttpsServer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
#Named(value = "studentManagedBean")
#RequestScoped
public class StudentManagedBean {
private int id, wiek;
private String nazwisko, email, adres;
public StudentManagedBean() {
}
public StudentManagedBean(int id, int wiek, String nazwisko, String email, String adres) {
//konstruktory
this.id = id;
this.wiek = wiek;
this.nazwisko = nazwisko;
this.email = email;
this.adres = adres;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWiek() {
return wiek;
}
public void setWiek(int wiek) {
this.wiek = wiek;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdres() {
return adres;
}
public void setAdres(String adres) {
this.adres = adres;
}
//
public static Connection conn = null;
public static PreparedStatement pstmt = null;
public static ResultSet rs = null;
private String str = "";
//
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
//Alt+enter
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studenci?zeroDateTimeBehavior=convertToNull", "root", "");
} catch (ClassNotFoundException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public ArrayList<StudentManagedBean> GetAllStudent() {
ArrayList<StudentManagedBean> arr = new ArrayList<>();
str = "SELECT s.id, s.nazwisko, s.wiek, s.adres, s.email FROM student s";
getConnection();
try {
pstmt = conn.prepareStatement(str);
rs = pstmt.executeQuery();
while (rs.next()) {
StudentManagedBean st = new StudentManagedBean();
st.setId(rs.getInt("id"));
st.setNazwisko(rs.getString("nazwisko"));
st.setWiek(rs.getInt("wiek"));
st.setAdres(rs.getString("adres"));
st.setEmail(rs.getString("email"));
//
arr.add(st);
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
return arr;
}
public void add() {
getConnection();
str = "insert into student(nazwisko, wiek, adres, email) values(?,?,?,?)";
try {
pstmt = conn.prepareStatement(str);
pstmt.setString(1, this.getNazwisko());
pstmt.setInt(2, this.getWiek());
pstmt.setString(3, this.getAdres());
pstmt.setString(4, this.getEmail());
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Zaktualizowano dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
public void Edit() {
ArrayList<StudentManagedBean> arrList = GetAllStudent();
FacesContext fc = FacesContext.getCurrentInstance();
// Map<String,String> mapParam = fc.getExternalContext().getInitParameterMap();
// idStudent = mapParam.get("id");
int idStudent;
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
idStudent = Integer.parseInt(request.getParameter("id"));
//
for (StudentManagedBean studentManagedBean : arrList) {
if (studentManagedBean.getId() == idStudent) {
this.setId(studentManagedBean.getId());//błąd
this.setNazwisko(studentManagedBean.getNazwisko());
this.setWiek(studentManagedBean.getWiek());
this.setAdres(studentManagedBean.getAdres());
this.setEmail(studentManagedBean.getEmail());
}
}
setId(idStudent);
}
public void update() {
getConnection();
str = "update student set nazwisko=?, wiek=?, adres=?, email=? where id=?";
// Map<String,String> mapParam = fc.getExternalContext().getInitParameterMap();
// idStudent = mapParam.get("id");
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
int idStudent = Integer.parseInt(request.getParameter("id"));
try {
pstmt = conn.prepareStatement(str);
pstmt.setString(1, this.getNazwisko());
pstmt.setInt(2, this.getWiek());
pstmt.setString(3, this.getAdres());
pstmt.setString(4, this.getEmail());
pstmt.setInt(5, idStudent);
System.out.println(getNazwisko());
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Zaktualizowano dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
public void delete() {
getConnection();
str = "DELETE FROM student where id=?";
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
int idStudent = Integer.parseInt(request.getParameter("id"));
try {
pstmt = conn.prepareStatement(str);
pstmt.setInt(1, idStudent);
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Usunięto dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
}
It works pretty well, and I wanted to upgrade it - so everyone can see the data, but only logged in users can edit, add and delete records.
I found login tutorial: http://www.journaldev.com/7252/jsf-authentication-login-logout-database-example
How can I restrict edit, add and delete functions only for users that are logged in?
CRUD app is using RequestScope, login uses SessionScope, can i even use two different scopes in one app?
Should I use two different databases for login and students, or should I put it in one database, just two tables?
You can use the rendered attribute, which by default is set to true.
// Your form for inserting data to the database
<h:form rendered="#{studentManagedBean.isLoggedIn}">
...
</h:form>
// delete button
<h:commandButton action="#{studentManagedBean.delete()}"
rendered="#{studentManagedBean.isLoggedIn}" />
You have to add a variable and a method to your managedbean to check whether the user is logged in or not.
private boolean loggedIn;
// getter and setter
public boolean isLoggedIn(){
return loggedIn;
}

SessionListener causes ExceptionInInitializerError

I am trying to implement a SessionListener which I plan to use for logging active user sessions (name/time) so that I can let manager know who all are available at anytime. However, when I add it, I see sessionCreated message and then I see this JVM error on server console. No java code is executed after it.
HTTP JVM: com.ibm.xsp.webapp.FacesServlet$ExtendedServletException:
java.lang.ExceptionInInitializerError HTTP JVM: Error type not
found:java.lang.ExceptionInInitializerError import
javax.servlet.http.HttpSessionEvent;
Here is my SessionTracker.java:
import com.ibm.xsp.application.ApplicationEx;
import com.ibm.xsp.application.events.SessionListener;
public class SessionTracker implements SessionListener {
public void sessionCreated(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session created***");
}
public void sessionDestroyed(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session destroyed ***");
}
}
Here is what I see in xpages_exec*.log under IBM_Technical_Support directory.
Context Path: /igdmnext/igdm.nsf Page Name: /Services.xsp
java.lang.ExceptionInInitializerError at
java.lang.J9VMInternals.initialize(J9VMInternals.java:221) at
java.lang.J9VMInternals.newInstanceImpl(Native Method) at
java.lang.Class.newInstance(Class.java:1688) at
com.ibm.xsp.util.ManagedBeanUtil.getBean(ManagedBeanUtil.java:61) at
com.ibm.xsp.extlib.component.rest.CustomService.findBeanInstance(CustomService.java:225)
at
com.ibm.xsp.extlib.component.rest.CustomService$ScriptServiceEngine.renderService(CustomService.java:257)
at
com.ibm.domino.services.HttpServiceEngine.processRequest(HttpServiceEngine.java:170)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService._processAjaxRequest(UIBaseRestService.java:259)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService.processAjaxRequest(UIBaseRestService.java:236)
at
com.ibm.xsp.util.AjaxUtilEx.renderAjaxPartialLifecycle(AjaxUtilEx.java:206)
at
com.ibm.xsp.webapp.FacesServletEx.renderAjaxPartial(FacesServletEx.java:249)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialView(FacesServletEx.java:200)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialViewSync(FacesServletEx.java:169)
at
com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:155)
at com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:160) at
com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138) at
com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:576)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:853)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:796)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:565)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319)
at
com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662)
at
com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313)
at
com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)
Caused by: java.lang.NullPointerException at
org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23)
at
org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18)
at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
com.hcl.igdm.util.EndUserMap.(EndUserMap.java:46) --> this is my custom java class which works if I do not implement SessionTracker above at
java.lang.J9VMInternals.initializeImpl(Native Method) at
java.lang.J9VMInternals.initialize(J9VMInternals.java:199) ... 27
more
** EndUserMap.java **
package com.hcl.igdm.util;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewEntryCollection;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.utils.Factory.SessionType;
import com.hcl.igdm.Activity;
import com.hcl.igdm.Phases;
import com.hcl.igdm.Stages;
import com.ibm.commons.util.StringUtil;
import com.ibm.commons.util.io.json.JsonJavaArray;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
import com.ibm.xsp.extlib.util.ExtLibUtil;
/**
* #author agnihotri.a
*
*/
public class EndUserMap extends CustomServiceBean implements Serializable {
private static final long serialVersionUID = 1L;
private static String requestedType = "";
static Session session = Factory.getSession(SessionType.NATIVE);
static Database db = session.getCurrentDatabase();
static View allView = db.getView("mapAll");
public static void setRequestedType(String requestType) {
requestedType = requestType;
}
public static String getRequestedType() {
return requestedType;
}
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
FacesContext faccon = FacesContext.getCurrentInstance();
/**** read requested type from query string parameters ****/
String reqType = request.getParameter("type");
try {
JsonJavaObject jjo = new JsonJavaObject();
PrintWriter pw = response.getWriter();
if (reqType.equalsIgnoreCase("Map") || "".equalsIgnoreCase(reqType)) {
setRequestedType("Map");
pw.write(getEndUserMap().toString());
} else if (reqType.equalsIgnoreCase("Activity")) {
setRequestedType("Activity");
request.getParameter("ukey");
try {
jjo = getActivity(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Phase")) {
request.getParameter("ukey");
try {
setRequestedType("Phase");
jjo = getPhase(request.getParameter("ukey"));
jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Stage")) {
request.getParameter("ukey");
try {
setRequestedType("Stage");
jjo = getStage(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
faccon.responseComplete();
}
public static JsonJavaObject getActivity(String ukey) throws Exception {
Activity activity = new Activity();
activity.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) activity.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
jjo.put("title", activity.getValue("Title"));
jjo.put("teaser", activity.getValue("Teaser"));
jjo.put("ukey", activity.getUnid());
jjo.put("overview", activity.getValue("Overview"));
jjo.put("inputs", activity.getValue("Inputs"));
jjo.put("outputs", activity.getValue("Outputs"));
jjo.put("order", activity.getValue("SortOrder"));
jjo.put("artefacts", activity.getArtefacts());
jjo.put("kmlinks", activity.getValue("KMLinks"));
jjo.put("kmenabled", activity.getValue("KMEnabled"));
jjo.put("resources", activity.getResources());
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty()) {
if (mappings.containsKey("Substage")) {
// jjo.put("substage", mappings.get("Substage").get(0));
jjo.put("substage", getStage(mappings.get("Substage").get(0)));
} else if (mappings.containsKey("Stage")) {
// jjo.put("stage", mappings.get("Stage").get(0));
jjo.put("stage", getStage(mappings.get("Stage").get(0)));
}
}
return jjo;
}
public static JsonJavaObject getStage(String ukey) {
Stages stage = new Stages();
stage.load(ukey);
String stageType = (String) stage.getValue("StageType");
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) stage.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
jjo.put("title", stage.getValue("Title"));
jjo.put("ukey", stage.getUnid());
jjo.put("overview", stage.getValue("Overview"));
jjo.put("order", stage.getValue("Row"));
jjo.put("type", stageType);
jjo.put("status", (String) stage.getValue("Status"));
if (!mappings.isEmpty()) {
if (mappings.containsKey("Stream")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
for (String key : mappings.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
}
} catch (Exception ex) {
// do nothing
}
}
jjo.put("stream", mapStreamJJA);
} else {
jjo.put("stream", "");
}
/** below mapping check handles substages */
if (mappings.containsKey("Stage") && !StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
JsonJavaArray mapPhaseJJA = new JsonJavaArray();
// as this is substage ..we'll get phase from parent stage
for (String key : mappings.get("Stage")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
TreeMap<String, ArrayList<String>> stageMap = Mappings.loadMyMap(key);
if (!stageMap.isEmpty() && stageMap.containsKey("Phase")) {
for (String phase : stageMap.get("Phase")) {
Map<String, Object> entryMapPhase = allView.getFirstEntryByKey(phase).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMapPhase.get("status")) || isAdmin()) {
mapPhaseJJA.add(entryMapPhase);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
jjo.put("stage", mapStreamJJA);
jjo.put("phase", mapPhaseJJA);
}
if (mappings.containsKey("Phase") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapPhJJA = new JsonJavaArray();
for (String key : mappings.get("Phase")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapPhJJA.add(entryMap);
}
}
jjo.put("phase", mapPhJJA);
} else {
if (!jjo.containsKey("phase")) {
jjo.put("phase", "");
}
}
if (mappings.containsKey("Activity")) {
JsonJavaArray actJJA = new JsonJavaArray();
for (String key : mappings.get("Activity")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
actJJA.add(entryMap);
}
} catch (Exception ex) {
}
}
jjo.put("child", "Activities");
jjo.put("activities", actJJA);
} else if (mappings.containsKey("Substage") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray ssJJA = new JsonJavaArray();
for (String key : mappings.get("Substage")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
ssJJA.add(entryMap);
}
}
jjo.put("child", "Substages");
jjo.put("substages", ssJJA);
}
}
return jjo;
}
public static JsonJavaObject getPhase(String ukey) {
Phases phase = new Phases();
phase.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) phase.getValue("Status"), "Live")) {
return null;
}
jjo.put("title", phase.getValue("Title"));
jjo.put("ukey", phase.getUnid());
jjo.put("status", phase.getValue("Status"));
jjo.put("overview", phase.getValue("Overview"));
jjo.put("order", phase.getValue("SortOrder"));
try {
jjo.put("artefacts", phase.getArtefacts());
} catch (Exception e) {
jjo.put("artefacts", null);
e.printStackTrace();
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty() && mappings.containsKey("Stage")) {
JsonJavaArray jja = new JsonJavaArray();
for (String key : mappings.get("Stage")) {
ViewEntry stage = allView.getFirstEntryByKey(key);
if (null != stage) {
if (isAdmin() || "Live".equalsIgnoreCase((String) stage.getColumnValue("status"))) {
Map<String, Object> stg = stage.getColumnValuesMap();
TreeMap<String, ArrayList<String>> stgMap = Mappings.loadMyMap(key);
if (!stgMap.isEmpty() && stgMap.containsKey("Stream")) {
JsonJavaArray stgStreamArr = new JsonJavaArray();
for (String stream : stgMap.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(stream).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
stgStreamArr.add(entryMap);
}
} catch (Exception ex) {
}
}
stg.put("stream", stgStreamArr);
}
jja.add(stg);
}
}
}
jjo.put("stages", jja);
}
return jjo;
}
public static JsonJavaObject getEndUserMap() {
setRequestedType("Map");
JsonJavaObject endUserMap = new JsonJavaObject();
try {
ArrayList<String> docTypes = new ArrayList<String>();
docTypes.add("Phase");
docTypes.add("Stream");
for (String dtype : docTypes) {
View view = db.getView("map" + dtype);
JsonJavaArray jja = new JsonJavaArray();
ViewEntryCollection vec;
if (isAdmin()) {
vec = view.getAllEntries();
} else {
vec = view.getAllEntriesByKey("Live");
}
for (ViewEntry ve : vec) {
jja.add(ve.getColumnValuesMap());
}
endUserMap.put(dtype, jja);
}
} catch (Exception e) {
e.printStackTrace();
}
return endUserMap;
}
#SuppressWarnings("unchecked")
public static boolean isAdmin() {
List<String> roleList = ExtLibUtil.getXspContext().getUser().getRoles();
if (!roleList.isEmpty() && roleList.contains("[admin]")) {
return true;
} else {
return false;
}
}
}
Caused by: java.lang.NullPointerException at org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23) at org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18) at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
It seems to be hitting an error getting the signer session.
This may be a timing issue, caused by it running in a different ClassLoader, before the ODA Factory has initialised the factory's sessions. I'm not sure how to confirm that, but if your error is hitting the logs before the XOTS logging at server startup, that would almost certainly be the case.
Alternatively, it may be specific to not finding the signer. I've tended to use Factory.getSession(SessionType.NATIVE) rather than a signer session. That runs under server's identity, which should be high enough and avoids the issue of multiple signers etc.

#ManagedProperty - access properties Injected from one view scoped bean into another view scoped bean

I have injected one view scoped bean into another view scoped bean , and I can access some properties of the first bean but others appear as null in #PostContruct. How can I see their real value?
Thanks in advance
Update:
I can only see the value of properties updated in #PostContruct of the first bean and not others
Bean 1(SelectOfferMpans)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.corejsf.SofycNavigation;
import sofyc.corejsf.SofycParamNames;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerFindVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
#ManagedBean
#ViewScoped
public class SelectOfferMpans implements Serializable{
/**
* Logger.
*/
private static Logger log = LogginManager.getLogger(SelectOfferMpans.class.getName());
static {
adq_ren_types = new String[2];
}
private final String ID_OFFER_SELECT_MPANS_FORM = "selectMpans";
private String menuOrigin;
/**
* Parametro de busqueda del formulario.
*/
private String registrationNumber;
private List<CustomerFindVO> customerfoundList;
private CustomerFindVO customerfound;
private String companyRegNo;
private String customerId;
private CustomerFindVO selectedCustomer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites;
private List<MpanVO> siteMpans;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private final static String[] adq_ren_types;
private Map<String,String> hh_nhh_types;
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public CustomerFindVO getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(CustomerFindVO selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyRegNo() {
return companyRegNo;
}
public void setCompanyRegNo(String companyRegNo) {
this.companyRegNo = companyRegNo;
}
public List<CustomerFindVO> getCustomerfoundList() {
return customerfoundList;
}
public void setCustomerfoundList(List<CustomerFindVO> customerfoundList) {
this.customerfoundList = customerfoundList;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public CustomerFindVO getCustomerfound() {
return customerfound;
}
public void setCustomerfound(CustomerFindVO customerfound) {
this.customerfound = customerfound;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Creates a new instance of SelectOfferMpans
*/
public SelectOfferMpans() {
}
#PostConstruct
public void init() {
try{
if(log.isDebugEnabled()) {
log.debug("INIT");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
}catch(Exception e)
{
log.error("SearchCustomer:Init", e);
JSFHelper.addErrorMessage("messagesError", e.getMessage());
}
}
public void findCustomer() throws Exception {
CustomerFindVO customer=null;
try{
if (log.isDebugEnabled()) {
log.debug("Searching Customer....");
}
IOffersBean offersBean = BeanInstanceLocator.getOffersBean();
customerfound = offersBean.searchCustomer(companyRegNo);
if (customerfound!=null){
this.setOfferSites(offersBean.getCustomerSites(customerfound.getCustomerId()));
}
else{
this.setOfferSites(null);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
if (log.isDebugEnabled()) {
log.debug("Customer Data Found");
}
} catch (Throwable t) {
log.error("findCustomer:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
}
public String goToOffers(){
try{
JSFHelper.addParamToRequest(SofycParamNames.CUSTOMER_ID, customerfound.getCustomerId());
JSFHelper.addParamToRequest(SofycParamNames.OPTION, this.getMenuOrigin());
return SofycNavigation.VIEW_CREATE_OFFERS_PAGE;
} catch (Throwable t) {
log.error("goToOffers:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error navigating to offers page");
return null;
}
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
private SelectItem[] createFilterOptions1(Map<String,String> data, boolean select) {
//SelectItem[] options = new SelectItem[data.size() + 1];
SelectItem[] options;
int i = 0;
if (select==true) {
options = new SelectItem[data.size() + 1];
options[i] = new SelectItem("", "Select");
i++;
}
else{
options = new SelectItem[data.size()];
}
for (Map.Entry e: data.entrySet()) {
options[i] = new SelectItem(e.getKey().toString(), e.getValue().toString());
//options[i + 1] = new SelectItem(e.getValue().toString(),e.getKey().toString());
i++;
}
return options;
}
private Map<String,String> cargaHHNHH() {
Map<String,String> hh_nhh_types= new HashMap<String,String>();
hh_nhh_types.put("HH","HH");
hh_nhh_types.put("NHH","NHH");
return hh_nhh_types;
}
}
Bean 2(CreateOffer) property selectedSites of the first bean appears always as null and It's loaded in findCustomer Method.
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleEvent;
import org.primefaces.event.UnselectEvent;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerVO;
import sofyc.valueobject.MddMeasurementClassVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
import sofyc.valueobject.ProfileClassVO;
import sofyc.valueobject.SiteVO;
import sofyc.valueobject.TradebookVO;
#ManagedBean
#ViewScoped
public class CreateOffer implements Serializable {
private static Logger log = LogginManager.getLogger(CreateOffer.class.getName());
/**
* Creates a new instance of CreateOffer
*/
static {
adq_ren_types = new String[2];
}
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
//#ManagedProperty(value="#{selectOfferMpans}")
//private SelectOfferMpans selectOfferMpans;
private OfferSitesVO[] selectedSites;
/*public void setSelectOfferMpans(SelectOfferMpans selectOfferMpans) {
this.selectOfferMpans = selectOfferMpans;
}*/
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
/**
* Valores posibles de donde viene la pagina.
*/
private final String CREATE_OFFERS_OPTION = "CREATE";
private final String OFFERS_OPTION = "OFFERS";
private String menuOrigin;
/**
* Corresponde a la columna CUSTOMER_ID.
*/
private Integer customerId;
private Map<String,String> managers;
private Date offerFromDate;
private Date offerToDate;
private Date expiryDate;
private Integer tradeBookId;
private String creditScore;
private String consultantMargin;
private String spMargin;
private Integer productId;
private Integer profileClassId;
private String measurementClassId;
private Integer curveId;
/**
* Customer selected.
*/
private CustomerVO customer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites1;
public OfferSitesVO[] getSelectedSites1() {
return selectedSites1;
}
public void setSelectedSites1(OfferSitesVO[] selectedSites1) {
this.selectedSites1 = selectedSites1;
}
private List<MpanVO> siteMpans;
//private final static String[] hh_nhh_types;
private Map<String,String> hh_nhh_types;
private final static String[] adq_ren_types;
//private final static String[] cotOfferTypes;
private Map<String,String> cotOfferTypes;
private Map<String,String> offerType;
private Map<String,String> loadCurve;
//private final static String[] offerType;
//private final static String[] loadCurve;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private SelectItem[] cotOfferList;
private String cotOfferSelection;
private String comcOfferSelection;
private String copcOfferSelection;
private String offerTypeSelection;
private String loadCurveSelection;
//La oferta es de tipo HH o NHH
private String offerHH_NHH;
private SelectItem[] offerTypeList;
private SelectItem[] loadCurveList;
/**
* Site selected.
*/
private SiteVO site;
private MpanVO mpan;
private List<SiteVO> sites;
private List<MpanVO> mpans;
private List<TradebookVO> tradeBookList;
private Map<String,Integer> ProductList;
private List<ProfileClassVO> profileClassList;
private List<MddMeasurementClassVO> measurementClassList;
private Map<String,Integer> CurveList;
#PostConstruct
public void init() {
if(log.isDebugEnabled()) {
log.debug("********************** CreateOffer::init **********************");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
//Valor por defecto de COT
cotOfferSelection="0";
//Valor por defecto de COMC
comcOfferSelection="0";
//Valor por defecto de COPC
copcOfferSelection="0";
//Valor por defecto de OfferType
offerTypeSelection="0";
//Valor por defecto de loadCurve
loadCurveSelection="0";
offerHH_NHH="NHH";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
//cotOfferList = createFilterOptions(cotOfferTypes);
this.setCotOfferTypes(cargaCOT());
cotOfferList = createFilterOptions1(cotOfferTypes,false);
this.setOfferType(cargaofferType());
offerTypeList = createFilterOptions1(offerType,false);
this.setLoadCurve(cargaloadCurve());
loadCurveList = createFilterOptions1(loadCurve,false);
populateRequestParamsInViewVars();
initCustomerInfo();
CurveList = new LinkedHashMap<String,Integer>();
ProductList = new LinkedHashMap<String,Integer>();
//hh_nhh_List = new LinkedHashMap<String,Integer>();
profileClassId=2;
measurementClassId="A";
curveId=1;
tradeBookId=3;
profileClassList = new ArrayList<ProfileClassVO>();
measurementClassList = new ArrayList<MddMeasurementClassVO>();
tradeBookList = new ArrayList<TradebookVO>();
loadProfileClass();
loadMeasurementClass();
loadTradeBook();
}
public void onRowSelect(SelectEvent event) {
//FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
//event.getComponent().
}
public void onRowUnselect(UnselectEvent event) {
//FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
}
public String getOfferTypeSelection() {
return offerTypeSelection;
}
public void setOfferTypeSelection(String offerTypeSelection) {
this.offerTypeSelection = offerTypeSelection;
}
public String getLoadCurveSelection() {
return loadCurveSelection;
}
public void setLoadCurveSelection(String loadCurveSelection) {
this.loadCurveSelection = loadCurveSelection;
}
public SelectItem[] getOfferTypeList() {
return offerTypeList;
}
public void setOfferTypeList(SelectItem[] offerTypeList) {
this.offerTypeList = offerTypeList;
}
public SelectItem[] getLoadCurveList() {
return loadCurveList;
}
public void setLoadCurveList(SelectItem[] loadCurveList) {
this.loadCurveList = loadCurveList;
}
public List<ProfileClassVO> getProfileClassList() {
return profileClassList;
}
public void setProfileClassList(List<ProfileClassVO> ProfileClassList) {
this.profileClassList = ProfileClassList;
}
public MpanVO getMpan() {
return mpan;
}
public void setMpan(MpanVO mpan) {
this.mpan = mpan;
}
public List<MpanVO> getMpans() {
return mpans;
}
public void setMpans(List<MpanVO> mpans) {
this.mpans = mpans;
}
public List<SiteVO> getSites() {
return sites;
}
public void setSites(List<SiteVO> sites) {
this.sites = sites;
}
public CustomerVO getCustomer() {
return customer;
}
public void setCustomer(CustomerVO customer) {
this.customer = customer;
}
public SiteVO getSite() {
return site;
}
public void setSite(SiteVO site) {
this.site = site;
}
public String getCreditScore() {
return creditScore;
}
public void setCreditScore(String creditScore) {
this.creditScore = creditScore;
}
public String getConsultantMargin() {
return consultantMargin;
}
public void setConsultantMargin(String consultantMargin) {
this.consultantMargin = consultantMargin;
}
public String getSpMargin() {
return spMargin;
}
public void setSpMargin(String spMargin) {
this.spMargin = spMargin;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public Map<String, String> getOfferType() {
return offerType;
}
public void setOfferType(Map<String, String> offerType) {
this.offerType = offerType;
}
public Map<String, String> getLoadCurve() {
return loadCurve;
}
public void setLoadCurve(Map<String, String> loadCurve) {
this.loadCurve = loadCurve;
}
public String getOfferHH_NHH() {
return offerHH_NHH;
}
public void setOfferHH_NHH(String OfferHH_NHH) {
this.offerHH_NHH = OfferHH_NHH;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Metodo que inicializa los valores del cliente.
*/
private void initCustomerInfo() {
this.setSites(new ArrayList<SiteVO>());
this.setMpans(new ArrayList<MpanVO>());
List<OfferSitesVO> offerSitesAux = new ArrayList<OfferSitesVO>();
FacesMessage msg = null;
try{
log.debug("initCustomerInfo: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
this.setCustomer(offerBean.getCustomer(customerId));
this.setManagers(offerBean.getManagerList());
if (CREATE_OFFERS_OPTION.equals(menuOrigin)){
if (selectedSites!=null){
for(int i = 0; i < selectedSites.length; i++){
offerSitesAux.add(selectedSites[i]);
}
}
this.setOfferSites(offerSitesAux);
}
else{
this.setOfferSites(offerBean.getCustomerSites(customerId));
}
this.setHh_nhh_List(offerBean.getHHNHHList());
this.setAdq_ren_List(offerBean.getAdquisitionRenewList());
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer ProductId) {
this.productId = ProductId;
}
public List<TradebookVO> getTradeBookList() {
return tradeBookList;
}
public void setTradebookList(List<TradebookVO> tradeBookList) {
this.tradeBookList = tradeBookList;
}
public List<MddMeasurementClassVO> getMeasurementClassList() {
return measurementClassList;
}
public void setMeasurementClassList(List<MddMeasurementClassVO> MeasurementClassList) {
this.measurementClassList = MeasurementClassList;
}
public Integer getProfileClassId() {
return profileClassId;
}
public void setProfileClassId(Integer ProfileClassId) {
this.profileClassId = ProfileClassId;
}
public String getMeasurementClassId() {
return measurementClassId;
}
public void setMeasurementClassId(String MeasurementClassId) {
this.measurementClassId = MeasurementClassId;
}
public Integer getCurveId() {
return curveId;
}
public void setCurveId(Integer CurveId) {
this.curveId = CurveId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Date getOfferFromDate() {
return offerFromDate;
}
public void setOfferFromDate(Date OfferFromDate) {
this.offerFromDate = OfferFromDate;
}
public Date getOfferToDate() {
return offerToDate;
}
public void setOfferToDate(Date OfferToDate) {
this.offerToDate = OfferToDate;
}
public Integer getTradeBookId() {
return tradeBookId;
}
public void setTradeBookId(Integer tradeBookId) {
this.tradeBookId = tradeBookId;
}
public Map<String, String> getManagers() {
return managers;
}
public void setManagers(Map<String, String> managers) {
this.managers = managers;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public String getCopcOfferSelection() {
return copcOfferSelection;
}
public void setCopcOfferSelection(String copcOfferSelection) {
this.copcOfferSelection = copcOfferSelection;
}
public String getComcOfferSelection() {
return comcOfferSelection;
}
public void setComcOfferSelection(String comcOfferSelection) {
this.comcOfferSelection = comcOfferSelection;
}
public Map<String, String> getCotOfferTypes() {
return cotOfferTypes;
}
public void setCotOfferTypes(Map<String, String> cotOfferTypes) {
this.cotOfferTypes = cotOfferTypes;
}
public String getCotOfferSelection() {
return cotOfferSelection;
}
public void setCotOfferSelection(String cotOfferSelection) {
this.cotOfferSelection = cotOfferSelection;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public SelectItem[] getCotOfferList() {
return cotOfferList;
}
public void setCotOfferList(SelectItem[] cotOfferList) {
this.cotOfferList = cotOfferList;
}
private void loadProfileClass() {
FacesMessage msg = null;
try{
log.debug("ProfileClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List ProfileClassLista = offerBean.getProfileClassList(offerHH_NHH);
this.setProfileClassList((ArrayList<ProfileClassVO>) ProfileClassLista);
if(ProfileClassLista == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Profile_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("ProfileClassLista: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
private void loadMeasurementClass() {
FacesMessage msg;
try{
log.debug("MeasurementClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List MeasureClassList = offerBean.getMeasurementClassList();
this.setMeasurementClassList((ArrayList<MddMeasurementClassVO>) MeasureClassList);
if(measurementClassList == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Measurement_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("loadMeasurementClass: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
}
I have injected one request scoped bean into another view scoped bean
You're not allowed to inject a bean into another bean of a wider scope.
As a rule, the following abominations are not allowed :)
#RequestScoped >> #ViewScoped
#ViewScoped >>#SessionScoped
#SessionScoped >> #ApplicationScoped
EDIT (Based on your update): Injecting a property of a bean, as against injecting the bean itself, will result in a static injection. The static injection means that the value that's injected into the target is what's available as at the time of injection. As a the time the following line was executed:
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
selectedSites is null. So what you should be doing there instead is injecting the entire bean
#ManagedProperty(value="#{selectOfferMpans}")
This way, you'll have access to the current value of whatever variable you're interested in

Resources