Making a password verification into a class - java

I have a program grabbing a password from the user, then it checks if the conditions are met or not then outputs "Valid Password" or "Invalid Password". This works, and I was able to turn the verification aspect into a method in the same program and it works, but I want to make it into a class where I can just say if( validate(pw) == true ) ... or at least if( v.getValidation() == true ) ... in any program and it will test my conditions. I've used custom classes before but for some reason everything I try does not work on this one, I've been at it for days.
Here's my method:
public boolean validate( String pw )
{
boolean l = false, u = false, lo = false, d = false, r = true;
if( pw.length() >= 6 )
{ l = true; }
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ u = true; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lo = true; }
if( Character.isDigit( pw.charAt(i) ) )
{ d = true; }
}
if( l == false || u == false || lo == false || d == false )
{ r = false; }
return r;
}
Edit:
Thank you all for your input, this is what it came out to in the end:
public class Password
{
public static boolean validate( String pw )
{
boolean result = false;
int upper = 0, lower = 0, digit = 0;
if( pw.length() >= 6 )
{
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ upper++; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lower++; }
if( Character.isDigit( pw.charAt(i) ) )
{ digit++; }
}
}
if( upper >= 1 && lower >= 1 && digit >= 1 )
{ result = true; }
return result;
}
}

You do not need to make a whole class for this. You can do something like:
public static void main(String[] args) {
boolean valid = validate("PassWord22");
}
public static boolean validate( String pw ) {}
Also some notes on your method:
You don't need to do l == true or l == false in your if statement. You can simply do:
if( !l || !u || !lo || !d )
{ r = false; }
In fact you can just return
return l && u && lo && d;
If the length is not 6 or greater, simply return false. This will save checking all the letters in the String
I would come up with better variable names. Single/two letter variable names makes it very hard to tell what they represent, and easy to mix up. (instead of l you could have length and instead of u you could have upper)
Also this can be easier solved with regex and String.matches():
public static boolean validate(String pw) {
String pattern = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).+$";
return (pw.length() > 5 && pw.matches(pattern));
}

I got it working, turned out to be an error in the code that the compiler was not picking up. I wanted to delete the question but they wont let me for some reason. So in case you're curious this is what my class looks like functioning:
public class Password
{
private String pw;
public Password()
{
pw = "";
}
public Password( String pw )
{
this.pw = pw;
}
public boolean getPassword( String pw )
{
boolean l = false, u = false, lo = false, d = false, r = true;
if( pw.length() >= 6 )
{ l = true; }
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ u = true; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lo = true; }
if( Character.isDigit( pw.charAt(i) ) )
{ d = true; }
}
if( l == false || u == false || lo == false || d == false )
{ r = false; }
return r;
}

Related

Comparing 2 objects, wrong equals() and hashcode?

can somebody tell me why it returns "not equal"? Im searching for this for a long time and nothing... I think there is problem with my hashcode or/and equals method.
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.setFirstName("Kamil");
s1.setLastName("Witam");
s1.setMark(3.0);
s1.setAge(12);
Student s2 = new Student();
s2.setFirstName("Kamil");
s2.setLastName("Witam");
s2.setMark(3.0);
s2.setAge(12);
if( s1.equals(s2)){
System.out.println("równe");
}
else{
System.out.println("sraka");
}
}
}
And my hashCode:
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ( ( firstName == null ) ? 0 : firstName.hashCode() );
result = prime * result + ( ( lastName == null ) ? 0 : lastName.hashCode() );
long temp;
temp = Double.doubleToLongBits( mark );
result = prime * result + (int) ( temp ^ ( temp >>> 32 ) );
return result;
}
And equals:
public boolean equals( Object obj )
{
if ( this == obj )
return true;
if ( obj == null )
return false;
if ( getClass() != obj.getClass() )
return false;
Student other = (Student) obj;
if ( age != other.age )
return false;
if ( firstName == null )
{
if ( other.firstName != null )
return false;
}
else
if ( !firstName.equals( other.firstName ) )
return false;
if ( lastName == null )
{
if ( other.lastName != null )
return false;
}
else
if ( !lastName.equals( other.lastName ) )
return false;
if ( mark != other.mark )
return false;
return true;
}
Can somebody explain it to me :/? Thanks

How to run this portion of code?

i found this snippet of code on stack and i wanted to try it out on my machine but it keeps giving me an error of
Main method not found in class Main, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
can anyone help me figure out what to do?
This is the portion of the code i wanted to try on my machine
public static void main(String[] args) {
}
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next(")");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
Try this.
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("\\(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("\\(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next("\\)");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
sample output
System.out.println(parse(" IF ( 0 0 - ) ( 1 1 + ) ( 2 2 + ) ( 3 3 + )"));
// -> 4

How to increase test coverage using junit and Eclemma?

I have a simple class:
public class NPP {
// inputs
public int m__water_pressure = 0;
public boolean m__blockage_button = false;
public boolean m__reset_button = false;
public int old_m__pressure_mode = 0;
public boolean old_m__reset_button = false;
public boolean old_m__blockage_button = false;
public int old_m__water_pressure = 0;
// outputs
public int c__pressure_mode = 0;
public boolean c__the_overriden_mode = false;
public int c__the_safety_injection_mode = 0;
public int p__pressure_mode = 0;
public boolean p__the_overriden_mode = false;
public int p__the_safety_injection_mode = 0;
public void method__c__pressure_mode() {
if ( m__water_pressure >= 9 && old_m__water_pressure < 9 && c__pressure_mode == 0 ) {
p__pressure_mode = 1;
} else if ( m__water_pressure >= 10 && old_m__water_pressure < 10 && c__pressure_mode == 1 ) {
p__pressure_mode = 2;
} else if ( m__water_pressure < 9 && old_m__water_pressure >= 9 && c__pressure_mode == 1 ) {
p__pressure_mode = 0;
} else if ( m__water_pressure < 10 && old_m__water_pressure >= 10 && c__pressure_mode == 2 ) {
p__pressure_mode = 1;
}
}
public void method__c__the_overriden_mode() {
if ( m__blockage_button == true && old_m__blockage_button == false && m__reset_button == false && !(c__pressure_mode==2) ) {
p__the_overriden_mode = true;
} else if ( m__reset_button == true && old_m__reset_button == false && !(c__pressure_mode==2) ) {
p__the_overriden_mode = false;
} else if ( c__pressure_mode==2 && !(old_m__pressure_mode==2) ) {
p__the_overriden_mode = false;
} else if ( !(c__pressure_mode==2) && old_m__pressure_mode==2 ) {
p__the_overriden_mode = false;
}
}
public void method__c__the_safety_injection_mode() {
if ( c__pressure_mode == 0 && c__the_overriden_mode == true ) {
p__the_safety_injection_mode = 0;
} else if ( c__pressure_mode == 0 && c__the_overriden_mode == false ) {
p__the_safety_injection_mode = 1;
} else if ( c__pressure_mode == 1 || c__pressure_mode == 2 ) {
p__the_safety_injection_mode = 0;
}
}
}
And i've wrote this junit class:
import static org.junit.Assert.*;
import org.junit.Test;
public class NPPTest {
#Test
public void testMethod__c__pressure_mode() {
NPP npp = new NPP();
npp.m__water_pressure = 3;
npp.old_m__water_pressure = 5;
npp.c__pressure_mode = 2;
npp.method__c__pressure_mode();
assertEquals(1, npp.p__pressure_mode);
}
#Test
public void testMethod__c__the_overriden_mode() {
NPP npp = new NPP();
npp.m__blockage_button = false;
npp.old_m__blockage_button = true;
npp.m__reset_button = false;
npp.method__c__the_overriden_mode();
assertFalse(npp.p__the_overriden_mode);
}
#Test
public void testMethod__c__the_safety_injection_mode() {
NPP npp = new NPP();
npp.c__pressure_mode = 2;
npp.c__the_overriden_mode = false;
npp.method__c__the_safety_injection_mode();
assertEquals(1, npp.p__the_safety_injection_mode);
}
}
I've been asked to write some tests and to cover 100% of code coverage. But what exactly does it mean? How can i achieve this? I've ran Eclemma and i've got only 46%.
100% code coverage means that every line of code is covered by a test.
In other words, your test code should call and go through everything that has been written and make sure it works as expected.
In your case, it means that all the methods must be called and every if-else if case must be tested.
Even though 100% code coverage is very sexy, what matters most is the quality of your test suite.
85% code coverage might be near perfect if all the 15% left is some getters/setters, call to external APIs that is useless to check, glue code that is very very difficult to test and so on. It is up to you to realize what code can and should be tested and what code can be left without knowing that you are leaving holes (and bombs?) in your app.

Split string which contains escaped delimiters

delimiter is |
escaping character is \
and string is for example "A|B\|C\\|D\\\|E|\\\\F"
I want to get array:
{"A", "B|C\", "D\|E", "\\F"}
So delimiter can be escaped but escaping character can be also escaped. Does somebody know how to parse this in Java ?
Thanks.
Edit:
I created this terribly looking solution. At least It works perfectly and It is possible to define escaping character, delimiter and if empty string should be removed easily.
SOLUTION (Eggyal posted better one, look down):
private List<String> parseString(String string, String delimiter, boolean removeEmpty) {
String escapingChar = "\\";
String escapingCharInRegexp = "\\\\";
boolean begined = false;
List<String> parsed = new ArrayList<String>();
List<Integer> begins = new ArrayList<Integer>();
List<Integer> ends = new ArrayList<Integer>();
List<Integer> delimitersPositions = new ArrayList<Integer>();
List<String> explodedParts = new ArrayList<String>();
int i;
for(i = 0; i < string.length(); i++) {
if( ( string.substring(i, i+1).equals(escapingChar) || string.substring(i, i+1).equals(delimiter) ) && !begined ) {
begins.add(i);
begined = true;
if( i + 1 == string.length() ) {
begined = false;
ends.add(i+1);
}
} else if( ( !string.substring(i, i+1).equals(escapingChar) && !string.substring(i, i+1).equals(delimiter) && begined ) ) {
begined = false;
ends.add(i);
} else if( begined && string.substring(begins.get(begins.size()-1), i).indexOf(delimiter) != -1 ) {
begined = false;
ends.add(i);
begined = true;
begins.add(i);
}
if( ( i + 1 == string.length() && begined ) ) {
begined = false;
ends.add(i+1);
}
}
List<Integer> toRemove = new ArrayList<Integer>();
for( i = 0; i < begins.size(); i++ ) {
if( string.substring(begins.get(i), ends.get(i)).indexOf(delimiter) == -1 ) {
toRemove.add(i);
}
}
for( i = 0; i < toRemove.size(); i++ ) {
begins.remove(toRemove.get(i)-i);
ends.remove(toRemove.get(i)-i);
}
for( i = 0; i < begins.size(); i++ ) {
if( ( ends.get(i) - begins.get(i) ) % 2 != 0 ) {
delimitersPositions.add(ends.get(i)-1);
}
}
for( i = 0; i <= delimitersPositions.size(); i++ ) {
int start = (i == 0) ? 0 : delimitersPositions.get(i-1)+1;
int end = ( i != delimitersPositions.size()) ? delimitersPositions.get(i) : string.length();
if( removeEmpty ) {
if( !string.substring(start, end).equals("") ) {
explodedParts.add(string.substring(start, end));
}
} else {
explodedParts.add(string.substring(start, end));
}
}
for (i = 0; i < explodedParts.size(); i++)
parsed.add(explodedParts.get(i).replaceAll(escapingCharInRegexp+"(.)", "$1"));
return parsed;
}
static final char ESCAPING_CHAR = '\\';
private List<String> parseString(final String str,
final char delimiter,
final boolean removeEmpty)
throws IOException
{
final Reader input = new StringReader(str);
final StringBuilder part = new StringBuilder();
final List<String> result = new ArrayList<String>();
int c;
do {
c = input.read(); // get the next character
if (c != delimiter) { // so long as it isn't a delimiter...
if (c == ESCAPING_CHAR) // if it's an escape
c = input.read(); // use the following character instead
if (c >= 0) { // only if NOT at end of string...
part.append((char) c); // append to current part
continue; // move on to next character
}
}
/* we're at either a real delimiter, or end of string => part complete */
if (part.length() > 0 || !removeEmpty) { // keep this part?
result.add(part.toString()); // add current part to result
part.setLength(0); // reset for next part
}
} while (c >= 0); // repeat until end of string found
return result;
}
Because you are both splitting and unescaping, you need a separate step for each process:
String[] terms = input.split("(?<=[^\\\\]|[^\\\\]\\\\\\\\)\\|");
for (int i = 0; i < terms.length; i++)
terms[i] = terms[i].replaceAll("\\\\(.)", "$1");
Here's some test code:
public static void main(String[] args) {
String input = "A|B\\|C\\\\|D\\\\\\|E|\\\\\\\\F";
String[] terms = input.split("(?<=[^\\\\]|[^\\\\]\\\\\\\\)\\|");
for (int i = 0; i < terms.length; i++)
terms[i] = terms[i].replaceAll("\\\\(.)", "$1");
System.out.println(input);
System.out.println(Arrays.toString(terms));
}
Output:
A|B\|C\\|D\\\|E|\\\\F
[A, B|C\, D\|E, \\F]
There is no escape sequence in java like you've mentioned "\|".
It'll cause compile time error.

boolean expression parser in java

Are there any java libraries or techniques to parsing boolean expressions piecemeal?
What I mean is given an expression like this:
T && ( F || ( F && T ) )
It could be broken down into a expression tree to show which token caused the 'F' value, like so (maybe something like this):
T && <- rhs false
( F || <- rhs false
( F && T ) <- eval, false
)
I am trying to communicate boolean expression evaluations to non-programmers. I have poked around with Anlr, but I couldn't get it to do much (it seems to have a bit of a learning curve).
I'm not opposed to writing it myself, but I'd rather not reinvent the wheel.
You could do this with MVEL or JUEL. Both are expression language libraries, examples below are using MVEL.
Example:
System.out.println(MVEL.eval("true && ( false || ( false && true ) )"));
Prints:
false
If you literally want to use 'T' and 'F' you can do this:
Map<String, Object> context = new java.util.HashMap<String, Object>();
context.put("T", true);
context.put("F", false);
System.out.println(MVEL.eval("T && ( F || ( F && T ) )", context));
Prints:
false
I've coded this using Javaluator.
It's not exactly the output you are looking for, but I think it could be a start point.
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.astesana.javaluator.*;
public class TreeBooleanEvaluator extends AbstractEvaluator<String> {
/** The logical AND operator.*/
final static Operator AND = new Operator("&&", 2, Operator.Associativity.LEFT, 2);
/** The logical OR operator.*/
final static Operator OR = new Operator("||", 2, Operator.Associativity.LEFT, 1);
private static final Parameters PARAMETERS;
static {
// Create the evaluator's parameters
PARAMETERS = new Parameters();
// Add the supported operators
PARAMETERS.add(AND);
PARAMETERS.add(OR);
// Add the parentheses
PARAMETERS.addExpressionBracket(BracketPair.PARENTHESES);
}
public TreeBooleanEvaluator() {
super(PARAMETERS);
}
#Override
protected String toValue(String literal, Object evaluationContext) {
return literal;
}
private boolean getValue(String literal) {
if ("T".equals(literal) || literal.endsWith("=true")) return true;
else if ("F".equals(literal) || literal.endsWith("=false")) return false;
throw new IllegalArgumentException("Unknown literal : "+literal);
}
#Override
protected String evaluate(Operator operator, Iterator<String> operands,
Object evaluationContext) {
List<String> tree = (List<String>) evaluationContext;
String o1 = operands.next();
String o2 = operands.next();
Boolean result;
if (operator == OR) {
result = getValue(o1) || getValue(o2);
} else if (operator == AND) {
result = getValue(o1) && getValue(o2);
} else {
throw new IllegalArgumentException();
}
String eval = "("+o1+" "+operator.getSymbol()+" "+o2+")="+result;
tree.add(eval);
return eval;
}
public static void main(String[] args) {
TreeBooleanEvaluator evaluator = new TreeBooleanEvaluator();
doIt(evaluator, "T && ( F || ( F && T ) )");
doIt(evaluator, "(T && T) || ( F && T )");
}
private static void doIt(TreeBooleanEvaluator evaluator, String expression) {
List<String> sequence = new ArrayList<String>();
evaluator.evaluate(expression, sequence);
System.out.println ("Evaluation sequence for :"+expression);
for (String string : sequence) {
System.out.println (string);
}
System.out.println ();
}
}
Here is the ouput:
Evaluation sequence for :T && ( F || ( F && T ) )
(F && T)=false
(F || (F && T)=false)=false
(T && (F || (F && T)=false)=false)=false
Evaluation sequence for :(T && T) || ( F && T )
(T && T)=true
(F && T)=false
((T && T)=true || (F && T)=false)=true
I recently put together a library in Java specifically to manipulate boolean expressions: jbool_expressions.
It includes a tool too parse expressions out of string input:
Expression<String> expr = ExprParser.parse("( ( (! C) | C) & A & B)")
You can also do some fairly simple simplification:
Expression<String> simplified = RuleSet.simplify(expr);
System.out.println(expr);
gives
(A & B)
If you wanted to step through the assignment then, you could assign values one by one. For the example here,
Expression<String> halfAssigned = RuleSet.assign(simplified, Collections.singletonMap("A", true));
System.out.println(halfAssigned);
shows
B
and you could resolve it by assigning B.
Expression<String> resolved = RuleSet.assign(halfAssigned, Collections.singletonMap("B", true));
System.out.println(resolved);
shows
true
Not 100% what you were asking for, but hope it helps.
Check out BeanShell. It has expression parsing that accepts Java-like syntax.
EDIT: Unless you're trying to actually parse T && F literally, though you could do this in BeanShell using the literals true and false.
Try this.
static boolean parseBooleanExpression(String s) {
return new Object() {
int length = s.length(), index = 0;
boolean match(String expect) {
while (index < length && Character.isWhitespace(s.charAt(index)))
++index;
if (index >= length)
return false;
if (s.startsWith(expect, index)) {
index += expect.length();
return true;
}
return false;
}
boolean element() {
if (match("T"))
return true;
else if (match("F"))
return false;
else if (match("(")) {
boolean result = expression();
if (!match(")"))
throw new RuntimeException("')' expected");
return result;
} else
throw new RuntimeException("unknown token");
}
boolean term() {
if (match("!"))
return !element();
else
return element();
}
boolean factor() {
boolean result = term();
while (match("&&"))
result &= term();
return result;
}
boolean expression() {
boolean result = factor();
while (match("||"))
result |= factor();
return result;
}
boolean parse() {
boolean result = expression();
if (index < length)
throw new RuntimeException(
"extra string '" + s.substring(index) + "'");
return result;
}
}.parse();
}
And
public static void main(String[] args) {
String s = "T && ( F || ( F && T ) )";
boolean result = parseBooleanExpression(s);
System.out.println(result);
}
output:
false
The syntax is
expression = factor { "||" factor }
factor = term { "&&" term }
term = [ "!" ] element
element = "T" | "F" | "(" expression ")"
mXparser handles Boolean operators - please find few examples
Example 1:
import org.mariuszgromada.math.mxparser.*;
...
...
Expression e = new Expression("1 && (0 || (0 && 1))");
System.out.println(e.getExpressionString() + " = " + e.calculate());
Result 1:
1 && (0 || (0 && 1)) = 0.0
Example 2:
import org.mariuszgromada.math.mxparser.*;
...
...
Constant T = new Constant("T = 1");
Constant F = new Constant("F = 0");
Expression e = new Expression("T && (F || (F && T))", T, F);
System.out.println(e.getExpressionString() + " = " + e.calculate());
Result 2:
T && (F || (F && T)) = 0.0
For more details please follow mXparser tutorial.
Best regards

Categories

Resources