Java, Passing parameters from one class to other class - java

I want to keep all validation methods (phone number validation, numeric validation) in a separate class and let the other classes to access validation methods commonly.How do I do this? Can someone assist me please.
class Validation {
public static boolean validateQty(String txt) {
String regx = "^0([1-9]){2}([0-9]){7}$";
Pattern compile = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
Matcher matcher = compile.matcher(txt);
return matcher.find();
}
public static boolean validateLetters(String txt) {
String regx = "[a-zA-Z]+\\.?";
Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(txt);
return matcher.find();
}
}
class ItemDetails {
private void addItem() {
boolean b = validateLetters(txtItemName.getText()); // I want to pass txtItemName value to Class Validation's validateLetters()
boolean c = validateQty(txtQty.getText());
}
}

Since these are static methods, you can call them by prefixing the class name:
boolean b = Validation.validateLetters(txtItemName.getText());
boolean c = Validation.validateQty(txtQty.getText());
You might also find it useful to pass the entire item to a single validate() method.

As these are static methods you can access like this
boolean b = Validation .validateLetters(txtItemName.getText());
boolean c = Validation .validateQty(txtQty.getText());
or create an object of Validation
Validation v=new Validation ();
boolean b = v .validateLetters(txtItemName.getText());
boolean c =v .validateQty(txtQty.getText());

boolean b = Validation .validateLetters(txtItemName.getText());
boolean c = Validation .validateQty(txtQty.getText());
Since your method in Validation class method validateLetters and validateQty is static you can call it this way . Otherwise you have to create instance of Validation first. Like
Validation v = new Validation();
boolean b = v.validateLetters(txtItemName.getText());
boolean c = v.validateQty(txtQty.getText());

Related

How to make sure a string has a certain format

currently I have a code like this
public class Department {
public static final String MESSAGE_DEPARTMENT_CONSTRAINTS =
"Department names should only contain alphanumeric characters and spaces, and it should not be blank\n"
+ "Department names should start with a name, followed by 'Management'";
public static final String DEPARTMENT_VALIDATION_REGEX = "[\\p{Alnum}][\\p{Alnum} ]*";
public final String fullDepartment;
public Department(String department) {
requireNonNull(department);
checkArgument(isValidDepartment(department), MESSAGE_DEPARTMENT_CONSTRAINTS);
fullDepartment = department;
}
/**
* Returns true if a given string is a valid department name.
*/
public static boolean isValidDepartment(String test) {
return (test.matches(DEPARTMENT_VALIDATION_REGEX) && (test.indexOf("Management") >= 0));
}
#Override
public String toString() {
return fullDepartment;
}
#Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Department // instanceof handles nulls
&& fullDepartment.equals(((Department) other).fullDepartment)); // state check
}
#Override
public int hashCode() {
return fullDepartment.hashCode();
}
}
I would like the code to only allow only valid departments name to be created
Example:
Junior Management
Senior Management
However, now I'm facing a problem where the word Management can be placed at anywhere and it's still considered valid
Example:
Management
Management Junior
How can I ensure that the word Management is a requirement at the back of a department name when I'm creating a department? Thanks.
Just change this function to this:
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX)
&& test.endsWith("Management")
&& !test.equals("Management");
}
If you think you will need more sophisticated checks you can also change your department validation regex to:
public static final String DEPARTMENT_VALIDATION_REGEX = "(\\p{Alnum}+ )+Management";
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX);
}
Note that this will still allow "Management Management" and also "M8n8g3m3nt Management" since you used \\p{Alnum}. If you only need alphabet characters
use \\p{Alpha}. If you want to catch the exception of "Management Management" you might want to do:
public static boolean isValidDepartment(String test) {
return test.matches(DEPARTMENT_VALIDATION_REGEX)
&& !test.equals("Management Management");
}
You should be able to do it all through the regex, but might get too complicated and unreadable for just one exception you can easily check with .equals().
Two ways to do it
a. Using startsWith() and endsWith() in StringUtils ,or just startsWith() and endsWith() that String provides
boolean endsWith = StringUtils.endsWith("Managemet") && !StringUtils.startsWith("Managemet");
b. Using regex .*?Management$,in this expression using .*? to include space and other special characters
String str ="Test Management";
String regex = ".*?Management$";
System.out.println(str.matches(regex));

Does it make sense to have input parameters to a class?

I created a class of DocumentFilter type as follows:
public class CustomDocumentFilter extends DocumentFilter
{
private StyledDocument styledDocument;
private JTextPane panetxt;
public CustomDocumentFilter(JTextPane panetxt) {
this.panetxt = panetxt; // Not really necessary
this.styledDocument = panetxt.getStyledDocument();
}
private final StyleContext styleContext = StyleContext.getDefaultStyleContext();
Pattern pattern = buildPattern(mystring);
private Pattern buildPattern(String mystring)
{
StringBuilder sb = new StringBuilder();
String[] toke = StringUtils.split(mystring,",");
for (String token : toke) {
sb.append("\\b");
sb.append(token);
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
Pattern p = Pattern.compile(sb.toString());
return p;
}
My question is: how to include mystring within the call of CustomDocumentFilter?:
//String mystring="lalala";
((AbstractDocument) editeur.getDocument()).setDocumentFilter(new CustomDocumentFilter(editeur));
EDIT:
Regarding the first way Jonathan suggests, I get this:
error: cannot find symbol Pattern pattern = buildPattern(mystring); ^ symbol: variable mystring location: class TextEditor.CustomDocumentFilter
I don't know if it has to do with the Pattern clause
Not 100% sure what is desired from the description. But I think your simply trying to ask how to get your local string value into your new CustomDocumentFilter object.
Well that is simple and you have choices! More than the two I show here.
first easy way is to add it to the constructor
public CustomDocumentFilter(JTextPane panetxt, String myString) {
...
pattern = buildPattern(mystring);
}
((AbstractDocument) editeur.getDocument()).setDocumentFilter(new CustomDocumentFilter(editeur, myString));
another way is to use a method that returns the object
public CustomDocumentFilter myFunction(String myString) {
pattern = buildPattern(mystring);
return this;
}
((AbstractDocument) editeur.getDocument()).setDocumentFilter(new CustomDocumentFilter(editeur).myFunction(myString));

JavaParser only showing comment, not JavaDoc

Disclaimer: I am only a lowly trainee, so please forgive me if I made elementary mistakes :(
I am writing an automatic API generator, and the classes need JavaDoc as well as comments because some of the values the API contains shouldn't be written down in the JavaDoc (exampleResponse for example).
However, it seems that the comments above the individual Methods replace the Javadoc, so when I want to get the description from the JavaDoc (which i want to do so I don't have to write it again in the comments), I have a problem.
Using getJavadoc() always returns null. I also attempted to use getOrphanComments(), but it returned null. Did I misunderstand the documentation? I assumed if I wrote two comments above a method, the top one would move to orphanComments for that method.
Is there any way to work around this?
Let the MethodDeclaration object is method
than you can get java doc using
if( method.hasComment() && method.getComment() instanceof JavadocComment ){
JavadocComment javaDoc = (JavadocComment)method.getComment();
// now you can get the content using
String content = javaDoc.getContent();
}
For the following types:
public final String name;
public final String signature;
public final String returnType;
public final Type returnFullType; // com.github.javaparser.ast.type.Type
public final String body;
public final String[] modifiers;
public final String[] parameterNames;
public final String[] parameterTypes;
public final Type[] parameterFullTypes; // com.github.javaparser.ast.type.Type
public final String[] exceptions;
public final String jdComment;
public final MethodDeclaration nativeJP_API_reference; // com.github.javaparser.ast.body.MethodDeclaration
This is a constructor for a class Method of my own concoction:
Method (MethodDeclaration md)
{
NodeList<Modifier> ml = md.getModifiers();
NodeList<Parameter> pl = md.getParameters();
NodeList<ReferenceType> te = md.getThrownExceptions();
this.nativeJP_API_reference = md;
this.name = md.getNameAsString();
this.signature = md.getDeclarationAsString();
this.returnType = md.getType().toString();
this.returnFullType = md.getType();
this.body = md.getBody().isPresent() ? md.getBody().get().toString() : null; // In ConstructorDeclaration, this is an Optional<BlockStmt>, not here!
this.modifiers = new String[ml.size()];
this.parameterNames = new String[pl.size()];
this.parameterTypes = new String[pl.size()];
this.parameterFullTypes = new com.github.javaparser.ast.type.Type[pl.size()];
this.exceptions = new String[te.size()];
this.jdComment = md.hasJavaDocComment() ? md.getJavadocComment().get().toString() : null;
int i = 0;
for (Parameter p : pl)
{
parameterNames[i] = p.getName().toString();
parameterTypes[i] = p.getType().toString();
parameterFullTypes[i] = p.getType();
i++;
}
i = 0;
for (Modifier m : ml) modifiers[i++] = m.toString();
i = 0;
for (ReferenceType r : te) exceptions[i++] = r.toString();;
}

Method is undefined for the type. Help me fix it

I create private boolean method isMp3() but java say me that this method is undefined for such type.
if (directoryItem.isFile() && directoryItem.isMp3()){
resultListOfFiles.add(directoryItem);
}
I don't want to sand to method any values.
I want use it like boolean method 'isDirectory()'. I know, I do something wrong, show me my mistake, please.
private boolean isMp3(){
Pattern pattern;
final String FILE_PATTERN = "([^\\s]+(\\.(?i)(mp3))$)";
pattern = Pattern.compile(FILE_PATTERN);
Matcher matcher = pattern.matcher(this.toString());
if (matcher.find()){
return true;
}
else{
return false;
}
}
If I use "this" statement correctly?
As #Claus suggested, if you could pass the File object, you can make it work. That's the correct way.
public class MyClass {
public boolean isMp3(File file) {
Pattern pattern;
final String FILE_PATTERN = "([^\\s]+(\\.(?i)(mp3))$)";
pattern = Pattern.compile(FILE_PATTERN);
Matcher matcher = pattern.matcher(file.toString());
if (matcher.find()) {
return true;
} else {
return false;
}
}
public void myMethod() {
File file = new File("file1.mp3");
if (isMp3(file)) {
System.out.println("is an MP3");
} else {
System.out.println("not an MP3");
}
}
}
In your example, the calling code might look like this,
File directoryItem;
// you get 'directoryItem' from somewhere. directoryItem of type 'File'
if (directoryItem.isFile() && isMp3(directoryItem)) {
resultListOfFiles.add(directoryItem);
}
You are declaring the method as private and it looks like you are not using it inside of the class. If you change the isMp3 method to public this should solve your problem.
See Controlling Access to Members of a Class for more info.
You're getting the compiler error because directoryItem is not the same type (class) as the class you have isMp3 defined (member). Think about whether isMp3 is defined in a class where is makes sense, and refactor if not since this would indicate poor class design.

Using a config/property file with variables

sI use a simple text-file like this
BMG-P (someLongComplicatedExpression)(.*P)
BMG T (someLongComplicatedExpression)(.*[Tt])
BMG MPA (someLongComplicatedExpression)(.*MPA)
to configure my application (Simple import with bufferedReader.readLine().split("\t")). What is bugging me is the redundance.
I am thinking about a solution like this:
%s=(someLongComplicatedExpression)
BMG-P %s(.*P)
BMG T %s(.*[Tt])
BMG MPA %s(.*MPA)
where I read the value of my variables (like %s), then replace their occurrences in the Strings after the import.
My questions are:
What alternative approaches do you know?
What is an easy way to implement the replacement of my variables in my code?
Can you point me to any frameworks that support property-files like that?
I wrote this simple extension to the Java Properties class:
import java.io.Serializable;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Allows properties to contain expansions of the form ${propertyName}. This
* class makes no attempt to detect circular references, so be careful.
*/
public class ExpandingProperties extends Properties implements PropertySource {
private static final long serialVersionUID = 259782782423517925L;
private final Expander expander = new Expander();
#Override
public String getProperty(String key) {
return expander.expand(super.getProperty(key), this);
}
}
class Expander implements Serializable {
private static final long serialVersionUID = -2229337918353092460L;
private final Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
/**
* Expands variables of the form "${variableName}" within the
* specified string, using the property source to lookup the
* relevant value.
*/
public String expand(final String s, final PropertySource propertySource) {
if (s == null) {
return null;
}
final StringBuffer sb = new StringBuffer();
final Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
final String variableName = matcher.group(1);
final String value = propertySource.getProperty(variableName);
if (value == null) {
throw new RuntimeException("No property found for: " + variableName);
}
matcher.appendReplacement(sb, value.replace("$", "\\$"));
}
matcher.appendTail(sb);
return sb.toString();
}
}
interface PropertySource {
String getProperty(String key);
}
Example usage:
public static void main(String[] args) {
Properties properties = new ExpandingProperties();
properties.put("myVar", "myLongExpression");
properties.put("foo", "${myVar}_1");
properties.put("bar", "${foo}_abc");
System.out.println(properties.getProperty("bar"));
}
Prints:
myLongExpression_1_abc
As ExpandingProperties is an extension of Properties it inherits all the load...() methods for loading values from property files.
An alternative is EProperties which does a similar thing to the above code, but goes even further and allows you to nest property files etc. I found it overkill for what I needed.

Categories