Getting a java.lang.StringIndexOutOfBoundsException using Constructor - constructor

My professor asked for us to make two separate java classes for a popular problem where you have to build an employee email based off of a first name, last name, and employee ID number.
If you'd like to see the problem:
Assignment
The problem is happening in the substring. I think I vaguely know why, but I'm not actually entirely sure how to solve the issue.
Here's the first class:
public class EmployeeSchmidt
{
public String FirstName = "";
public String LastName = "";
public String EmID = "";
public String Email = "";
public EmployeeSchmidt(String FirstName, String LastName, String EmID)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.EmID = EmID;
Generator();
}
public String getFirstName()
{
return FirstName;
}
public void setFirstName(String em)
{
FirstName = em;
}
public String getLastName()
{
return LastName;
}
public void setLastName(String em)
{
LastName = em;
}
public String getEmID()
{
return EmID;
}
public void setEmID(String em)
{
EmID = em;
}
public String getEmail()
{
return Email;
}
public void setEmail(String em)
{
Email = em;
}
String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
public void Generator()
{
Email = (fName + lName + eID + "#initech.com");
}
}
And the second class:
import java.util.Scanner;
public class EmployeeInfo
{
public static void main(String[] args)
{
EmployeeSchmidt em1 = new EmployeeSchmidt("","","");
Scanner in = new Scanner (System.in);
System.out.println("Please enter your first name.");
em1.setFirstName(in.next());
System.out.println("Please enter your last name.");
em1.setLastName(in.next());
System.out.println("Please enter your 5-digit Employee ID.");
em1.setEmID(in.next());
em1.Generator();
System.out.println();
System.out.println(em1.getFirstName());
System.out.println(em1.getLastName());
System.out.println(em1.getEmID());
System.out.println("Your Employee Email is " + em1.getEmail());
}
}
And this is the error I'm getting:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1963)
at EmployeeSchmidt.<init>(EmployeeSchmidt.java:57)
at EmployeeInfo.main(EmployeeInfo.java:6)
The Scanner isn't necessary, but our professor offered extra credit if we were able to do it. I'm just absolutely lost.

There is an error cause you are trying to substring the name variables and assign them to member variables in the class body. Not inside any method. As they will be empty strings when the class gets intialized, the exception is thrown.
Change the EmployeeSchmidt java class to following.
public class EmployeeSchmidt {
public String FirstName = "";
public String LastName = "";
public String EmID = "";
public String Email = "";
public EmployeeSchmidt(String FirstName, String LastName, String EmID) {
this.FirstName = FirstName;
this.LastName = LastName;
this.EmID = EmID;
Generator();
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String em) {
FirstName = em;
}
public String getLastName() {
return LastName;
}
public void setLastName(String em) {
LastName = em;
}
public String getEmID() {
return EmID;
}
public void setEmID(String em) {
EmID = em;
}
public String getEmail() {
return Email;
}
public void setEmail(String em) {
Email = em;
}
public void Generator() {
String fName = null;
if (FirstName != null && FirstName.length() >= 2) {
fName = (FirstName.substring(0, 2));
}
String lName = null;
if (LastName != null && LastName.length()>=4) {
lName = (LastName.substring(0, 4));
}
String eID = null;
if (EmID != null && EmID.length()>=4) {
eID = (EmID.substring(3, 4));
}
Email = (fName + lName + eID + "#initech.com");
}
}

Note the placement of the declarations of variables fName, lName, and eID in your code:
String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
public void Generator()
{
Email = (fName + lName + eID + "#initech.com");
}
They are outside any method, and therefore they are instance variables. These initializations will be performed when each instance is initialized, before the body of the constructor. At that point, you are guaranteed that the base strings are all empty (because of their own, prior, initializers).
Perhaps you want those to be local variables of the Generator() method. In that case, their initializers would not run until Generator() is invoked, at which point the FirstName, LastName, and EmID variables will have the values set by the constructor.
Note, however, that even that does not fully protect you from an out-of-bounds string index. Consider, for instance, an employee whose last name is "Wu" -- that's fewer than four characters. There are two things you can do to solve this problem:
Pad the strings with blanks or some other character to ensure that they are at least as long as you need them to be before computing the substrings (and be prepared for trailing blanks/whatever in the results; example: fName = (FirstName + "..").subString(0,2);), or
Test the string lengths before trying to extract substrings, and use the whole string instead where appropriate. Alternatively, fail (throwing an exception) if the string is not long enough.

you must make the substring in method because if it outside the method you make substring of the
FirstName = "";
LastName = "";
EmID = "";
Email = "";
and that's error you want to substring of the input of user
you can make that solution make it in method
public String getinfo()
{ String fName = (FirstName.substring(0,2));
String lName = (LastName.substring(0,4));
String eID = (EmID.substring(3,4));
Email=Generator(fName,lName,eID);
return Email;}
public String Generator(String fName,String lName,String eID)
{
Email = (fName + lName + eID + "#initech.com");
return Email;
then in the second class you do that
System.out.println("Your Employee Email is " + em1.getinfo());
without Generator before
i hope you understand me

Related

What is org.h2.jdbc.JdbcSQLDataException: Invalid value "3" for parameter "columnIndex" [90008-200]?

I'm trying to use JDBC authentication for my spring security when I hit the error message below. I'm trying to register all the email and password in the User class to be valid logins. I'm not sure if there is a problem with my sql statement or my User class. Any help if appreciated!
Caused by: org.h2.jdbc.JdbcSQLDataException:
Invalid value "3" for parameter "columnIndex" [90008-200]
Spring security
#Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication()
// To find logins in the h2 database
.dataSource(dataSource)
.usersByUsernameQuery("select email, password " +
"from User " +
"where email = ?")
.authoritiesByUsernameQuery("select email, role " +
"from User " +
"where email =?");
}
User class
#Entity
public class User {
private String firstName;
private String lastName;
#Size(min = 6, message ="Enter at least 6 characters")
#ValidPassword
private String password;
private String matchingPassword;
private String passportNumber;
private String address;
private String phoneNumber;
#ValidEmail
private String email;
// Mark as primary key
#Id
// Will be auto generated
#GeneratedValue
private long id;
private String role;
public User(#NotNull String firstName, #NotNull String lastName,
#Size(min = 6, message = "Enter at least 6 characters") #NotNull String password,
#NotNull String passportNumber, #NotNull String address, #NotNull String phoneNumber, String email,
String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passportNumber = passportNumber;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.role = role;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + ", password=" + password
+ ", matchingPassword=" + matchingPassword + ", passportNumber=" + passportNumber + ", address="
+ address + ", phoneNumber=" + phoneNumber + ", email=" + email + ", id=" + id + ", role=" + role + "]";
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setId(long id) {
this.id = id;
}
protected User() {
}
public long getId() {
return id;
}
}
EDIT: Answer to this question is marked below
Spring security expects 3 columns for the usersByUserName query. Here is the default query used if you don't specify one.
public static final String DEF_USERS_BY_USERNAME_QUERY
= "select username, password, enabled from users where username = ?";
So if you don't have such column for enabling and disabling user, use the following query
select email, password, 'true' as enabled from User where email = ?
Reference
https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.html

#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);

Trying to extend a class in java and running into problems

I was wondering if anyone could help me with a problem I am encountering when trying to extend a class. I want to be able to add a first name and a last name which is part of my base class to an extended class.
Here is a snippet from my base class Person.java
public class Person
{
private String firstName = "";
private String lastName = "";
private String id = "";
public Person()
{
}
public Person(String firstName, String lastName, String id)
{
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
And here is the class where I am trying to extend the base class:
public TeamMember(String firstName, String lastName, String team, String id, String role)
{
super(firstName, lastName);
this.team = team;
this.id = id;
this.role = role;
}
The error I receive is:
Error:(25, 9) java: constructor Person in class xxx.xxxx.xxx.xx
cannot be applied to given types;
required: no arguments
found: java.lang.String,java.lang.String
reason: actual and formal argument lists differ in length
I had to create a constructor that matched what was in the super() in the extended class in the base class.
This is what I added to the base class to make it work.
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
Try this.
public TeamMember(String firstName, String lastName, String team, String id, String role)
{
super(firstName, lastName, id);
this.team = team;
this.role = role;
}
Id is a private property of base class, so cannot be accessed in derived class.
private String id = "";

How to select multiple records from table in hibernate

I am trying to get multiple values from a web page form and search the value from databate using hibernate query and retrieve the result and display it in a new page.
I need to get these text fields and even if any of the field is empty, I need to run a search query in database via controller and return set of results in a new page. I tried to store the result in array list of ArrayList but it didnt work. Could anyone please help me?
I am trying to get the text values from from web page in controller:
String lastname = request.getParameter("lastname");
String firstname = request.getParameter("firstname");
String gender = request.getParameter("gender");
String speciality = request.getParameter("speciality");
String keyword = request.getParameter("keyword");
I have Doctor's table which has all these texts fields stored. Lastname, firstname, gender, speciality. I have a class named doctor which links to the database.
#Entity
#Table(name="DOCTOR_DETAILS")
public class Doctor {
#Id
#Column (nullable=false)
private int npi;
#Column (nullable=false)
private String firstName;
#Column (nullable=false)
private String lastName;
#Column (nullable=false)
private String gender;
#Column (nullable=false)
private String speciality;
public int getNpi() {
return npi;
}
public void setNpi(int npi) {
this.npi = npi;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getSpeciality() {
return speciality;
}
public void setSpeciality(String speciality) {
this.speciality = speciality;
}
}
I need to run a select query to retrieve the records from table. Even if any of the 4 fields are empty, the query should retrieve the records.
try {
begin();
ArrayList <String> cntList = new ArrayList<String>();
Query q = getSession().createQuery("select * from
doctor where lastName = :lastName or firstName =:firstName or
gender=:gender or speciality = :speciality");
q.setString("username", username);
cntList = (ArrayList<String>) q.list();
commit();
return cntList;
}
I tried the below way of using Hibernate criteria, but I am getting an error. Am I going wrong anywhere?.
I wrote below code in my controller:
Below part in my DAO class which connects to the database.
But I am getting below error:
Could you please help me out?
The code worked fine and returned the list of results. I tried to follow the steps provided in tutorial point site, but I am getting a cast error.
"Type mismatch: cannot convert from int to doctor.
A type mismatch asking me to change
Doctor doctor = iterator.next();
to
int doctor = iterator.next();
which is something weird, since I cannot retrieve values from Doctor class.
You should use Hibernate criteria query with disjunction. It's been designed to handle this sort of situations. Try this code snippet
public List<Doctor> getSearchResult(String firstName, String lastName, String gender, String speciality, Session session) {
Criteria cr = session.createCriteria(Doctor.class);
Disjunction or = Restrictions.disjunction();
if (firstName != null)
or.add(Restrictions.ilike("firstName", firstName+"%"));
if (lastName != null)
or.add(Restrictions.ilike("lastName", "%"+lastName));
if (gender != null)
or.add(Restrictions.eq("gender", gender));
if (speciality != null)
or.add(Restrictions.ilike("speciality", "%"+speciality+"%"));
cr.add(or);
return (List<Doctor>) cr.list();
}
You can get idea about Hibernate Criteria queries here.

the request sent by the client was syntactically incorrect when sending post requests

The method in myController looks like this
#RequestMapping(value="/{processId}/dependents", method=RequestMethod.POST,consumes="application/json")
#ResponseBody
public Dependents postdependent(#ModelAttribute ProcessContext process,#RequestBody Dependent dependent) {
return process.getDependents().addDependent(dependent);
}
My gets and delete work perfectly.
But whenever I do a post I am getting the request sent by the client was syntactically incorrect.
JSON for post request:
"{
'dependentId' : '1003',
'firstName' : 'Vishu',
'lastName' : 'poodari',
'birthDate' : '1970/04/15'
}"
Please I tried all combinations by using single quotes, doubles quotes everything.
I am using rest-shell for doing the operations.
Please find my Dependent Class
public class Dependent {
private String dependentId;
private String firstName;
private String lastName;
private String birthDate;
#JsonCreator
public Dependent(#JsonProperty("dependentId") String dependentId, #JsonProperty("firstName") String firstName, #JsonProperty("lastName")String lastName,
#JsonProperty("birthDate") String birthDate) {
this.dependentId = dependentId;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
public String getDependentId() {
return dependentId;
}
public void setDependentId(String dependentId) {
this.dependentId = dependentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
}
syntactically incorrect means problem with the json,please replace the single quote with double.
{"dependentId" : "1003",
"firstName" : "Vishu",
"lastName" : "poodari",
"birthDate" : "1970/04/15"
}
also check the json keys should match with your Dependent class attribute names, and the data should be convertible by the parser.
Error *The request sent by the client was syntactically incorrect"** in most of the case means that jackson is not able to desalinize(convert json string to object) because default constructor is missing.
In your case there is missing default constructor, you have parameterized constructor which override default and jackson is not able create object
public Dependent(#JsonProperty("dependentId") String dependentId, #JsonProperty("firstName") String firstName, #JsonProperty("lastName")String lastName,
#JsonProperty("birthDate") String birthDate) { this.dependentId = dependentId;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
Add also default constructor into your class and everything will be working
public Dependent() {
}
When using curl (on dos) i had the same problem. I needed to use all double quotes and therefore mask the ones within the body part:
C:>curl -H "Content-Type: application/json" -X POST -d "{\"id\":1,\"firstName\":\"Hans\",\"lastName\":\"Muster\"}" http://localhost:8081/persons