How to check if boolean false - boolean-operations

I am new to java.. Please help me for the below
I need to print "Authentication failed" when Boolean is false. But the below code is displaying both Success & Failed messages even authentication is successful.
*
switch(choice){
case 1:
System.out.println("Enter the username");
String name = scan.nextLine();
System.out.println("Enter the password");
String password = scan.nextLine();
Boolean result = true;
for(Account a :accountArray )
{
result = a.authentication(name, password);
if(result)
{
System.out.println("Authentication successful");
}
else
{
result=false;
}
}
if(!result)
{
System.out.println("Authentication failed");
}
break;
*
Current Output:
Enter the username
vicky
Enter the password
vicky123
Authentication successful
Authentication failed

It would seem from the output you show, you have more than one Account in accountArray, and what is happening is that one of the accounts in the array matches, but the last one does not. So as you loop over accountArray, it sets result according to that account. One of the accounts in the array succeeds (you print "Authentication successful" once), and the last one does not match. After the loop you print "Authetication failed", as that last check set result to false.
Probably what you want it to put a break; after printing "Authentication successful" -- once you find an account that matches, you're done and don't want to look at any of the later accounts in the vector. But as you never say what you are actually trying to do, it is hard to say.
In addition, the else clause in the loop is redundant -- it runs if result is false, so setting it to false again is pointless. Your code will also leave result as true if the accountArray is empty, and not print any message; that may or may not be sensible.

Related

String matching in scripts

I have a code to reply to all operator messages in SAP. I need it to be applied specifically based on string match. As i am new to scripts, I don't have much idea in which language it has been orignally written. Please help me with the issue. Thanks.
{
String query = "select OperatorMessage.* from OperatorMessage";
for (OperatorMessage oMessage : jcsSession.executeObjectQuery(OperatorMessage.TYPE, query))
{
//Check the operator message requires a reply
if (oMessage.getReplyStatus() == ReplyStatus.valueOf("Required"))
{
oMessage.setReply("Acknowledge");
jcsSession.persist();
}
}
}
My expected output should be, that it should work only with the provided string for string match. Example of such string can be:
"Please check PROCESS_X_215, 4693422521, in XYZ_Queue with status Error"

Writing a PHP if Blank statement

I'm new to PHP so this will sound basic to most people but I need to write the code for when a variable returns nothing (blank).
My variable is $winner, but sometimes there is no winner, in this case it just leaves the page blank, I would like it so if there is no winner then it will display "no winner".
This is my attempt:
if empty($winner) {
echo "no winner";
}
You can make a function to check the variable's valaue with null or empty...
function IsEmptyString($Season){
return (!isset($Season) || trim($Season)==='');
}
This function can be used to check the same.
Just use:
if (!$winner) { // will catch "", null
echo "no winner"
}

PDO login script won't work

I changed this login script to PDO. Now it passes the username but get's stuck fetchAll line. I need help please. thanks
<?php
session_start();
include_once"includes/config.php";
if (isset($_POST['admin_login'])) {
$admin_user = trim($_POST['admin_user']);
$admin_pw = trim($_POST['admin_pw']);
if ($admin_user == NULL OR $admin_pw == NULL) {
$final_report.="Please complete all the fields below..";
} else {
$check_user_data = $db->prepare("SELECT * FROM `admin`
WHERE `admin_user`='$admin_user'");
$check_user_data->execute();
if ($check_user_data->fetchColumn() == 0) {
$final_report.="This admin username does not exist..";
} else {
$get_user_data = $check_user_data->fetchAll($check_user_data);
if ($get_user_data['admin_pw'] == $admin_pw) {
$start_idsess = $_SESSION['admin_user'] = "".$get_user_data['admin_user']."";
$start_passsess = $_SESSION['admin_pw'] = "".$get_user_data['admin_pw']."";
$final_report.="You are about to be logged in, please wait a few moments...";
header('Location: admin.php');
}
}
}
}
?>
Not checking return value prepare() or execute() for false. You need to check for SQL errors and handle them, stopping the code instead of continuing on blithely.
Not using query parameters in the prepared statement, still interpolating $_POST content into the query unsafely. You're missing the benefit of switching to PDO, and leaving yourself vulnerable to SQL injection attack.
You're storing passwords in plaintext, which is unsafe. See You're Probably Storing Passwords Incorrectly.
Do you really need to SELECT * if you only use the admin_pw column? Hint: no.
PDOStatement::fetchAll() returns an array of arrays, not just one array for a row. Read the examples in the documentation for fetchAll().

Using Jasypt: The checkPassword method is returning false when the passwords should match.

To give you some background, my team and I are creating a program that stores usernames and passwords in a database. We are using Java and interacting with the Database through java code.
We use Jasypt to encrypt the usernames and passwords. I am using the BasicPasswordEncryptor in Jasypt to encrypt both. The usernames encrypt fine and are stored in the database fine. However, when the login is checked and said BasicPasswordEncryptor attempts to check the plaintext username against the encrypted password, it always returns false. I have done a series of checks to focus down where the problem is occuring. As far as I know, it's a problem with Jasypt. Does anyone know what the problem is, a possible solution, or a more optimal method? Thank you. I will post the code.
Here is where the encryption occurs.
public void register(String userName, String passWord){
String encryptedUsername = e.encryptPassword(userName);
String encryptedPassword = e.encryptPassword(passWord);
System.out.println("Registered eU: " + encryptedUsername);
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/PandaBox", "root", "");
statement = con.prepareStatement("insert into Users (username, password, logged) values (?,?,?)");
statement.setString(1, encryptedUsername);
statement.setString(2, encryptedPassword);
statement.setInt(3, 0);
boolean x = statement.execute();
System.out.println("IT REGISTERED");
} catch (SQLException o) {
o.printStackTrace();
}
}
Where "e" is the BasicPasswordEncryptor object. Here is the login check.
public boolean checkLogin(String inputedUsername, String inputedPassword) {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/PandaBox", "root", "");
statement = con.prepareStatement("select * from Users");
rs = statement.executeQuery();
System.out.println(inputedUsername + " / " + inputedPassword);
while(rs.next()){
String usernameInDatabase = rs.getString("username");
System.out.println(usernameInDatabase);
if (e.checkPassword(inputedUsername, usernameInDatabase)) {
System.out.println("Username correct.");
statement = con.prepareStatement("select password from Users where username = ?");
statement.setString(1, usernameInDatabase);
rs = statement.executeQuery();
String passwordInDatabase = rs.toString();
if(passwordIsCorrect(inputedPassword, passwordInDatabase)){
return true;
}
}
}
return false;
} catch (SQLException o) {
// TODO Auto-generated catch block
o.printStackTrace();
return false;
}
}
I'm jasypt's author.
From your message, it isn't clear to me whether you are observing this issue when matching the user name or the password --you say 'attempts to check the plaintext username against the encrypted password', which makes no sense--. Nevertheless, one of the most common reasons for problems like yours is that your database columns are not big enough for storing your hashed user names and/or passwords.
The size of the hashing result will depend on the algorithm and salt configuration being used, but for a BasicPasswordEncryptor, which uses MD5 and a salt size of 8 bytes, you should expect your hashes to be 16-byte (hash) plus 8 bytes (salt), plus 8 additional bytes because of textual Base64 encoding. A total of 32 bytes.
Also think that many DBMS measure varchar fields in chars and not bytes, so you should do the appropiate conversion depending on the character encoding being used at your table.
I always recommend to check column sizes first because many DBMS's do not raise an error if you try to store a varchar which is too long for a column --they simply truncate it. I don't know MySQL's behaviour, but Oracle does exactly this. And when you try to decrypt it back... it doesn't match.
So checking your column sizes could be a good starting point. And remember jasypt has a users forum at http://forum.jasypt.org
Oh, and by the way-- forgive me if this is just ad-hoc demo code, but just in case: you should make sure you close all your Statement and ResultSet objects in 'finally' blocks before reusing them... so you should use different 'statement' and 'rs' variables in the inner iteration block, and close them each time.
Regards.
Optimisation 1 : Use a WHERE clause.

A misbehaving WCF service asynch call

Okay, I have a WCF service which is going to be acting as a way to access my SQL database. That part has become largely irrelevant to this question, since for some reason my WCF service crashes. Or, at least, it causes my client Silverlight application to crash. This is why I come here to ask you guys about it.
So here's the code. Bear in mind that it is called asynchronously from my Silverlight client. When it is done, the string that is returned from this method is put on the screen for the client.
public string AddClients(IEnumerable<Client> newClients)
{
int nAdded = 0;
int nelse = 0;
string str = "";
List<Client> newClientsList = newClients.ToList();
List<Client> existingClients = dc.Clients.ToList();
List<Client> clientsToAdd = new List<Client>();
return newClientsList.Count.ToString();
foreach (Client client in newClientsList)
{
var clt = existingClients.FirstOrDefault(c => c.ClientName == client.ClientName);
if (clt == null)
{
return clt.ClientName;
//str = str + " found: " + clt.ClientName + "\n";
//dc.Clients.(clt);
//existingClients.Add(clt);
// clientsToAdd.Add(clt);
nAdded++;
}
else
{
nelse++;
}
}
if (nAdded > 0)
{
//str = str + " more than one nAdded";
// dc.Clients.InsertAllOnSubmit(clientsToAdd);
// dc.SubmitChanges();
}
return nelse.ToString();
}
You may be able to figure out what's supposed to be happening, but most of it's not happening now due to the fact that it's not working out for me very well.
At the moment, as you can see, there is a return quite early on (before the foreach). With things as they are, that works okay. You press a button in the client, it makes the call, and then returns. So as it is, you get '3' returned as a string (this is the size of newClients, the parameter). That is okay, and at least proves that the service can be connected to, that it returns messages okay, and what not.
If I remove that top most return, this is where it gets interesting (well, problematic). It should either return clt.ClientName, in the if (clt==null) condition, or it should return nelse.ToString() which is right at the end.
What do I actually get? Nothing. The method for the completion never seems to get called (the message box it shows never appears).
I've commented most of the stuff out. Surely it has to get to one of these conditions! Have I missed something really obvious here? I really have been attempting to debug this for ages, but nothing! Can someone see something obvious that I can't see?
For the record, 'dc' is the data context, and dc.Clients is a list of Client entities.
I could be missing something, but won't this throw a NullReferenceException? That has to be at least part of your problem.
if (clt == null)
{
return clt.ClientName;
...
I dont understand why you are trying to return the name of the first newly found client from the list you received. Why not just return an integer with total count of newly found clients that you are inserting in the database.
Try:
public string AddClients(IEnumerable<Client> newClients)
{
string str = "";
List<Client> newClientsList = newClients.ToList();
//to save processor and network
List<string> existingClients = dc.Clients.Select(x => x.ClientName).ToList();
List<Client> clientsToAdd = (from nc in newClientsList
join ec in existingClients on nc.ClientName equals ec into nec
from ec in nec.DefaultIfEmpty()
where ec == null
select nc).ToList();
if (clientsToAdd.Count > 0)
{
dc.Clients.InsertAllOnSubmit(clientsToAdd);
foreach (Client c in clientsToAdd)
str += "found: " + c.ClientName + "\n";
return str;
}
return "0 new clients found";
}
easier, simpler, cleaner.