MongoDB NULL Pointer Exception while getting JSON as input - java

package com.demo.mongodb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
public class Driver {
private static DBCollection channelDBcollection;
public static void main(String[] args) throws IOException {
DB db = (new MongoClient("localhost",27017)).getDB("demo");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
boolean flag = false;
while(!flag) flag = autenticate(db, bufferedReader);
}
private static boolean autenticate(DB db, BufferedReader bufferedReader) throws IOException{
boolean flag = true;
System.out.println("User: ");
String user = bufferedReader.readLine();
System.out.println("Password: ");
String password = bufferedReader.readLine();
if(db.authenticate(user, password.toCharArray())){
DBCollection channDbCollection = db.getCollection("Channel");
String command = null;
while(true){
System.out.println("What do you want to do ? ");
command = bufferedReader.readLine();
if(command.equals("exit")) break ;
else if(command.equals("findALL")) findAll(channDbCollection);
else if(command.equals("insertJSON")) insertJSON(bufferedReader,channDbCollection);
}
}
else{
System.out.println("invalid user/password");
flag = false;
}
return flag;
}
private static void findAll(DBCollection dbCollection){
DBCursor dbCursor = channelDBcollection.find();
while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}
private static void insertJSON(BufferedReader bufferedReader,DBCollection channDbCollection) throws IOException {
System.out.println("JSON: ");
channDbCollection.insert((DBObject) JSON.parse(bufferedReader.readLine()));
}
}
I make Database in MongoDB like :-
use demo
db.addUser("root","root")
While i executed application then while i enter for JSON , i found null pointer can someone help me to take out of this ?

in your
private static void findAll(DBCollection dbCollection){
DBCursor dbCursor = channelDBcollection.find();
while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}
function, you use global variable channelDBcollection (which is null at the time of call) instead of parameter dbCollection (which is not used anywhere in the method);
what you think is "not null" is the local variable with confusing name "channDbCollection", but it's not used anywhere;
I suggest you to revise your approach to naming, using global variables and coding style in general.

Related

Iterating over a CSV file within a TestNG DataProvider

I'm a little confused as to how best to implement a simple DataProvider, having not done so before.
I have a very simple comma delimited .csv file:
978KAL,625JBH,876SSH,452GSH
I simply need to read it in and iterate over the records, running the same test for each record until done.
My code so far:
String csvFile = "src/test/resources/registrationsData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
#DataProvider(name="getRegistrations")
private Object[] getCSVTestData() {
Object [] registrationsObject;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String [] registrations = line.split(cvsSplitBy);
System.out.println( registrations[0] + "," + registrations[1]);
}
} catch//File not found & IOException handling here
registrationsObject = new Object[][]{registrations};
return registrationsObject;
}
#Test(dataProvider = "getRegistrations")
public void getRegistrations(String registration){
Object[] objRegArray = getCSVTestData();
for(int i=0; objRegArray.length>i; i++){
//run tests for every record in the array (csv file)
}
}
I know that I need to use an Object array return type for the Data Provider method.
I'm unclear as to how (and/or the best way) to retrieve each record from the objRegArray object.
This is a basic Collections question I guess; can anyone point me the right way?
Check this code with my explanation below:
package click.webelement.testng;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
public class OneLineCSV {
final static String CSV_FILE = "/path_to_file/oneline.csv";
final static String DELIMETER = ",";
#DataProvider(name = "test")
public Iterator<Object[]> testDP(){
try {
Scanner scanner = new Scanner(new File(CSV_FILE)).useDelimiter(DELIMETER);
return new Iterator<Object[]>() {
#Override
public boolean hasNext() {
return scanner.hasNext();
}
#Override
public Object[] next() {
return new Object[]{scanner.next()};
}
};
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
#Test(dataProvider = "test")
public void testOneLineCSV(String value){
System.out.println(value);
}
}
So I would use Scanner class hence it has the convenient facility to parse a string into tokens.
I would also use the capability to return Iterator<Object[]> in your data provider since Scanner is designed in that way. You simply wrap it with new Iterator that converts String that is returned by Scanner.next() to new Object[]{scanner.next}.
Using Iterator with Scanner is really more comfortable since you may not know how many values you will have to provide. So you shouldn't care of defining array size.

How do I assert that when I put in two string inputs that a specific array is output JUnit testing

Hey guys I have a problem, I would like to assert that when I input 2 specific strings that an array is returned. I want to use the assert statement and parameterized testing to do this however my current assert statement is showing an error, I have placed my code below please help:
My inputs are both String data type and my output from the drop course is an array
import IT_chatbot.drop_course;
#RunWith(Parameterized.class)
public class drop_course_test {
drop_course check;
#Before
public void setUp() throws Exception {
check= new drop_course();
}
private String[] output;
private String input1;
private String input2;
public drop_course_test(String output[],String input1,String input2 )
{
this.output=output;
this.input1=input1;
this.input2=input2;
}
#Parameters
public static Collection testConditions(){
String[] droplist1={"ITE222 Web Development 2","ITE365 Software Quality Management","ITE446 Current Topics in Software Engineering","ITE220 Programming 1"};
return Arrays.asList(new Object [][]{
{droplist1, "216110116","ITE200"},
});
}
#Test
public void test() {
assertEquals(output, drop_course.drop(input1, input2));
}
}
The method i am trying to test can be seen below:
package IT_chatbot;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class drop_course {
public static String[] drop(String studentID, String courseCode){
String filePath = "enrolled_courses"+studentID+".txt";
String disenrolled_subtracted[]=new String[5];
int value_at=0;
System.out.println("Your Course has been dropped the following are your current courses:");
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
while ((lineText = lineReader.readLine()) != null) {
if(lineText.contains(courseCode)){
lineText = lineText.replace(lineText, "");
FileWriter writer = new FileWriter("filePath", true);
writer.write("-disenrolled-"+lineText);
}else{
System.out.println(lineText);
disenrolled_subtracted[value_at]=lineText;
value_at=value_at+1;
}
}
lineReader.close();
} catch (IOException ex) {
System.err.println(ex);
}
return disenrolled_subtracted;
}
Use Method
Assert.assertArrayEquals( expectedResult, result );
Instead of
assertEquals

getting stuck in replacing stopwords(txt.file) from data stored as list fetched from database

Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
Kindly view code at for loop part where using replace method
I am Unable to replace stop words from data I have fetched from data base.
error shows ,array bound exception:1.
I amunable to resolve it ,give me some suggestion
package chatbot;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.IntStream;
public class keywords{
private static Scanner scan2;
private static final String driverName = "oracle.jdbc.driver.OracleDriver";
private static final String QUER = null;
//private static final String SCOR = null;
// private static final String SCORE =
private static final String ANSW = null;
public static void main(String[] args) throws IOException, SQLException {
Connection con = null;
Statement stmnt = null;
ResultSet result = null;
Set<String> list1= new HashSet<>();
try {
Class.forName(driverName);
con = DriverManager.getConnection("jdbc:oracle:thin:#10.144.97.144:1521:NQLDEV", "DEVNQL", "DEVNQL");
stmnt = con.createStatement();
System.out.println("Connection established");
List<String> rsl1 = new ArrayList<>();
List<String> rsl3 = new ArrayList<>();
String query = "SELECT * FROM DEVNQL.CHATKEY";
ResultSet rs = stmnt.executeQuery(query);
while (rs.next()) {
rsl1.add(rs.getString(1));
rsl3.add(rs.getString(3));
}
//System.out.println("result "+rsl1 + " "+rsl3);
File file = new File("M:\\Documents\\stop-word-list.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine()) != null){
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(st));
//List<String> ux = new ArrayList<>(Arrays.asList(st));
for(int i=0;i<rsl1.size()-1;i++){
for(String n:wordList)
if(rsl1.contains(n.getBytes()[i])){
rsl1.get(i).replace(n.charAt(i)+"\\rsl1+", "");
//note this will remove spaces at the end
}
}
System.out.println(rsl1);
}}
// for (int i=0;i<=rsl1.size()-1;i++){
/*
for (String removeword:wordList){
System.out.println("removeword "+removeword+ " "+rsl1.get(i)+
" "+rsl1.get(i).contains(removeword));
rsl1.get(i).replace("hi","abcd********");
if (rsl1.get(i).contains(removeword)) {
rsl1.get(i).replace("hi","abcd********");
} // end if
} // end for
*/ // } // end for
// System.out.println("result "+rsl1);
// }
// System.out.println("replace "+rsl1.get(0).replace("hi", "abcde"));
// }
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
fi`enter code here`nally {
if (stmnt != null) {
stmnt.close();
}
if (con != null) {
con.close();
}
}
}}
replace actually returns a new String as in Java Strings are immutatable
so
String newString = rsl1.get(i).replace(n.charAt(i)+"\\rsl1+", "");

java.lang.nullpointerexception in url connection

I am a beginner in java programming. I am trying to read response from url and insert into database. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at javaapp.JavaApplication1.parseResponseString(JavaApplication1.java:41)
at javaapp.JavaApplication1.main(JavaApplication1.java:71)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
And here is the code i have written
enter code here package javaapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
Map<String,String> responseMap=new HashMap<String, String>();
static String input;
public void getResponseFromUrl() throws IOException
{
URL url = new URL("http://localhost:8084/home/Home");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())) ;
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<h1>"))
{
String input = inputLine;
input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
}
}
public void parseResponseString(String input)
{
String params[]=input.split(",");
for(String param:params)
{
String key= param.substring(0,param.indexOf('='));
String value= param.substring(param.indexOf('=')+1,param.length());
responseMap.put(key, value);
System.out.println(param);
}
}
public void insertToDatabase() throws SQLException, ClassNotFoundException
{
Connection conn=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jai","jaikiran");
String insertQuery = " INSERT INTO value_1 (username1,username2,username3,username4,username5) "+
" values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1,responseMap.get("username1"));
pstmt.setString(2,responseMap.get("username2"));
pstmt.setString(3,responseMap.get("username3"));
pstmt.setString(4,responseMap.get("username4"));
pstmt.setString(5,responseMap.get("username5"));
pstmt.executeUpdate();
}
public static void main(String[] args) throws MalformedURLException, IOException, SQLException, ClassNotFoundException
{
JavaApplication1 application =new JavaApplication1();
application.getResponseFromUrl();
application.parseResponseString(input);//shows exception here
try {
application.insertToDatabase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in advance,please helpme..
The static String input; is null by default and you're passing it to the parseResponseString() method.
You need to assign a value to the input variable.
I believe you wanted the assignment to be done in the getResponseFromUrl() method, where you have created a new input variable. In order to have the static String input; assigned with a value, you need to refer it with the this keyword.
if (inputLine.contains("<h1>"))
{
String input = inputLine;
this.input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
at the getResponseFromUrl method the String input is a new variable;
you must change the String input = inputLine; to String input2 = inputLine; and input = input2.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
your code become :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
Map<String,String> responseMap=new HashMap<String, String>();
static String input;
public void getResponseFromUrl() throws IOException
{
URL url = new URL("http://localhost:8084/home/Home");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())) ;
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<h1>"))
{
String input2 = inputLine;
input = input2.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
}
}
}
public void parseResponseString(String input)
{
String params[]=input.split(",");
for(String param:params)
{
String key= param.substring(0,param.indexOf('='));
String value= param.substring(param.indexOf('=')+1,param.length());
responseMap.put(key, value);
System.out.println(param);
}
}
public void insertToDatabase() throws SQLException, ClassNotFoundException
{
Connection conn=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jai","jaikiran");
String insertQuery = " INSERT INTO value_1 (username1,username2,username3,username4,username5) "+
" values (?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1,responseMap.get("username1"));
pstmt.setString(2,responseMap.get("username2"));
pstmt.setString(3,responseMap.get("username3"));
pstmt.setString(4,responseMap.get("username4"));
pstmt.setString(5,responseMap.get("username5"));
pstmt.executeUpdate();
}
public static void main(String[] args) throws MalformedURLException, IOException, SQLException, ClassNotFoundException
{
JavaApplication1 application =new JavaApplication1();
application.getResponseFromUrl();
application.parseResponseString(input);//shows exception here
try {
application.insertToDatabase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I think your problem is here:
String input = inputLine;
input = input.substring(input.indexOf("<h1>") + 4, input.indexOf("</h1>"));
Declaring a new variable input in the first line prevents your code to assign the value to the private field input (which is what you are probably trying to do).
Besides, the first line is useless, just remove it and use directly inputLine in the second one:
input = inputLine.substring(inputLine.indexOf("<h1>") + 4, inputLine.indexOf("</h1>"));
I can be wrong... but you define a String input as a field of your class...
I believe that you want to use in public void getResponseFromUrl() the String input field and not the local input!!
Why I say that... obviously you try in the public void parseResponseString(String input) to take the data in the input field but you don't have anything in there... so you get NullPointerException.
So what you need to change is in:
public void getResponseFromUrl() throws IOException
{
.....
/*String input = inputLine; -> wrong, because you want to use a field and not a local var... */
input = inputLine; /* now you are using the class field input */
input = input.substring...
...
}

Remove Duplicate Lines from Text using Java

I was wondering if anyone has logic in java that removes duplicate lines while maintaining the lines order.
I would prefer no regex solution.
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
if (lines.add(uniqueLine = super.readLine()))
return uniqueLine;
return "";
}
//for testing..
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
if (strLine != "")
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Modified Version:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"/home/emil/Desktop/ff.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If you feed the lines into a LinkedHashSet, it ignores the repeated ones, since it's a set, but preserves the order, since it's linked. If you just want to know whether you've seena given line before, feed them into a simple Set as you go on, and ignore those which the Set already contains/contained.
It can be easy to remove duplicate line from text or File using new java Stream API. Stream support different aggregate feature like sort,distinct and work with different java's existing data structures and their methods. Following example can use to remove duplicate or sort the content in File using Stream API
package removeword;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.*;
import static java.util.stream.Collectors.joining;
public class Java8UniqueWords {
public static void main(String[] args) throws IOException {
Path sourcePath = Paths.get("C:/Users/source.txt");
Path changedPath = Paths.get("C:/Users/removedDouplicate_file.txt");
try (final Stream<String> lines = Files.lines(sourcePath )
// .map(line -> line.toLowerCase()) /*optional to use existing string methods*/
.distinct()
// .sorted()) /*aggregrate function to sort disctincted line*/
{
final String uniqueWords = lines.collect(joining("\n"));
System.out.println("Final Output:" + uniqueWords);
Files.write(changedPath , uniqueWords.getBytes(),WRITE, TRUNCATE_EXISTING);
}
}
}
Read the text file using a BufferedReader and store it in a LinkedHashSet. Print it back out.
Here's an example:
public class DuplicateRemover {
public String stripDuplicates(String aHunk) {
StringBuilder result = new StringBuilder();
Set<String> uniqueLines = new LinkedHashSet<String>();
String[] chunks = aHunk.split("\n");
uniqueLines.addAll(Arrays.asList(chunks));
for (String chunk : uniqueLines) {
result.append(chunk).append("\n");
}
return result.toString();
}
}
Here's some unit tests to verify ( ignore my evil copy-paste ;) ):
import org.junit.Test;
import static org.junit.Assert.*;
public class DuplicateRemoverTest {
#Test
public void removesDuplicateLines() {
String input = "a\nb\nc\nb\nd\n";
String expected = "a\nb\nc\nd\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
#Test
public void removesDuplicateLinesUnalphabetized() {
String input = "z\nb\nc\nb\nz\n";
String expected = "z\nb\nc\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
}
Here's another solution. Let's just use UNIX!
cat MyFile.java | uniq > MyFile.java
Edit: Oh wait, I re-read the topic. Is this a legal solution since I managed to be language agnostic?
For better/optimum performance, it's wise to use Java 8's API features viz. Streams & Method references with LinkedHashSet for Collection as below:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
public class UniqueOperation {
private static PrintWriter pw;
enter code here
public static void main(String[] args) throws IOException {
pw = new PrintWriter("abc.txt");
for(String p : Files.newBufferedReader(Paths.get("C:/Users/as00465129/Desktop/FrontEndUdemyLinks.txt")).
lines().
collect(Collectors.toCollection(LinkedHashSet::new)))
pw.println(p);
pw.flush();
pw.close();
System.out.println("File operation performed successfully");
}
here I'm using a hashset to store seen lines
Scanner scan;//input
Set<String> lines = new HashSet<String>();
StringBuilder strb = new StringBuilder();
while(scan.hasNextLine()){
String line = scan.nextLine();
if(lines.add(line)) strb.append(line);
}

Categories

Resources