I need a Fake Data Generator (e.g., For a person's personal information like first name, last name, email and all) for console based jdbc application.
Because I want to add those data of random person to MySQL database.
My code for MySQL as below :
String url1 = "jdbc:mysql://localhost:3306/restaurant";
String user = "root";
String password = "root";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database restaurant");
// I want add data generator here.
}
You have DataFactory. It generated names (even some specific region names), addresses, birth dates or other dates, general random strings, you can even give it some arrays of random stuff to generate from, etc
Edit: usage example
In order to get different output each time, create it with your seed for Random(). The best seed is nano time:
DataFactory df1 = DataFactory.create(System.nanoTime());
Everytime you create it, you will get different output.
You can use jFairy. This will best suited for you.
The github link for a project : https://github.com/Codearte/jfairy/tree/master/src/main
Code Example:
Fairy fairy = Fairy.create();
Person person = fairy.person();
System.out.println(person.fullName());
You can checkout randomizer for random data generation.This library helps to create random data from given Model class.Checkout below example code.
public class Person {
#FirstName
String mFirstName;
#LastName
String mLastName;
#Email
String mEmailId;
}
//Generate random 100 Person(Model Class) object
Generator<Person> generator = new Generator<>(Person.class);
List<Person> persons = generator.generate(100);
As there are many built in data generator is accessible using annotation,You also can build custom data generator.I suggest you to go through documentation provided on library page.
You can use dummycreator library for generating dummy objects dummycreator.
It can be used like this
public static <T> T create(final Class<T> clazz) {
return dummyCreator.create(clazz);
}
More, you can specify bindings for specifying how to generate some classes.
static {
bindings.add(String.class, new RandomStringFactory());
bindings.add(Examination.class, new RandomExaminationFactory());
}
I've recently authored a library called MockNeat. It allows you to bootstrap data generation.
On the wiki page there is detailed tutorial on how you can programatically generate SQL Inserts for your application.
Related
This is a banking system and I have to create two user levels, Manager and Cashier. I have to provide username and password for manager and manager has to provide username and password for a cashier. I am not really sure how to code validation for cahsier login. This has to be coded in Java in Netbeans IDE (GUI)
My point is just a concern as your question needs you to have a basic understanding of Java. I am not sure whether you are storing your login details in a database or in a text file. If you store the data in a database, then you can just use the normal java validation techniques described below:
Get a username and a password from the cashier.
Select the records that match the user name and password you've entered above from the database.
Print a message if the number of records that you match is zero.
Login the cashier if the entered records match the ones stored in the database.
Please refer to here for more information on connecting to the database and storing/retrieving user data using java.
Also, note that banking applications should be more secure and therefore the best practice is to store seeded hashes of the passwords and use a cryptographically strong hashing function.
In case you are saving your data in a text file, then you can refer to this sample code . You can read more about the Java Scanner Class here. You can also decide to use a map to map all users on registering and then just check the map to confirm the login details.
N/B: In all of these cases, check if the username and password fields are empty before you submit the details.
If this were a real application, you would store usernames and hashed-and-salted versions of the passwords on disk (or you would query them over a network), ideally using bcrypt, pbkdf2, or another strong and upgrade-able password-hashing scheme. There are multiple open-source libraries that implement those for you.
Since this appears to be a programming exercise, the question of how you store them is probably mandated by whoever wrote it, and security may therefore be minimal.
The easiest way (which is not secure at all) of implementing this is to keep a password file around. You could, for example, use something similar to the following code:
public class InsecurePasswordStore {
private Map<String, String> passwords = new HashMap<>();
public void setPassword(String user, String password) {
passwords.put(user, password);
}
public boolean isPasswordCorrect(String user, String password) {
return passwords.get(user) != null && passwords.get(user).equals(password);
}
public void save(File file) throws IOException {
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
for (Map.Entry<String, String> e: passwords.entrySet()) {
writer.println(e.getKey());
writer.println(e.getValue());
}
}
}
public void load(File file) throws IOException {
passwords.clear();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
boolean finished = false;
while ( ! finished) {
String user = reader.readLine();
String password = reader.readLine();
if (user == null || password == null) {
finished = true;
} else {
passwords.put(user, password);
}
}
}
}
public static void main(String[] args) throws IOException {
InsecurePasswordStore store = new InsecurePasswordStore();
File passwordFile = new File("secrets.txt");
// create initial password file before first run
store.setPassword("manager", "12345");
store.save(passwordFile);
// load file when the app is launched
store.load(passwordFile);
// check password for a user
String badGuess = "2345";
System.out.println("Is " + badGuess
+ " the correct password for the manager? " + store.isPasswordCorrect("manager", badGuess));
String goodGuess = "12345";
System.out.println("Is " + goodGuess
+ " the correct password for the manager? " + store.isPasswordCorrect("manager", goodGuess));
// if the password was correct, set another username-password pair
if (store.isPasswordCorrect("manager", goodGuess)) {
store.setPassword("cashier", "abcde");
}
store.save(passwordFile);
}
}
My answer is more a series of questions and suggestions to get you to think about how to do it. Also, I cannot be very specific because you have provided very little detail in your question.
Question 1, after your manager enters the cashier details, where do you store them? In memory? In a file? In a database? Something else?
Question 2, when validating the cashier login, why would you not validate the cashier details against that database/file/memory store? The answer is you should validate your cashier logins against the place where they are stored.
Also for whatever it is worth, you should never hardcode a logon (e.g. the manager) into an application (not even for testing). Why?
There is no way to get rid of it without releasing a new version of the software.
It is a security risk (because of reason 1).
If you do it in testing, it is entirely possible that you will forget to remove it before the code is released. Then reason 2 applies.
There is no need for it - you can simply "seed" your user store with a single record representing the manager's login and default password (ideally with a "password has expired" indication) in your distribution or if you have an installer, prompt the person doing the setup to create the manager login during the installation process.
Therefore, the way you validate the manager's credentials will be exactly the same as everybody else.
This will (should) have the advantage of a simpler program which will be easier to maintain.
And just in case, the way you tell the difference between the manager, the cashier, a supervisor or whatever other user types that you might have (or need in the future) is via a role. In your user data store have a field that define which role the user is in (e.g. manager, cashier etc). Another model is "muliple fields" where you indicate that a user has that role (and thus access to the associated function or not). For example, you might have manager, supervisor, cashier, backoffice etc roles. Then just put a true/false in your user record that indicates whether that user can access the functions associated with a particular role.
Finally, your program becomes simpler because your logic is now simply
if user has manager role then display manager menu
if user has supervisor role then display supervisor menu"
etc
Note that there is no else in the above psuedo code.
For my Java application I am trying to use ScalaCheck to write some property-based unit tests. For that purpose I need generators, but all the tutorials I can find use a constructor with parameters to generate objects.
The object I need to generate does not have constructor parameters, and I cannot add such a constructor since it is from an external library.
I now have the following (JwtClaims is from the package org.jose4j.jwt):
def genClaims: Gen[JwtClaims] = {
val url = arbString
val username = arbString
val claims = new JwtClaims()
claims.setNotBeforeMinutesInThePast(0)
claims.setExpirationTimeMinutesInTheFuture(60)
claims.setSubject(username) // error about Gen[String] not matching type String
claims
}
Any suggestions on how to write my generator? I have zero knowledge of Scala, so please be patient if I've made an 'obvious' mistake :) My expertise is in Java, and testing using ScalaCheck is my first venture into Scala.
You need to be returning a generator of a claims object, not a claims object. The generator is effectively a function that can return a claims object. The normal way I go about this is with a for comprehension (other people prefer flatMap, but I think this reads more clearly).
def genClaims: Gen[JwtClaims] = {
for {
url <- arbitrary[String]
username <- arbitrary[String]
} yield {
val claims = new JwtClaims()
claims.setNotBeforeMinutesInThePast(0)
claims.setExpirationTimeMinutesInTheFuture(60)
claims.setSubject(username)
claims
}
}
I want output in the following format, which we get in as400 when WRKSPLF is executed
I am using the following code for retrieving the information from as400
try
{
AS400 as400System = new AS400();
String strSpooledFileName;
SpooledFileList splfList = new SpooledFileList(as400System);
splfList.openAsynchronously();
splfList.waitForListToComplete();
Enumeration enume= splfList.getObjects();
ArrayList<SpoolVO> list = new ArrayList<SpoolVO>();
while( enume.hasMoreElements() )
{
SpoolVO splVO = new SpoolVO();
SpooledFile splf = (SpooledFile)enume.nextElement();
if (splf != null)
{
// output this spooled file's name
splVO.setFileName(splf.getStringAttribute(SpooledFile.ATTR_SPOOLFILE));
splVO.setUserName(splf.getStringAttribute(SpooledFile.ATTR_JOBUSER));
splVO.setUserData(splf.getStringAttribute(SpooledFile.ATTR_USERDATA));
splVO.setDevice(splf.getStringAttribute(SpooledFile.ATTR_OUTPUT_QUEUE));
splVO.setTotalPages(splf.getIntegerAttribute(SpooledFile.ATTR_PAGES));
splVO.setCurrentPage(splf.getIntegerAttribute(SpooledFile.ATTR_CURPAGE));
splVO.setCopy(splf.getIntegerAttribute(SpooledFile.ATTR_COPIES));
list.add(splVO);
}
}
splfList.close();
Now by using the above code I am able to get all the fields except the Options(Opt). I want Options field in java which enables me to do all the operations like send, change, hold, etc. as specified in screenshot.
Is this possible doing with java??
Thanks in advance.
Guessing that you are using JT400 you would use SpooledFileList and SpooledFile to get the details you want. Edit your question to explain the specific details you want to retrieve. Post the code you tried.
Edit:
The Options field is not an attribute of a spooled file; you can't retrieve it from anywhere. It is a field on the display panel that lets the user request an action to be performed by the WRKSPLF command. You will need to provide that functionality within your Java program. For example, if your end user types a 3, you would issue the HLDSPLF command. If she types a 6, you would issue the RLSSPLF command.
I am working on refactoring an existing application written in PowerBuilder and Java and which runs on Sybase EA Server (Jaguar). I am building a small framework to wrap around Jaguar API functions that are available in EA Server. One of the classes is to get runtime statistics from EA Server using the Monitoring class.
Without going into too much detail, Monitoring is a class in EA Server API that provides Jaguar Runtime Monitoring statistics (actual classes are in C++; EA Server provides a wrapper for these in Java, so they can be accessed through CORBA).
Below is the simplified version of my class. (I made a superclass which I inherit from for getting stats for components, conn. caches, HTTP etc).
public class JagMonCompStats {
...
public void dumpStats(String type, String entity) {
private String type = "Component";
private String entity = "web_business_rules";
private String[] header = {"Active", "Pooled", "invoke"};
// This has a lot more keys, simplified for this discussion
private static short[] compKeys = {
(short) (MONITOR_COMPONENT_ACTIVE.value),
(short) (MONITOR_COMPONENT_POOLED.value),
(short) (MONITOR_COMPONENT_INVOKE.value)
};
private double[] data = null;
...
/* Call to Jaguar API */
Monitoring jm = MonitoringHelper.narrow(session.create("Jaguar/Monitoring"));
data = jm.monitor(type, entity, keys);
...
printStats(entity, header, data);
...
}
protected void printStats(String entityName, String[] header, double[] data) {
/* print the header and print data in a formatted way */
}
}
The line data = jm.monitor is the call to Jaguar API. It takes the type of the entity, the name of the entity, and the keys of the stats we want. This method returns a double array. I go on to print the header and data in a formatted output.
The program works, but I would like to get experts' opinion on OO design aspect. For one, I want to be able to customize printStats to be able to print in different formats (for e.g., full blown report or a one-liner). Apart from this, I am also thinking of showing the stats on a web page or PowerBuilder screen, in which case printStats may not even be relevant. How would you do this in a real OO way?
Well, it's quite simple. Don't print stats from this class. Return them. And let the caller decide how the returned stats should be displayed.
Now that you can get stats, you can create a OneLinerStatsPrinter, a DetailedStatsPrinter, an HtmlStatsFormatter, or whatever you want.
I need to extract two pieces of information about two IP addresses and then write those information plus two addresses.
I was thinking of a Set of Pairs for IP addresses, but by which data structure I can write all these information?
Thanks
PcapPacketHandler<String> jPacketHandler = new PcapPacketHandler<String>(){
int totalLength = 0;
public void nextPacket(PcapPacket packet, String user) {
Ip4 ip = new Ip4();
String sIP;
String dIP;
if (packet.hasHeader(ip) == false){
return;
}
totalLength = totalLength+ ip.getPayloadLength();
sIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.source());
dIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.destination());
System.out.println("SIP = "+sIP+" "+"destIP = "+dIP+" "+"Payload Length = "+ip.getPayloadLength());
System.out.println("Total Length = "+totalLength);
}
};
pcap.loop(10, jPacketHandler, "");
pcap.close();
Even though this isn't a Javascript app, you could use JSON as it provides a concise way to read/store multiple pieces of data together. Check out the JSON Java Documentation for details about classes, and to download the related source.
If you're just writing the information you could always use a Hashmap. Unless you know what you're planning to do with the data, it's hard to say what's best.
Just make a custom class (POJO), and depending on how you want to write it make it Serializable. That way you can clearly name your fields (and getters and setters) making your code easier to read (and extend).
some thing like this...
class BigClass { //<br>
private IPAdreess addr1; //<br>
private IPAddress addr2; //<br>
private SomeInfo additionalInfo;//<br>
//implement accessors//<br>
//implement equals, hashCode//<br>
}//<br>
IPAddress, SomeInfo are your user types. In java, InetAddress represents IP address. This may be much more than your custom type.
The selection of suitable data structure of "set" could be decided many factors.. Do you want to retain the order? Do you populate it via multiple threads? How many entries you expect in the set? 100s? A million?
Why not post your code? It may be easier to give feedback with real code..
I don't quite understand what graph you exactly want to plot. What I would do is
Dump all data into an sql database
Run a query to produce input for your chart.
Plot the chart e.g. with JFreeChart or even Excel
I imagine a query along the line
select source_ip, dest_ip, sum(time), sum(sent_bytes) group by source_ip, dest_ip