Combining attributes in a class - java

I have the following custom class
class rollingD {
private String settDate;
private String publishingPeriodCommencingTime;
private String fuelTypeGeneration;
public String getSettDate() {
return settDate;
}
public void setSettDate(String settDate) {
this.settDate = settDate;
}
public String getPublishingPeriodCommencingTime() {
return publishingPeriodCommencingTime;
}
public void setPublishingPeriodCommencingTime(String publishingPeriodCommencingTime) {
this.publishingPeriodCommencingTime = publishingPeriodCommencingTime ;
}
public String getFuelTypeGeneration() {
return fuelTypeGeneration;
}
public void setFuelTypeGeneration(String fuelTypeGeneration) {
this.fuelTypeGeneration = fuelTypeGeneration;
}
#Override
public String toString() {
return String.format("%s,%s,%s",
settDate,
publishingPeriodCommencingTime,
fuelTypeGeneration);
}}
The items add to my array list as below
ArrayList<rollingD> aList = new ArrayList<>();
The attributes
settDate
and
publishingPeriodCommencingTime
are separate entities
01/04/2020
and
21:34:26
What i would like to do is within my class i want to combine my attributes before adding them to the array list
so i would end up with
01/04/2020 21:34:26
as a single attribute
I would therefore only have 2 attributes in my arraylist which i can then sort etc
Can someone provide assistance please.
I have tried streaming a map afterwards and combining the streams after but i realised that is not an ideal solution as i need to then work with the arraylist further down the line and ideally with datetimestamp and the value as my only two items
This is the code for parsing the API
while(parser.hasNext()) {
XMLEvent event = parser.nextEvent();
switch(event.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();
String qName = startElement.getName().getLocalPart();
if (qName.equalsIgnoreCase("settDate")) {
rD = new rollingD(null,null,null);
bMarks = true;
} else if (qName.equalsIgnoreCase("publishingPeriodCommencingTime")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("fuelTypeGeneration")) {
bNickName = true;
aList.add(rD);
}
break;
case XMLStreamConstants.CHARACTERS:
Characters characters = event.asCharacters();
if(bMarks) {
// System.out.println("settDate: " + characters.getData());
rD.getTimeStamp(characters.getData(),null,null);
bMarks = false;
}
if(bLastName) {
// System.out.println("publishingPeriodCommencingTime: " + characters.getData());
rD.getTimeStamp(null,characters.getData(),null);
bLastName = false;
}
if(bNickName) {
// System.out.println("fuelTypeGeneration: " + characters.getData());
rD.getTimeStamp(null,null,characters.getData());
bNickName = false;
}
break;
case XMLStreamConstants.END_ELEMENT:
EndElement endElement = event.asEndElement();
//List<String> namesList = aList.stream()
//.map(x->x.getSettDate()+" "+ x.getPublishingPeriodCommencingTime()+","+ x.getFuelTypeGeneration())
//.collect(Collectors.toList());
//Collections.sort(namesList);
//
//for (String name : namesList) {
//System.out.println(name);
//}
if(endElement.getName().getLocalPart().equalsIgnoreCase("item")) {
System.out.println();
}
break;
}
}

Do it as follows:
class RollingD {
private String settDate;
private String publishingPeriodCommencingTime;
private String fuelTypeGeneration;
private String timeStamp;
public RollingD(String settDate, String publishingPeriodCommencingTime, String fuelTypeGeneration) {
this.settDate = settDate;
this.publishingPeriodCommencingTime = publishingPeriodCommencingTime;
this.fuelTypeGeneration = fuelTypeGeneration;
timeStamp = settDate != null && publishingPeriodCommencingTime != null && !settDate.isEmpty()
&& !publishingPeriodCommencingTime.isEmpty() ? settDate + " " + publishingPeriodCommencingTime : "";
}
public String getTimeStamp() {
return settDate != null && publishingPeriodCommencingTime != null && !settDate.isEmpty()
&& !publishingPeriodCommencingTime.isEmpty() ? settDate + " " + publishingPeriodCommencingTime : "";
}
// ..Do not create any setter for timeStamp
// ..Other getters and setters
#Override
public String toString() {
return "RollingD [settDate=" + settDate + ", publishingPeriodCommencingTime=" + publishingPeriodCommencingTime
+ ", fuelTypeGeneration=" + fuelTypeGeneration + ", timeStamp=" + timeStamp + "]";
}
}
Demo:
public class Main {
public static void main(String[] args) {
RollingD rd1 = new RollingD("", "", "G");
System.out.println(rd1);
RollingD rd2 = new RollingD("01/04/2020", "", "G");
System.out.println(rd2);
RollingD rd3 = new RollingD("", "21:34:26", "G");
System.out.println(rd3);
RollingD rd4 = new RollingD("01/04/2020", "21:34:26", "G");
System.out.println(rd4);
}
}
Output:
RollingD [settDate=, publishingPeriodCommencingTime=, fuelTypeGeneration=G, timeStamp=]
RollingD [settDate=01/04/2020, publishingPeriodCommencingTime=, fuelTypeGeneration=G, timeStamp=]
RollingD [settDate=, publishingPeriodCommencingTime=21:34:26, fuelTypeGeneration=G, timeStamp=]
RollingD [settDate=01/04/2020, publishingPeriodCommencingTime=21:34:26, fuelTypeGeneration=G, timeStamp=01/04/2020 21:34:26]

The are some miss-concepts on your approach.
Do not need to do any combinations of parameters inside base object(or before adding to).
Just added as you did the objects on List Data Structure
Your issues is maybe: How to process further the list, based on stored-objects
properties.(eg: sorting based on names, date_hours,etc)
Here I strongly advise to search on List methods capabilities.(using a comparator, etc)

Related

Why is my Java Program returning only the last String in an ArrayList

I want my Java Program to return a String response based on if/else conditions but it only responds to the last element in the ArrayList.
I have been working on this for two days without success.
I will appreciate a direction as to what am doing wrongly. Thank You
import java.io.IOException;
import java.util.logging.Logger;
public class ScanUtility implements IScanUtility {
Logger logger = Logger.getLogger("ScanUtility");
private String performHostScan(String nodeName) {
Process OSCmdProcess = null;
Integer exitValue = null;
String OScmd = null;
String exitMessage = null;
String OScmd = new String("/usr/bin/ssh ansible#" + nodeName + " " + "/tmp/openscapscan.bash rheldisa");
try {
OSCmdProcess = Runtime.getRuntime().exec(OScmd);
exitValue = OSCmdProcess.waitFor();
if (exitValue.equals(0)) {
exitMessage = ("Succeeded on" + " " + nodeName);
return exitMessage;
} else {
exitMessage = ("Failed on" + " " + nodeName);
return exitMessage;
}
} catch (IOException ioExcep) {
ioExcep.printStackTrace();
} catch (InterruptedException interExcep) {
interExcep.printStackTrace();
}
return exitMessage;
}
//This method takes an ArrayList of hosts from the servlet controller
// and passes the list to the ScanUtility Method above
//============================================================
public String generateHostName(List<String> addressList){
String statusMessage = null;
for(String nodeName: addressList){
statusMessage = new ScanUtility().performHostScan(nodeName);
}
return statusMessage;
}
}
The problem is that you are overwriting statusMessage on ever iteration of your loop. I believe what you want to do is put all the Strings into an ArrayList<String>.
public ArrayList<String> generateHostName(List<String> addressList){
ArrayList<String> statusMessage = new ArrayList<>();
for(String nodeName: addressList){
statusMessage.add(new ScanUtility().performHostScan(nodeName));
}
return statusMessage;
}
Apparently, you want to return a list of status messages (a status message from each server that you are scanning).
public List<String> getResponsesFromAddresses(List<String> addresses) {
final ScanUtility scanUtility = new ScanUtility();
return addresses.stream()
.map(scanUtility::performHostScan)
.collect(Collectors.toList());
}
The method name is misleading. I have changed it to getResponsesFromAddresses - that is what the method actually does.
Try this:
public List<String> generateHostName(List<String> addressList){
List<String> statusMessages = new ArrayList<>();
for(String nodeName: addressList){
statusMessages.add(new ScanUtility().performHostScan(nodeName));
}
return statusMessages;
}

Using array as key for hashmap java

i have a method that puts some value(obtained from an excel file) into a hashmap with an array as the key
public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws
IOException
{
System.out.println(engine.txtY + "Processing HashMap "
+ "sbsBusServiceData..." + engine.txtN);
int counterPass = 0, counterFail = 0, stopCounter = 0;
String dataExtract, x = "";
String[] stopInfo = new String[3];
List<String[]> stopsData = new ArrayList<String[]>();
List<String> serviceNum = new Vector<String>();
HashMap<List<String>, List<String[]>> sbsBusServiceData =
new HashMap<List<String>, List<String[]>>();
String dataPath = this.dynamicPathFinder(
"Data\\SBS_Bus_Routes.csv");
BufferedReader sbsBusServiceDataPop = new BufferedReader(
new FileReader(dataPath));
sbsBusServiceDataPop.readLine();
//Skips first line
while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
try {
String[] dataParts = dataExtract.split(",", 5);
if (!dataParts[4].equals("-")){
if (Double.parseDouble(dataParts[4]) == 0.0){
sbsBusServiceData.put(serviceNum, stopsData);
String serviceNum1 = "null", serviceNum2 = "null";
if(!serviceNum.isEmpty()){
serviceNum1 = serviceNum.get(0);
serviceNum2 = serviceNum.get(1);
}
System.out.println("Service Number " + serviceNum1
+ ":" + serviceNum2 + " with " + stopCounter
+ " stops added.");
stopCounter = 0;
//Finalizing previous service
serviceNum.Clear();
serviceNum.add(0, dataParts[0]);
serviceNum.add(1, dataParts[1]);
//Adding new service
}
}
stopInfo[0] = dataParts[2];
stopInfo[1] = dataParts[3];
stopInfo[2] = dataParts[4];
stopsData.add(stopInfo);
//Adding stop to service
stopCounter++;
counterPass++;
}
catch (Exception e) {
System.out.println(engine.txtR + "Unable to process "
+ dataExtract + " into HashMap sbsBusServiceData."
+ engine.txtN + e);
counterFail++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG + counterPass + " number of lines"
+ " processed into HashMap sbsBusServiceData.\n" + engine.txtR
+ counterFail + " number of lines failed to process into "
+ "HashMap sbsBusServiceData.");
return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction},
// <{RouteSequence, bsCode, Distance}>
this method work for putting the values into the hashmap but i cannot seem to get any value from the hashmap when i try to call it there is always a nullpointerexception
List<String> sbsTest = new Vector<String>();
sbsTest.add(0, "10");
sbsTest.add(1, "1");
System.out.println(sbsBusServiceData.get(sbsTest));
try{
List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
String x = sbsServiceResults.get(1)[0];
System.out.println(x);
} catch(Exception e){
System.out.println(txtR + "No data returned" + txtN + e);
}
this is a sample of the file im reading the data from:
SBS
How can i get the hashmap to return me the value i want?
Arrays are not suitable as keys in HashMaps, since arrays don't override Object's equals and hashCode methods (which means two different array instances containing the exact same elements will be considered as different keys by HashMap).
The alternatives are to use a List<String> instead of String[] as the key of the HashMap, or to use a TreeMap<String[]> with a custom Comparator<String[]> passed to the constructor.
If you are having fixed array size then the example I'm posting might be useful.
Here I've created two Object one is Food and Next is Product.
Here Food object is use and added method to get string array.
public class Product {
private String productName;
private String productCode;
public Product(String productName, String productCode) {
this.productName = productName;
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Food Model Class: Use as a Object instead of String[] and achieve String[] functionality.
public class Food implements Comparable<Food> {
private String type;
private String consumeApproach;
public Food(String type, String consumeApproach) {
this.type = type;
this.consumeApproach = consumeApproach;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConsumeApproach() {
return consumeApproach;
}
public void setConsumeApproach(String consumeApproach) {
this.consumeApproach = consumeApproach;
}
public String[] FoodArray() {
return new String[] { this.type, this.consumeApproach };
}
//Implement compareTo method as you want.
#Override
public int compareTo(Food o) {
return o.getType().compareTo(this.type);
}
}
Using HashMap example
public class HashMapKeyAsArray {
public static void main(String[] args) {
HashMap<Food,List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static HashMap<Food,List<Product>> dataSetLake(){
HashMap<Food,List<Product>> data = new HashMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple","123"));
fruitA.add(new Product("Banana","456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato","999"));
vegetableA.add(new Product("Tomato","987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple","123"));
fruitB.add(new Product("Banana","456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato","999"));
vegetableB.add(new Product("Tomato","987"));
Food foodA = new Food("Fruits","Read To Eat");
Food foodB = new Food("Vegetables","Need To Cook");
Food foodC = new Food("VegetablesC","Need To Cook C");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodC, vegetableA);
return data;
}
Using TreeMap example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class TreeMapKeyAsArray {
public static void main(String[] args) {
TreeMap<Food, List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static TreeMap<Food, List<Product>> dataSetLake() {
TreeMap<Food, List<Product>> data = new TreeMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple", "123"));
fruitA.add(new Product("Banana", "456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato", "999"));
vegetableA.add(new Product("Tomato", "987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple", "123"));
fruitB.add(new Product("Banana", "456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato", "999"));
vegetableB.add(new Product("Tomato", "987"));
Food foodA = new Food("Fruits", "Read To Eat");
Food foodB = new Food("Vegetables", "Need To Cook");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodB, vegetableA);
return data;
}
}

Having Error while recurssing though A list of Objects that contains another List

I have a class in Java which has an object
List<GroupNavigationItemSRO> children
Now Every GroupNaviagationItemSRO has the same List
List<GroupNavigationItemSRO> children
NOw i want to iterate through every GroupNavigationSRO and populate a List of String . Currently i am trying to do that like this
void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){
System.out.println("PRINT");
for(GroupNavigationItemSRO item : items) {
nitems.add(item.getUrl());
System.out.println(item.getUrl());
// g.add(item.getUrl());
System.out.println("PRINT");
List<GroupNavigationItemSRO> nextItem = item.getChildren();
if (nextItem != null && nextItem.size()>0) {
getNavItems(nextItem,nitems);
}
}
}
When i only print the objects ,it doesn't give any errors But as soon as i try and add to the List the recurssion stops
nitems.add(item.getUrl())
Why is this happening . Here's the entire java file in case its helpful
#Service("labelSearchService")
public class LabelSearchServiceImpl extends AbstractSearchService {
private static final String version = SearchVersion.VERSION_2.getValue();
private static final Logger LOG = LoggerFactory.getLogger(LabelSearchServiceImpl.class);
private static final String EXPIRY_SET = "expiry";
private static final String DATA_SET = "data";
#Autowired
#Qualifier("searchServiceFactory")
private ISearchServiceFactory searchServiceFactory;
#Autowired
IAerospikeTopSellingBrandsCacheService topSellingBrandsCacheService;
#Autowired
private LabelSearchCacheServiceImplFactory labelSearchCacheServiceImplFactory;
#Autowired
AerospikeGuidedResponse aerospikeGuidedResponse ;
List<String> g = null;
#Override
public SearchSRO getSolrResponse(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, String sortBy,
String userZone, String vertical, String clickSrc, boolean isSpellCheckEnabled, String categoryURL, boolean isNested) throws SearchException, ShardNotFoundException, IllegalAccessException {
String originalKeyword = searchTerm;
searchTerm = SearchUtils.modifySearchTerm(searchTerm);
SearchSRO sro = new SearchSRO();
boolean isPartialSearch = SearchUtils.isPartialSearchEnabled();
keyGenerator.setPartialSearch(SearchUtils.isPartialSearchEnabled());
LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL);
// for 'ALL' categories labelNode would be null.
LOG.info("categoryURL : " + categoryURL);
if (ALL.equals(categoryURL)) {
if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) {
return new SearchSRO();
}
sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical,
isPartialSearch, isSpellCheckEnabled, originalKeyword, false, isNested);
} else if (labelNode != null) {
sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled,
originalKeyword, isNested, false,categoryURL);
} else {
throw new SearchException("Search was hit without selecting any category");
}
// this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget'
SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) {
LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)
+ " but number of matched results are " + sro.getNoOfMatches());
sro = new SearchSRO();
}
return sro;
}
#Override
public SearchSRO getSolrResponseForMobile(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number,
String sortBy, String userZone, String vertical, String clickSrc, boolean isBinSearch, int noOfResultsPerBin, boolean isSpellCheckEnabled, boolean isPartialSearch,
String categoryURL) throws SearchException, ShardNotFoundException, IllegalAccessException {
String originalKeyword = searchTerm;
searchTerm = SearchUtils.modifySearchTerm(searchTerm);
SearchSRO sro = new SearchSRO();
isPartialSearch = isPartialSearch && SearchUtils.isPartialSearchEnabled();
// this is to disable partial search in case of PWSTBT
if (ClickSourceType.PWSTBT_WIDGET.getValue().equalsIgnoreCase(clickSrc)) {
isPartialSearch = false;
}
LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL);
// for 'ALL' categories labelNode would be null
if (ALL.equals(categoryURL)) {
if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) {
return new SearchSRO();
}
// Response for Search result page in mobile - same as web.
sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical,
isPartialSearch, isSpellCheckEnabled, originalKeyword, true, false);
} else if (labelNode != null) {
sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled,
originalKeyword, false, true,categoryURL);
} else {
throw new SearchException("Search was hit without selecting any category");
}
// this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget'
SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) {
LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)
+ " but number of matched results are " + sro.getNoOfMatches());
sro = new SearchSRO();
}
return sro;
}
#Autowired
private IUserPersonaSegmentService personaSegmentService;
#Autowired
private IContextHolder<SearchRequestContext> ctxProvider;
private boolean isClientPersonaEnabled(SearchRequestContext ctx) {
SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
String clientsEnabled = cache.getProperty(SearchProperty.PERSONA_CLIENTS_ENABLED);
String client = ctx.req.getContextSRO().getAppIdent();
return !StringUtils.isEmpty(client) && !StringUtils.isEmpty(clientsEnabled) && Pattern.matches("(?i).*\\b" + client + "\\b.*", clientsEnabled);
}
protected UserSegmentDTO setupPersonalizationContext(LabelNodeSRO labelNode, String searchTerm, String sortBy) {
SearchRequestContext ctx = ctxProvider.getContext();
if (ctx == null || ctx.req == null) {
LOG.warn("No Request Context found");
return null;
}
SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
// check if Personalization is enabled
if (labelNode == null || !cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) || StringUtils.isEmpty(searchTerm)
|| !SolrSortCategory.RELEVANCY.getValue().equalsIgnoreCase(sortBy) || !isClientPersonaEnabled(ctx)) {
LOG.debug("Personalization not enabled");
return null;
}
LOG.info("Trying to set up personalization context");
// setup the context for later use
ctx.personaSegments = personaSegmentService.getUserSegments(ctx.req.getUserTrackingId(), labelNode.getNodePath());
return ctx.personaSegments;
}
#Override
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode,
int start, int number, String sortBy, String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, boolean isNested, boolean isMobile,String categoryURL)
throws SearchException, ShardNotFoundException, IllegalAccessException {
LOG.info("------------------Product category page---------------");
// build cache key considering campaign id
keyGenerator.setCampaignId(String.valueOf(campaignId));
// Search results will vary based on isNested flag even for exact same keywords hence, when we cache
// we cache both results with different key
keyGenerator.setNested(isNested);
SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class);
LOG.info("sortBy : " + sortBy + ", personalization Enabled : " + cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) + ", labelNode : " + labelNode);
// try to set persona context
keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, searchTerm, sortBy));
SearchSRO searchSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch,
isSpellCheckEnabled, originalKeyword, isNested, isMobile,categoryURL);
/*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();
if (coreContext != null) {
if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
String cacheKey = keyGenerator.buildKey();
try {
final AerospikeClient aClient = AerospikeClientFactory.getInstance();
LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
aClient.delete(null, new Key("search", DATA_SET, cacheKey));
} catch (AerospikeException e) {
e.printStackTrace();
}
}
}*/
return searchSRO;
}
#Override
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, boolean partialSearch, boolean isBrand, String categoryUrl,
String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes, GetFiltersRequest request) throws SearchException, ShardNotFoundException {
String key = new KeyGenerator(String.valueOf(categoryId), String.valueOf(campaignId), q, keyword, partialSearch, null, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey();
if (campaignId != null) {
LOG.info("Get Filters for Campaign Products wrt : " + key);
}
FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFiltersForProducts(key, categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,request);
return filterListSRO;
}
#Override
public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword,
boolean partialSearch, boolean isBrand, String categoryUrl, String userZone,
HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes)
throws SearchException, ShardNotFoundException {
return getFiltersForProducts(categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,null);
}
#Override
public FilterListSRO getFilterValuesForFilter(String categoryId, String campaignId, String q, String keyword, boolean partialSearch, String filterName, String fullQ,
String categoryUrl, String[] filtersToFetch, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException, NumberFormatException, ShardNotFoundException {
String uniqueFilterKey = new KeyGenerator(categoryId, campaignId, q, keyword, partialSearch, filterName, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey();
String[] filterNames = filterName.split(",");
FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFilterValuesForFilter(uniqueFilterKey, categoryId, campaignId, q, keyword, partialSearch, filterNames, categoryUrl, filtersToFetch,
userZone, hyperlocalCriteria, pinCodes);
/*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();
if (coreContext != null) {
if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
String cacheKey = uniqueFilterKey.concat(".FilterSRO");
try {
final AerospikeClient aClient = AerospikeClientFactory.getInstance();
LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
aClient.delete(null, new Key("search", DATA_SET, cacheKey));
} catch (AerospikeException e) {
e.printStackTrace();
}
}
}*/
return filterListSRO;
}
#Override
public GroupNavigationSRO getGroupNavigation(KeyGenerator keyGenerator, String keyword, String q, String categoryUrl, Integer campaignId, boolean isSpellCheck, String userZone) throws IllegalAccessException {
GroupNavigationSRO sro = new GroupNavigationSRO();
try {
ProductCategoryCache categoryCache = CacheManager.getInstance().getCache(ProductCategoryCache.class);
LabelNodeSRO labelNode = ALL.equals(categoryUrl) ? null : categoryCache.getLabelForLabelPath(categoryUrl);
if (!ALL.equals(categoryUrl) && labelNode == null) {
LOG.error("Invalid label : " + categoryUrl);
return null;
}
// try to setup persona context - using sort to relevancy since group left nav doesn't change with sortBy
keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, keyword, SolrSortCategory.RELEVANCY.getValue()));
sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGroupNavigation(keyGenerator, keyword, q, categoryUrl, campaignId, isSpellCheck, userZone);
/*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext();
if (coreContext != null) {
if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) {
String cacheKey = keyGenerator.buildKey().concat(".GroupNavigationSRO");
try {
final AerospikeClient aClient = AerospikeClientFactory.getInstance();
LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey);
aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey));
aClient.delete(null, new Key("search", DATA_SET, cacheKey));
} catch (AerospikeException e) {
e.printStackTrace();
}
}
}*/
} catch (SearchException e) {
LOG.error("Error in fetching GroupSRO: ", e);
}
return sro;
}
#Override
public QueryResponse setCategoryFilterQueryAndExecute(SearchCriteria sc, Integer id) throws SearchException {
labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().setCategoryFilterQuery(sc, id);
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().executeQuery(sc.buildQuery(), id);
}
#Override
public Long getProductCategoryCount(Integer categoryId, String categoryUrl) {
Long count = CacheManager.getInstance().getCache(ProductCategoryCache.class).getCategoryCountByUrl(categoryUrl);
if (count == null) {
count = new Long(0);
}
LOG.info("Product Category Counts for CategoryUrl: " + categoryUrl + " = " + count);
return count;
}
#Override
public List<TopSellingProductCategorySRO> getTopSellingProductsforCategories(List<Integer> categoryIds, List<String> categoryUrls) {
List<TopSellingProductCategorySRO> topSellingProductCategorySROs = new ArrayList<TopSellingProductCategorySRO>();
for (String categoryUrl : categoryUrls) {
try {
TopSellingProductCategorySRO topSellingProductCategorySRO = null;
Integer searchId = ShardResolverService.getSearchIdByLabel(categoryUrl);
QueryResponse rsp = searchServiceFactory.getSearchService(SearchVersion.VERSION_2.getValue()).getTopProductsInfoById(searchId,
CacheManager.getInstance().getCache(SearchConfigurationCache.class).getIntegerProperty(SearchProperty.MAX_TOP_SELLING_PRODUCTS_PER_CATEGORY));
List<Long> pogIds = SearchUtils.extractTopProductsByCategoryId(rsp);
if (pogIds != null && !pogIds.isEmpty()) {
topSellingProductCategorySRO = new TopSellingProductCategorySRO(categoryUrl, pogIds);
topSellingProductCategorySROs.add(topSellingProductCategorySRO);
}
} catch (Exception e) {
LOG.error("Unable to get Top Selling Products for categoryId: " + categoryUrl + ", Exception:" + e.getMessage());
}
}
return topSellingProductCategorySROs;
}
#Override
public List<TopSellingBrandSRO> getTopSellingBrandsforCategories(List<Integer> categoryIds, List<String> categoryUrls) {
List<TopSellingBrandSRO> topSellingBrandSROs = new ArrayList<TopSellingBrandSRO>();
for (String categoryUrl : categoryUrls) {
TopSellingBrandSRO topSellingBrandSRO = topSellingBrandsCacheService.getTopSellingBrandsByUrl(categoryUrl);
if (topSellingBrandSRO != null) {
topSellingBrandSROs.add(topSellingBrandSRO);
}
}
return topSellingBrandSROs;
}
#Override
public List<TopSellingBrandSRO> getAllTopSellingProducts(){
List<TopSellingBrandSRO> topSellingBrandSROs = topSellingBrandsCacheService.getAllTopSellingProducts();
return topSellingBrandSROs;
}
#Override
public FacetSRO getFacets(String cachekey, String keyword, String queryFieldName, String[] facetFields, Map<String, List<String>> filterMap, int number) throws SearchException {
// update values for mainCategoryXpath & categoryXpath fields
/*if(SolrFields.CATEGORY_XPATH.equals(queryFieldName) || SolrFields.MAIN_CATEGORY_XPATH.equals(queryFieldName)) {
String labelPath = SearchUtils.getLabelPathByUrl(keyword);
keyword = String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath));
}*/
for (String filterField : filterMap.keySet()) {
if (SolrFields.CATEGORY_XPATH.equals(filterField) || SolrFields.MAIN_CATEGORY_XPATH.equals(filterField)) {
List<String> searchIds = new ArrayList<String>();
for (String val : filterMap.get(filterField)) {
String labelPath = SearchUtils.getLabelPathByUrl(val);
searchIds.add(String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath)));
}
filterMap.put(filterField, searchIds);
}
}
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFacets(cachekey, keyword, queryFieldName, facetFields, filterMap, number);
}
#Override
public FilterListSRO getSRPFilters(KeyGenerator keyGenerator, String q, String keyword, boolean partialSearch, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException {
if (StringUtils.isEmpty(keyword)) {
LOG.error("Invalid parameters.");
return null;
}
keyword = SearchUtils.modifySearchTerm(keyword);
if (StringUtils.isEmpty(keyword)) {
LOG.info(" Returning empty filters for empty keyword.");
return new FilterListSRO();
}
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSRPFilters(keyGenerator.buildKey(), q, keyword, partialSearch, categoryUrl, userZone, hyperlocalCriteria, pinCodes);
}
#Override
public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm,
Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, int start, int number, String sortBy,
String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword,
boolean isNested, boolean isMobile) throws SearchException, ShardNotFoundException, IllegalAccessException {
// TODO Auto-generated method stub
return getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, isMobile, null);
}
#Override
public String getmodelSearch(String query, String type) throws SearchException {
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getmodelSearch(query, type);
}
#Override
public String classifierResponse(String query, String type) throws SearchException {
try {
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getClassifierResponse(query, type);
} catch (JsonGenerationException e) {
return e.getMessage();
} catch (JsonMappingException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
}
public GetGuidedSearchResponse getGuides(String query, String url) {
if(!StringUtils.isEmpty(query) && !StringUtils.isEmpty(url) && url.equalsIgnoreCase("ALL"))
{
KeyGenerator keyGenerator = new KeyGenerator();
keyGenerator.setQ("sNapDeAl.sEarcH.getGuides=" +"##"+ query+ "##"+ url);
return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGuides(keyGenerator, query, url);
}
return null;
}
public GetGuidedSearchResponse getFilteredGuides(String query ,GetGroupLeftNavResponse leftNavBarResponse) {
g=null;
GroupNavigationSRO groups = leftNavBarResponse.getGroups();
List<GroupNavigationItemSRO> items = groups.getItems() ;
// List<String> nitems = getNavItems(items);
List<String> nitems = null;
getNavItems(items,nitems);
System.out.println("SIZE" + nitems.size());
List<String> navItems = new ArrayList<String>();
System.out.println("GETTING GUIDED FILE FROM AEROSPIKE");
List<String> guideItems = aerospikeGuidedResponse.getGuides(query);
//HashMap<String,String> nodeUrlMapping = new HashMap<String,String>();
if(guideItems.isEmpty())
{
System.out.println("\n\n\n\n" + "EMPTY GUIDED" + " \n\n\n\n\n");
}
guideItems.set(0, guideItems.get(0).trim());
System.out.println("GUIDED RESPONSE");
for(int i=0 ; i < guideItems.size() ;i ++)
{
System.out.println(guideItems.get(i));
}
/*for (int i =0 ;i < items.size() ;i++) {
List<GroupNavigationItemSRO> children_items = items.get(i).getChildren();
String s = items.get(i).getNodePath();
String m = items.get(i).getUrl();
System.out.println(s + " " + m);
navItems.add(m);
//nodeUrlMapping.put(s,m);
for (int j=0;j<children_items.size();j++) {
String r = children_items.get(j).getNodePath();
String n = children_items.get(j).getUrl();
System.out.println(r +" " + n);
// nodeUrlMapping.put(r,n);
navItems.add(n);
}
}*/
System.out.println("ITEM RESPONSE");
//navItems = g ;
for(int i=0 ; i < navItems.size() ;i ++)
{
System.out.println(navItems.get(i));
}
List<String> filteredGuides = new ArrayList<String>();
for(int i=0 ; i < guideItems.size() ;i++)
{
if(navItems.contains(guideItems.get(i)))
filteredGuides.add(guideItems.get(i));
else {
}
}
System.out.println("NAV ITEMS" + navItems.size() + navItems.toString());
System.out.println("GUIDE ITEMS" + filteredGuides.size() + filteredGuides.toString());
List<WidgetEntity> entities = new ArrayList<WidgetEntity>();
/* Iterator it = nodeUrlMapping.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}*/
for(int i=0;i<filteredGuides.size();i++)
{
String guide = filteredGuides.get(i);
guide = guide.trim();
System.out.println(guide);
LabelNodeSRO labelSRO = getLableSRO(guide);
System.out.println(labelSRO.toString() + guide);
WidgetEntity entity = new WidgetEntity();
entity.setId(labelSRO.getUrl());
entity.setName(labelSRO.getDisplayName());
entity.setType("category");
entities.add(entity);
}
System.out.println("ENTITIES DEtails" );
GetGuidedSearchResponse response = new GetGuidedSearchResponse();
for(int i =0 ;i<entities.size();i++)
{
System.out.println(entities.get(i).getId() + entities.get(i).getName() + entities.get(i).getType());
// System.out.println(nodeUrlMapping.get(entities.get(i).getId()));
}
response.setEntities(entities);
return response;
}
LabelNodeSRO getLableSRO(String guide)
{
System.out.println(guide + "GET");
LabelNodeSRO label =SearchUtils.getLabelNodeByNodePath(guide);
return label;
}
void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){
System.out.println("PRINT");
for(GroupNavigationItemSRO item : items) {
nitems.add(item.getUrl());
System.out.println(item.getUrl());
// g.add(item.getUrl());
System.out.println("PRINT");
List<GroupNavigationItemSRO> nextItem = item.getChildren();
if (nextItem != null && nextItem.size()>0) {
getNavItems(nextItem,nitems);
}
}
}
}
You could try something like this, when you return a list with all Strings, and if there are no more elments stop the recursivity and returns an empty list
List<String> getNavItems(List<GroupNavigationItemSRO> items){
List<String> results = new ArrayList();
System.out.println("PRINT");
if(items != null && !items.isEmpty()){
for(GroupNavigationItemSRO item : items) {
results.add(item.getUrl());
System.out.println(item.getUrl());
// g.add(item.getUrl());
System.out.println("PRINT");
results.addAll(getNavItems(item.getChildren()));
}
}
}
return results;
}
In getFilteredGuides() method you're passing nitems as null and this would cause NullPointerException.
Just Pass it as the following:
List<String> nitems = new ArrayList<String>();
getNavItems(items,nitems);
Or you can add a check for null inside getNavItems() method and initialize it accordingly:
void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){
if(nitems == null)
{
nitems = new ArrayList<String>();
}
System.out.println("PRINT");
for(GroupNavigationItemSRO item : items) {
nitems.add(item.getUrl());
System.out.println(item.getUrl());
// g.add(item.getUrl());
System.out.println("PRINT");
List<GroupNavigationItemSRO> nextItem = item.getChildren();
if (nextItem != null && nextItem.size()>0) {
getNavItems(nextItem,nitems);
}
}
}

Handling a .data file with uneven whitespaces delimited and populate to an bean object using java program

How to handle file data as shown below, which is delimited by uneven whitespaces, where if tokenizer is used based on space, it'll give tokens which cannot be assigned to java bean fields directly.
Below is the content Data of cheapdata4.data:
(TX 260816.<
0954F2003EGGPLEIBLNX37PU ZC550 Z <CA C A L L8 STAF P18 UL15 KIDL
0001F0148BIKFEDDSGWI2797 ZA319 Z <CATGWI2 C M V104 GMH4 GMH UL60 EDDS
4893F1416EGPGEGHFGJOID ZSR20 Z <AAEGPGD C A LT TLA DCS L612 N859 Q41
7945F1400EGSHEGCCLOG63JF ZD328 Z <(A C A R L OTBE Y70 EGCC
7946F1647EGSHEGGWAZE01F ZE50P Z <(A C A R LT MAM1 LAPR ABBO BKY2
7947F1701EGSHEGCCLOG63JF ZD328 Z <(A C A R L / MAM0 OTBE POL ROSU
4368F1657ESSBEGGWBLJ59BF ZC56X Z <RAUBLJ5 A LT UN86 UP7 UP25 EGGW
4369F1728ESSBEGCCETI226L MLJ45 012<RAUETI2 A L UL97 Y70 EGCC
4370F0551LHBPEGGWWZZ196 ZA321 Z <RAUWZZ1 A MT UL60 UY6 UM20 EGGW
7950END 260816.<
package com.msa.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.msa.bean.CheapData;
public class FinalParser {
public static void main(String[] args) {
BufferedReader reader;
try {
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(
new FileReader(
"C:\\Users\\Desktop\\assignment\\cheapdata4.data"));
System.out.println("Reading file...");
String line = reader.readLine();
line = line.replaceAll("\\s{2,}", " ");
String[] toks = line.replace(" ", ",").trim().split(",");
line = line.replaceAll("\\s{2,}", " ");
String[] headerTokens = line.split(" +");
String fileStartDate = headerTokens[1].substring(0, 6);
List<String> cheapDataContent = new ArrayList<>();
String[] lineTokens = { "" };
CheapData cheapFileDets = null;
List<CheapData> cheapDataList = new ArrayList<>();
while (line != null) {
line = reader.readLine();
line = line.replaceAll("\\s{2,4}", " ");
// line = line.replaceAll("\\s{2}", " NA ");
// line = line.replaceAll(" ",", ");
// line = line.replaceAll("\\,{2}", "");
lineTokens = line.split(" +");
int len = lineTokens.length;
// String fileEndDate ="";
if (len == 2) {
String fileEndDate = lineTokens[1].substring(0, 6);
if (fileStartDate.equals(fileEndDate)) {
break;
} else {
System.out.println("Date mismatch...");
}
}
if (len >= 6) {
cheapFileDets = new CheapData();
String lineNum = lineTokens[0].substring(0, 4);
cheapFileDets.setLineNum(lineNum);
String cheapReference = lineTokens[0].substring(4);
cheapFileDets.setCheapReference(cheapReference);
cheapFileDets.setDate(fileStartDate);
cheapFileDets.setAircraftCode(lineTokens[1]);
cheapFileDets.setIdentifierCode(lineTokens[2]);
cheapFileDets.setLicenseCode(lineTokens[3]);
if (lineTokens[4].equals("C"))
cheapFileDets.setCodeOne(lineTokens[4]);
else
cheapFileDets.setCodeOne(null);
if (lineTokens[5].equals("A"))
cheapFileDets.setCodeTwo(lineTokens[5]);
else
cheapFileDets.setCodeTwo(null);
if (lineTokens[6].equals("R"))
cheapFileDets.setCodeThree(lineTokens[6]);
else
cheapFileDets.setCodeThree(null);
} else {
if (len == 7)
cheapFileDets.setIdCode(lineTokens[7]);
else
cheapFileDets.setIdCode(null);
}
List<String> miscList = new ArrayList<>();
for (int i = 7; i < len - 1; i++) {
miscList.add(lineTokens[i]);
}
StringBuilder miscAll = new StringBuilder("");
for (String miscs : miscList) {
miscAll.append(miscs + " ");
}
cheapFileDets.setMiscAll(miscAll.toString());
cheapDataList.add(cheapFileDets);
}
System.out.println("File content" + sb.toString());
System.out.println("file date is: " + fileStartDate);
System.out.println("*************");
/*
* for (String strToks : lineTokens) { System.out.println(strToks);
* }
*/
// System.out.println(cheapDataList);
Iterator<CheapData> itrCheapData = cheapDataList.listIterator();
while (itrCheapData.hasNext()) {
System.out.println(itrCheapData.next());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
package com.msa.bean;
public class CheapData {
private String lineNum;
private String date;
private String cheapReference;
private String aircraftCode;
private String identifierCode;
private String licenseCode;
private String codeOne;
private String codeTwo;
private String codeThree;
private String idCode;
private String miscAll;
public String getLineNum() {
return lineNum;
}
public void setLineNum(String lineNum) {
this.lineNum = lineNum;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCheapReference() {
return cheapReference;
}
public void setCheapReference(String cheapReference) {
this.cheapReference = cheapReference;
}
public String getAircraftCode() {
return aircraftCode;
}
public void setAircraftCode(String aircraftCode) {
this.aircraftCode = aircraftCode;
}
public String getIdentifierCode() {
return identifierCode;
}
public void setIdentifierCode(String identifierCode) {
this.identifierCode = identifierCode;
}
public String getLicenseCode() {
return licenseCode;
}
public void setLicenseCode(String licenseCode) {
this.licenseCode = licenseCode;
}
public String getCodeOne() {
return codeOne;
}
public void setCodeOne(String lineTokens) {
this.codeOne = lineTokens;
}
public String getCodeTwo() {
return codeTwo;
}
public void setCodeTwo(String lineTokens) {
this.codeTwo = lineTokens;
}
public String getCodeThree() {
return codeThree;
}
public void setCodeThree(String codeThree) {
this.codeThree = codeThree;
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
public String getMiscAll() {
return miscAll;
}
public void setMiscAll(String miscAll) {
this.miscAll = miscAll;
}
public CheapData(String lineNum, String date, String cheapReference,
String aircraftCode, String identifierCode, String licenseCode,
String codeOne, String codeTwo, String codeThree, String idCode,
String miscAll) {
super();
this.lineNum = lineNum;
this.date = date;
this.cheapReference = cheapReference;
this.aircraftCode = aircraftCode;
this.identifierCode = identifierCode;
this.licenseCode = licenseCode;
this.codeOne = codeOne;
this.codeTwo = codeTwo;
this.codeThree = codeThree;
this.idCode = idCode;
this.miscAll = miscAll;
}
#Override
public String toString() {
return "CheapData [lineNum=" + lineNum + ", date=" + date
+ ", cheapReference=" + cheapReference + ", aircraftCode="
+ aircraftCode + ", identifierCode=" + identifierCode
+ ", licenseCode=" + licenseCode + ", codeOne=" + codeOne
+ ", codeTwo=" + codeTwo + ", codeThree=" + codeThree
+ ", idCode=" + idCode + ", miscAll=" + miscAll + "]";
}
public CheapData() {
super();
}
}
Please can anyone help me out in this regard. I want to parse above file and populate each columns from that to an object using setters in java.
Please do suggest me how to achieve this and kindly let me know if my query not clear.

pass a HashMap by reference

I have a multiple-multi-dimensional HashMap() instances, I am using them to store hierarchical data from a database;
HashMap<String, HashMap<String, ArrayList<String>>>
I add to them with 3 primary methods that we'll refer to as addTop(), addMid() and addLow(). The methods all accept parameters that match their data group and a string, each method returns the next dimension of the HashMap();
public static HashMap<String, ArrayList<String>> addTop(HashMap<String, HashMap<String, ArrayList<String>>> data, String val) { ... };
public static ArrayList<String> addMid(HashMap<String, ArrayList<String>> data, String val) { ... };
public static String addLow(ArrayList<String> data, String val) { ... };
I call these, usually, in sequence in between a few checks and perform additional checks inside the methods. Essentially all these methods do is add val to data then return an empty HashMap();
out = new HashMap();
data.put(val, out);
return out;
When I check at the end of the loop/data-population all of the data from addMid() & addLow() is missing. Why is this?
I thought Java worked by reference when dealing with complex objects, such as HashMap().
What can I do to ensure that addMid() and addLow() update the master HashMap()?
EDIT: Included code. It compiles and runs but there are other problems, I have stripped out as much as I can to demonstrate whats happening, except the SQL stuff, that won't compile, sorry. the method that is run at start is sqlToArray();
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
public class Av2 {
protected class AvailLookup {
private Integer key;
private String value;
public AvailLookup(Integer inKey, String inValue) {
key = inKey;
value = inValue;
}
public void updateName(String name) {
value = name;
}
public Integer getKey() {
return key;
}
public String getValue() {
return value;
}
public String toString() {
return value;
}
}
private static HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> data = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
private static Sql sql = new Sql("PlantAvail");
public static HashMap<AvailLookup, ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
for (AvailLookup lookup : inArray.keySet()) {
if (lookup.getKey() == channel) {
out = inArray.get(lookup);
System.out.println("Channel: " + channel + " found");
break;
}
}
if (out == null) {
System.out.println("Channel: " + channel + " not found");
}
}
return out;
}
public static HashMap<AvailLookup, ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, String channel) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
for (AvailLookup lookup : inArray.keySet()) {
if (lookup.getValue() != null) {
if (lookup.getValue().equalsIgnoreCase(channel)) {
out = inArray.get(lookup);
System.out.println("Channel: " + channel + " found");
break;
}
}
}
if (out == null) {
System.out.println("Channel: " + channel + " not found");
}
}
return out;
}
public static HashMap<AvailLookup, ArrayList<AvailLookup>> addChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer id, String name) {
HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
if (inArray != null ) {
if (getChannel(inArray, id) == null) {
out = new HashMap<AvailLookup, ArrayList<AvailLookup>>();
inArray.put(new AvailLookup(id, name), new HashMap<AvailLookup, ArrayList<AvailLookup>>());
System.out.println("Channel: added " + id);
} else {
System.out.println("Channel: " + id + " already exists");
}
} else {
System.out.println("Channel: " + id + " already exists");
}
return out;
}
public static void removeChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
boolean pass = false;
HashMap<AvailLookup, ArrayList<AvailLookup>> channelLookup = getChannel(inArray, channel);
for (AvailLookup lookup : channelLookup.keySet()) {
if (lookup.getKey() == channel) {
inArray.remove(channel);
System.out.println("Channel: " + channel + " removed");
pass = true;
break;
}
}
if (!pass) {
System.out.println("Channel: " + channel + " cannot be removed");
}
}
public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
ArrayList<AvailLookup> out = null;
for(AvailLookup lookup : channel.keySet()) {
if (lookup.getKey() == device) {
out = channel.get(device);
System.out.println("Device: " + device + " found");
break;
}
}
if (out == null) {
System.out.println("Device: " + device + " not found");
}
return out;
}
public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, String device) {
ArrayList<AvailLookup> out = null;
for(AvailLookup lookup : channel.keySet()) {
if (lookup.getValue() == device) {
out = channel.get(device);
System.out.println("Device: " + device + " found");
break;
}
}
if (out == null) {
System.out.println("Device: " + device + " not found");
}
return out;
}
public static ArrayList<AvailLookup> addDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer id, String value) {
ArrayList<AvailLookup> out = null;
if (getDevice(channel, id) == null) {
out = new ArrayList<AvailLookup>();
channel.put(new AvailLookup(id, value), new ArrayList<AvailLookup>());
System.out.println("Device: added " + id);
} else {
System.out.println("Device: " + id + " already exists");
}
return out;
}
public static void removeDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
boolean pass = false;
ArrayList<AvailLookup> deviceLookup = getDevice(channel,device);
for (AvailLookup lookup : deviceLookup) {
if (lookup.getKey() == device) {
channel.remove(device);
System.out.println("Device: " + device + " removed");
pass = true;
break;
}
}
if (!pass) {
System.out.println("Device: " + device + " cannot be removed");
}
}
public static AvailLookup getHost(ArrayList<AvailLookup> hosts, Integer host) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == host) {
out = hostLookup;
System.out.println("Host: " + host + " found");
}
}
if (hosts.contains(host)) {
} else {
System.out.println("Host: " + host + " not found");
}
return out;
}
public static AvailLookup getHost(ArrayList<AvailLookup> hosts, String host) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getValue() == host) {
out = hostLookup;
System.out.println("Host: " + host + " found");
}
}
if (hosts.contains(host)) {
} else {
System.out.println("Host: " + host + " not found");
}
return out;
}
public static AvailLookup addHost(ArrayList<AvailLookup> hosts, Integer id, String value) {
AvailLookup out = null;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == id) {
out = hosts.set(id, new AvailLookup(id, value));
System.out.println("Host: " + id + " found");
break;
}
}
if (out == null) {
System.out.println("Host: " + id + " not found");
}
return out;
}
public static void removeHost(ArrayList<AvailLookup> hosts, Integer host) {
boolean pass = false;
for (AvailLookup hostLookup : hosts) {
if (hostLookup.getKey() == host) {
hosts.remove(hostLookup);
System.out.println("Host: " + host + " removed");
pass = true;
}
}
if (!pass) {
System.out.println("Host: " + host + " cannot be removed");
}
}
public static ArrayList<AvailLookup> otherHosts(ArrayList<AvailLookup> hosts, Integer key, String value) {
ArrayList<AvailLookup> out = null;
for (AvailLookup host : hosts) {
if (host.getKey() != key) {
if (out == null) {
out = new ArrayList<AvailLookup>();
}
out.add(new AvailLookup(key, value));
}
}
if (out != null) {
if (out.size() > 1) {
System.out.println("Host: generated other hosts");
}
}
return out;
}
public static AvailLookup nextHost(ArrayList<AvailLookup> otherHosts) {
AvailLookup out = null;
if (otherHosts != null) {
out = otherHosts.get(0);
System.out.println("Host: getting next host");
} else {
System.out.println("Host: no other host");
}
return out;
}
public static void sqlToArray() {
HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> tempData = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
Integer iHost = null;
Integer iDevice = null;
Integer iChannel = null;
String sHost = null;
String sDevice = null;
String sChannel = null;
HashMap<AvailLookup, ArrayList<AvailLookup>> channel = null;
ArrayList<AvailLookup> device = null;
Sql obj = new Sql("plantavail");
obj.query("select j_channel.id as channelid, j_channel.name as channelname, j_device.id as deviceid, j_device.name as devicename, j_io.id as hostid, j_io.host as hostname, alias"
+ " from j_io"
+ " left join j_channel on j_io.id = j_channel.iofk"
+ " left join j_device on j_channel.iofk = j_device.id");
try {
while(obj.getResult().next()) {
sChannel = obj.getResult().getString("channelname");
sDevice = obj.getResult().getString("devicename");
sHost = obj.getResult().getString("hostname");
iChannel = obj.getResult().getInt("channelid");
iDevice = obj.getResult().getInt("deviceid");
iHost = obj.getResult().getInt("hostid");
channel = addChannel(tempData, iChannel, sChannel);
if (channel != null) {
device = addDevice(channel, iDevice, sDevice);
if (device != null) {
addHost(device, iHost, sHost);
}
}
}
} catch (SQLException e1) {
e1.printStackTrace();
}
data = tempData;
}
}
Be careful with accidentally overriding your existing map values. If you use java 8 you can use:
map.computeIfAbsent("entry", s -> new ArrayList<>());
Before Java 8 you need to check if the value is null:
List<String> list = map.get("entry");
if(list == null){
list = map.put("entry", new ArrayList<String>());
}
Also you need to make sure that you update your map correctly:
A little example:
Map<String, String> map = new HashMap<>();
String a = "a";
String b = "b";
map.put(a, b);
System.out.println(map.get(a));
b = "c";
System.out.println(map.get(a));
System.out.println(b);
The output is:
b
b
c
So you see if you update b the map does not get updated. Now the same thing with a map in a map:
final String a = "a";
final String b = "b";
Map<String, Map<String, String>> topMap = new HashMap<>();
Map<String, String> middleMap = topMap.getOrDefault(a, new HashMap<>());
middleMap.put(b, "c");
topMap.put("a", middleMap);
System.out.println(topMap.get(a).get(b));
middleMap.replace(b, "d");
System.out.println(topMap.get(a).get(b));
topMap.put("a", middleMap);
System.out.println(topMap.get(a).get(b));
The output is:
c
d
d
But why? Shouldn't it be 'c c d'? NO! Because a String in Java is immutable, but a Map is not. If you consider this you should be able to solve your problem.
You need to check if there is already a map for this key:
Map<...> result = data.get(val);
if(null == result) {
result = new HashMap();
data.put(val, result);
}
return out;
Without this, the second attempt to add values to the same key will overwrite the existing map instead of appending to it.

Categories