I'm trying to make an application in Java to check my password security.
This is what I already did:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "123123";
char[] charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt);
break;
}
attempt = bf.toString();
System.out.println("" + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else {
cg[index] = cs[0];
index--;
}
}
else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
But I take a long time to get the "123123" as password (Maybe I don't even get it, I'm not sure)...
Is there a better method to do this with upper/lower alphabetical letters and numbers? Thank you.
Related
I do not usually ask here.
I have a problem with the code I wrote down - I built a compression code - implementation of LZ77.
Everything works in code - when I use files that are based on ascii text in English.
When I use a bmp file - which works differently from a plain text file - I have a problem.
In a text file - I can write the character as it is - it works.
In the bmp file - when I try to compress it - I come across characters that are not English text letters - so I can not compress the file
That I'm trying to write a letter in English into a String builder it works - but in other characters - I can not write them inside the stringBuilder - as I try to write them - it performs null.
code:
main:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
String inPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\Tiny24bit.bmp";
String outPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\encoded.txt";
String decompressedPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\decoded.bmp";
int windowSize = 512;
int lookaheadBufferSize = 200;
LZ77 compress = new LZ77(inPath,outPath,windowSize,lookaheadBufferSize);
compress.compress();
LZ77 decompress = new LZ77(outPath,decompressedPath,windowSize,lookaheadBufferSize);
decompress.decompress();
System.out.println("DONE!");
}
}
LZ77
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.nio.file.Files;
import java.util.BitSet;
public class LZ77 {
private String inPath = null;
private String outPath = null;
private File inFile;
private File outFile;
private final int windowSize;
private final int lookaheadBufferSize;
private final int searchBufferSize;
private int nextByteIndex = 0;
private int nextBitIndex = 0;
private int currentSearchBufferSize = 0;
private int currentLookaheadBufferSize = 0;
private int appendToWindowBuffer = 0;
private byte[] source = null;
public LZ77(String inPath,String outPath,int windowSize,int lookaheadBufferSize) throws IOException
{
this.inPath = inPath;
this.outPath = outPath;
this.inFile = new File(inPath);
this.outFile = new File(outPath);
this.windowSize = windowSize;
this.lookaheadBufferSize = lookaheadBufferSize;
this.searchBufferSize = windowSize - lookaheadBufferSize;
this.source = Files.readAllBytes(inFile.toPath());
}
public void compress() throws IOException
{
StringBuilder dictionary = new StringBuilder();
bufferInitialize(dictionary);
StringBuilder compressed = new StringBuilder();
encode(dictionary,compressed);
addSizeBitsMod64(compressed);
//System.out.println(compressed);
writeFile(compressed);
}
public void bufferInitialize(StringBuilder dictionary)
{
for (int i = 0; i < lookaheadBufferSize; i++) {
if(source.length>nextByteIndex) {
dictionary.append((char)Byte.toUnsignedInt(source[nextByteIndex]));
nextByteIndex++;
currentLookaheadBufferSize++;
}
else
{
break;
}
}
}
public void encode(StringBuilder dictionary,StringBuilder compressed)
{
while(currentLookaheadBufferSize > 0)
{
Match match = findMatch(dictionary);
WriteMatch(compressed,match.offset,match.length,dictionary.charAt(currentSearchBufferSize + match.length));
appendToWindowBuffer = increaseBuffer(match.length);
appendBuffer(dictionary);
}
}
public Match findMatch(StringBuilder dictionary)
{
Match match= new Match(0,0, "");
String matchedString = null;
int offset;
int matchLookAheadIndex = currentSearchBufferSize;
if(!haveAnyMatch(dictionary))
{
}
else {
matchedString = "" + dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
while(offset != -1 && matchLookAheadIndex < dictionary.length() - 1)
{
match.SetLength(match.length + 1);
match.SetOffset(offset);
match.SetValue(matchedString);
matchLookAheadIndex++;
matchedString +=dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
}
}
return match;
}
public int findMatchIndex(StringBuilder dictionary,String value)
{
int stringLength = value.length();
String tmpMatch = null;
int offsetMatch;
for (int i = currentSearchBufferSize - 1; i >=0; i--)
{
tmpMatch = dictionary.substring(i, i +stringLength );
offsetMatch = currentSearchBufferSize - i;
if(tmpMatch.equals(value))
{
return offsetMatch;
}
}
return -1;
}
public boolean haveAnyMatch(StringBuilder dictionary)
{
if (currentSearchBufferSize == 0)
{
return false;
}
if(!isExistInSearchBuffer(dictionary,dictionary.charAt(currentSearchBufferSize)))
{
return false;
}
return true;
}
public boolean isExistInSearchBuffer(StringBuilder dictionary, char isCharAtDictionary)
{
for (int i = 0; i < currentSearchBufferSize; i++) {
if(dictionary.charAt(i) == isCharAtDictionary)
{
return true;
}
}
return false;
}
public int increaseBuffer(int matchLength)
{
return 1 + matchLength;
}
public int findBitSize(int decimalNumber) {
if(decimalNumber >= 256)
{
return 16;
}
else
{
return 8;
}
}
public void convertStringToBitSet(StringBuilder compressed,BitSet encodedBits)
{
for (int i = 0; i < compressed.length(); i++) {
if(compressed.charAt(i)==1)
{
encodedBits.set(i);
}
}
}
public BitSet ConvertToBits(StringBuilder compressed)
{
BitSet encodedBits = new BitSet(compressed.length());
int nextIndexOfOne = compressed.indexOf("1", 0);
while( nextIndexOfOne != -1)
{
encodedBits.set(nextIndexOfOne);
nextIndexOfOne++;
nextIndexOfOne = compressed.indexOf("1", nextIndexOfOne);
}
return encodedBits;
}
public void writeFile(StringBuilder compressed) throws IOException
{
BitSet encodedBits = new BitSet(compressed.length());
encodedBits = ConvertToBits(compressed);
FileOutputStream writer = new FileOutputStream(this.outPath);
ObjectOutputStream objectWriter = new ObjectOutputStream(writer);
objectWriter.writeObject(encodedBits);
objectWriter.close();
}
public void appendBuffer(StringBuilder dictionary)
{
for (int i = 0; i < appendToWindowBuffer && i < source.length; i++) {
if(ableDeleteChar(dictionary))
{
dictionary.deleteCharAt(0);
}
if(nextByteIndex<source.length)
{
char nextByte = (char)Byte.toUnsignedInt(source[nextByteIndex]);
dictionary.append(nextByte);
nextByteIndex++;
}
else
{
currentLookaheadBufferSize--;
}
if(currentSearchBufferSize < searchBufferSize)
{
currentSearchBufferSize++;
}
}
appendToWindowBuffer = 0;
}
public void WriteMatch(StringBuilder compressed,int offset, int length, char character)
{
/*int offsetBitSizeCheck, lengthBitSizeCheck;
offsetBitSizeCheck = findBitSize(offset);
lengthBitSizeCheck = findBitSize(length);
*/
String offsetInBits = writeInt(offset);
String LengthInBits = writeInt(length);
String characterInBits = writeChar(character);
String totalBits = offsetInBits + LengthInBits + characterInBits;
compressed.append(totalBits);
//compressed.append("<"+ offset + ","+ length +","+ character + ">");
System.out.print("<"+ offset + ","+ length +","+ character + ">");
}
public String writeInt(int decimalNumber)
{
int BitSizeCheck = findBitSize(decimalNumber);
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString(decimalNumber));
while (binaryString.length() < BitSizeCheck)
{
binaryString.insert(0, "0");
}
if(BitSizeCheck == 8)
{
binaryString.insert(0, "0");
}
else
{
binaryString.insert(0, "1");
}
return binaryString.toString();
}
public String convertNumToBinaryString(int decimalNumber)
{
return Integer.toString(decimalNumber, 2);
}
public String writeChar(char character)
{
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString((int)character));
while (binaryString.length() < 8)
{
binaryString.insert(0, "0");
}
return binaryString.toString();
}
public boolean ableDeleteChar(StringBuilder dictionary)
{
if(dictionary.length() == windowSize )
{
return true;
}
if(currentLookaheadBufferSize < lookaheadBufferSize)
{
if(currentSearchBufferSize == searchBufferSize)
{
return true;
}
}
return false;
}
public void addSizeBitsMod64(StringBuilder compressed)
{
int bitsLeft = compressed.length()%64;
String bitsLeftBinary = writeInt(bitsLeft);
compressed.insert(0, bitsLeftBinary);
}
public void decompress () throws ClassNotFoundException, IOException
{
BitSet source = readObjectFile();
//System.out.println(source.toString());
StringBuilder decompress = new StringBuilder ();
int bitSetLength = findLengthBitSet(source);
decode(decompress,bitSetLength,source);
writeDecode(decompress);
}
public BitSet readObjectFile() throws IOException, ClassNotFoundException
{
FileInputStream input = new FileInputStream(this.inPath);
ObjectInputStream objectInput = new ObjectInputStream(input);
BitSet restoredDataInBits = (BitSet) objectInput.readObject();
objectInput.close();
return restoredDataInBits;
}
public void decode(StringBuilder decompress, int bitSetLength,BitSet source)
{
System.out.println("decode: ");
System.out.println();
while(nextBitIndex < bitSetLength)
{
Match match = convertBitsToMatch(source);
//System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
addDecode(decompress, match);
}
}
public void addDecode(StringBuilder decompress, Match match)
{
int RelativeOffset;
char decodeChar;
if(match.length == 0 && match.offset == 0)
{
decompress.append(match.value);
}
else
{
RelativeOffset = decompress.length() - match.offset;
System.out.println(RelativeOffset);
for (int i = 0; i < match.length; i++) {
decodeChar = decompress.charAt(RelativeOffset);
decompress.append(decodeChar);
RelativeOffset++;
}
decompress.append(match.value);
}
}
public Match convertBitsToMatch(BitSet source)
{
int offset;
int length;
char character;
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
offset = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
offset = findOffsetLengthMatch(16,source);
}
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
length = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
length = findOffsetLengthMatch(16,source);
}
character = findCharacterMatch(source);
//System.out.println("offset: " + offset + " length: " + length);
Match match = new Match(length,offset,""+character);
System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
return match;
}
public int findOffsetLengthMatch(int index, BitSet source)
{
StringBuilder offsetLengthBinary = new StringBuilder();
for (int i = 0; i < index; i++) {
if(source.get(nextBitIndex) == false)
{
offsetLengthBinary.append('0');
nextBitIndex++;
}
else
{
offsetLengthBinary.append('1');
nextBitIndex++;
}
}
int offsetLengthDecimal = convertBinaryStringToDecimal(offsetLengthBinary);
//System.out.println("problem here: " + offsetLengthDecimal + " the binary is : " + offsetLengthBinary);
return offsetLengthDecimal;
}
public char findCharacterMatch(BitSet source)
{
StringBuilder charBinary = new StringBuilder();
for (int i = 0; i < 8; i++) {
if(source.get(nextBitIndex) == false)
{
charBinary.append('0');
nextBitIndex++;
}
else
{
charBinary.append('1');
nextBitIndex++;
}
}
char charDecimal = (char)convertBinaryStringToDecimal(charBinary);
return charDecimal;
}
public int findLengthBitSet(BitSet source)
{
StringBuilder lengthBinary = new StringBuilder();
for (int i = 0; i < 9; i++) {
if(source.get(i) == false)
{
lengthBinary.append('0');
nextBitIndex++;
}
else
{
lengthBinary.append('1');
nextBitIndex++;
}
}
int lengthModule = convertBinaryStringToDecimal(lengthBinary);
int lengthNotUsed = 64 - lengthModule;
int fullLength = source.size() - lengthNotUsed + 9 ;
return fullLength;
}
public int convertBinaryStringToDecimal(StringBuilder lengthBinary)
{
int length = Integer.parseInt(lengthBinary.toString(), 2);
//System.out.println("length: " + length + "lengthBinary: " + lengthBinary);
return length;
}
public void writeDecode (StringBuilder decompress) throws IOException
{
Writer write = new FileWriter(this.outFile);
write.write(decompress.toString());
write.close();
}
}
Match
public class Match {
protected int length;
protected int offset;
protected String value;
public Match(int length, int offset, String value)
{
this.length=length;
this.offset=offset;
this.value = value;
}
public void SetOffset(int offset) { this.offset = offset; }
public void SetLength(int length) { this.length = length; }
public void SetValue(String value) { this.value = value; }
public void AddValue(char value) { this.value += value; }
public void Reset()
{
this.offset = 0;
this.length = 0;
this.value = "";
}
}
I have recently started working on this program, and I'm new to inter-thread communications such as wait and notify. However when I run this, the notify doesn't seem to execute correctly. Here is the code: (sorry about the extra stuff)
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
Main console = new Main();
console.restart();
}
public void restart() throws InterruptedException {
Scanner restartinput = new Scanner(System.in);
System.out.println("System has been restarted");
System.out.println("Restarting requires an admin restart password.");
System.out.println("You may also login as a normal user to reboot but will cause that account to be temporarily locked.");
System.out.println("Enter 1 for normal user, 2 for admin");
String input12 = restartinput.nextLine();
boolean lockall = false;
if (input12.equals("1")) {
System.out.println("Enter username:");
String input13 = restartinput.nextLine();
if (input13.equals("normalusertest")) {
boolean passwordgotten2 = false;
while (passwordgotten2 == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword2 = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword2 = input.nextLine();
String plaintextguess2 = new String(enteredpassword2);
if (plaintextguess2.hashCode() == realhashedpassword2) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else if (plaintextguess2.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess2 = input.nextLine();
if (overridepasswordguess2.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
for (int w = 0; w <= 45; w++) {
System.out.println(".");
}
fulllogin(0, 1);
} else {
System.out.println("That is not a normal username");
}
}
if (input12.equals("2")) {
boolean gottenpassword3 = false;
while (gottenpassword3 == false) {
System.out.println("Enter the restart password:");
String input8 = restartinput.nextLine();
if (input8.hashCode() == 48818447) {
System.out.println("Access granted.");
System.out.println("Restarting.");
for (int j = 0; j <= 45; j++) {
System.out.println(".");
}
gottenpassword3 = true;
}
}
fulllogin(0, 0);
}
}
public void fulllogin(int lockall, int locknormalusertest) throws InterruptedException {
int lockall1 = lockall;
int locknormalusertest1 = locknormalusertest;
Scanner usernameScanner = new Scanner(System.in);
System.out.println("Username:");
String inputtedusername = usernameScanner.nextLine();
String username = login(inputtedusername, lockall1, locknormalusertest1);
int currentadministrativelevel = 0;
if (username.equals("admintest")) {
currentadministrativelevel = 2;
}
if (username.equals("normalusertest")) {
currentadministrativelevel = 1;
}
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
public void runCommands(String username, int administrativelevel, int lockall, int locknormalusertest) throws InterruptedException {
int currentadministrativelevel = administrativelevel;
System.out.println("Command:");
Scanner commandinput = new Scanner(System.in);
String input2 = commandinput.nextLine();
if (input2.equals("/manage")) {
if (currentadministrativelevel == 2) {
System.out.println("1 user to manage");
System.out.println("Enter 1 to manage normalusertest");
if (commandinput.nextLine().equals("1")) {
System.out.println("1 to view data, 2 to manage password, 3 to lock/unlock user");
String input1 = commandinput.nextLine();
if (input1.equals("1")) {
System.out.println("No data to view currently");
}
if (input1.equals("2")) {
System.out.println(
"To log in to this account use '/override' as the password. The admin override password is the square of the password for this account.");
}
if (input1.equals("3")) {
System.out.println("'/lock' or '/unlock'");
System.out.println("Command:");
String input10 = commandinput.nextLine();
if (input10.equals("/lock")) {
System.out.println("Reenter password to confirm lock:");
System.out.println("Reenter PIN:");
String input9 = commandinput.nextLine();
if (input9.hashCode() == 1662305) {
System.out.println("Locking normalusertest.");
for (int o = 0; o <= 45; o++) {
System.out.println(".");
}
fulllogin(lockall, 1);
}
}
if (input10.equals("/unlock")) {
System.out.println("Reenter password to confirm unlock:");
System.out.println("Reenter PIN:");
String input11 = commandinput.nextLine();
if (input11.hashCode() == 1662305) {
System.out.println("Unlocking normalusertest.");
for (int p = 0; p <= 45; p++) {
System.out.println(".");
}
fulllogin(lockall, 0);
}
}
}
}
}
if (currentadministrativelevel == 1) {
System.out.println("No users to manage.");
}
}
if (input2.equals("/chat")) {
System.out.println("'/view' or '/send'");
String input14 = commandinput.nextLine();
if (input14.equals("/send")) {
System.out.println("Enter a user to send a message to. Capitalization matters.");
String input15currenttouser = commandinput.nextLine();
System.out.println("Message:");
String input16currentmessage = commandinput.nextLine();
try {
sendMessage(username, input15currenttouser, input16currentmessage, lockall, locknormalusertest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (input14.equals("/view")) {
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
}
}
if (input2.equals("/logout")) {
System.out.println("Logging out.");
;
for (int i = 0; i <= 45; i++) {
System.out.println(".");
}
fulllogin(lockall, locknormalusertest);
} else {
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
}
public String login(String username, int lockall, int locknormalusertest) throws InterruptedException {
if (username.equals("normalusertest") && (lockall == 1 || locknormalusertest == 1)) {
System.out.println("This account has been temporarily locked.");
fulllogin(lockall, locknormalusertest);
}
if (username.equals("normalusertest") && lockall == 0 && locknormalusertest == 0) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else if (plaintextguess.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess = input.nextLine();
if (overridepasswordguess.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "normalusertest";
}
if (username.equals("admintest")) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1662305;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "admintest";
} else {
System.out.println("Invalid username");
return "error";
}
}
public void sendMessage(String fromuser, String touser, String message, int lockall, int locknormalusertest) throws InterruptedException {
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
}
}
After /view is typed, the program just waits and then has "Command:" again, even though it should be printing "notify test".
I didn't grasp the whole concept of the application, but two issues seem apparent:
You're not starting any threads, therefore, there won't be any
inter-thread communications, because the only thread you'll have is
Main. Running your application on multiple threads could be
achieved, for example, by having Main extend Thread, creating
multiple instances in your static main method, and calling
start() on each. (This is just a technical example that most
likely wouldn't be appropriate for your needs, as you wouldn't want
to start printing to the console from multiple threads.)
The following synchronized blocks are trying to communicate via a
boolean viewed, but since they're each creating it as their own
local variable, they never get to each other:
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
// ...
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
Threads need to communicate via data that's scoped appropriately to be
accessible to all of them. For example, if you create the threads as in my
example in #1, you can create a static field on Main and all
instances will have access to that.
public class Main {
// The 'static' keyword makes this variable available to all Main instances
private static boolean viewed = false;
// ...
I'd suggest that you read up on Java scopes and dig into this excellent resource to get a better grasp on the concepts of multithreading: http://tutorials.jenkov.com/java-concurrency/index.html
I am trying to perform an interval based search where I am loading from a file and trying to find the interval where my ipaddress lies. Below is my code. This code only works for long but not working for the ip address whose integer version is not a long number.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class RangeBasedSearchAsn {
public static class AsnInfo {
private long asn;
private String ipSubnet;
private String isp;
#Override
public String toString() {
return "Here are the details:\n"
+ this.asn + " " + this.ipSubnet + " " + this.isp ;
}
public AsnInfo(long asn, String ipSubnet, String isp) {
this.asn = asn;
this.ipSubnet = ipSubnet;
this.isp = isp;
}
public long getAsn() {
return asn;
}
public void setAsn(long asn) {
this.asn = asn;
}
public String getIpSubnet() {
return ipSubnet;
}
public void setIpSubnet(String ipSubnet) {
this.ipSubnet = ipSubnet;
}
public String getIsp() {
return isp;
}
public void setIsp(String isp) {
this.isp = isp;
}
}
public static class Range {
private long upper;
private AsnInfo asnInfo;
public Range(long upper, AsnInfo value) {
this.upper = upper;
this.asnInfo = value;
}
public long getUpper() {
return upper;
}
public void setUpper(long upper) {
this.upper = upper;
}
public AsnInfo getValue() {
return asnInfo;
}
public void setValue(AsnInfo value) {
this.asnInfo = value;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
long key = 848163455L;
NavigableMap<Long, Range> asnTreeMap = new TreeMap<>();
System.out.println(System.currentTimeMillis());
System.out.println("Loading isp Map.");
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("C:\\Talend\\TalendTestArea\\rbl_ipv4_zone.txt");
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
StringTokenizer st = new StringTokenizer(line, ";");
while (st.hasMoreTokens() && st.countTokens() == 7) {
st.nextToken();
st.nextToken();
long token1 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token1);
long token2 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token2);
long token3 = Long.parseLong(st.nextToken());
System.out.println("here is token1:" + token3);
asnTreeMap.put(token1, new Range(token2, new AsnInfo(token3,st.nextToken(),st.nextToken())));
}
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
System.out.println("Loading Over.");
System.out.println(System.currentTimeMillis());
System.out.println("Starting Lookup.");
long[] ips = {30503936L};
for(int i = 0 ; i < ips.length;i++){
System.out.println(asnTreeMap.size());
Map.Entry<Long, Range> entry = asnTreeMap.floorEntry(ips[i]);
if (entry == null) {
System.out.println("Value not valid");
} else if (key <= entry.getValue().upper) {
System.out.println("Carrier = " + entry.getValue().asnInfo.toString() + "\n");
} else {
System.out.println("Not found");
}
System.out.println(System.currentTimeMillis());
}
}
}
Below is the output run: 1432262970924 Loading isp Map. Loading
Over. 1432262975089 Starting Lookup. 540772 Not found
1432262975089\n BUILD SUCCESSFUL (total time: 4 seconds)
An IP address is a 32-bit unsigned integer. In Java, ints are 32-bit signed integers.
If you use a signed int to represent an IP address, you'll have to accommodate into your code the fact that the upper half of all IP addresses will in fact be negative.
Java 7 doesn't provide built-in support for unsigned ints, so you'd have to implement the desired behavior or find another class wrapper (from somewhere) for Integer that fulfills your need.
Java 8 introduced methods in the Integer class for comparing ints as unsigned. See https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html for the appropriate methods.
For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.
I have written the following method to detemine whether file in question is formatted with DOS/ MAC, or UNIX line endings.
I see at least 1 obvious issue:
1. i am hoping that i will get the EOL on the first run, say within first 1000 bytes. This may or may not happen.
I ask you to review this and suggest improvements which will lead to hardening the code and making it more generic.
THANK YOU.
new FileFormat().discover(fileName, 0, 1000);
and then
public void discover(String fileName, int offset, int depth) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
FileReader a = new FileReader(new File(fileName));
byte[] bytes = new byte[(int) depth];
in.read(bytes, offset, depth);
a.close();
in.close();
int thisByte;
int nextByte;
boolean isDos = false;
boolean isUnix = false;
boolean isMac = false;
for (int i = 0; i < (bytes.length - 1); i++) {
thisByte = bytes[i];
nextByte = bytes[i + 1];
if (thisByte == 10 && nextByte != 13) {
isDos = true;
break;
} else if (thisByte == 13) {
isUnix = true;
break;
} else if (thisByte == 10) {
isMac = true;
break;
}
}
if (!(isDos || isMac || isUnix)) {
discover(fileName, offset + depth, depth + 1000);
} else {
// do something clever
}
}
Your method seems unnecessarily complicated. Why not:
public class FileFormat {
public enum FileType { WINDOWS, UNIX, MAC, UNKNOWN }
private static final char CR = '\r';
private static final char LF = '\n';
public static FileType discover(String fileName) throws IOException {
Reader reader = new BufferedReader(new FileReader(fileName));
FileType result = discover(reader);
reader.close();
return result;
}
private static FileType discover(Reader reader) throws IOException {
int c;
while ((c = reader.read()) != -1) {
switch(c) {
case LF: return FileType.UNIX;
case CR: {
if (reader.read() == LF) return FileType.WINDOWS;
return FileType.MAC;
}
default: continue;
}
}
return FileType.UNKNOWN;
}
}
Which puts this in a static method that you can then call and use as:
switch(FileFormat.discover(fileName) {
case WINDOWS: ...
case MAC: ...
case UNKNOWN: ...
}
Here's a rough implementation that guesses the line ending type based on a simple majority and falls back on unknown in a worst-case scenario:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.EnumMap;
import java.util.Map;
import java.util.Scanner;
class LineEndings
{
private enum ExitState
{
SUCCESS, FAILURE;
}
public enum LineEndingType
{
DOS("Windows"), MAC("Mac OS Classic"), UNIX("Unix/Linux/Mac OS X"), UNKNOWN("Unknown");
private final String name;
private LineEndingType(String name)
{
this.name = name;
}
public String toString()
{
if (null == this.name) {
return super.toString();
}
else {
return this.name;
}
}
}
public static void main(String[] arguments)
{
ExitState exitState = ExitState.SUCCESS;
File inputFile = getInputFile();
if (null == inputFile) {
exitState = ExitState.FAILURE;
System.out.println("Error: No input file specified.");
}
else {
System.out.println("Determining line endings for: " + inputFile.getName());
try {
LineEndingType lineEndingType = getLineEndingType(inputFile);
System.out.println("Determined line endings: " + lineEndingType);
}
catch (java.io.IOException exception) {
exitState = ExitState.FAILURE;
System.out.println("Error: " + exception.getMessage());
}
}
switch (exitState) {
case SUCCESS:
System.exit(0);
break;
case FAILURE:
System.exit(1);
break;
}
}
private static File getInputFile()
{
File inputFile = null;
Scanner stdinScanner = new Scanner(System.in);
while (true) {
System.out.println("Enter the input file name:");
System.out.print(">> ");
if (stdinScanner.hasNext()) {
String inputFileName = stdinScanner.next();
inputFile = new File(inputFileName);
if (!inputFile.exists()) {
System.out.println("File not found.\n");
}
else if (!inputFile.canRead()) {
System.out.println("Could not read file.\n");
}
else {
break;
}
}
else {
inputFile = null;
break;
}
}
System.out.println();
return inputFile;
}
private static LineEndingType getLineEndingType(File inputFile)
throws java.io.IOException, java.io.FileNotFoundException
{
EnumMap<LineEndingType, Integer> lineEndingTypeCount =
new EnumMap<LineEndingType, Integer>(LineEndingType.class);
BufferedReader inputReader = new BufferedReader(new FileReader(inputFile));
LineEndingType currentLineEndingType = null;
while (inputReader.ready()) {
int token = inputReader.read();
if ('\n' == token) {
currentLineEndingType = LineEndingType.UNIX;
}
else if ('\r' == token) {
if (inputReader.ready()) {
int nextToken = inputReader.read();
if ('\n' == nextToken) {
currentLineEndingType = LineEndingType.DOS;
}
else {
currentLineEndingType = LineEndingType.MAC;
}
}
}
if (null != currentLineEndingType) {
incrementLineEndingType(lineEndingTypeCount, currentLineEndingType);
currentLineEndingType = null;
}
}
return getMostFrequentLineEndingType(lineEndingTypeCount);
}
private static void incrementLineEndingType(Map<LineEndingType, Integer> lineEndingTypeCount, LineEndingType targetLineEndingType)
{
Integer targetLineEndingCount = lineEndingTypeCount.get(targetLineEndingType);
if (null == targetLineEndingCount) {
targetLineEndingCount = 0;
}
else {
targetLineEndingCount++;
}
lineEndingTypeCount.put(targetLineEndingType, targetLineEndingCount);
}
private static LineEndingType getMostFrequentLineEndingType(Map<LineEndingType, Integer> lineEndingTypeCount)
{
Integer maximumEntryCount = Integer.MIN_VALUE;
Map.Entry<LineEndingType, Integer> mostFrequentEntry = null;
for (Map.Entry<LineEndingType, Integer> entry : lineEndingTypeCount.entrySet()) {
int entryCount = entry.getValue();
if (entryCount > maximumEntryCount) {
mostFrequentEntry = entry;
maximumEntryCount = entryCount;
}
}
if (null != mostFrequentEntry) {
return mostFrequentEntry.getKey();
}
else {
return LineEndingType.UNKNOWN;
}
}
}
There is a whole lot wrong with this. You need to understand the FileInputStream class better. Note that read is not guaranteed to read all the bytes you requested. offset is the offset into the array, not the file. And so on.