Java- Getting variables from method into other method - java

I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.
Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];
JTextField input_day =new JTextField(DateDay);
// input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);
and in the other method I need these variables:
input_datum.setText(reportDate);
if(check_datum.isSelected()){
CustomDateFinal[0] = datumvar;
input_datum.setText(CustomDateFinal[0]);
}
Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)
EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE

Are these methods in the same class? If so, why don't you declare the variables outside the method? That way their scope is across all methods. If not, you could create getters/setters for each variable.

It's a design problem:
The objet containing the methods createFields and customKeyEvent has to exchange some values between those.
Then, you could create a structure (class) return by createFields, that contains your created field and the values customKeyEvent needs.
Or, you could externalize values and create type's properties. During the call of createFields, set the properties value, and after, you could get it from customKeyEvent. But take care of possibly multithreading access: choose the good accessibility of your properties for your problem.
I think the second choice is the best ; these solution respect the role suggested by the name of createFields method.
It could be a good practice to you to learn about design patterns. That's some classics of basic design problem resolution.
It still helps me every day.

Related

Creating configurations interface for Model Project (JAVA)

Currently I am creating a java Project that will be used by many people to (in theory) create a product, each with their own set of configurations, in a straightforward, fast and with standardized mechanisms.
If I were using a GUI, it would be easier to handle the configurations in different files, however, because I am making it just an editable project, I see myself in the need of putting all the constants in a single class/file so as to centralize the area where the respective engineer configures the product he is creating. Thus I have the following Constants interface:
public interface Constants {
//ROUTE OF FOLDERS
String PATH_ACTUALIZ = "..\\actualiz\\";
String PATH_ENTRADAS = "..\\entries\\";
String PATH_SALIDAS = "..\\outputs\\";
String PATH_ENTRADAS_CARTAS = PATH_ENTRADAS + "CARTAS\\";
String PATH_ENTRADAS_ANEXOS = PATH_ENTRADAS + "ANEXOS\\";
String PATH_SALIDAS_PDF = PATH_SALIDAS + "PDF\\";
//ROUTE OF FILES
String PATH_FILE_SPOOL_CLIENTE = PATH_ENTRADAS + "spool.txt";
String PATH_FILE_SPOOL_ERRORES = PATH_SALIDAS + "Reporte_de_Errores.txt";
String PATH_FILE_BASE_EMAIL = PATH_SALIDAS + "BaseEmail_[OP].txt";
String PATH_FILE_DATA_VAR = PATH_SALIDAS + "DataVar_[OP].txt";
String PATH_FILE_BASE = PATH_SALIDAS + "Base.obj";
String NAME_FILE_LOG = "Log.txt";
//DESIGNER
String DESIGNER_DELIMITER = "\t"; //Other options "»", "|"
String DESIGNER_CANAL = "AA01";
//GUI INFORMATION
String NAME_RESPONSABLE = "JOHN DOE";
String TITULO_MENSAJE_ERROR = "Error when processing the data.";
String TITULO_MENSAJE_INFORMACION = "Processing data";
//HTML
String HTML = "123";
//SEGMENTS
HashMap<String, String> HMSEGMENTO = new HashMap<String, String>(); //Initialization missing.
}
The last line of which is a HashMap because the data involves several pairs of String to String, including one that is returned by default if the key provided isn't found, however I find myself at a standstill because there is no elegant/simple way add data to a Hashmap inside an Interface.
Other solutions I've looked into include the use of Java Properties, but I also wouldn't be able to add data to it in this interface.
So my larger question becomes if I'm even doing this right at all. Any sources or ideas on software development that would direct to the right path would be greatly appreciated.
Finally I understand my question is slightly broad. If there is a way to make it more specific, I would appreciate the help too.
Serious non-answer: don't do this.
Java invented Properties to exactly give you that: the ability to specify runtime configuration information in text files. And when you need multiple layers - that is also possible using property files (you could for example have a base property file that defines useful defaults, and then different people can provide their own property files that "override" those properties that they need to be changed).
And when you insist on using interfaces to "wrap" your constants (although exactly that is considered a bad practice) - please don't stuff everything into the same interface. Instead identify the different "categories" you need and have one file per category.
Your approach is determined to end up with monolithic spaghetti code.

How do I convert a String to date in velocity template?

I want to convert $departureFromDate (format:yyyy-MM-dd) to date object so that I can perform increment operations on it. I have been trying to do it the following way:
#set($departureFromDate = "{{jsonPath request.body
'$.departureFromDate'}}")
#set($dateObj = $date.toDate('yyyy-MM-dd',"$departureFromDate"))
#set($calendar = $date.getCalendar())
$calendar.setTime($dateObj)
$calendar.add(6,5)
The above code works if give an actual date like:
#set($dateObj = $date.toDate('yyyy-MM-dd',"2018-09-22"))
But does not work when I try to use $departureFromDate
There are several problems in your code. First, as user7294900 noted, the right value of the first assignation seems quite weird. Then, you don't need to instanciate yourself a calendar (plus, you can write $date.calendar instead of $date.getCalendar(), and you don't need double quotes around string arguments).
#set($body = '{ "departureFromDate" : "2018-03-01" }')
$json.parse($body)
#set($departureFromDate = $json.departureFromDate)
#set($dateObj = $date.toDate('yyyy-MM-dd', $departureFromDate))
#set($calendar = $date.toCalendar($dateObj))
$calendar.add(6, 5)
The above code uses a JSON parsing tool, whose parse() method renders a json wrapper, that you shall provide in your context.
As a final advise, if you hadn't already thought of it, be sure to print $obj and $obj.class.name in your context as a trivial debugging technique if you don't understand what happens.

Regex *or other method* to sort through entire URL that's all text

This link: http://www.otc.edu/GEN/schedule/all_classes_fall.txt contains classes for my college, and I am trying to take all of this data and store it in a ClassInformationFall object I have created. Basically, the classes begin at the class title in the format like this : "ABR-100-101" and have class instructor, days it occurs, start/end time, etc.
I have written some regex to pick out the class title, and some of the easier things like start and ending time, but I have been struggling on trying to get the rest of it out. I was thinking about setting up some code where anytime another class title is encountered, it adds the following text to a new ClassInformationFall object, which I am storing in a list of that type. Even if I had that, though, I still haven't been able to successfully extract all of the data for all of the things that make up the class.
What would be the regex to pick this information out, or is regex even the way to go?
Thanks for any help, this has stumped me for awhile.
PS - I am developing the application using this in Java.
If the fields are always in the same order, you can just split each line by tabs and deal with the resulting array.
String line = bufferedReader.readLine();
while (line != null) {
String[] data = line.split("\\t+");
String name = data[0];
String credits = data[2];
String description = data[3];
String professor = data[11];
ClassInfo ci = new ClassInfo(name, credits, description, professor);
classInfoList.add(ci);
line = bufferedReader.readLine();
}

How to use an array value as field in Java? a1.section[2] = 1;

New to Java, and can't figure out what I hope to be a simple thing.
I keep "sections" in an array:
//Section.java
public static final String[] TOP = {
"Top News",
"http://www.mysite.com/RSS/myfeed.csp",
"top"
};
I'd like to do something like this:
Article a1 = new Article();
a1.["s_" + section[2]] = 1; //should resolve to a1.s_top = 1;
But it won't let me, as it doesn't know what "section" is. (I'm sure seasoned Java people will cringe at this attempt... but my searches have come up empty on how to do this)
Clarification:
My article mysqlite table has fields for the "section" of the article:
s_top
s_sports
...etc
When doing my import from an XML file, I'd like to set that field to a 1 if it's in that category. I could have switch statement:
//whatever the Java version of this is
switch(section[2]) {
case "top": a1.s_top = 1; break;
case "sports": a1.s_sports = 1; break;
//...
}
But I thought it'd be a lot easier to just write it as a single line:
a1["s_"+section[2]] = 1;
In Java, it's a pain to do what you want to do in the way that you're trying to do it.
If you don't want to use the switch/case statement, you could use reflection to pull up the member attribute you're trying to set:
Class articleClass = a1.getClass();
Field field = articleClass.getField("s_top");
field.set(a1, 1);
It'll work, but it may be slow and it's an atypical approach to this problem.
Alternately, you could store either a Map<String> or a Map<String,Boolean> inside of your Article class, and have a public function within Article called putSection(String section), and as you iterate, you would put the various section strings (or string/value mappings) into the map for each Article. So, instead of statically defining which sections may exist and giving each Article a yes or no, you'd allow the list of possible sections to be dynamic and based on your xml import.
Java variables are not "dynamic", unlink actionscript for exemple. You cannot call or assign a variable without knowing it at compile time (well, with reflection you could but it's far to complex)
So yes, the solution is to have a switch case (only possible on strings with java 1.7), or using an hashmap or equivalent
Or, if it's about importing XML, maybe you should take a look on JAXB
If you are trying to get an attribute from an object, you need to make sure that you have "getters" and "setters" in your object. You also have to make sure you define Section in your article class.
Something like:
class Article{
String section;
//constructor
public Article(){
};
//set section
public void setSection(Section section){
this.section = section;
}
//get section
public String getSection(){
return this.section;
}

Simple way to use parameterised UI messages in Wicket?

Wicket has a flexible internationalisation system that supports parameterising UI messages in many ways. There are examples e.g. in StringResourceModel javadocs, such as this:
WeatherStation ws = new WeatherStation();
add(new Label("weatherMessage", new StringResourceModel(
"weather.${currentStatus}", this, new Model<String>(ws)));
But I want something really simple, and couldn't find a good example of that.
Consider this kind of UI message in a .properties file:
msg=Value is {0}
Specifically, I wouldn't want to create a model object (with getters for the values to be replaced; like WeatherStation in the above example) only for this purpose. That's just overkill if I already have the values in local variables, and there is otherwise no need for such object.
Here's a stupid "brute force" way to replace the {0} with the right value:
String value = ... // contains the dynamic value to use
add(new Label("message", getString("msg").replaceAll("\\{0\\}", value)));
Is there a clean, more Wicket-y way to do this (that isn't awfully much longer than the above)?
Take a look at Example 4 in the StringResourceModel javadoc - you can pass a null model and explicit parameters:
add(new Label("message",
new StringResourceModel(
"msg", this, null, value)));
msg=Value is {0}
I think the most consistent WICKETY way could be accomplished by improving Jonik's answer with MessageFormat:
.properties:
msg=Saving record {0} with value {1}
.java:
add(new Label("label", MessageFormat.format(getString("msg"),obj1,obj2)));
//or
info(MessageFormat.format(getString("msg"),obj1,obj2));
Why I like it:
Clean, simple solution
Uses plain Java and nothing else
You can replace as many values as you want
Work with labels, info(), validation, etc.
It's not completely wickety but it is consistent with wicket so you may reuse these properties with StringResourceModel.
Notes:
if you want to use Models you simply need to create a simple model that override toString function of the model like this:
abstract class MyModel extends AbstractReadOnlyModel{
#Override
public String toString()
{
if(getObject()==null)return "";
return getObject().toString();
}
}
and pass it as MessageFormat argument.
I don't know why Wicket does not support Model in feedback message. but if it was supported there was no reason to use these solutions and you could use StringResourceModel everywhere.
There's a way, which although still involves creating a model, doesn't requires a bean with a getter.
given this message in a properties file:
msg=${} persons
Here's how to replace the placeholder with a value, be it a local variable, a field or a literal:
add(new Label("label", new StringResourceModel("msg", new Model<Serializable>(5))));
When faced with something like described in the question, I would now use:
.properties:
msg=Saving record %s with value %d
Java:
add(new Label("label", String.format(getString("msg"), record, value)));
Why I like it:
Clean, simple solution
Uses plain Java and nothing else
You can replace as many values as you want (unlike with the ${} trick). Edit: well, if you actually need to support many languages where the replaced values might be in different order, String.format() is no good. Instead, using MessageFormat is a similar approach that properly supports this.
Disclaimer: this is "too obvious", but it's simpler than the other solutions (and definitely nicer than my original replaceAll() hack). I originally sought for a "Wicket-y" way, while this kinda bypasses Wicket—then again, who cares? :-)
In case you have a Model in your Component which holds an object with values you want to access from your placeholders as substitutions, you can write:
new StringResourceModel("salutation.text", getModel());
Let's imagine getModel()'s return type is IModel<User> and User contains fields like firstName and lastName. In this case you can easily access firstName and lastName fields inside your property string:
salutation.text=Hej ${firstName} ${lastName}, have a nice day!
Further information you can find here: https://ci.apache.org/projects/wicket/apidocs/8.x/org/apache/wicket/model/StringResourceModel.html#StringResourceModel-java.lang.String-org.apache.wicket.model.IModel-
Creating a Model for your Label really is The Wicket Way. That said, you can make it easy on yourself with the occasional utility function. Here's one I use:
/**
* Creates a resource-based label with fixed arguments that will never change. Arguments are wrapped inside of a
* ConvertingModel to provide for automatic conversion and translation, if applicable.
*
* #param The component id
* #param resourceKey The StringResourceModel resource key to use
* #param component The component from which the resourceKey should be resolved
* #param args The values to use for StringResourceModel property substitutions ({0}, {1}, ...).
* #return the new static label
*/
public static Label staticResourceLabel(String id, String resourceKey, Component component, Serializable... args) {
#SuppressWarnings("unchecked")
ConvertingModel<Serializable>[] models = new ConvertingModel[args.length];
for ( int i = 0; i < args.length; i++ ) {
models[i] = new ConvertingModel<Serializable>( new Model<Serializable>( args[i] ), component );
}
return new CustomLabel( id, new StringResourceModel( resourceKey, component, null, models ) );
}
Details I'm glossing over here are:
I've created my own ConvertingModel which will automatically convert objects to their String representation based on the IConverters available to the given component
I've created my own CustomLabel that applies custom label text post-processing (as detailed in this answer)
With a custom IConverter for, say, a Temperature object, you could have something like:
Properties key:
temperature=The current temperature is ${0}.
Page.java code:
// Simpler version of method where wicket:id and resourceKey are the same
add( staticResourceLabel( "temperature", new Temperature(5, CELSIUS) ) );
Page.html:
<span wicket:id='temperature'>The current temperature is 5 degrees Celsius.</span>
The downside to this approach is that you no longer have direct access to the Label class, you can't subclass it to override isVisible() or things like that. But for my purposes it works 99% of the time.

Categories

Resources