Notepad to HashMap- Java - java

I wrote a small program that reads from a text file based on supplied user type Admin/ Customer and prints single id and password, which is working. Code below
public class TextReader {
//A method to load properties file
public static Properties readProp() throws IOException {
Properties prop = new Properties();
FileInputStream file = new FileInputStream("C:\\Users\\config.text");
prop.load(file);
return prop;
}
//Read the file using method above
public static void getUser(String userType) throws IOException {
Properties prop = readProp();
String userName=prop.getProperty(userType+ "_User");
String userPassword=prop.getProperty(userType+ "_Psd");
System.out.println(" The user is " + userName + " password " + userPassword);
}
public static void main(String[] args) throws IOException {
getUser("Admin");
}
}
Test file:
Admin_User=jjones#adm.com
Admin_Psd=test123
Cust_User=kim#cust.com
Cust_Psd=test123
I wanted to modify it so that I can now add those to a HashMap. So I removed the userType argument
public static void getUser() throws IOException {
Properties prop = readProp();
String userName = prop.getProperty("_User");
String userPassword = prop.getProperty("_Psd");
HashMap<String, String> hmp = new HashMap<String, String>();
hmp.put(userName, userPassword);
for (Map.Entry<String, String> credentials : hmp.entrySet()) {
System.out.println(credentials.getKey() + " " + credentials.getValue());
}
//System.out.println(" The user is " + userName + " password " + userPassword);
}
I get null null as output. I cannot think of a way to get them in HashMap, I can use some hint/help.
Expected output: user name, password as key value pair
jjones#adm.com test123
kim#cust.com test123

To convert a Properties object to a HashMap<String, String>, copy all the entries:
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
hmp.put(name, prop.getProperty(name));
If the properties file can contain other properties, filter while copying, e.g.
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
if (name.endsWith("_User") || name.endsWith("_Psd"))
hmp.put(name, prop.getProperty(name));
Or the same using regex:
Pattern suffix = Pattern.compile("_(User|Psd)$");
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
if (suffix.matcher(name).find())
hmp.put(name, prop.getProperty(name));

Related

CSV parsed into three dimensional HashMap in Java

I'm attempting to parse a CSV file into a HashMap. The CSV file contains name, email and age.
I've attempted it below but haven't had any luck progressing with it - beginner to Java
public class Extract {
public HashMap<String, Map<String, Integer>> readFile(String filename) {
HashMap<String, Map<String, Integer>> people = new HashMap<>();
try {
Scanner in = new Scanner(new File(filename));
String line;
while(in.hasNext()) {
line = in.nextLine();
String[] keyValue = line.split(",");
people.put(keyValue[0], keyValue[2], keyValue[3]);
}
in.close();
}
catch(Exception e) {
e.printStackTrace();
}
return people;
}
}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
Extract e = new Extract();
String peopleFile = ("relationships.csv");
HashMap<String, String> person1 = e.readFile(peopleFile);
person1.get("Bob");
}
}
So here is the code as it should suit you. Try to understand what happens here. It seems that you're still struggling a little when it comes to Maps and how to use them properly.
public class Extract {
public HashMap<String, HashMap<String, String>> readFile(String filename) {
HashMap<String, HashMap<String, String>> people = new HashMap<>();
HashMap<String, String> metaData = new HashMap<>();
try {
Scanner in = new Scanner(new File(filename));
String line;
while(in.hasNext()) {
line = in.nextLine();
String[] keyValue = line.split(",");
// 1st put email address and age in the inner Map
metaData = new HashMap<>();
metaData.put("email", keyValue[1]);
metaData.put("age", keyValue[2]);
// 2nd put the inner Map into the outer Map, referenced by the person's name
people.put(keyValue[0], metaData);
}
in.close();
}
catch(Exception e) {
e.printStackTrace();
}
return people;
}
}
public class Main {
public static void main(String[] args) {
Extract e = new Extract();
String peopleFile = ("relationships.csv");
HashMap<String, HashMap<String, String>> person1 = e.readFile(peopleFile);
// 1st: get the inner Map of Bob
// If you use the get()-method, you tell the outer Map to hand you the inner Map of Bob.
HashMap<String, String> metaData = person1.get("Bob");
// 2nd: get the metaData off the inner Map
String email = metaData.get("email");
Integer age = Integer.valueOf(metaData.get("age"));
}
}

Struts2 change form field using interceptor

I am newbie in struts2.
In interceptor how can i change value of form field and then submitting it to database?
For example when user enters firstName value in form then when it submits i want to change firstName and then submit it to database.
Here is my interceptor's code
public class TestInterceptor extends AbstractInterceptor implements Interceptor
{
#Override
public String intercept(ActionInvocation actionInvocation) throws Exception
{
ValueStack stack = actionInvocation.getStack();
Map<String, Object> params = ActionContext.getContext().getParameters();
Set<String> keys = params.keySet();
System.out.println(keys + " " + stack.size());
/*
* for (String key : keys)
* {
* String[] value = (String[]) params.get(key);
* System.out.println(value.length + " , " + value[0]);
* }
*/
Map<String, Object> context = new HashMap<String, Object>();
context.put("firstNames", "Changed");
context.put("firstName", "Changed");
stack.setParameter("firstName", "Changeds");
stack.push(context);
String result = actionInvocation.invoke();
return result;
}
}
In your code simply you need to change value in the map. no need to put any other context.
Map<String, Object> params = actionInvocation.getInvocationContext().getParameters();
params.put("firstName", "Changed");
Try this:
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
Map<String,Object> parameters = (Map<String,Object>)context.get(ActionContext.PARAMETERS);
Map<String, Object> parametersCopy = new HashMap<String, Object>();
parametersCopy.putAll(parameters);
parametersCopy.put("myParam", "changedValue");
context.put(ActionContext.PARAMETERS, parametersCopy);
return invocation.invoke();
}

How to set depth of simple JAVA web crawler

I wrote a simple recursive web crawler to fetch just the URL links from the web page recursively.
Now I am trying to figure out a way to limit the crawler using depth but I am not sure how to limit the crawler by specific depth (I can limit the crawler by top N links but I want to limit using depth)
For Ex: Depth 2 should fetch Parent links -> children(s) links--> children(s) link
Any inputs is appreciated.
public class SimpleCrawler {
static Map<String, String> retMap = new ConcurrentHashMap<String, String>();
public static void main(String args[]) throws IOException {
StringBuffer sb = new StringBuffer();
Map<String, String> map = (returnURL("http://www.google.com"));
recursiveCrawl(map);
for (Map.Entry<String, String> entry : retMap.entrySet()) {
sb.append(entry.getKey());
}
}
public static void recursiveCrawl(Map<String, String> map)
throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
recursiveCrawl(recurSive);
}
}
public synchronized static Map<String, String> returnURL(String URL)
throws IOException {
Map<String, String> tempMap = new HashMap<String, String>();
Document doc = null;
if (URL != null && !URL.equals("") && !retMap.containsKey(URL)) {
System.out.println("Processing==>" + URL);
try {
URL url = new URL(URL);
System.setProperty("http.proxyHost", "proxy");
System.setProperty("http.proxyPort", "port");
doc = Jsoup.connect(URL).get();
if (doc != null) {
Elements links = doc.select("a");
String FinalString = "";
for (Element e : links) {
FinalString = "http:" + e.attr("href");
if (!retMap.containsKey(FinalString)) {
tempMap.put(FinalString, FinalString);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
retMap.put(URL, URL);
} else {
System.out.println("****Skipping URL****" + URL);
}
return tempMap;
}
}
EDIT1:
I thought of using worklist hence modified the code. I am not exactly sure how to set depth here too (I can set the number of webpages to crawl but not exactly depth). Any suggestions would be appreciated.
public void startCrawl(String url) {
while (this.pagesVisited.size() < 2) {
String currentUrl;
SpiderLeg leg = new SpiderLeg();
if (this.pagesToVisit.isEmpty()) {
currentUrl = url;
this.pagesVisited.add(url);
} else {
currentUrl = this.nextUrl();
}
leg.crawl(currentUrl);
System.out.println("pagesToVisit Size" + pagesToVisit.size());
// SpiderLeg
this.pagesToVisit.addAll(leg.getLinks());
}
System.out.println("\n**Done** Visited " + this.pagesVisited.size()
+ " web page(s)");
}
Based on the non-recursive approach:
Keep a worklist of URLs pagesToCrawl of type CrawlURL
class CrawlURL {
public String url;
public int depth;
public CrawlURL(String url, int depth) {
this.url = url;
this.depth = depth;
}
}
initially (before entering the loop):
Queue<CrawlURL> pagesToCrawl = new LinkedList<>();
pagesToCrawl.add(new CrawlURL(rootUrl, 0)); //rootUrl is the url to start from
now the loop:
while (!pagesToCrawl.isEmpty()) { // will proceed at least once (for rootUrl)
CrawlURL currentUrl = pagesToCrawl.remove();
//analyze the url
//updated with crawled links
}
and the updating with links:
if (currentUrl.depth < 2) {
for (String url : leg.getLinks()) { // referring to your analysis result
pagesToCrawl.add(new CrawlURL(url, currentUrl.depth + 1));
}
}
You could enhance CrawlURL with other meta data (e.g. link name, referrer,. etc.).
Alternative:
In my upper comment I mentioned a generational approach. Its a bit more complex than this one. The basic Idea is to keep to lists (currentPagesToCrawl and futurePagesToCrawl) together with a generation variable (starting with 0 and increasing every time currentPagesToCrawl gets empty). All crawled urls are put into the futurePagesToCrawl queue and if currentPagesToCrawl both lists will be switched. This is done until the generation variable reaches 2.
You could add a depth parameter on the signature of your recursive method eg
on your main
recursiveCrawl(map,0);
and
public static void recursiveCrawl(Map<String, String> map, int depth) throws IOException {
if (depth++ < DESIRED_DEPTH) //assuming initial depth = 0
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
recursiveCrawl(recurSive, depth);
}
}
]
You can do something like this:
static int maxLevels = 10;
public static void main(String args[]) throws IOException {
...
recursiveCrawl(map,0);
...
}
public static void recursiveCrawl(Map<String, String> map, int level) throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
if (level < maxLevels) {
recursiveCrawl(recurSive, ++level);
}
}
}
Also, you can use a Set instead of a Map.

Read json file and how to change hard coding path

Question : I want to change the hard coding json file path. The path will be from detailsListHM but I dont know how to do it.
Here is my main program
public class Program {
// hard coding json file path
private static final String filePath = "C:/appSession.json";
public static void main(String[] args)
{
taskManager();
}
public static void taskManager()
{
detailsHM = jsonParser(filePath);
}
public static HashMap<String, String> jsonParser(String jsonFilePath)
{
HashMap<String, String> detailsHM = new HashMap<String, String>();
String refGene = "";
try {
// read the json file
FileReader reader = new FileReader(filePath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
Here is another class called CustomConfiguration
public class CustomConfiguration {
private static HashMap<String, String> detailsListHM =new HashMap<String,String>();
public static void readConfig(String a) {
//read from config.properties file
try {
String result = "";
Properties properties = new Properties();
String propFileName = a;
InputStream inputStream = new FileInputStream(propFileName);
properties.load(inputStream);
// get the property value and print it out
String lofreqPath = properties.getProperty("lofreqPath");
String bamFilePath = properties.getProperty("bamFilePath");
String bamFilePath2 = properties.getProperty("bamFilePath2");
String resultPath = properties.getProperty("resultPath");
String refGenPath = properties.getProperty("refGenPath");
String filePath = properties.getProperty("filePath");
Set keySet = properties.keySet();
List keyList = new ArrayList(keySet);
Collections.sort(keyList);
Iterator itr = keyList.iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
String value = properties.getProperty(key.toString());
detailsListHM.put(key, value);
}
} catch (IOException ex) {
System.err.println("CustomConfiguration - readConfig():" + ex.getMessage());
}
}
public static HashMap<String, String> getConfigHM() {
return detailsListHM;
}
Add a new property call "json-filepath" and read like
String filePath = properties.getProperty("json-filepath");
So the end user can change the json file path even during the runtime.
you can pass the filePath parameter by using the main parameters.
public static void main(String[] args) {
String filePath = null;
if(args.length > 0) {
filePath = args[0];
}
}
And invoke your main class like this:
java Program C:/appSession.json

How to create a directory in "user.home"?

How would you create a directory inside the user's home?
I know how to create a normal directory, but how do you set a path for it with user.home?
boolean success = new java.io.File(System.getProperty("user.home"), "directory_name").mkdirs();
System Properties
To Improving the post answer! gathered all the information and put it together.
public static void main(String[] args) {
String myDirectory = "Yash"; // user Folder Name
String path = getUsersHomeDir() + File.separator + myDirectory ;
if (new File(path).mkdir()) {
System.out.println("Directory is created!");
}else{
System.out.println("Failed to create directory!");
}
getOSInfo();
}
public static void getOSInfo(){
String os = System.getProperty("os.name");
String osbitVersion = System.getProperty("os.arch");
String jvmbitVersion = System.getProperty("sun.arch.data.model");
System.out.println(os + " : "+osbitVersion+" : "+jvmbitVersion);
}
public static String getUsersHomeDir() {
String users_home = System.getProperty("user.home");
return users_home.replace("\\", "/"); // to support all platforms.
}
To print all available properties.
for (Entry<Object, Object> e : System.getProperties().entrySet()) {
System.out.println(String.format("%s = %s", e.getKey(), e.getValue()));
}

Categories

Resources