add alert in body of java jersey application - java

for a project I'm developing an app with web services
My problem concerns the login page, that is when I manage that the user has not registered, I would like to show an alert on the same login page..
#Path("postlogincookie")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postLoginAdminCookie(#FormParam("username") String username, #FormParam("password") String password)
{
java.sql.Connection con = null;
SqliteConnection sqlite = new SqliteConnection();
sqlite.setDbPath(dbPath);
con = sqlite.connect();
String query = "SELECT Username,Password,Role FROM User WHERE Username ='"+username+"' and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
if(!rs.next())
{
return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build();
}
currently I use return Response.status(Response.Status.UNAUTHORIZED).entity("Non sei registrato, registrati!").build(); but I don't want to change page to give the error message.
is there a solution to give a message of alert or error on login page?

Related

How to request Rest API eclipse service in postman?

I generate this Rest API service in java eclipse, now i am not sure how to test this in Postman.
So can anyone guide me on how the #QueryParam json object will be written in postman?
#Path("/UpdateTenantProfile")
public class UpdateTenantProfile {
#SuppressWarnings({ "unchecked" })
#POST
#Path("UpdateTenantProfiledetails")
#Produces("application/json")
#Consumes("application/json")
public String UpdateTenantProfilem(#QueryParam("profileDetail") JSONObject profileDetail) throws JSONException {
Connection dbConnection = null;
Statement stmt = null;
JSONObject jsarr = new JSONObject();
try {
// con.setAutoCommit(false);
dbConnection = DBConnection.getDBConnection();
dbConnection.setAutoCommit(false);
stmt = (Statement) dbConnection.createStatement();
// System.out.println("Iam entering try catch bloxck");
// System.out.println("length of json data"+kcm.length());
String PIDNO = profileDetail.getString("PIDNO");
String GENDER = profileDetail.getString("GENDER");
String TENANTNAME = profileDetail.getString("TENANTNAME");
String EMAIL = profileDetail.getString("EMAIL");
String OFFPHONE = profileDetail.getString("OFFPHONE");
String MOBILE = profileDetail.getString("MOBILE");
Either it's inside url, body or form data I don't have idea about it,
You can give encoded Query Param in the Postman Inside Params tab near Auth Tab as shown below.
You can do encoding of data from https://www.url-encode-decode.com/
Edit :
As you can see I got a perfect response from API. I returned the Value of JSON from API.

How to configure spring security with Office 365 authentication?

I'm new to spring-security. I understood basics of spring-security about authentication-manager and other stuff.
I'm using angularjs as front end, and spring 3.0.5 as backend.
I want to add spring security for role based authorization to my existing project.
I also want to authenticate user using office 365. So, i created application in https://apps.dev.microsoft.com/ and given redirect URI as my localhost action.
Using my code, I'm able to authenticate using office 365 and able to get username in redirected action.
#RequestMapping(value="/getCodeAndProcess", method=RequestMethod.POST)
private ModelAndView getCodeAndProcess(#RequestParam("code") String code, HttpServletRequest request) throws Exception {
HttpSession session = null;
try {
session = request.getSession(false);
session.setMaxInactiveInterval(45*60);
String username = helper.processCodeAndGetUsername(code); //this is I'm getting using office 365.
String userRole = helper.getUserRoleBasedOnUsername(username);
System.out.println("================userRole================="+userRole);
if(username != "") {
session.setAttribute("username", username);
session.setAttribute("userRole", userRole);
}else {
session.invalidate();
throw new Exception("username not found");
}
return new ModelAndView("redirect:/adminDashboard/showDashboard");
}catch(Exception e) {
log.error("Error while processing on users authentication.",e );
session.invalidate();
return new ModelAndView("redirect:/login/loginPage");
}
}
Now, I don't get how to configure username and roles in security-context.xml, so that i can use #PreAuthorize("hasRole('ROLE_USER')") , isAuthenticated(), <sec:authorize in my application. (What to add in security-context.xml? So, that it bind username with role as it doing in form login scenario.)
Can you please help to understand this workflow?

How can we use string variable from another class in SQL statement

Login class:
public static String n=request.getParameter("userName");
public static String p=request.getParameter("userPass");
Servlet class:
PreparedStatement ps1= con.prepareStatement("insert into "+Login.n+" values(?,?,?)");
In login class im using a html page where it shows name and password..so when ever user login it validates his pass by Loginps class and returns to login servlet where i placed html form are dress ,dou,pattern fileds ..here action given to servlet class where servlet class request parameters dress ,dou, pattern ...in preparedstatement("sql query have to insert into"+here i want string n value +"values (?,?,?)")
I want to use string n from Login class so that I can make a dynamic tables when user created his account.
Any help appreciated.
Login class:
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if("YOURSERVLETCLASS".checkUser(n, p))
{
// anything you like for example forwarding to welcome page
RequestDispatcher rs = request.getRequestDispatcher("welcome.html");
rs.forward(request, response);
}else {
// if not correct back to index page
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
Servlet class:
public static boolean checkUser(String n,String p){
boolean status=false;
try{
// set your connection here Connection con = .....
PreparedStatement ps=con.prepareStatement(
"INSERT INTO userdetails(username,password)"+"VALUES(?,?)");
ps.setString(1,n);
ps.setString(2,p);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}

Android (libGDX) http connection with mySQL using PHP server side scripting

I am trying to connect my libGDX(java) android project with a mySQL database through a server side PHP scripting in order to implement a login process using POST method (this includes a username and password).
Therefore, i am facing unexpectable problems. For your info i am using XAMPP and APACHE web server locally.
What i am facing! Some times the PHP script sends back the following response string, as if not recognizing the POST parameters (despite the fact that POST message includes them and contain values (string)!!):
<b>Notice</b>: Undefined index: username in <b>C:\xampp\htdocs\login\login.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>C:\xampp\htdocs\login\login.php</b> on line <b>6</b><br />
Some other, the debugger (on Android studio) which is enabled to show me the debugging logs, stops displaying any log after pressing 2-5 times the btnclickLogin() (is shown below), which implements the login activity.
This sounds to me that http connection hangs up and maybe the click button's listener does not respones any more!!!
The more strange one, is that SOMETIMES the same code, returns "success" and everything works fine.
The android code is the next
private void btnclickLogin() {
//Getting values from edit texts
Gdx.app.setLogLevel(Application.LOG_DEBUG);
final String username = usernamefld.getText().toString().trim();
final String password = passwordfld.getText().toString().trim();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", username);
parameters.put("password", password);
Gdx.app.debug("Login process started.", "Username=/" + username + "/ Password=/" + password + "/");
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest;
httpRequest = requestBuilder.newRequest().method(Net.HttpMethods.POST).url("http://192.168.1.2/login/login.php").content(HttpParametersUtils.convertHttpParameters(parameters)).build();
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setTimeOut(6000);
Gdx.net.sendHttpRequest(httpRequest, new HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String status = httpResponse.getResultAsString().trim();
Gdx.app.debug("Return result by the server=", status);
if(status.contains("success"))
game.setScreen(new StartingScreen(game));
}
#Override
public void failed(Throwable t) {
String status = "failed";
Gdx.app.debug("Connection failed due to the next error:", t.getMessage());
}
#Override
public void cancelled() {
}
});
httpRequest.reset();
Gdx.app.debug("Exiting", "From login button function");
}
PHP scripts are
For login.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//Creating sql query
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
//importing dbConnect.php script
require_once('dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con); }?>
For dbConnect.php
<?php
define('HOST',"localhost");
define('USER',"root");
define('PASS',"");
define('DB',"userlogging");
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Connection failed: ' . $conn->connect_error);
$con->set_charset("utf8"); ?>
Please give a hand to overcome this problem and make the http connection "stable"!!
Thanks a lot.
Mishra sorry for the latest of my reply.
Yes, actually i have placed a print_r to see the values that come up to PHP script and found that both parameters were missing.
After so much searches on the internet and alternative solutions that found, i have not found out why does it happen. So, i replaced the HttpRequestBuilder.
Finally, in order to have a complete working code, i used the next and everything works fine now.
final String username = usernamefld.getText().toString().trim();
final String password = passwordfld.getText().toString().trim();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("username", username);
parameters.put("password", password);
final HttpRequest httpRequest = new HttpRequest(Net.HttpMethods.POST);
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setHeader("Upgrade", "HTTP/1.1, HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11");
httpRequest.setUrl(LOGIN_URL);
httpRequest.setContent(HttpParametersUtils.convertHttpParameters(parameters));
httpRequest.setTimeOut(6000);
Thanks again for your help.

Testing user account alfresco CMIS if exist

I am working in a JavaEE project and i want simply see if the user ho logged in with a username and a password have an account in Alfresco, I user the getSession method but it doesn't return if the username and password are wrong (doesn't exist).
private static Session getSession(String serverUrl, String username, String password) {
SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
Map<String, String> params = new HashMap<>();
params.put(SessionParameter.USER, username);
params.put(SessionParameter.PASSWORD, password);
params.put(SessionParameter.ATOMPUB_URL, serverUrl);
params.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
List<Repository> repos = sessionFactory.getRepositories(params);
if (repos.isEmpty()) {
System.out.println(" repository doesn't exist ");
throw new RuntimeException("Server has no repositories!");
}
return repos.get(0).createSession();
}
Thank you
After many research i discover the Rest Api for Alfresco
GET /alfresco/service/api/people/{userName}
for my case I used it and worked for me
you can find more in this link https://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference (how to add a person, how to check if someone is a member of a private site ... ).

Categories

Resources