I'm following Googles tutorial on Protocol Buffers using Java: https://developers.google.com/protocol-buffers/docs/javatutorial
and I'm struggling as to how the tutorial writes to a file (i.e. taking user input)? What type of file do you write to? a .proto or .txt (or however you want to save your data).
addressbook.proto :
package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
message AddressBook {
repeated Person person = 1;
}
I'm not going to paste the file here on Stack I've compiled to java with protoc. I done that using
protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
in terminal.
Generated File Link - http://pastebin.com/1w7ibDru
I've also downloaded the Protobuf 2.5.0 jar and added it as a library to my project
AddPerson.java :
import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
class AddPerson {
// This function fills in a Person message based on user input.
static Person PromptForAddress(BufferedReader stdin,
PrintStream stdout) throws IOException {
Person.Builder person = Person.newBuilder();
stdout.print("Enter person ID: ");
person.setId(Integer.valueOf(stdin.readLine()));
stdout.print("Enter name: ");
person.setName(stdin.readLine());
stdout.print("Enter email address (blank for none): ");
String email = stdin.readLine();
if (email.length() > 0) {
person.setEmail(email);
}
while (true) {
stdout.print("Enter a phone number (or leave blank to finish): ");
String number = stdin.readLine();
if (number.length() == 0) {
break;
}
Person.PhoneNumber.Builder phoneNumber =
Person.PhoneNumber.newBuilder().setNumber(number);
stdout.print("Is this a mobile, home, or work phone? ");
String type = stdin.readLine();
if (type.equals("mobile")) {
phoneNumber.setType(Person.PhoneType.MOBILE);
} else if (type.equals("home")) {
phoneNumber.setType(Person.PhoneType.HOME);
} else if (type.equals("work")) {
phoneNumber.setType(Person.PhoneType.WORK);
} else {
stdout.println("Unknown phone type. Using default.");
}
person.addPhone(phoneNumber);
}
return person.build();
}
// Main function: Reads the entire address book from a file,
// adds one person based on user input, then writes it back out to the same
// file.
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: AddPerson ADDRESS_BOOK_FILE");
System.exit(-1);
}
AddressBook.Builder addressBook = AddressBook.newBuilder();
// Read the existing address book.
try {
addressBook.mergeFrom(new FileInputStream(args[0]));
} catch (FileNotFoundException e) {
System.out.println(args[0] + ": File not found. Creating a new file.");
}
// Add an address.
addressBook.addPerson(
PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
System.out));
// Write the new address book back to disk.
FileOutputStream output = new FileOutputStream(args[0]);
addressBook.build().writeTo(output);
output.close();
}
}
I obviously get the error:
Usage: AddPerson ADDRESS_BOOK_FILE
I presume the AddPerson class takes in a File (a .txt perhaps?) in main and there is no file, hence why?
// Main function: Reads the entire address book from a file,
// adds one person based on user input, then writes it back out to the same
// file.
The comment says file, but I don't know what type of file?
Can someone show me what I'm suppose to do to actually write to a file. I'm not too sure what type of file to write to as well.
There is not that many Protobuf tutorials out there :/
Forgive me if this questions is trivial, I have never worked with proto buffers.
Thank you.
Related
I have a simple project where I created a Store with customers, products and employees. Each is represented by a Class of course and I also have a CSV file for each one of them to be able to load data from and save data to it.
I'm facing issues where the file reading/writing is working, but not really. For example, I have the ability to save each file individually so if for instance I want to create a new customer, I'd save it to the list and then to the file. Issue is, once I do it for another Class (i.e if I create a new employee) and then save it again, the customer file object I saw in the CSV earlier is deleted. BUT, once I add a new object again, that same object reappears again. Hope you can somehow understand, but here is a more detailed view:
customer.csv is empty:
Me creating a new customer:
Created and saved to CSV:
Now, if I go to the other menu, and click on "Save all data" that jon snow customer object will be gone. Then if I create a new customer, then it will be added to the CSV file, along with the jon snow I added earlier. So why is it gone in the first place?
So here is the whole file reader/writer code I'm using:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
class CSV {
static void CreateFile(String filename) { //Create new file
try {
File fileToCreate = new File(filename);
if (fileToCreate.createNewFile()) {
System.out.println("File created sucessfully: " + fileToCreate.getName());
}
} catch (IOException e) {
System.out.println("Cannot create file!");
}
}
static void ReadFile(String path_and_filename){
try {
File fileToRead = new File(path_and_filename);
Scanner myReader = new Scanner(fileToRead);
System.out.println("Reading file "+path_and_filename+" :");
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
System.out.println();
} catch (FileNotFoundException e) {
System.out.println("There is no such file "+"\"path_and_filename\""+".\n");
}
}
// The StringBuilder in Java represents a mutable sequence of characters.
// Java's built in String class is not mutable.
static void saveArrayListToFile(List<Output> listToSave, String fileName, String sep) throws Exception {
StringBuilder ans = new StringBuilder();
for (Output record : listToSave) {
ans.append(record.createOutput());
ans.append(sep);
}
saveStringToFile(ans.toString(), fileName);
System.out.println("\nData saved to "+ fileName);
}
static void saveArrayListToFile1(ArrayList<String> listToSave, String fileName, String sep){
StringBuilder ans = new StringBuilder();
for (Object record : listToSave) {
ans.append(record.toString());
ans.append(sep);
}
saveStringToFile(ans.toString(), fileName);
System.out.println("\nList was saved to file "+fileName+"\n");
}
static void saveStringToFile(String data, String fileName){
BufferedWriter bufferedWriter=null;
try {
bufferedWriter = new BufferedWriter(
new FileWriter(fileName,false));
bufferedWriter.write(data);
} catch (IOException e) {
System.out.println("Cannot write to file");
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Cannot write to file");
}
}
}
}
When I'm creating a new customer, I call it from a menu and it looks like this:
switch (selection) {
case 1:
try {
System.out.println("You're registering as a new customer");
String custID = ObjectIDs.generateID();
System.out.println("Enter first name:");
String firstName = sc.next();
System.out.println("Enter last name:");
String lastName = sc.next();
st.newCustomer(custID, firstName, lastName);
st.saveCustomersList();
} catch (Exception e) {
e.printStackTrace();
}
break;
the saveCustomerList() function is this:
#SuppressWarnings("unchecked")
void saveCustomersList() throws Exception {
CSV.saveArrayListToFile((List<Output>)(List<?>) customers, CUSTOMERS_FILE_PATH,"\n");
}
And then the functions calls saveArrayListToFile() to save it.
The behavior is the same with Product and Employee projects, so I randomly chose to show how it acts when creating a new Product.
I hope I added enough information. If needed, I can paste more code in but I already feel it's very cluttered. Hopefully it's ok.
Thank you very much :)
At the moment it's hard to say, as one can only hypothesise as to what happens when you click on "Save all data". There are some weird things (what is saveArrayListToFile and saveArrayListToFile11? Why does one declare an exception? When are these called?).
Having said that, look at the actual file writing method saveStringToFile, it says:
bufferedWriter = new BufferedWriter(new FileWriter(fileName,false));
This false there means 'do not append to file, rewrite it from scratch'. So each time you call it, file contents are discarded and replaced from what you provide to the method call. So my somewhat educated guess would be:
You save customer one to file (gets cleared, customer 1 written) and
append the customer to a list of customers (that's my guess)
You
save customer two to file (file gets cleared, so only customer 2 is
saved), you add to list to customers (do you?)
Then you choose 'save all' which gets list of customers, and save them in one go, a single call to the method. The file is cleared, all customers are saved.
But it's all guessing. Try creating a minimal, reproducible example
In addition to pafau k. I would like to add some things at least I would do differently...
First of all:
Things that can cause errors or unexpected behaviour:
Everything below is in saveStringToFile
Like already pointed out the Initialisation of the BufferedWriter: It should be initialized like this:
bufferedWriter = new BufferedWriter(new FileWriter(filename, true));
This puts the File into appending mode (if you want to append to a file you can also get rid of the boolean (second argument) entirely because appending is standard: new FileWriter(filename))
If for some case the Creation of the BufferedWriter failed you will still have a null-pointing object as bufferedWriter. This however means that you will be surprised with a NullPointerException in your finally block. To prevent this first of all do a check in your finally block:
if (bufferedWriter != null) {
// Close your bufferedWriter in here
}
Also, if you run into an error you will likely be presented with the same error message twice.
Now cosmetics:
Things that I would write differently for aesthetic reasons:
Java methods (and static "methods") are always starting with a small letter :)
This means it should be public static void createFile() for example or static void readFile()
variables and parameters of methods do not contain seperators like _ but instead if you want to make it more readable you start with a small letter and for each seperation you use a capital letter for that: e.g. String thisIsAVeryLongVariableWithALotOfSeperations = "Foo";
The generic types in saveArrayListToFile1() work like a placeholder. So you declare ArrayList<String> listToSave so you don't need a cast in the following for-loop: You can simply write:
for (String record : listToSave) {
ans.append(record);
ans.append(sep);
}
I hope this fixes all errors or complications. :)
I am working on a java code for school and I have spent days on it and I just don't think that I'm heading in the right direction. Here is the info on the project:
For security-minded professionals, it is important that only the appropriate people gain access to data in a computer system. This is called authentication. Once users gain entry, it is also important that they only see data related to their role in a computer system. This is called authorization. For the zoo, you will develop an authentication system that manages both authentication and authorization. You have been given a credentials file that contains credential information for authorized users. You have also been given three files, one for each role: zookeeper, veterinarian, and admin. Each role file describes the data the particular role should be authorized to access. Create an authentication system that does all of the following:
Asks the user for a username
Asks the user for a password
Converts the password using a message digest five (MD5) hash
It is not required that you write the MD5 from scratch. Use the code located in this document and follow the comments in it to perform this operation.
Checks the credentials against the valid credentials provided in the credentials file
Use the hashed passwords in the second column; the third column contains the actual passwords for testing and the fourth row contains the
role of each user.
Limits failed attempts to three before notifying the user and exiting the program
Gives authenticated users access to the correct role file after successful authentication
The system information stored in the role file should be displayed. For example, if a zookeeper’s credentials is successfully authenticated, then the contents from the zookeeper file will be displayed. If an admin’s credentials is successfully authenticated, then the contents from the admin file will be displayed.
Allows a user to log out
Stays on the credential screen until either a successful attempt has been made, three unsuccessful attempts have been made, or a user chooses to exit
Here are the five text files I was given:
admin.txt
Hello, System Admin!
As administrator, you have access to the zoo's main computer system.
This allows you to monitor users in the system and their roles.
credentials.txt
griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin
validateCredentials.txt
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package authentication;
import java.security.MessageDigest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
*
* #author JoeP
*/
public class ValidateCredentials {
private boolean isValid;
private String filePath;
private String credentialsFileName;
public ValidateCredentials() {
isValid = false;
//filePath = "C:\\Users\\joep\\Documents\\NetBeansProjects\\ Authentication\\";
filePath = "";
credentialsFileName = "credentials";
}
public boolean isCredentialsValid(String userName, String passWord) throws Exception {
String original = passWord;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("");
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString()); //sb.toString() is what you'll need to compare password strings
isValid = readDataFiles(userName, sb.toString());
return isValid;
}
public boolean readDataFiles(String userName, String passWord) throws IOException {
FileInputStream fileByteStream1 = null; // File input stream
FileInputStream fileByteStream2 = null; // File input stream
Scanner inFS1 = null; // Scanner object
Scanner inFS2 = null; // Scanner object
String textLine = null;
boolean foundCredentials = false;
// Try to open file
System.out.println("");
System.out.println("Opening file " + credentialsFileName + ".txt");
fileByteStream1 = new FileInputStream(filePath + "credentials.txt");
inFS1 = new Scanner(fileByteStream1);
System.out.println("");
System.out.println("Reading lines of text.");
while (inFS1.hasNextLine()) {
textLine = inFS1.nextLine();
System.out.println(textLine);
if (textLine.contains(userName) && textLine.contains(passWord)) {
foundCredentials = true;
break;
}
}
// Done with file, so try to close it
System.out.println("");
System.out.println("Closing file " + credentialsFileName + ".txt");
if (textLine != null) {
fileByteStream1.close(); // close() may throw IOException if fails
}
if (foundCredentials == true) {
// Try to open file
System.out.println("");
System.out.println("Opening file " + userName + ".txt");
fileByteStream2 = new FileInputStream(filePath + userName + ".txt");
inFS2 = new Scanner(fileByteStream2);
System.out.println("");
while (inFS2.hasNextLine()) {
textLine = inFS2.nextLine();
System.out.println(textLine);
}
// Done with file, so try to close it
System.out.println("");
System.out.println("Closing file " + userName + ".txt");
if (textLine != null) {
fileByteStream2.close(); // close() may throw IOException if fails
}
}
return foundCredentials;
}
}
veterinarian.txt
Hello, Veterinarian!
As veterinarian, you have access to all of the animals' health records. This allows you to view each animal's medical history, current treatments/illnesses (if any), and maintain a vaccination log.
zookeeper.txt
Hello, Zookeeper!
As zookeeper, you have access to all of the animals information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.
Finally, this is the code that I have so far, but when I try to run it in Netbeans it just won't work.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.List;
import java.util.Scanner;
public class Authentication {
public static void main(String args[]) {
try {
Scanner scan = null;
scan = new Scanner(new File("credentials.txt"));
String credentials[][] = new String[100][4];
int count = 0;
while (scan.hasNextLine()) {
//read name and hased pass
credentials[count][0] = scan.next();
credentials[count][1] = scan.next();
//get original pass from file
String l[] = scan.nextLine().split("\"[ ]+");
l[0] = l[0].trim();
l[0] = l[0].replace("\"", "");
credentials[count][2] = l[0];
credentials[count][3] = l[1].trim();
count++;
}
//ask for user input
Scanner scanio = new Scanner(System.in);
boolean RUN = true;
int tries = 0;
while (RUN) {
System.out.println("**WELCOME**");
System.out.println("1) Login");
System.out.println("2) Exit");
int ch = Integer.parseInt(scanio.nextLine().trim());
if (ch == 1) {
//increment number of attempts
tries++;
//ask for user and pass
System.out.print("Input username:");
String username = scanio.nextLine();
System.out.print("Input password:");
String password = scanio.nextLine();
//generate hash
MessageDigest md;
md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
String hPassword = sb.toString();
boolean badUser = true;
for (int i = 0; i < count; i++) {
if (username.contentEquals(credentials[i][0])) {
if (hPassword.contentEquals(credentials[i][1])) {
//everything looks good. login
List<String> data = null;
//check type of user and print
switch (credentials[i][3]) {
case "zookeeper":
data = Files.readAllLines(Paths.get("zookeeper.txt"), Charset.defaultCharset());
break;
case "admin":
data = Files.readAllLines(Paths.get("admin.txt"), Charset.defaultCharset());
break;
case "veterinarian":
data = Files.readAllLines(Paths.get("veterinarian.txt"), Charset.defaultCharset());
break;
default:
break;
}
for (String s : data) {
System.out.println(s);
}
//reset tries
tries = 0;
//now what to do?
System.out.println("\n1) Logout.");
System.out.println("2) Exit.");
ch = Integer.parseInt(scanio.nextLine().trim());
if (ch == 2) {
RUN = false;
}
badUser = false;
break;
}
}
}
if (badUser) {
System.out.println("Invalid Username or password.");
}
} else {
RUN = false;
break;
}
//thief alert!!
if (tries == 3) {
RUN = false;
System.out.println("Too many invlaid attempts.");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
PLEASE HELP ME!!!
THANK YOU!!!
Youa re getting a FileNotFoundException. That is, Netbeans is not finding your credentials.txt file (which possibly is located in a different directory). Make sure your credentials.txt file is located in your Netbeans project directory, as follows:
1) Find your project directory by going to the "Netbeans "Projects" tab, right-clicking in your project folder and selecting "Properties". The "Project folder" will be shown on at the top of the new window displayed (i.e. "C:\Users\admin\Documents\NetBeansProjects\YourProjectName").
2) Place your credentials.txt file in that project directory.
3) Re-run your code.
It's just as the question is titled. The area where I'm having an issue is with the if/else properties.. and also, how would I go about changing it from an API interface to an array type interface? Sorry if my formatting is poor. Feel free to correct me.
Program corrected and running how it is intended:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner; // Needed for the Scanner class
public class PasswordVerifier2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String input;
System.out.print("Please enter your password: ");
input = keyboard.nextLine();
if (authenticate1(input)) {
System.out.println("This program is working if this text is found within outputfile.txt.");
File file = new File("outputfile.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("This program is working if this text is found within outputfile.txt.");
}else if (authenticate2(input)) {
System.out.println("It works.");
}else{
System.out.println("Error: Wrong password.");
}
}
private static boolean authenticate1(String password1) {
return ((password1.length() == 6)
&& (password1.matches("beep11"))
&& (password1.matches("beep11"))
&& (password1.matches("beep11")));
}
private static boolean authenticate2(String password2) {
return ((password2.length() == 6)
&& (password2.matches("beep22"))
&& (password2.matches("beep22"))
&& (password2.matches("beep22")));
}
}
If you are using/applying one of the two methods to authenticate the user then you can use if.. else if, e.g.:
if (authenticate1(input)) {
// some code
}else if (authenticate2(input)) {
//some code
}else{
System.out.println("Error: Wrong password.");
}
EDIT
To get rid of compilation error at authenticate2, you either need to move that authenticate2 to your main class or include the class name in method call, e.g.
change
if (authenticate2(input)) {
to
if (authenticate2.authenticate2(input))
This will make sure the control does not go into second if block if first one is successful and vice versa.
in my advanced java class we are to write an application that reads a .txt file ("nasdaqlisted.txt") that is seperated by pipes ("|") and pull out all of the stocks that have a test issue that = "Y". My application reads my file, but prints out the test cases still. I'm trying to use an if statement to compare what is stored in testIssue to "Y", but I can't figure out why this won't work. Here is my source code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public class readTextFile
{
private Scanner input = null;
private File file = null;
public void openFile()
{
try
{
file = new File("nasdaqlisted.txt");
input = new Scanner(file);
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file.");
System.exit(1);
}
}
public void readFile()
{
sortTextFile sort = new sortTextFile();
try
{
try
{
file = new File("nasdaqlisted.txt");
input = new Scanner(file);
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file.");
System.exit(1);
}
while (input.hasNext())
{
StringTokenizer st = new StringTokenizer(input.nextLine(), "|");
while (st.hasMoreTokens())
{
input.nextLine();
sort.setSymbol(st.nextToken());
sort.setSecurity(st.nextToken());
sort.setMarket(st.nextToken());
sort.setTest(st.nextToken());
sort.setFinancial(st.nextToken());
sort.setSize(st.nextToken());
if (!sort.getTestIssue().equals("Y"))
{
System.out.println(sort.getSymbol());
System.out.println(sort.getSecurityName());
System.out.println(sort.getTestIssue());
}
}
}
}
catch (NoSuchElementException noSuchElementException)
{
System.err.println("Improperly formed file.");
System.exit(1);
}
}
public void closeFile()
{
if (input != null)
{
input.close();
}
}
}
And here is the end of the output I'm getting with the test stocks still printing out:
Security Name: Zalicus Inc. - Common Stock
Test Issue: N
Symbol: ZN
Security Name: Zion Oil & Gas Inc - Common Stock
Test Issue: N
Symbol: ZOLT
Security Name: Zoltek Companies, Inc. - Common Stock
Test Issue: N
Symbol: ZU
Security Name: zulily, inc. - Class A Common Stock
Test Issue: N
Symbol: ZVZZT
Security Name: NASDAQ TEST STOCK
Test Issue: Y
Symbol: ZXYZ.A
Security Name: Nasdaq Symbology Test Common Stock
Test Issue: Y
Improperly formed file.
Process finished with exit code 1
If System.out.println(sort.getTestIssue()); outputs "Test Issue: Y", then sort.getTestIssue() is not equal to "Y".
Maybe you want to use endsWith or a regexp or something else
I am creating a basic password based login system. It uses MD5 to secure the password. The correct password is "csk" (without quotes). If anyone enters that correctly, he gets access to a key.html file in the local computer. But if someone enters the wrong password for three consecutive times, he gets "banned" from logging in again. But the design that I have constructed bans the user only for that particular session. If he opens the terminal again, it starts from the very beginning. If the variable count is greater than 3 (three) from the last time, then the program, on execution via void main() would display "You are banned". I want to keep it basic and not use JDBC and SQL and such. Also, this is a local application and not a web-based one. I'm quite confused what approach I should take on this. Here's my code that I've cooked up:
import java.math.*;
import java.security.*;
import java.io.*;
import java.util.*;
import java.net.HttpURLConnection;
public class pwd {
public static void main(String[] args)throws NoSuchAlgorithmException, IOException, InterruptedException {
int count = 1;
boolean run = true;
while (run && count<4){
System.out.println("Enter the password");
Scanner kb = new Scanner(System.in);
String pass = kb.nextLine();
String pd = "ea0882721f7f44384ce772375696f9a6"; //Password is "csk" without quotes geeks, this is it's MD5
// so enter "csk" in the terminal
// to run the program on execution
String md5sum = md5(pass);
String os = System.getProperty("os.name");
boolean o = false;
int win = os.indexOf("Windows");
if (md5sum.equals(pd)){
System.out.println("You've logged in successfully, get the Key now");
String url = "file:///C:/Users/<username>/Desktop/key.html"; // example www
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
run = false;
}
else {
System.out.println("You've entered the wrong password, try again.");
System.out.println();
run = true;
if (count>=3) {
System.out.println("You are banned from logging in, due to repeated unsuccessful login attempts.");
}
++count;
}
}
}
public static String md5(String input)throws NoSuchAlgorithmException, IOException {
String md5 = null;
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(input.getBytes(), 0, input.length());
md5 = new BigInteger(1, digest.digest()).toString(16);
return md5;
}
}
EDIT: There's no need for me to change MD5 hashing to anything else, it's just a basic one.
you can simply write to a file with java.io.FileWriter
FileWriter writer = null;
String text = "username";
try{
writer = new FileWriter("banned.txt", true);
writer.write("\r\n");
writer.write(text,0,text.length());
}catch(IOException ex){
ex.printStackTrace();
}finally{
if(writer != null){
writer.close();
}
}
The above code allows you to add a line in a file.
To read the file, you can do like this (java.io.BufferedReader):
BufferedReader reader = new BufferedReader(new FileReader("banned.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// check the username here
}
Hum what you want to do can be done but you have to create a kind of "login page" because as it is now (with the code you gave) there is no user information involved.
To save the important information of the ban, you can for example save a boolean in a file (or the user when you have it) and read this same file at the beginning of your code in order to know if user is ban or not. In this case you have to change your code to add the information of ban or not before trying the new input codes ;)
If you don't have a login page, so no user once you ban someone no one will be able to log any more :)
PS: Java class start with a Upper case not pwd but Pwd normally
PS2: Your count will always be increased because it's not in a else ;) so every try of new code will increase it even if the user is ban ;)