dimanche 19 avril 2015

Data not being stored when using Spring JPA with android

I am developing an app which would talk to the server which is developed using spring. I got to a point where we i was getting data from the google api and wanted to pass it to the spring server. But when i do pass it, the server accepts it but the data is not being stored in the mysql database.


Here is the code I am using:


This is the main spring application + controller:



@EnableJpaRepositories(basePackageClasses = StudentRepository.class)

@SpringBootApplication
public class Demo3Application {

public static void main(String[] args) {
SpringApplication.run(Demo3Application.class, args);
}
}

@RestController
class StudentController
{
@Autowired
public StudentRepository students;

@RequestMapping(value = "/getstudent", method = RequestMethod.GET)
public @ResponseBody List<Student> fetchStudents()
{

if(students.count() == 0)
{
Vector<VideoList> no_video = new Vector<VideoList>();
VideoList no_v = new VideoList("No Videos found", null, null, null);
no_video.add(no_v);
return no_video;
return null;
}

return null;
}

@RequestMapping(value = "/poststudent" , method = RequestMethod.POST)
public @ResponseBody String putStudents(@RequestBody Student v )
{

students.save(v);

return "Student Successfully Added";


}

@RequestMapping(value = "/searchstudent/{str}" , method = RequestMethod.GET)
public @ResponseBody String searchStudent(
@PathVariable("str") String searchQuery
)
{
if(students.existsByEmail(searchQuery)){
List<Student> sList = students.findEmail(searchQuery,new PageRequest(0, 1));
Student s = sList.get(0);
String str = "";
Vector<CourseList> c = s.getCourses();
Iterator<CourseList> it = c.iterator();
while(it.hasNext()){
str.concat(it.next().toString());
str.concat("\n");
}
return str;
}

return null ;

}

@RequestMapping(value = "/addcourse" , method = RequestMethod.POST)
public @ResponseBody String postCourse(@RequestParam String email, @RequestParam String course){
List<Student> sList = students.findEmail(email,new PageRequest(0, 1));
Student s = sList.get(0);
CourseList c = new CourseList();
c.setName(course);
s.addCourse(c);
students.save(s);
return null;
}

}


This is the Student class:



@Entity
@Table(name = "table1")
public class Student {

private String name;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String email;

private Vector<CourseList> courses = new Vector<CourseList>();//CourseList is just a class to store data about various courses.
public Student(){}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public Vector<CourseList> getCourses(){
return courses;
}
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public void setCourses(Vector<CourseList> courses){
this.courses = courses;
}
public void addCourse(CourseList c){
courses.add(c);
}
}


This is my repository:



@Repository
@Transactional
public interface StudentRepository extends CrudRepository<Student,String>{

@Query("SELECT s FROM Student s WHERE email = ?1")
public List<Student> findEmail(String searchQuery, Pageable pageable);

@Query("SELECT CASE WHEN COUNT(s) > 0 THEN 'true' ELSE 'false' END FROM Student s WHERE s.email = ?1")
public boolean existsByEmail(String searchQuery);


}


This is my application.properties file:



spring.datasource.url: jdbc:mysql://localhost/mydb
spring.datasource.driverClassName: com.mysql.jdbc.Driver
spring.datasource.username: root
spring.datasource.password:root

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


And finally here is the android code to test the above:



public class MainActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {

private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "MainActivity";

// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;

private boolean mSignInClicked;

private ConnectionResult mConnectionResult;

private SignInButton btnSignIn;
private Button btnSignOut;
private ImageView imgProfilePic;
private TextView txtName, txtEmail, course;
private LinearLayout llProfileLayout;
private Button SC;

private String personName;
private String personPhotoUrl;
private String personGooglePlusProfile;
private String email;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
course = (TextView) findViewById(R.id.txtCourses);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
SC=(Button)findViewById(R.id.Scourse);

// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
SC.setOnClickListener(this);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}

protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}

if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;

if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}

}

@Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}

mIntentInProgress = false;

if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

// Get user's information
getProfileInformation();


// Update the UI after signin
updateUI(true);

}

/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
getCourses();
SC.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
course.setText(" ");
SC.setVisibility(View.GONE);
}
}

private void getCourses(){
new StudentSearch().execute();
}



private class StudentSearch extends AsyncTask<String, Void, String >
{

String content = "";
@Override
protected String doInBackground(String... urls) {

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://ift.tt/1Don8s7"+email);

StringBuffer studentString = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpget);
InputStream responseString = response.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(responseString));
String res = "";
if ((res = reader.readLine()) == null) {
studentString.append("");
HttpPost httpPost = new HttpPost("http://ift.tt/1yH0v6s");

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", personName);
jsonObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}

try {
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httpPost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}

} else {
studentString.append(res);
studentString.append("\n");
while ((res = reader.readLine()) != null) {
studentString.append(res);
studentString.append("\n");
}

}
}
catch(Exception e)
{
e.printStackTrace();
}

return studentString.toString();
}

@Override
protected void onPostExecute(String s) {
if (!s.isEmpty()){
course.setText("Courses Taken:\n"+s);}
else
course.setText("No Courses Taken!");

}
}

/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName = currentPerson.getDisplayName();
personPhotoUrl = currentPerson.getImage().getUrl();
personGooglePlusProfile = currentPerson.getUrl();
email = Plus.AccountApi.getAccountName(mGoogleApiClient);

Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);

txtName.setText(personName);
txtEmail.setText(email);

// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;

new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);

} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}

/**
* Button on click listener
* */
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
signOutFromGplus();
break;
case R.id.Scourse:
{
Intent intent=new Intent(MainActivity.this,SelectCourse.class);
startActivity(intent);
break;
}
}
}

/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}

/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}

/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

}


I am a total newbie when it comes to developing spring code and would really appreciate some help.


Aucun commentaire:

Enregistrer un commentaire