Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.prgguru.jersey;
- import javax.ws.rs.Consumes;
- import javax.ws.rs.GET;
- import javax.ws.rs.POST;
- import javax.ws.rs.Path;
- import javax.ws.rs.PathParam;
- import javax.ws.rs.Produces;
- import javax.ws.rs.QueryParam;
- import javax.ws.rs.core.MediaType;
- //Path: http://localhost/<appln-folder-name>/register
- @Path("/reg")
- public class reg {
- // HTTP POST Method
- @POST
- // Path: http://localhost/<appln-folder-name>/register/doregister
- @Path("/doreg")
- // Produces JSON as response
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- // Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz
- public String doReg( @QueryParam("username") String uname, @QueryParam("password") String pwd, @QueryParam("photo") String pht){
- //public String doReg( @PathParam("username") String uname, @PathParam("password") String pwd, @PathParam("photo") String pht){
- String response = "";
- System.out.println(uname+" "+pwd+" "+pht+" ");
- int retCode = registerUser(uname, pwd, pht);
- if(retCode == 0){
- response = Utitlity.constructJSON("register",true);
- }else if(retCode == 1){
- response = Utitlity.constructJSON("register",false, "You are already registered");
- }else if(retCode == 2){
- response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
- }else if(retCode == 3){
- response = Utitlity.constructJSON("register",false, "Error occured");
- }
- return response;
- }
- private int registerUser(String uname, String pwd,String photo) {
- System.out.println("Inside checkCredentials");
- System.out.println(uname+" "+pwd+" "+photo);
- int result = 3;
- if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
- System.out.println("passou no controlo do nulo");
- try{
- if(DBConnection.checkLogin(uname, pwd)){
- System.out.println("");
- result = 1;
- } else {
- DBConnection.insertUser(uname, pwd, photo);
- result = 0;
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- result = 3;
- }
- }
- return result;
- }
- }
- package com.example.pedrooliveira.jsontest;
- import android.app.Activity;
- import android.app.ProgressDialog;
- import android.content.Intent;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.MediaStore;
- import android.util.Base64;
- import android.util.Log;
- import android.view.View;
- import android.widget.EditText;
- import android.widget.Toast;
- import org.json.JSONException;
- import org.json.JSONObject;
- import com.loopj.android.http.AsyncHttpClient;
- import com.loopj.android.http.AsyncHttpResponseHandler;
- import com.loopj.android.http.RequestParams;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- public class MainActivity extends Activity {
- EditText password;
- EditText username;
- ProgressDialog prgDialog;
- private static int RESULT_LOAD_IMG = 1;
- String photo = "default";
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- prgDialog = new ProgressDialog(this);
- // Set Progress Dialog Text
- prgDialog.setMessage("Please wait...");
- // Set Cancelable as False
- prgDialog.setCancelable(false);
- password = (EditText) findViewById(R.id.password);
- username = (EditText) findViewById(R.id.username);
- }
- public void uploadPhoto(View view){
- Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- // Start the Intent
- startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- try {
- // When an Image is picked
- if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
- // Get the Image from data
- Uri selectedImage = data.getData();
- String[] filePathColumn = { MediaStore.Images.Media.DATA };
- Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- String picturePath = cursor.getString(columnIndex);
- cursor.close();
- File f = new File(picturePath);
- String imageName = f.getName();
- byte[] userphoto = readImageOnlyBytes(f);
- photo = Base64.encodeToString(userphoto ,Base64.DEFAULT);
- } else {
- Toast.makeText(this, "You haven't picked Image",Toast.LENGTH_LONG).show();
- }
- } catch (Exception e) {
- Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
- }
- }
- public static byte[] readImageOnlyBytes(File file) throws IOException {
- //Logger.getLogger(Main.class.getName()).log(Level.INFO, "[Open File] " + file.getAbsolutePath());
- InputStream is = new FileInputStream(file);
- // Get the size of the file
- long length = file.length();
- // You cannot create an array using a long type.
- // It needs to be an int type.
- // Before converting to an int type, check
- // to ensure that file is not larger than Integer.MAX_VALUE.
- if (length > Integer.MAX_VALUE)
- {
- // File is too large
- }
- // Create the byte array to hold the data
- byte[] bytes = new byte[(int) length];
- // Read in the bytes
- int offset = 0;
- int numRead = 0;
- while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)
- {
- offset += numRead;
- }
- // Ensure all the bytes have been read in
- if (offset < bytes.length)
- {
- throw new IOException("Could not completely read file " + file.getName());
- }
- // Close the input stream and return bytes
- is.close();
- return bytes;
- }
- public void loginUser(View view){
- String pwd = password.getText().toString();
- String usr = username.getText().toString();
- String pht = this.photo;
- RequestParams params = new RequestParams();
- params.put("password", pwd);
- params.put("username", usr);
- params.put("photo", pht);
- // Put Http parameter password with value of Password Edit Value control
- invokeWS(params);
- }
- public void invokeWS(RequestParams params){
- // Show Progress Dialog
- prgDialog.show();
- // Make RESTful webservice call using AsyncHttpClient object
- AsyncHttpClient client = new AsyncHttpClient();
- Log.d("params: ",params.toString());
- //Log.d("Parameters",params.toString());
- client.post(getApplicationContext(),"http://192.168.2.84:8080/useraccount/reg/doreg", (RequestParams) params, new AsyncHttpResponseHandler() {
- @Override
- public void onSuccess(String response) {
- // Hide Progress Dialog
- prgDialog.dismiss();
- try {
- // JSON Object
- JSONObject obj = new JSONObject(response);
- // When the JSON response has status boolean value assigned with true
- if (obj.getBoolean("status")) {
- Toast.makeText(getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
- // Navigate to Home screen
- Log.d("Suuu", "a");
- }
- // Else display error message
- else {
- Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
- }
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
- e.printStackTrace();
- }
- }
- // When the response returned by REST has Http response code other than '200'
- //@Override
- public void onFailure(int statusCode, Throwable error, String content) {
- // Hide Progress Dialog
- prgDialog.hide();
- // When Http response code is '404'
- if (statusCode == 404) {
- Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
- }
- // When Http response code is '500'
- else if (statusCode == 500) {
- Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
- }
- // When Http response code other than 404, 500
- else {
- Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement