Write in StringBuilder - a value that is not char - java

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 = "";
}
}

Related

BufferOverflowException in java threads

Receiving an exception "BufferOverflowException" while running sikuli script via threads. The same script works properly without thread object. I have no clue what causes the bufferoverflowexception. Please guide.
Sample Code:-
import org.sikuli.script.*; // Library import
public class Sikuli {
private Screen screen = new Screen();
private Pattern getPattern(String imagePath) {
return new Pattern(imagePath);
}
public void click(String imagePath) throws FindFailed, InterruptedException {
screen.click(getPattern(imagePath));
}
public void sendKeys(String value) {
screen.type(value);
}
import Sukuli // Custom sikuli class import
public class foo {
Sikuli sk = new Sikuli();
public void test() {
Thread t1 = new Thread(() -> {
sk.click(new Pattern("imagePath"));
sk.type("fooboo");
});
t1.start();
}
}
From Sikuli Library Methods which are being referred by my class methods:-
public int type(String text) {
try {
return this.keyin((Object)null, text, 0);
} catch (FindFailed var3) {
return 0;
}
}
private <PFRML> int keyin(PFRML target, String text, int modifiers) throws FindFailed {
if (target != null && 0 == this.click(target, 0)) {
return 0;
} else {
Debug profiler = Debug.startTimer("Region.type", new Object[0]);
if (text != null && !"".equals(text)) {
String showText = "";
for(int i = 0; i < text.length(); ++i) {
showText = showText + Key.toJavaKeyCodeText(text.charAt(i));
}
String modText = "";
String modWindows = null;
if ((modifiers & 4) != 0) {
modifiers -= 4;
modifiers |= 4;
log(3, "Key.WIN as modifier", new Object[0]);
modWindows = "Windows";
}
if (modifiers != 0) {
modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers));
if (modWindows != null) {
modText = modText.replace("Meta", modWindows);
}
}
Debug.action("%s TYPE \"%s\"", new Object[]{modText, showText});
log(3, "%s TYPE \"%s\"", new Object[]{modText, showText});
profiler.lap("before getting Robot");
IRobot r = this.getRobotForRegion();
int pause = 20 + (Settings.TypeDelay > 1.0 ? 1000 : (int)(Settings.TypeDelay * 1000.0));
Settings.TypeDelay = 0.0;
profiler.lap("before typing");
r.typeStarts();
for(int i = 0; i < text.length(); ++i) {
r.pressModifiers(modifiers);
r.typeChar(text.charAt(i), KeyMode.PRESS_RELEASE);
r.releaseModifiers(modifiers);
r.delay(pause);
}
r.typeEnds();
profiler.lap("after typing, before waitForIdle");
r.waitForIdle();
profiler.end();
return 1;
} else {
return 0;
}
}
}
Trace logs:-
[log] CLICK on L[1517,53]#S(0) (555 msec)[log] TYPE "fooboo"Exception in thread "Thread-4" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:521)
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:169)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeString(AbstractStreamEncoder.java:127)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeStringData(AbstractStreamEncoder.java:171)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encode(AbstractStreamEncoder.java:157)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.encodeMessage(EventChannelEncoder.java:398)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.setOutErr(EventChannelEncoder.java:188)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.testOutput(EventChannelEncoder.java:183)
at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:113)
at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:44)
at org.apache.maven.surefire.common.junit4.JUnit4RunListener.writeTestOutput(JUnit4RunListener.java:235)
at org.apache.maven.surefire.api.report.ConsoleOutputCapture$ForwardingPrintStream.println(ConsoleOutputCapture.java:144)
at org.sikuli.basics.Debug.log(Debug.java:881)
at org.sikuli.basics.Debug.action(Debug.java:645)
at org.sikuli.script.Region.keyin(Region.java:4613)
at org.sikuli.script.Region.type(Region.java:4493)
at Sikuli.sendKeys(Sikuli.java:87)

Hazelcast 2.5 Concurrency issues

We are running hazelcast 2.5 as a cluster to replicate objects through applications. There are, at the moment, one producer and 3 consumers. The updates from the writer go as high as 10000 per minute and the consumers read every second searching for updates in the clustered map.The writer is a java native application running under a Debian 8 server with java 7. The hazelcast server is on the same machine as the producer but on an independent application. All the consumers are tomcat 7 apps running under a Debian 8 machine with java 7. The problem we are facing is that in average about 4 percent of the data clustered is reaching the consumerĀ“s end garbled in the shared map. The code for the producer is the following :
Long imei;
Integer clase;
HazelCastobjGpsData datoGps;
HazelCastobjTelemetria datoTelemetria;
Set<HazelCastpkQueue> keys = HazelCast.tmpQueue.keySet();
for (Iterator<HazelCastpkQueue> i = keys.iterator(); i.hasNext();) {
HazelCastpkQueue current = i.next();
clase = current.getClase();
imei = current.getImei();
if (clase == CLASE_GPS) // GPS
{
try {
HazelCast.clienteHC.getLock(imei).lock();
datoGps = (HazelCastobjGpsData) HazelCast.tmpQueue
.remove(current);
HazelCast.instMapGPS.put(current.getImei(), datoGps);
HazelCast.instQueue.put(new HazelCastpkQueue(imei,
CLASE_GPS), CLASE_GPS);
} catch (Throwable t) {
System.out.println("Error HazelCast Gps Update: " + imei
+ " :" + t.getMessage());
if (!HazelCast.clienteHC.isActive()) {
System.out.println("Hazelcast no activo");
}
} finally {
HazelCast.clienteHC.getLock(imei).unlock();
}
} else // Telemetria
{
try {
HazelCast.clienteHC.getLock(imei).lock();
datoTelemetria = (HazelCastobjTelemetria) HazelCast.tmpQueue
.remove(current);
HazelCast.instMapTelemetria.put(new HazelCastpkQueue(imei,
clase), datoTelemetria);
HazelCast.instQueue.put(new HazelCastpkQueue(imei, clase),
clase);
} catch (Throwable t) {
System.out.println("Error HazelCast Telemetria Update: "
+ imei + " :" + t.getMessage());
if (!HazelCast.clienteHC.isActive()) {
System.out.println("Hazelcast no activo");
}
} finally {
HazelCast.clienteHC.getLock(imei).unlock();
}
}
}
Where HazelCastobjGpsData datoGps; is the object to be rescued by the consumers and HazelCast.instMapGPS.put(current.getImei(), datoGps); is the map with problems. It has a long as a key.
The code for the server is the following:
public class HazelServer {
#SuppressWarnings("unused")
private static ConcurrentMap<Long,HazelCastobjGpsData> instMapGPS;
#SuppressWarnings("unused")
private static ConcurrentMap<HazelCastpkQueue,HazelCastobjTelemetria> instMapTelemetria;
#SuppressWarnings("unused")
private static ConcurrentMap<HazelCastpkQueue,Integer> instQueue;
#SuppressWarnings("unused")
private static BlockingQueue<HazelCastpkTisPanicoQueue> tisPanicQueue;
public static void main(final String[] args) {
System.out.println("HazelCast Server init 03/03/2015");
init();
System.out.println("OK");
}
private static void init() {
try {
HazelcastInstance hcServer = Hazelcast.newHazelcastInstance(null);
instMapGPS = hcServer.getMap("gps");
instMapTelemetria = hcServer.getMap("telemetria");
instQueue = hcServer.getMap("colagpstele");
tisPanicQueue = hcServer.getQueue("cola_panico_tis");
} catch (Throwable t) {
System.out.println("Error al tratar de obtener mapas: " + t.getMessage());
}
}
}
The consumers code is the following
public static void fetchHazelCast() {
try {
if (GetHazelCast.isHazelcastActive()) {
double errores = 0;
double count=0;
Set<HazelCastpkQueue> keys = GetHazelCast.hcQueue.keySet();
for (final Iterator<HazelCastpkQueue> i = keys.iterator(); i.hasNext();) {
HazelCastpkQueue currentKey = i.next();
if (currentKey.getClase() == CLASE_GPS) // GPS Base
{
if(Realtime.newGPS(GetHazelCast.hcGPS.get(currentKey.getImei()))){
errores++;
}
count++;
} else // Telemetria
{
Realtime.newTelemetria(GetHazelCast.hcTelemetria.get(currentKey));
}
//count++;
GetHazelCast.hcQueue.remove(currentKey);
currentKey = null;
}
/*ReqInit.logger.warn("Errores "+(double)errores);
ReqInit.logger.warn("Cantidad "+(double)count);
ReqInit.logger.warn("Porcentaje "+(double) ((((double)errores)*100.0f)/(double)count));*/
if(count>0){
double promedio = (double) ((((double)errores)*100.0f)/(double)count);
CloudWatchSubmit.sendMetric("metricasreq", "errores", errores);
CloudWatchSubmit.sendMetric("metricasreq", "cantidad", count);
CloudWatchSubmit.sendMetric("metricasreq", "erroresporcentaje", promedio);
}
keys = null;
} else {
System.out.println("Hazelcast no activo...");
GetHazelCast.contectarHZRealTime();
}
} catch (Exception e) {
e.printStackTrace();
}
}
note that the consumer only takes out the data that has been updated recently, this is done because there is a map whith keys that are been updated, once the data is out thar key is removed from that map.
The following is the code of the object
public class HazelCastobjGpsData implements DataSerializable {
private static final long serialVersionUID = 1L;
private Calendar utc;
private Calendar lastupdate;
private String now = "n/a";
private double latitud = 0.0, longitud = 0.0, altitud = 0.0,
velocidad = 0.0, cog = 0.0, nsat = 4.0, hdop = 2.0, adc1 = -200,
adc2 = -200, adc3 = -200, adc4 = -200, bateria = -1;
private int ignicion, io1 = -1, io2 = -1, io3 = -1, io4 = -1, power = -1,
antirobo = -1, panico = -1;
private long imei = 0L, driverId = -1;
private boolean valid = true;
private long odometro = -1L;
private long horometro = -1L;
private String ip = "N/A";
private long ibutton2 = -1;
private long ibutton3 = -1;
private long ibutton4 = -1;
private long odometroInterno = -1L;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
private double anterior_lat = 0.0;
private double anterior_lon = 0.0;
private double anterior_sog = 0;
private double anterior_cog = 0;
private double anterior_ignicion = 0;
private long anterior_odometro = 0;
private long anterior_horometro = 0;
private long delta_time = 0;
private double delta_dist = 0;
private long trailerId = -1L;
private long tripTime = 0L;
private long horometroInterno = 0L;
public long getHorometroInterno() {
return horometroInterno;
}
public void setHorometroInterno(long horometroInterno) {
this.horometroInterno = horometroInterno;
}
public void setAnterior(HazelCastobjGpsData anterior) {
this.setDelta_dist(Math.round((new Geo(this.latitud, this.longitud)
.distanceKM(new Geo(anterior.getLatitud(), anterior
.getLongitud()))) * 1000));
this.setDelta_time((this.getUTC().getTimeInMillis() - anterior.getUTC()
.getTimeInMillis()) / 1000);
this.setAnterior_cog(anterior.getCOG());
this.setAnterior_sog(anterior.getVelocidad());
this.setAnterior_lat(anterior.getLatitud());
this.setAnterior_lon(anterior.getLongitud());
this.setAnterior_ignicion(anterior.getIgnicion());
}
private boolean fromDB = false;
private int evento = 0; // Por tiempo, curva u otro
public Calendar getUTC() {
return utc;
}
public String getNow() {
return now;
}
public double getLatitud() {
return latitud;
}
public double getLongitud() {
return longitud;
}
public double getAltitud() {
return altitud;
}
public double getVelocidad() {
return velocidad;
}
public double getCOG() {
return cog;
}
public String getCOGtoString() {
String txtDireccion = "";
if ((this.cog >= 0) && (this.cog <= 5)) {
txtDireccion = "Norte";
} else if ((this.cog > 5) && (this.cog <= 85)) {
txtDireccion = "Noreste (NorOriente)";
}
else if ((this.cog > 85) && (this.cog <= 95)) {
txtDireccion = "Este (Oriente)";
} else if ((this.cog > 95) && (this.cog <= 175)) {
txtDireccion = "Sureste (SurOriente)";
}
else if ((this.cog > 175) && (this.cog <= 185)) {
txtDireccion = "Sur";
}
else if ((this.cog > 185) && (this.cog <= 265)) {
txtDireccion = "Suroeste (SurPoniente)";
} else if ((this.cog > 265) && (this.cog <= 275)) {
txtDireccion = "Oeste (Poniente)";
} else if ((this.cog > 275) && (this.cog <= 355)) {
txtDireccion = "Noroeste (NorPoniente)";
}
else if ((this.cog > 355) && (this.cog <= 360)) {
txtDireccion = "Norte";
}
return txtDireccion;
}
public double getNsat() {
return nsat;
}
public double getHdop() {
return hdop;
}
public double getAdc1() {
return adc1;
}
public double getAdc2() {
return adc2;
}
public double getBateria() {
return bateria;
}
public int getIgnicion() {
return ignicion;
}
public int getIo(int index) {
int io_array[] = { 0, this.io1, this.io2, this.io3, this.io4,this.panico };
return io_array[index];
}
public int getIo1() {
return io1;
}
public int getIo2() {
return io2;
}
public int getIo3() {
return io3;
}
public int getIo4() {
return io4;
}
public int getPower() {
return power;
}
public long getHorometro() {
return horometro;
}
public long getOdometro() {
return odometro;
}
public int getEvento() {
return evento;
}
public int getAntirobo() {
return antirobo;
}
public int getPanico() {
return panico;
}
public long getImei() {
return imei;
}
public long getDriverId() {
return driverId;
}
public boolean isValid() {
return valid;
}
public Calendar getLastupdate() {
return lastupdate;
}
public void setLastupdate(Calendar lastupdate) {
this.lastupdate = lastupdate;
}
public HazelCastobjGpsData() {
}
public HazelCastobjGpsData(final GpsData original) {
this.imei = original.getImei();
this.driverId = original.getDriverId();
this.panico = original.getPanico();
this.antirobo = original.getAntirobo();
this.ignicion = original.getIgnicion();
this.now = original.getNow();
this.ip = original.getIpaddress();
if (original.getDriverIdArray() != null
&& original.getDriverIdArray().length == 4) {
this.ibutton2 = original.getDriverIdArray()[1];
this.ibutton3 = original.getDriverIdArray()[2];
this.ibutton4 = original.getDriverIdArray()[3];
} else {
this.ibutton2 = -1;
this.ibutton3 = -1;
this.ibutton4 = -1;
}
if (original.getTimeCalendar() == null || !original.isFullProcessed()
|| original.isOnlyStatus()) {
this.valid = false;
Calendar fecha_gps = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
fecha_gps.setTimeInMillis(0);
this.utc = fecha_gps;
this.lastupdate = original.getLastUpdate();
} else {
this.utc = original.getTimeCalendar();
this.latitud = original.getLatitud();
this.longitud = original.getLongitud();
this.altitud = original.getAltitud();
this.velocidad = original.getVelocidad();
this.cog = original.getCOG();
this.nsat = original.getNSAT();
this.io1 = original.getIo1();
this.io2 = original.getIo2();
this.io3 = original.getIo3();
this.io4 = original.getIo4();
this.hdop = original.getHdop();
this.adc1 = original.getAdc();
this.adc2 = original.getAdc2();
this.power = original.getPower();
this.bateria = original.getBateria();
this.odometro = original.getOdometro();
this.horometro = original.getHorometro();
this.evento = original.getEvento();
this.setTrailerId(original.getTrailerId());
this.setTripTime(original.getTripTime());
this.setHorometroInterno(original.getHorometroInterno());
}
}
// Para INIT por BD
public HazelCastobjGpsData(final boolean fromDB, final long imei,
final String registro, final Calendar utc,
final Calendar lastupdate, final long driverid,
final double latitud, final double longitud, final double altitud,
final double velocidad, final double cog, final double nsat,
final double hdop, final double adc1, final double adc2,
final double adc3, final double adc4, final double bateria,
final int ignicion, final int io1, final int io2, final int io3,
final int io4, final int power, final int antirobo,
final int panico, final long odometro, final long horometro,
final int evento) {
this.imei = imei;
this.driverId = driverid;
this.panico = panico;
this.antirobo = antirobo;
this.ignicion = ignicion;
this.now = registro;
this.utc = utc;
this.lastupdate = lastupdate;
this.latitud = latitud;
this.longitud = longitud;
this.altitud = altitud;
this.velocidad = velocidad;
this.cog = cog;
this.nsat = nsat;
this.io1 = io1;
this.io2 = io2;
this.io3 = io3;
this.io4 = io4;
this.hdop = hdop;
this.adc1 = adc1;
this.adc2 = adc2;
this.adc3 = adc3;
this.adc4 = adc4;
this.power = power;
this.bateria = bateria;
this.horometro = horometro;
this.odometro = odometro;
this.setFromDB(fromDB);
}
#Override
public void readData(final DataInput arg0) throws IOException {
this.utc = Calendar.getInstance();
try {
this.utc.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(arg0.readUTF()));
} catch (ParseException e) {
ReqInit.logger.fatal(e.getMessage(), e);
}
this.lastupdate = Calendar.getInstance();
try {
this.lastupdate.setTime(new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS").parse(arg0.readUTF()));
} catch (ParseException e) {
ReqInit.logger.fatal(e.getMessage(), e);
}
this.now = arg0.readUTF();
this.latitud = arg0.readDouble();
this.longitud = arg0.readDouble();
this.altitud = arg0.readDouble();
this.velocidad = arg0.readDouble();
this.cog = arg0.readDouble();
this.nsat = arg0.readDouble();
this.hdop = arg0.readDouble();
this.adc1 = arg0.readDouble();
this.adc2 = arg0.readDouble();
this.adc3 = arg0.readDouble();
this.adc4 = arg0.readDouble();
this.bateria = arg0.readDouble();
this.ignicion = arg0.readInt();
this.io1 = arg0.readInt();
this.io2 = arg0.readInt();
this.io3 = arg0.readInt();
this.io4 = arg0.readInt();
this.power = arg0.readInt();
this.antirobo = arg0.readInt();
this.panico = arg0.readInt();
this.imei = arg0.readLong();
this.driverId = arg0.readLong();
this.valid = arg0.readBoolean();
this.odometro = arg0.readLong();
this.horometro = arg0.readLong();
this.evento = arg0.readInt();
this.ip = arg0.readUTF();
this.trailerId = arg0.readLong();
this.tripTime = arg0.readLong();
this.horometroInterno = arg0.readLong();
this.ibutton2 = arg0.readLong();
this.ibutton3 = arg0.readLong();
this.ibutton4 = arg0.readLong();
this.odometroInterno = arg0.readLong();
}
#Override
public void writeData(final DataOutput arg0) throws IOException {
arg0.writeUTF(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(utc.getTime()));
arg0.writeUTF(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(lastupdate.getTime()));
arg0.writeUTF(now);
arg0.writeDouble(latitud);
arg0.writeDouble(longitud);
arg0.writeDouble(altitud);
arg0.writeDouble(velocidad);
arg0.writeDouble(cog);
arg0.writeDouble(nsat);
arg0.writeDouble(hdop);
arg0.writeDouble(adc1);
arg0.writeDouble(adc2);
arg0.writeDouble(adc3);
arg0.writeDouble(adc4);
arg0.writeDouble(bateria);
arg0.writeInt(ignicion);
arg0.writeInt(io1);
arg0.writeInt(io2);
arg0.writeInt(io3);
arg0.writeInt(io4);
arg0.writeInt(power);
arg0.writeInt(antirobo);
arg0.writeInt(panico);
arg0.writeLong(imei);
arg0.writeLong(driverId);
arg0.writeBoolean(valid);
arg0.writeLong(odometro);
arg0.writeLong(horometro);
arg0.writeInt(evento);
arg0.writeUTF(ip);
arg0.writeLong(trailerId);
arg0.writeLong(tripTime);
arg0.writeLong(horometroInterno);
arg0.writeLong(ibutton2);
arg0.writeLong(ibutton3);
arg0.writeLong(ibutton4);
arg0.writeLong(odometroInterno);
}
public boolean isFromDB() {
return fromDB;
}
public void setFromDB(boolean fromDB) {
this.fromDB = fromDB;
}
public long getDeltaTime() {
return delta_time;
}
private void setDelta_time(long delta_time) {
this.delta_time = delta_time;
}
public double getAnteriorSog() {
return anterior_sog;
}
private void setAnterior_sog(double anterior_sog) {
this.anterior_sog = anterior_sog;
}
public double getAnterior_lon() {
return anterior_lon;
}
private void setAnterior_lon(double anterior_lon) {
this.anterior_lon = anterior_lon;
}
public double getAnterior_lat() {
return anterior_lat;
}
private void setAnterior_lat(double anterior_lat) {
this.anterior_lat = anterior_lat;
}
public double getAnteriorCog() {
return anterior_cog;
}
private void setAnterior_cog(double anterior_cog) {
this.anterior_cog = anterior_cog;
}
public double getAnteriorIgnicion() {
return anterior_ignicion;
}
private void setAnterior_ignicion(double anterior_ignicion) {
this.anterior_ignicion = anterior_ignicion;
}
public double getDeltaDist() {
return delta_dist;
}
private void setDelta_dist(double delta_dist) {
this.delta_dist = delta_dist;
}
public long getAnterior_odometro() {
return anterior_odometro;
}
public long getAnterior_horometro() {
return anterior_horometro;
}
public double getAdc3() {
return adc3;
}
public void setAdc3(double adc3) {
this.adc3 = adc3;
}
public double getAdc4() {
return adc4;
}
public void setAdc4(double adc4) {
this.adc4 = adc4;
}
public long getTrailerId() {
return trailerId;
}
public void setTrailerId(long trailerId) {
this.trailerId = trailerId;
}
public long getTripTime() {
return tripTime;
}
public void setTripTime(long tripTime) {
this.tripTime = tripTime;
}
public long getIbutton2() {
return ibutton2;
}
public void setIbutton2(long ibutton2) {
this.ibutton2 = ibutton2;
}
public long getIbutton3() {
return ibutton3;
}
public void setIbutton3(long ibutton3) {
this.ibutton3 = ibutton3;
}
public long getIbutton4() {
return ibutton4;
}
public void setIbutton4(long ibutton4) {
this.ibutton4 = ibutton4;
}
public long getOdometroInterno() {
return odometroInterno;
}
public void setOdometroInterno(long odometroInterno) {
this.odometroInterno = odometroInterno;
}
}
We are aware that we are using and older version of hazelcast but upgrade it is not an option yet, we want to know if there is a code issue first. Could you please help me to find the issue ?

Java security checking

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.

Using cyclic barrier does not wait till all threads finish

Here is what I am trying to do. I have a number of threads which should all wait at a common point before they proceed, so obvious solution is to use CyclicBarrier. But I want to also compute the total time taken by the threads to execute. I defined the following utility method in class ConcurrentExecutionActionTimer.
public static long elapsedTimeUsingCyclicBarrier(Executor executor, int concurrency, final Runnable action) throws InterruptedException
{
final Runnable barrierAction = new Runnable() {
#Override
public void run() {
System.out.println("Condition of barrier is met.");
}
};
final
CyclicBarrier barrier = new CyclicBarrier(concurrency, barrierAction);
final CountDownLatch done = new CountDownLatch(concurrency);
for(int i=0; i<concurrency; i++ ){
executor.execute(new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting at barrier.");
barrier.await();
action.run();
//Cyclic barrier gets reset automatically. Again wait for them to finish.
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} finally {
done.countDown();
}
}
});
}
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
}
Then I called it up like:
public static void main(String[] args) {
//Executor is replacement for common thread idiom: (new Thread(r)).start() to e.execute(r)
ExecutorService executor = Executors.newFixedThreadPool(10);
Worker action = new Worker();
int concurrency = 5;
try {
long elapsedTime = ConcurrentExecutionActionTimer.elapsedTimeUsingCyclicBarrier(executor, concurrency, action);
double seconds = (double)elapsedTime / 1000000000.0;
System.out.println("Time Taken approximately: " + seconds + "seconds.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Here Worker is suppose my thread that does some work. For example:
class Worker implements Runnable {
#Override
public void run() {
System.out.println("Doing work.");
for(int i=0; i<20; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
As I wanted to print the time taken I had to use CountDownLatch to make sure the control does not return back to main before all the threads are finished. Do we have any other way to make sure the same functionality?
You should use the same CyclicBarrier instance. The only difference is that you make the cyclic barrier count be #threads + 1. You can then use that barrier to calculate the time it took all of the threads to complete. The start time is calculated when the first barrier has been reached and the end time is calculated when the second barrier has been reached. This way you know approximately when all the threads have been started and when all of them have completed.
Therefore this:
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
becomes:
barrier.await()
long startNanoTime = System.nanoTime();
barrier.await();
return System.nanoTime() - startNanoTime;
import java.io.*;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
class BusLine {
private String destination;
protected static int max_seat, checkpoint;
private ArrayList<Bus> BUSA = new ArrayList<Bus>();
private ArrayList<Bus> BUSC = new ArrayList<Bus>();
private ArrayList<Group> GROUP_A = new ArrayList<Group>();
private ArrayList<Group> GROUP_C = new ArrayList<Group>();
public BusLine(int ms, int cp, String d) {
max_seat = ms;
checkpoint = cp;
destination = d;
}
public String getDestination() {
return destination;
}
public void printAirportCheckpoint() {
System.out.println();
System.out.printf("%s >> %d airport-bound buses have been allocated.", Thread.currentThread().getName(), BUSA.size());
}
public void printCityCheckpoint() {
System.out.println();
System.out.printf("%s >> %d city-bound buses have been allocated.", Thread.currentThread().getName(), BUSC.size());
System.out.println();
System.out.println();
}
public void BusBoundA() {
int temp = 0;
for (int i = 0; i < BUSA.size(); i++) {
if (BUSA.get(i).getName().equals("A" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== Airport Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "A" + i);
for (int j = 0; j < GROUP_A.size(); j++) {
if (GROUP_A.get(j).getBusname().equals("A" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_A.get(j).getName(), GROUP_A.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
public void BusBoundC() {
int temp = 0;
for (int i = 0; i < BUSC.size(); i++) {
if (BUSC.get(i).getName().equals("C" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== City Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "C" + i);
for (int j = 0; j < GROUP_C.size(); j++) {
if (GROUP_C.get(j).getBusname().equals("C" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_C.get(j).getName(), GROUP_C.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
synchronized public void allocateBus(Data d) {
TicketCounter T = (TicketCounter) (Thread.currentThread());
while (d.getSeat() != 0) {
if ("A".equals(d.getDestination())) {
if (BUSA.size() == 0 || BUSA.get(BUSA.size() - 1).getAvailableSeat() == 0) {
BUSA.add(new Bus("A" + BUSA.size()));
}
if (d.getSeat() <= BUSA.get(BUSA.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), d.getSeat()));
BUSA.get(BUSA.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSA.get(BUSA.size() - 1).getAvailableSeat());
BUSA.get(BUSA.size() - 1).Bookingseat(BUSA.get(BUSA.size() - 1).getAvailableSeat());
}
} else {
if (BUSC.size() == 0 || BUSC.get(BUSC.size() - 1).getAvailableSeat() == 0) {
BUSC.add(new Bus("C" + BUSC.size()));
}
if (d.getSeat() <= BUSC.get(BUSC.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), d.getSeat()));
BUSC.get(BUSC.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSC.get(BUSC.size() - 1).getAvailableSeat());
BUSC.get(BUSC.size() - 1).Bookingseat(BUSC.get(BUSC.size() - 1).getAvailableSeat());
}
}
}
}
}
class Group {
private String busname, name;
private int seat;
public Group(String n, String b, int s) {
busname = n;
name = b;
seat = s;
}
public String getName() { return name; }
public String getBusname() { return busname; }
public int getSeat() { return seat; }
}
class Bus {
private String Busname, group_name;
private int availableseat, seat;
public int getAvailableSeat() { return availableseat; }
public String getName() { return Busname; }
public void Bookingseat(int s) { availableseat -= s; }
public String getGroupname() { return group_name; }
public Bus(String n) {
availableseat = BusLine.max_seat;
Busname = n;
}
public Bus(String n, int s) {
group_name = n;
seat = s;
}
public Bus(String n, String gn, int s) {
Busname = n;
group_name = gn;
availableseat = s;
}
}
class Data {
private String name, destination;
private int seat, transaction, count = 0;
public int getCount() { return count; }
public int getTransaction() { return transaction; }
public String getName() { return name; }
public int getSeat() { return seat; }
public String getDestination() { return destination; }
public void finishedBooking(int s) { seat -= s; }
public Data(int t, String n, int s, String d) {
transaction = t;
name = n;
seat = s;
destination = d;
}
}
class TicketCounter extends Thread {
ArrayList<Data> transaction;
BusLine Airport, City;
private CyclicBarrier cfinish;
public void setCyclicBarrier(CyclicBarrier f) {
cfinish = f;
}
public TicketCounter(String n, ArrayList<Data> d, BusLine a, BusLine c) {
super(n);
transaction = d;
Airport = a;
City = c;
}
public void run() {
for (int i = 0; i < transaction.size(); i++) {
if (transaction.get(i).getTransaction() == BusLine.checkpoint) {
try {
cfinish.await();
cfinish.await();
} catch (Exception e) {}
}
if ("A".equals(transaction.get(i).getDestination())) {
Airport.allocateBus(transaction.get(i));
} else {
City.allocateBus(transaction.get(i));
}
}
}
}
class Userinput {
private ArrayList<Data> DATA1 = new ArrayList<Data>();
private ArrayList<Data> DATA2 = new ArrayList<Data>();
private ArrayList<Data> DATA3 = new ArrayList<Data>();
public Userinput() {}
public ArrayList<Data> getDATA1() { return DATA1; }
public ArrayList<Data> getDATA2() { return DATA2; }
public ArrayList<Data> getDATA3() { return DATA3; }
public void input() {
String infile[] = {"T1.txt", "T2.txt", "T3.txt"};
for (int i = 0; i < 3; i++) {
boolean opensuccess = false;
while (!opensuccess) {
try ( Scanner scanfile = new Scanner(new File(infile[i]));) {
while (scanfile.hasNext()) {
opensuccess = true;
String line = scanfile.nextLine();
String[] buf = line.split(",");
int transaction = Integer.parseInt(buf[0].trim());
String name = buf[1].trim();
int seat = Integer.parseInt(buf[2].trim());
String destination = buf[3].trim();
Data d = new Data(transaction, name, seat, destination);
switch (i) {
case 0: DATA1.add(d);
break;
case 1: DATA2.add(d);
break;
case 2: DATA3.add(d);
break;
}
}
} catch (FileNotFoundException e) {
System.out.println(e);
Scanner scan = new Scanner(System.in);
System.out.println("Enter new file name : ");
infile[i] = scan.nextLine();
}
}
}
}
}
public class Simulation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Thread Th = Thread.currentThread();
System.out.printf("%s >> Enter max seats = ", Th.getName());
System.out.println();
int max_seat = scan.nextInt();
System.out.printf("%s >> Enter checkpoints = ", Th.getName());
System.out.println();
int checkpoint = scan.nextInt();
Userinput U = new Userinput();
BusLine Airport = new BusLine(max_seat, checkpoint, "A");
BusLine City = new BusLine(max_seat, checkpoint, "C");
CyclicBarrier CB = new CyclicBarrier(4);
U.input();
TicketCounter[] T = {
new TicketCounter("T1", U.getDATA1(), Airport, City),
new TicketCounter("T2", U.getDATA2(), Airport, City),
new TicketCounter("T3", U.getDATA3(), Airport, City)};
for (int i = 0; i < 3; i++) {
T[i].setCyclicBarrier(CB);
T[i].start();
}
try {
CB.await();
Airport.printAirportCheckpoint();
City.printCityCheckpoint();
CB.await();
}catch (Exception e){}
for (int i = 0; i < 3; i++) {
try {
T[i].join();
} catch (Exception e) {
System.err.println(e);
}
}
Airport.BusBoundA();
City.BusBoundC();
}
}

How to determine File Format? DOS/Unix/MAC

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.

Categories

Resources