Authentification failed while connecting to ActiveDirectory from a remote host - java

I wrote the code on Ubuntu 16 and tried to connect to ActiveDirectory on a Windows Server 2012 virtual machine.
The user name is : siwar
The user password is : siwarmp
The domain name is: squeezer.celtron.com
The VM host address (Windows server 2012) : 192.168.1.115
The following code did not work and generated an Authentification:
package ldap;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.SizeLimitExceededException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LdapMain {
static DirContext ctx = null;
static String userLog = "cn=siwar,ou=users,dc=squeezer,dc=celtron,dc=com";
// static String userLog =
// "cn=siwar,cn=users,dc=squeezer,dc=celtron,dc=com";
static String userMP = "siwarmp";
public static void main(String args[]) throws Exception {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.1.115:389/");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=squeezer,dc=celtron,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "ldap");
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
getGroup(env, 500);
getRole(env, "readonly");
validateLogin(env, userLog, userMP);
}
private static SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
// String[] attrIDs = {"objectGUID"};
// searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
public static Boolean validateLogin(Hashtable<String, String> env, String userName, String userPassword) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, userPassword);
ctx = new InitialDirContext(env);
results = ctx.search("ou=users,dc=celtron,dc=com", "(objectclass=inetOrgPerson)",
getSimpleSearchControls());
// results = ctx.search("dc=celtron,dc=com",
// "(objectclass=inetOrgPerson)", getSimpleSearchControls());
results = ctx.search(userName, "(objectclass=*)", getSimpleSearchControls());
System.out.println(results);
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("cn");
String dn = (String) dnAttr.get();
System.out.println(dn);
Attribute gidAttr = attrs.get("gidNumber");
String gid = (String) gidAttr.get();
System.out.println(gid);
// User Exists, Validate the Password
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, userPassword);
return true;
}
return false;
} catch (AuthenticationException e) { // Invalid Login
return false;
} catch (NameNotFoundException e) { // The base context was not found.
return false;
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) { /* Do Nothing */
}
}
}
public static Boolean getRole(Hashtable<String, String> env, String roleName) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
ctx = new InitialDirContext(env);
results = ctx.search("cn=readonly,ou=roles,dc=celtron,dc=com", "(objectclass=organizationalRole)",
getSimpleSearchControls());
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("roleOccupant");
String dn = (String) dnAttr.get();
System.out.println(dn);
return true;
}
return false;
} catch (AuthenticationException e) { // Invalid Login
System.out.println("Auth failed");
return false;
} catch (NameNotFoundException e) { // The base context was not found.
return false;
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
}
}
}
public static String getGroup(Hashtable<String, String> env, int gid) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
ctx = new InitialDirContext(env);
results = ctx.search("ou=groups,dc=celtron,dc=com", "(gidNumber=500)", getSimpleSearchControls());
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("cn");
String dn = (String) dnAttr.get();
System.out.println(dn);
return dn;
}
return "";
} catch (AuthenticationException e) {
return "";
} catch (NameNotFoundException e) {
return "";
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
}
}
}
}

Related

LDAP get the groups which a user belongs

I'm newer coding ldap using spring-boot (ldapTemplate). I want to get the groups that a user belongs, get the list of membreOf attributes, I tried this:
#Override
public Person getUserInfo(String uid, String orgnisationUnit) throws InvalidNameException {
Name dn = bindDn(uid, orgnisationUnit);
return (Person ) ldapTemplate.lookup(dn, new LdapMapper());
}
This is myLdapMapper:
public class LdapMapper implements ContextMapper<Object> {
#Override
public Object mapFromContext(Object ctx) {
DirContextAdapter context = (DirContextAdapter) ctx;
Person p = new Person();
p.setFirstName(context.getStringAttribute("cn"));
p.setMailAddress(context.getStringAttribute("uid"));
p.setRoles(context.getObjectAttributes("memberOf")); // roles was declared like: private Object[] roles
return p;
}
}
Would you have any propositions ?
import java.io.*;
import java.text.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.xml.bind.*;
public class LdapConnection {
public void getUserDetail(String user_name, String passwd) throws NamingException {
DirContext ctx = null;
String username = user_name;
try {
ctx = context(user_name, passwd);
SearchControls searchCtls = new SearchControls();
String returnedAtts[] = {"sn", "mail", "cn", "givenName",
"telephoneNumber", "manager","memberOf"};
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=user)(mail=*))";
String searchBase = "OU=India,DC=<Domain Component>";
NamingEnumeration<?> answer = ctx.search(searchBase, searchFilter,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
try {
String cn = attrs.get("cn").get().toString();
String mail_id = attrs.get("mail").get().toString();
NamingEnumeration<?> memberOf = attrs.get("memberOf").getAll();
while (answer.hasMoreElements()) {
String member =(String)memberOf.next();
System.out.println("memberOf : " + member);
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
} catch (NamingException e) {
System.out.println(e.getMessage());
} finally {
if(!ctx.equals(null))
ctx.close(); }
}
/**
* This method will return Directory Context to the Called method,Used to
* bind with LDAP
*/
public DirContext context(String user, String passwd)
throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
String adminName = "CN=" + user
+ ",OU=User,OU=India,DC=<Domain Component>";
String adminPassword = passwd;
String ldapURL = <ldapserver url with port>;
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, adminName);
env.put(Context.SECURITY_CREDENTIALS, adminPassword);
DirContext ctx = new InitialLdapContext(env, null);
return ctx; }
public static void main(String[] args) throws NamingException {
LdapConnection ldap = new LdapConnection();
ldap.getUserDetail("username","password");
}
}`
I hope this code will solve you problem.

[B cannot be cast to java.lang.String in LDAP Search

When i am trying to search password of user from ldap server this
below error displayed
In this code its doesn't return user Password in String. It throws
java.lang.ClassCastException: [B cannot be cast to java.lang.String
Code:
public class selectEntry {
DirContext ldapContext = null;
public selectEntry() {
try {
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, url);
environment.put(Context.SECURITY_AUTHENTICATION, conntype);
environment.put(Context.SECURITY_PRINCIPAL, AdminDn);
environment.put(Context.SECURITY_CREDENTIALS, password);
ldapContext = new InitialDirContext(environment);
System.out.println("Bind successful");
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void getEntry() {
try {
SearchControls searcCon = new SearchControls();
searcCon.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration results
= ldapContext.search("uid=aruhat.aruhat,ou=openzki,dc=aruhat,dc=co,dc=in", "(uid=aruhat.aruhat)", searcCon);
if (results != null) {
while (results.hasMore()) {
SearchResult res = (SearchResult) results.next();
Attributes atbs = res.getAttributes();
Attribute atb = atbs.get("userPassword");
String name = (String) atb.get();
System.out.println("Name is :=> " + name);
}
} else {
System.out.println("fail");
}
} catch (Exception e) {
System.out.println("Exception Type:=> "+e);
System.out.println("Exception Message:=> "+e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new selectEntry().getEntry();
}
}
LDAP passwords are stored as hashes, not strings. The attribute value is returned as a byte[], as the exception says.
However you don't have any good reason for obtaining the hashed password attribute in the first place. It won't do you any good. Review your requirement. You should be binding as the user using the old password to test whether it's valid, not trying to read the password, which you won't get.
Retreiving binary attributes requires the ;binary suffix, e.g., userCertificate;binary. Then you have the Attribute object. Invoke
byte[] bytes = (byte[]) attr.get()
and you are done. Don't work with toString() or (String) cast.

Check username and password in Ldap server through java

I have to check if username and password gave from user are right matching with the Ldap server. I use two connection, in the first I retrieve dn from uid and in the second I connect to Ldap with dn and password.
I have a problem with retrieved dn, it doesn't have the right fields.
It returns
cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR: null:null:No attributes
and not
cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR,ou=people,dc=example,dc=com
As you can see, ou and dc are not returned so my second query fails.
This is my code
#Override
public void isAuthenticated(String username, String password) throws LdapException{
String dn;
Hashtable<String, Object> ldapEnv = new Hashtable<String, Object>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "secret");
String[] returnAttribute = {"dn"};
DirContext ctx = null;
NamingEnumeration<SearchResult> results = null;
try {
ctx = new InitialDirContext(ldapEnv);
SearchControls controls = new SearchControls();
controls.setReturningAttributes(returnAttribute);
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "uid=" + username ;
results = ctx.search(env.getRequiredProperty(PROPERTY_NAME_LDAP_USERSEARCHBASE), filter, controls);
if (results.hasMore())
dn = results.nextElement().toString();
else throw new LdapException("Wrong username. Please retry!");
} catch (Exception e) {
throw new LdapException(e);
} finally {
try{
if (results != null)
results.close();
if (ctx != null)
ctx.close();
}catch(Exception e){
throw new LdapException(e);
}
}
Hashtable<String, Object> authEnv = new Hashtable<String, Object>();
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, dn);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
new InitialDirContext(authEnv);
} catch (AuthenticationException authEx) {
throw new LdapException("Authentication error. Password was wrong");
} catch(Exception e){
throw new LdapException(e);
}
}
with this parameters
ldap.url=ldap://127.0.0.1:10389/dc=example,dc=com
ldap.userSearchBase=ou=people
I'm uing this value also for spring authentication but I have one method (send big file) that fails only if I use authentication so I would like to try to authenticate with java and not through Spring
Do you know why I have this problem? thanks
UPDATE: with
dn = results.nextElement().getNameInNamespace();
it works, is my codes robust?
This is jboss LDAP login module implementation you can compare you code:
full code link
protected void rolesSearch(LdapContext ctx, SearchControls constraints, String user, String userDN,
int recursionMax, int nesting) throws NamingException
{
LdapContext ldapCtx = ctx;
Object[] filterArgs = {user, sanitizeDN(userDN)};
boolean referralsExist = true;
while (referralsExist) {
NamingEnumeration results = ldapCtx.search(rolesCtxDN, roleFilter, filterArgs, constraints);
try
{
while (results.hasMore())
{
SearchResult sr = (SearchResult) results.next();
String dn;
if (sr.isRelative()) {
dn = canonicalize(sr.getName());
}
else {
dn = sr.getNameInNamespace();
}
if (nesting == 0 && roleAttributeIsDN && roleNameAttributeID != null)
{
if(parseRoleNameFromDN)
{
parseRole(dn);
}
else
{
// Check the top context for role names
String[] attrNames = {roleNameAttributeID};
Attributes result2 = null;
if (sr.isRelative()) {
result2 = ldapCtx.getAttributes(quoteDN(dn), attrNames);
}
else {
result2 = getAttributesFromReferralEntity(sr, user, userDN);
}
Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
if( roles2 != null )
{
for(int m = 0; m < roles2.size(); m ++)
{
String roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
}
// Query the context for the roleDN values
String[] attrNames = {roleAttributeID};
Attributes result = null;
if (sr.isRelative()) {
result = ldapCtx.getAttributes(quoteDN(dn), attrNames);
}
else {
result = getAttributesFromReferralEntity(sr, user, userDN);
}
if (result != null && result.size() > 0)
{
Attribute roles = result.get(roleAttributeID);
for (int n = 0; n < roles.size(); n++)
{
String roleName = (String) roles.get(n);
if(roleAttributeIsDN && parseRoleNameFromDN)
{
parseRole(roleName);
}
else if (roleAttributeIsDN)
{
// Query the roleDN location for the value of roleNameAttributeID
String roleDN = quoteDN(roleName);
String[] returnAttribute = {roleNameAttributeID};
try
{
Attributes result2 = null;
if (sr.isRelative()) {
result2 = ldapCtx.getAttributes(roleDN, returnAttribute);
}
else {
result2 = getAttributesFromReferralEntity(sr, user, userDN);
}
Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
if (roles2 != null)
{
for (int m = 0; m < roles2.size(); m++)
{
roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
catch (NamingException e)
{
PicketBoxLogger.LOGGER.debugFailureToQueryLDAPAttribute(roleNameAttributeID, roleDN, e);
}
}
else
{
// The role attribute value is the role name
addRole(roleName);
}
}
}
if (nesting < recursionMax)
{
rolesSearch(ldapCtx, constraints, user, dn, recursionMax, nesting + 1);
}
}
referralsExist = false;
}
catch (ReferralException e) {
ldapCtx = (LdapContext) e.getReferralContext();
}
finally
{
if (results != null)
results.close();
}
} // while (referralsExist)
}

Java LDAP returning always a single value instead of a list

I want to query my ldap to give me all users where sn contains a specific value (maier). However I always get a single result.
public LdapContext getLdapContext(){
LdapContext ctx = null;
try{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.url:389");
ctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
}catch(NamingException nex){
System.out.println("LDAP Connection: FAILED");
nex.printStackTrace();
}
return ctx;
}
private User getUserBasicAttributes(String username, LdapContext ctx) {
User user=null;
try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { "distinguishedName",
"sn",
"givenname",
"mail",
"telephonenumber"};
constraints.setReturningAttributes(attrIDs);
constraints.setCountLimit(200);
NamingEnumeration answer = ctx.search("DC=myDc,DC=com", "sn=*maier*", constraints);
if (answer.hasMore()) {
Attributes attrs = ((SearchResult) answer.next()).getAttributes();
System.out.println("distinguishedName "+ attrs.get("distinguishedName"));
System.out.println("givenname "+ attrs.get("givenname"));
System.out.println("sn "+ attrs.get("sn"));
System.out.println("mail "+ attrs.get("mail"));
System.out.println("telephonenumber "+ attrs.get("telephonenumber"));
}else{
throw new Exception("Invalid User");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return user;
}
Did I do anything wrong?
You're not looping, so of course you're only getting one result. Change if (answer.hasMore()) to while (answer.hasMore()).

Display details on specific user using rest web service, queryparam

I am making a log in form on java. Restful web service. I have done logging in and in registration. I have here inputting plate number. I want to retrieve data based on the inputted plate number. I have here the scanning only of the plate number if it is in the database, but I dont know how to display the details of it. Here's my code. I'm so confused. I don't know how to do it.
Constants.java
package com.taxisafe.connection;
public class Constants {
public static String dbClass = "com.mysql.jdbc.Driver";
private static String dbName= "taxisafe";
public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;
public static String dbUsername = "root";
public static String dbPassword = "";
}
DatabaseConnection.java
package com.taxisafe.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.taxisafe.objects.Objects;
public class DatabaseConnection {
#SuppressWarnings("finally")
public static Connection createConnection() throws Exception {
Connection koneksyon = null;
try {
Class.forName(Constants.dbClass);
koneksyon = DriverManager.getConnection(Constants.dbUrl, Constants.dbUsername, Constants.dbPassword);
} catch (Exception e) {
throw e;
} finally {
return koneksyon;
}
}
//CHECK FOR LOGIN
public static boolean checkUser(String username, String password) throws Exception { //checkLogin to checkUser
boolean UserRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM user WHERE username = '" + username + "' AND password=" + "'" + password + "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
UserRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return UserRecorded;
}
// REGISTER USER
public static boolean registertheUser(String name, String username, String email, String password) throws SQLException, Exception { //inserUser - registertheUser
boolean insertUser = false; //insertStatus - insertUser
Connection konek = null;
try{
try{
konek = DatabaseConnection.createConnection();
}
catch (Exception e){
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "INSERT into user(name, username, emailaddress, password) values('"+name+ "',"+"'" + username + "','"+ email + "','" + password + "')";
int dbrecord = statement.executeUpdate(code);
if (dbrecord > 0){
insertUser = true;
}
} catch (SQLException sqle){
throw sqle;
} catch (Exception e){
if (konek !=null){
konek.close();
}
throw e;
} finally{
if (konek !=null){
konek.close();
}
} return insertUser;
}
//CHECK PLATE NUMBER
public static boolean checkPlate(String platenumber) throws Exception { //checkLogin to checkUser
boolean PlateRecorded = false;
Connection konek = null;
try {
try {
konek = DatabaseConnection.createConnection();
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = konek.createStatement();
String code = "SELECT * FROM taxi WHERE taxi_plate_no = '" + platenumber+ "'";
ResultSet rs = statement.executeQuery(code);
while (rs.next()) {
PlateRecorded = true;
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (konek != null) {
konek.close();
}
throw e;
} finally {
if (konek != null) {
konek.close();
}
}
return PlateRecorded;
}
}
JsonConstruction.java
package com.taxisafe.json;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class JsonConstruction {
public static boolean isNotNull(String text){
return text !=null && text.trim().length() >=0 ? true : false;
}
public static String JSONResponse(String tag, boolean status){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
} catch (JSONException e){
} return object.toString();
}
public static String JSONResponse(String tag, boolean status, String errorMessage){
JSONObject object = new JSONObject();
try{
object.put("tag", tag);
object.put("status", new Boolean(status));
object.put("errorMessage", errorMessage);
} catch (JSONException e){
} return object.toString();
}
}
PlateNumberCheck.java
package com.taxisafe.server;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.sun.corba.se.impl.util.Utility;
import com.taxisafe.connection.DatabaseConnection;
import com.taxisafe.json.JsonConstruction;
#Path("platecheck") //for the url
public class PlateNumberCheck {
#GET
//To get the full url : http://Ipaddress:portnumber/#path/#getPath
#Path("/magcheck")
#Produces(MediaType.APPLICATION_JSON)
//Produces is for the response of JSON.
public String magcheck(#QueryParam("platenumber") String platenumber){
String sagot = "";
if(checkInput(platenumber)){
sagot = JsonConstruction.JSONResponse("checked", true);
} else{
sagot = JsonConstruction.JSONResponse("checked", false, "Not in the database");
}
return sagot;
}
private boolean checkInput (String platenumber){
System.out.println("Check Input");
boolean output = false;
if(JsonConstruction.isNotNull(platenumber)){
try{
output = DatabaseConnection.checkPlate(platenumber);
} catch (Exception e){
output = false;
}
} else{
output = false;
}
return output;
}
}
Please help me on how to display the details of the plate number.

Categories