Error When Running local Spark with jdbcRDD - mysql

I am trying to run spark job locally to read mysql table contents (in local machine) to jdbcRDD. From online i gathered the below source code and customised to read element table and load all the columns.
private static final JavaSparkContext sc = new JavaSparkContext(
new SparkConf().setAppName("SparkJdbc").setMaster("local[*]"));
private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
private static final String MYSQL_CONNECTION_URL = "jdbc:mysql://localhost:3306/ddm";
private static final String MYSQL_USERNAME = "root";
private static final String MYSQL_PWD = "root";
public static void main(String[] args) {
DbConnection dbConnection = new DbConnection(MYSQL_DRIVER,
MYSQL_CONNECTION_URL, MYSQL_USERNAME, MYSQL_PWD);
// Load data from MySQL
JdbcRDD<Object[]> jdbcRDD = new JdbcRDD<>(sc.sc(), dbConnection,
"select * from element where elementid >= ? and elementid <= ?",
1000, 1100, 10, new MapResult(),
ClassManifestFactory$.MODULE$.fromClass(Object[].class));
// Convert to JavaRDD
JavaRDD<Object[]> javaRDD = JavaRDD.fromRDD(jdbcRDD,
ClassManifestFactory$.MODULE$.fromClass(Object[].class));
// Join first name and last name
List<String> employeeFullNameList = javaRDD.map(
new Function<Object[], String>() {
private static final long serialVersionUID = 1L;
#Override
public String call(final Object[] record) throws Exception {
return record[2] + " " + record[3];
}
}).collect();
for (String fullName : employeeFullNameList) {
System.out.println(fullName);
}
}
static class DbConnection extends AbstractFunction0<Connection> implements
Serializable {
private static final long serialVersionUID = 1L;
private String driverClassName;
private String connectionUrl;
private String userName;
private String password;
public DbConnection(String driverClassName, String connectionUrl,
String userName, String password) {
this.driverClassName = driverClassName;
this.connectionUrl = connectionUrl;
this.userName = userName;
this.password = password;
}
#Override
public Connection apply() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
}
Properties properties = new Properties();
properties.setProperty("user", userName);
properties.setProperty("password", password);
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionUrl,
properties);
} catch (SQLException e) {
}
return connection;
}
}
static class MapResult extends AbstractFunction1<ResultSet, Object[]>
implements Serializable {
private static final long serialVersionUID = 1L;
public Object[] apply(ResultSet row) {
return JdbcRDD.resultSetToObjectArray(row);
}
}
However, when I execute the code i get below NullPointerException.
15/08/01 08:27:23 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)java.lang.NullPointerException
at org.apache.spark.rdd.JdbcRDD$$anon$1.<init>(JdbcRDD.scala:79)
at org.apache.spark.rdd.JdbcRDD.compute(JdbcRDD.scala:74)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:277)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:244)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:277)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:244)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:63)
at org.apache.spark.scheduler.Task.run(Task.scala:70)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I have looked up the jdbcrdd.scala code in github and at line 79 it points to SQL stmt.
val stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
So, the above statement is failing. I have given the required details, but it is throwing null exception. Can anyone help me where i am doing wrong?

I have overlooked my import statements. After i have added below code I am able to execute the spark program locally.
import java.sql.{PreparedStatement, Connection, ResultSet}

Related

#Query keep pulling null from database

I am currently having what I'd like to call as Code Block (Writer block but with coding). I have tried to check many times and make sure that everything is in the proper place but it keeps getting me a null despite the data that I ask in the #Query is exist.
This is the #Query that I currently have,
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
String findAllDenda(String x,String y,String z);
My expected output from there is a collection of "denda" from the table of "data_transaksi_model" which has the specific "tanggal", "name", and "masa_pajak" from that table. I have double checked the table that is created within the database and it has the same name as to what I inquire there,
As you can see, the table name is matchup and the name of the column name that has the name of what I want in my query is also match up. Just to make sure, I also check the structure of the database and it is indeed a string, also the same with others.
The table is the byproduct of the model from my Spring Boot's project that I have made.
#Entity
public class DataTransaksiModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "tanggal")
private String tanggal;
#NotNull
#Column(name = "no_kohir")
private String noKohir;
#NotNull
#Column(name = "no_urut")
private String noUrut;
#NotNull
#Column(name = "nama_wp")
private String namaWP;
#NotNull
#Column(name = "jam")
private String jam;
#NotNull
#Column(name = "nop")
private String nop;
#NotNull
#Column(name = "denda")
private String denda;
#NotNull
#Column(name = "jumlah_setoran")
private String jumlahSetoran;
#NotNull
#Column(name = "luas_tanah")
private String luasTanah;
#NotNull
#Column(name = "luas_bangunan")
private String luasBangunan;
#NotNull
#Column(name = "kecamatan")
private String kecamatan;
#NotNull
#Column(name = "kelurahan")
private String kelurahan;
#NotNull
#Column(name = "masa_pajak")
private String masaPajak;
#NotNull
#Column(name = "lokasi")
private String lokasi;
#NotNull
#Column(name = "pokok")
private String pokok;
#NotNull
#Column(name = "cabang")
private String cabang;
#NotNull
#Column(name = "User")
private String user;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getNoKohir() {
return noKohir;
}
public void setNoKohir(String noKohir) {
this.noKohir = noKohir;
}
public String getNoUrut() {
return noUrut;
}
public void setNoUrut(String noUrut) {
this.noUrut = noUrut;
}
public String getNamaWP() {
return namaWP;
}
public void setNamaWP(String namaWP) {
this.namaWP = namaWP;
}
public String getJam() {
return jam;
}
public void setJam(String jam) {
this.jam = jam;
}
public String getNop() {
return nop;
}
public void setNop(String nop) {
this.nop = nop;
}
public String getDenda() {
return denda;
}
public void setDenda(String denda) {
this.denda = denda;
}
public String getJumlahSetoran() {
return jumlahSetoran;
}
public void setJumlahSetoran(String jumlahSetoran) {
this.jumlahSetoran = jumlahSetoran;
}
public String getLuasTanah() {
return luasTanah;
}
public void setLuasTanah(String luasTanah) {
this.luasTanah = luasTanah;
}
public String getLuasBangunan() {
return luasBangunan;
}
public void setLuasBangunan(String luasBangunan) {
this.luasBangunan = luasBangunan;
}
public String getKecamatan() {
return kecamatan;
}
public void setKecamatan(String kecamatan) {
this.kecamatan = kecamatan;
}
public String getKelurahan() {
return kelurahan;
}
public void setKelurahan(String kelurahan) {
this.kelurahan = kelurahan;
}
public String getMasaPajak() {
return masaPajak;
}
public void setMasaPajak(String masaPajak) {
this.masaPajak = masaPajak;
}
public String getLokasi() {
return lokasi;
}
public void setLokasi(String lokasi) {
this.lokasi = lokasi;
}
public String getPokok() {
return pokok;
}
public void setPokok(String pokok) {
this.pokok = pokok;
}
public String getCabang() {
return cabang;
}
public void setCabang(String cabang) {
this.cabang = cabang;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
With that finished, I insert a data dummy into the database as the following.
Therefore, I tried to put the input of tanggal with "1170130", nama_wp with "SURATNO" and masa_pajak with "2016". However, I keep getting null instead of "9.166" in the collection. Where did I do wrong? I am using XAMPP, MySQL, and Spring Boot for this project.
/EDIT: I tried it manually in my XAMPP with SELECT denda FROM data_transaksi_modelWHERE nama_wp="SURATNO" AND masa_pajak="2014" AND tanggal="1170130" and it actually gives me a return
However, when I do it in my spring boot project it still return null.
//Edit2: I am using IntelliJ as my IDE and there is a warning (not an error) within the #Query annotation. It is said that "No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (alt+enter)" there is also a warning that said, "SQL dialect is not configured". If that is the source of the problem, how to fix it?
///edit3: I tried to fix around the query and it doesn't show the result that I wanted. This is the service that I am using for the repository
#Autowired
DataTransaksiDb dataTransaksiDb;
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
and this is the controller where I am using the service. The controller is using a multipart file where the data is taken out from the CSV that is uploaded where within the CSV has the table that is the same as the database.
#PostMapping("/uploadFile")
public static void uploadFile(#RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
if (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
InputStreamReader input = new InputStreamReader(file.getInputStream());
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
for (CSVRecord record : csvParser) {
String nama = record.get("nama_wp");
String masa = record.get("masa_pajak");
String tanggal = record.get("tanggal");
String denda = record.get("denda");
String jumlahSetoran = record.get("jumlah_setoran");
String pokok = record.get("pokok");
String luasTanah = record.get("luas_tanah");
String luasBangunan = record.get("luas_bangunan");
try {
System.err.println(tanggal + "\n" + nama + "\n" + masa);
List<String> results = rekonsiliasiService.getDenda(tanggal, nama, masa);
System.err.println("results " + results);
} catch (NullPointerException e) {
System.err.println(e);
}
}
response.sendRedirect("/rekonsiliasi");
} else {
response.sendRedirect("/rekonsiliasi");
}
}
Whatever the result of the input that I get, it keep getting catches by the nullpointerexception
////EDIT4:
I tried debugging it and from my controller, I tried to do System.err.println(rekonsiliasiService.getDenda(tanggal,nama,masa)); and it keep me getting a NullPointerException. Then I tried to see if the problem is the input of the parameter itself within the service
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak);
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
It never reached to the System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak); within my Service layer.
try this :
#Query(value = "select d.denda from DataTransaksiModel d WHERE d.tanggal=:x AND d.namaWP = :y AND d.masaPajak=:z")
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);
if it didn't work try this :
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);

Why am I getting InaccessibleObjectException when writing to JSON file

I'm using Gson to manage my Json file. I have a User class which looks like this:
public class User {
private StringProperty username;
private StringProperty password;
...
public User() {}
public User(String user, String pass, ...) {
this.username = new SimpleStringProperty(user);
this.password = new SimpleStringProperty(pass);
...
}
public String getUsername() {
return username.get();
}
public void setUsername(String username) {
this.username.set(username);;
}
...
}
And this is how I add a User to the Json file
public static boolean addUser(User user) throws IOException{
String users = new String(Files.readAllBytes(Paths.get("users.json")));
List<User> userList = getUsers(users);
if (userList.contains(user)) return false;
userList.add(user);
Writer writer = new FileWriter("users.json");
Gson gson = new GsonBuilder().create();
gson.toJson(userList, writer);
writer.close();
return true;
}
gson.toJson(userList, writer) is throwing this error:
Exception in thread "JavaFX Application Thread" java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.Object javafx.beans.property.SimpleStringProperty.bean accessible: module javafx.base does not "opens javafx.beans.property" to unnamed module #4bf59938
I know it has something to do with the StringProperty attributes, but I don't know what's wrong.

javafx tableview not able to fetch data while initializing

I'm trying to populate tableview at the time of loading. Please forgive if there is any mistake.
public class users {
public String username;
public String FullName;
public String password;
public String phone;
public String email;
public String doj;
public String city;
public String state;
public String address;
public ObservableList <ListEmply> emplylst = FXCollections.observableArrayList();
}
public class UserDetail {
#FXML
private ObservableList <ListEmply> emplylst;
#FXML
private TableView <ListEmply> tbl_employeeview;
#FXML
private TableColumn<Object, Object> employeename;
users User = new users();
Dbconnection dbcon = new Dbconnection();
Connection con;
PreparedStatement pst;
ResultSet rs;
public void showDetails(users User){
con = dbcon.geConnection();
try{
pst = con.prepareStatement("select room_no from room");
rs = pst.executeQuery();
while (rs.next()){
User.emplylst.add(new ListEmply(
rs.getString(1)
));
}
System.out.println(rs);
rs.close();
pst.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void usrdetails(){
tbl_employeeview.setItems(emplylst);
showDetails(User);
employeename.setCellValueFactory(new PropertyValueFactory<>("employeename"));
System.out.println(rs);
}
public void Initializable(URL url, ResourceBundle rb){
usrdetails();
}
}
ListEmply Class
public class ListEmply {
public String employeename;
public ListEmply(String employeename) {
super();
this.employeename = employeename;
}
public String getEmployeename() {
return employeename;
}
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
}
As described in the documentation, the controller method that is called to initialize the controller is called initialize(...), not Initializable(...):
public void initialize(URL url, ResourceBundle rb){
usrdetails();
}
As noted by #fabian in the comments, since you are not implementing the (legacy) interface Initializable and not using the parameters, you can omit the parameters from the method definition:
public void initialize(){
usrdetails();
}

Getting null pointer exception while calling EJB method from junit

I am writing unit Junit test case for entity java bean.But, when i call the EJB method i am getting an null pointer exception the code is like below
UserServiceTest.java
#PersistenceContext(unitName = "PU")
private EntityManager em;
private static UserService userService;
#Test
public void registerUser() {
userService = new UserService();
resultData = userService.registerUser(name, email, password, mobileNumber, countryId);
Assert.assertEquals(true, resultData.isSet);
Assert.assertEquals(message, resultData.message);
}
UserService.java
#PersistenceContext(unitName = "PU")
private EntityManager em;
public ResultData registerUser(String name, String email, String password, String mobileNumber, String countryId) {
try {
Query q = em.createNamedQuery("User.findByEmail", User.class).setParameter("email", email);
users = q.getResultList();
if (!users.isEmpty()) {
userDataClass.isSet = false;
userDataClass.message = "A user with this email already exists.";
return userDataClass;
}catch (Exception e) {
userDataClass.isSet = false;
}
The above code i debugged. When the ponter came to entityManager
Query q = em.createNamedQuery("User.findByEmail", User.class).setParameter("email", email);
I am getting an null pointer exception.
Can any one plz help me

How to write a junit test case for a method containing session map

I'm very new to Junit.
I'm writing junit for a interceptor.. It contains SessionMap in that.. while calling the interceptor from the test class I'm getting Null pointer exception at Session Map.
Below is my interceptor..
public String intercept(ActionInvocation actionInv) throws Exception {
ActionContext context = actionInv.getInvocationContext();
final HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
String callerAppName = request.getParameter(CustomerPortalConstants.CALLER);
if(callerAppName == null){
//caller name is passed in header in case of OnePortal service request
callerAppName = request.getHeader(CustomerPortalConstants.CALLER);
}
SessionMap<String,Object> sessionMap = ((SessionMap<String,Object>)ActionContext.getContext().getSession());
#SuppressWarnings("unchecked")
Map<String,AccountBean> accountsMap = (Map<String,AccountBean>)sessionMap.get(CustomerPortalConstants.ACCOUNTSMAP);;
if(accountsMap == null) {
accountsMap = new HashMap<String, AccountBean>();
sessionMap.put(CustomerPortalConstants.ACCOUNTSMAP, accountsMap);
}
Im getting error at this location
((SessionMap)ActionContext.getContext().getSession());
This is my Test class..
public class MultiAccountInterceptorTest extends StrutsTestCase implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String,AccountBean> accountsMap=new HashMap<String, AccountBean>();
Map<String, Object> sessionMap;
private String callerAppName="LMP";
private final HttpServletRequest mockHttpReq = createMock(HttpServletRequest.class);
MultiAccountInterceptor interceptor = new MultiAccountInterceptor();
#SuppressWarnings("unchecked")
#Before
public void setUp() throws Exception {
sessionMap = new HashMap<String, Object>();
}
#SuppressWarnings("unchecked")
#Test
public void testIntercept() throws Exception
{
MultiAccountInterceptor mockInterceptor = PowerMock.createNicePartialMockForAllMethodsExcept(MultiAccountInterceptor.class, "intercept");
final ActionInvocation mockInvocation = createMock(ActionInvocation.class);
final ActionContext mockContext = createMock(ActionContext.class);
expect(mockInvocation.getInvocationContext()).andReturn(mockContext);
System.out.println(mockContext);
expect( (HttpServletRequest)mockContext.get(ServletActionContext.HTTP_REQUEST)).andReturn(mockHttpReq);
System.out.println(mockHttpReq);
expect(mockHttpReq.getParameter(CustomerPortalConstants.CALLER)).andReturn(callerAppName);
System.out.println("Caller app name is"+ callerAppName);
System.out.println(sessionMap);
sessionMap.put(CustomerPortalConstants.ACCOUNTSMAP, accountsMap);
System.out.println(sessionMap);
replayAll();
mockInterceptor.intercept(mockInvocation);
}
#Override
public void setSession(Map<String, Object> sessionMap) {
this.sessionMap=sessionMap;
}
}
Can anyone provide me a solution for this problem..
Thanks in advance..