SVM Predict reading datatest - java

I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}

It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now

Related

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

Audio merging using OpenSL ES Android

I am trying to record my vocals and then merge them with an audio file together using OPENSL ES Library. I found this GitHub sample called Native-Audio. It merges the two audios. But the background audio file is playing much faster than the actual rate in the final output.
Please use headphones to notice the difference.
Samples Links: Before and After
Also, it uses the files from the assets folder only. How can I manually select MP3 files from file manager?
private void mixAudio(){
try {
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) ||
!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED))
{
// Show rationale and request permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
1000);
}
else {
buttonMix.setEnabled(false);
buttonMix.setText("MIXING....");
textViewMixPath.setText("");
buttonPlay.setEnabled(false);
buttonRecord.setEnabled(false);
buttonStart.setEnabled(false);
listView.setEnabled(false);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
//File file = new File(baseDir + "/mix.wav");
String path = Environment.getExternalStorageDirectory().getPath() + "/VocalRecorder";
File fileParent = new File(path);
if (!fileParent.exists()){
fileParent.mkdir();
}
final File file = new File(fileParent.getPath() + "/mix.wav");
//String author = getApplicationContext().getPackageName() + ".provider";
//Uri videoUri = FileProvider.get(this, author, mediaFile);
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//MediaMuxer muxer = new MediaMuxer(file.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
String beat = beats[selectedBeat];
//beat = beat.replace(".wav", ".mp3");
AssetFileDescriptor afd = getAssets().openFd(beat);
MediaCodec codec = null;
//ByteBuffer outputBuffer;
//short[] data; // data for the AudioTrack playback
//int outputBufferIndex = -1;
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
final long duration = Long.parseLong(durationStr);
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
// right now I am pointing to a URI but I have tested that both will
// play the media file using MediaPlayer
int sampleRate = 0;
int numChannels = 0;
int dstIndex = -1;
int numTracks = extractor.getTrackCount(); //This says 1
for (int i = 0; i < numTracks; ++i) { // so this will just run once
MediaFormat format = extractor.getTrackFormat(i); // getting info so it looks good so far
String mime = format.getString(MediaFormat.KEY_MIME); // "audio/mpeg"
if (mime.startsWith("audio/")) {
extractor.selectTrack(i);
codec = MediaCodec.createDecoderByType(mime);
codec.configure(format, null, null, 0);
//format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AMR_NB);
//dstIndex = muxer.addTrack(format);
//writer.setFrameRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
//writer.setSamplesPerFrame(format.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
//writer.setBitsPerSample(16);
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
break;
}
}
// Calculate the number of frames required for specified duration
long numFrames = (long)(duration * sampleRate/1000);
// Create a wav file with the name specified as the first argument
WavFile wavFile = WavFile.newWavFile(file, numChannels, numFrames, 16, sampleRate);
if (codec == null) {
throw new IllegalArgumentException("No decoder for file format");
}
//ByteBuffer[] inputBuffers = decoder.getInputBuffers();
//ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
/*
Boolean eosReceived = false;
while (!eosReceived) {
int inIndex = decoder.dequeueInputBuffer(1000);
if (inIndex >= 0) {
ByteBuffer buffer = decoder.getInputBuffer(inIndex);
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
// We shouldn't stop the playback at this point, just pass the EOS
// flag to mDecoder, we will get it again from the
// dequeueOutputBuffer
Log.d("DecodeActivity", "InputBuffer BUFFER_FLAG_END_OF_STREAM");
decoder.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
} else {
decoder.queueInputBuffer(inIndex, 0, sampleSize, extractor.getSampleTime(), 0);
extractor.advance();
}
int outIndex = decoder.dequeueOutputBuffer(info, 1000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
Log.d("DecodeActivity", "INFO_OUTPUT_BUFFERS_CHANGED");
//outputBuffers = decoder.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
MediaFormat format = decoder.getOutputFormat();
Log.d("DecodeActivity", "New format " + format);
//audioTrack.setPlaybackRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
Log.d("DecodeActivity", "dequeueOutputBuffer timed out!");
break;
default:
ByteBuffer outBuffer = decoder.getOutputBuffer(outIndex);
Log.v("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + outBuffer);
final byte[] chunk = new byte[info.size];
outBuffer.get(chunk); // Read the buffer all at once
outBuffer.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
//audioTrack.write(chunk, info.offset, info.offset + info.size); // AudioTrack write data
decoder.releaseOutputBuffer(outIndex, false);
break;
}
// All decoded frames have been rendered, we can stop playing now
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d("DecodeActivity", "OutputBuffer BUFFER_FLAG_END_OF_STREAM");
break;
}
}
}
*/
short recordedData[] = recordedData();
int recordMixStartIndex = -1;
//muxer.start();
codec.start();
Boolean sawInputEOS = false;
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
MediaCodec.BufferInfo infoMux = new MediaCodec.BufferInfo();
int count = 0;
while (!sawInputEOS) {
int inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_US);
Log.i(LOG_TAG, "inputBufIndex : " + inputBufIndex);
if (inputBufIndex >= 0) {
ByteBuffer dstBuf = codec.getInputBuffer(inputBufIndex);
int sampleSize = extractor.readSampleData(dstBuf, 0);
Log.i(LOG_TAG, "sampleSize : " + sampleSize);
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.i(LOG_TAG, "Saw input end of stream!");
sawInputEOS = true;
sampleSize = 0;
} else {
presentationTimeUs = extractor.getSampleTime();
Log.i(LOG_TAG, "presentationTimeUs " + presentationTimeUs);
}
codec.queueInputBuffer(inputBufIndex,
0, //offset
sampleSize,
presentationTimeUs,
sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!sawInputEOS) {
Log.i(LOG_TAG, "extractor.advance()");
extractor.advance();
}
}
final int res = codec.dequeueOutputBuffer(info, TIMEOUT_US);
if (res >= 0) {
int outputBufIndex = res;
ByteBuffer buf = codec.getOutputBuffer(outputBufIndex);
//final byte[] chunk = new byte[info.size];
//buf.get(chunk); // Read the buffer all at once
short[] shortArray = new short[info.size/2];
buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortArray);
buf.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
if (shortArray.length > 0) {
//mAudioTrack.write(chunk, 0, chunk.length);
//infoMux.presentationTimeUs = info.presentationTimeUs;
//infoMux.flags = info.flags;
//muxer.writeSampleData(dstIndex, ByteBuffer.wrap(chunk),
// infoMux);
long []longData = new long[shortArray.length];
// Merge data with vocal
// Calculate the time
final long bufferTimer = info.presentationTimeUs/1000;
int vocalCount = 0;
for (int i = 0; i < shortArray.length; i ++) {
//writer.writeShortLittle(shortArray[i]);
long offsetTime = i*1000/(sampleRate*2); // 2 channels
Boolean mixed = false;
if ((offsetTime + bufferTimer > recordStartTime) && (offsetTime + bufferTimer <= recordStopTime + 500)){
if (recordMixStartIndex == -1){
recordMixStartIndex = 0;
}
if (recordMixStartIndex < recordedData.length){
//Log.i("TAG", "############ mix record data: " + recordMixStartIndex);
longData[i] = TPMixSamples((int)(recordedData[recordMixStartIndex]), (int)shortArray[i]/3);
if (vocalCount >= 3) {
recordMixStartIndex++;
vocalCount = 0;
}
else{
vocalCount ++;
}
mixed = true;
}
}
else {
// All done, set sawInputEOS to stop mixing
if (bufferTimer > recordStopTime + 500){
sawInputEOS = true;
}
}
if (!mixed) {
longData[i] = shortArray[i];
}
}
Log.i("TAG", "############ write frames: " + longData.length/2);
wavFile.writeFrames(longData, longData.length/2);
count ++;
if (count % 5 == 0){
runOnUiThread(new Runnable() {
#Override
public void run() {
long percent = bufferTimer*100/duration;
buttonMix.setText("MIXING..." + percent + "%");
}
});
}
}
codec.releaseOutputBuffer(outputBufIndex, false /* render */);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
sawInputEOS = true;
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
//codecOutputBuffers = codec.getOutputBuffers();
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
final MediaFormat oformat = codec.getOutputFormat();
Log.d(LOG_TAG, "Output format has changed to " + oformat);
//mAudioTrack.setPlaybackRate(oformat.getInteger(MediaFormat.KEY_SAMPLE_RATE));
}
}
// Close the wavFile
wavFile.close();
// muxer.stop();
// muxer.release();
codec.stop();
codec.release();
extractor.release();
runOnUiThread(new Runnable() {
#Override
public void run() {
buttonMix.setText("MIX DONE");
buttonPlay.setEnabled(true);
buttonRecord.setEnabled(true);
textViewMixPath.setText(file.getPath());
buttonStart.setEnabled(true);
listView.setEnabled(true);
}
});
}
catch (Exception e){
}
}
});
thread.start();
}
}
catch (Exception e){
e.printStackTrace();
}
}
private final int INT16_MIN = - 32768;
private final int INT16_MAX = 32767;
private long TPMixSamples(int a, int b) {
if (a > INT16_MAX) {a = INT16_MAX;}
if (a < INT16_MIN) {a = INT16_MIN;}
return
// If both samples are negative, mixed signal must have an amplitude between the lesser of A and B, and the minimum permissible negative amplitude
a < 0 && b < 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MIN) :
// If both samples are positive, mixed signal must have an amplitude between the greater of A and B, and the maximum permissible positive amplitude
( a > 0 && b > 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MAX)
// If samples are on opposite sides of the 0-crossing, mixed signal should reflect that samples cancel each other out somewhat
:
a + b);
}
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native void createBufferQueueAudioPlayer(int sampleRate, int samplesPerBuf);
/////
public static native boolean createAssetAudioPlayer(AssetManager assetManager, String filename);
// true == PLAYING, false == PAUSED
public static native void setPlayingAssetAudioPlayer(boolean isPlaying);
public static native int getDurationAssetAudioPlayer();
public static native int getCurrentPositionAssetAudioPlayer();
//////
public static native boolean createUriAudioPlayer(String uri);
public static native void setPlayingUriAudioPlayer(boolean isPlaying);
public static native void setLoopingUriAudioPlayer(boolean isLooping);
public static native void setChannelMuteUriAudioPlayer(int chan, boolean mute);
public static native void setChannelSoloUriAudioPlayer(int chan, boolean solo);
public static native int getNumChannelsUriAudioPlayer();
public static native void setVolumeUriAudioPlayer(int millibel);
public static native void setMuteUriAudioPlayer(boolean mute);
public static native void enableStereoPositionUriAudioPlayer(boolean enable);
public static native void setStereoPositionUriAudioPlayer(int permille);
public static native boolean selectClip(int which, int count);
public static native void stopClip();
public static native boolean enableReverb(boolean enabled);
public static native boolean createAudioRecorder();
public static native void startRecording();
public static native void stopRecording();
public static native void pauseRecording();
public static native void resumeRecording();
public static native short[] recordedData();
public static native double recordedDuration();
public static native void shutdown();
/** Load jni .so on initialization */
static {
System.loadLibrary("native-audio-jni");
}

Tiny GP output in text file

I've recently stumbled upon Tiny GP (A Genetic Programming program), and I found it pretty useful, so I decided to change all System.out.println() in the program to a write to text file method.
Problem: In the text file, for some reason, only says "PROBLEM SOLVED", instead of printing out generations and other things that it is supposed to (see code).
Tiny GP modified class file:
package main;
/*
* Program: tiny_gp.java
*
* Author: Riccardo Poli (email: rpoli#essex.ac.uk)
*
* Modified by Preston Tang
*/
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class tiny_gp {
String Name;
double[] fitness;
char[][] pop;
static Random rd = new Random();
static final int ADD = 110,
SUB = 111,
MUL = 112,
DIV = 113,
FSET_START = ADD,
FSET_END = DIV;
static double[] x = new double[FSET_START];
static double minrandom, maxrandom;
static char[] program;
static int PC;
static int varnumber, fitnesscases, randomnumber;
static double fbestpop = 0.0, favgpop = 0.0;
static long seed;
static double avg_len;
static final int MAX_LEN = 10000,
POPSIZE = 100000,
DEPTH = 5,
GENERATIONS = 100,
TSIZE = 2;
public static final double PMUT_PER_NODE = 0.05,
CROSSOVER_PROB = 0.9;
public static double[][] targets;
public double run() {
/* Interpreter */
char primitive = program[PC++];
if (primitive < FSET_START) {
return (x[primitive]);
}
switch (primitive) {
case ADD:
return (run() + run());
case SUB:
return (run() - run());
case MUL:
return (run() * run());
case DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001) {
return (num);
} else {
return (num / den);
}
}
}
return (0.0); // should never get here
}
public int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_START) {
return (++buffercount);
}
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
public void setup_fitness(String fname) {
try {
int i, j;
String line;
BufferedReader in
= new BufferedReader(
new FileReader(fname));
line = in.readLine();
StringTokenizer tokens = new StringTokenizer(line);
varnumber = Integer.parseInt(tokens.nextToken().trim());
randomnumber = Integer.parseInt(tokens.nextToken().trim());
minrandom = Double.parseDouble(tokens.nextToken().trim());
maxrandom = Double.parseDouble(tokens.nextToken().trim());
fitnesscases = Integer.parseInt(tokens.nextToken().trim());
targets = new double[fitnesscases][varnumber + 1];
if (varnumber + randomnumber >= FSET_START) {
Write("too many variables and constants");
//System.out.println("too many variables and constants");
}
for (i = 0; i < fitnesscases; i++) {
line = in.readLine();
tokens = new StringTokenizer(line);
for (j = 0; j <= varnumber; j++) {
targets[i][j] = Double.parseDouble(tokens.nextToken().trim());
}
}
in.close();
} catch (FileNotFoundException e) {
Write("ERROR: Please provide a data file");
//System.out.println("ERROR: Please provide a data file");
System.exit(0);
} catch (Exception e) {
Write("ERROR: Incorrect data format");
//System.out.println("ERROR: Incorrect data format");
System.exit(0);
}
}
public double fitness_function(char[] Prog) {
int i = 0, len;
double result, fit = 0.0;
len = traverse(Prog, 0);
for (i = 0; i < fitnesscases; i++) {
for (int j = 0; j < varnumber; j++) {
x[j] = targets[i][j];
}
program = Prog;
PC = 0;
result = run();
fit += Math.abs(result - targets[i][varnumber]);
}
return (-fit);
}
public int grow(char[] buffer, int pos, int max, int depth) {
char prim = (char) rd.nextInt(2);
int one_child;
if (pos >= max) {
return (-1);
}
if (pos == 0) {
prim = 1;
}
if (prim == 0 || depth == 0) {
prim = (char) rd.nextInt(varnumber + randomnumber);
buffer[pos] = prim;
return (pos + 1);
} else {
prim = (char) (rd.nextInt(FSET_END - FSET_START + 1) + FSET_START);
switch (prim) {
case ADD:
case SUB:
case MUL:
case DIV:
buffer[pos] = prim;
one_child = grow(buffer, pos + 1, max, depth - 1);
if (one_child < 0) {
return (-1);
}
return (grow(buffer, one_child, max, depth - 1));
}
}
return (0); // should never get here
}
public int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_START) {
if (buffer[buffercounter] < varnumber) {
Write("X" + (buffer[buffercounter] + 1) + " ");
//System.out.print("X" + (buffer[buffercounter] + 1) + " ");
} else {
WriteDouble(x[buffer[buffercounter]]);
//System.out.print(x[buffer[buffercounter]]);
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" + ");
//System.out.print(" + ");
break;
case SUB:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" - ");
//System.out.print(" - ");
break;
case MUL:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" * ");
//System.out.print(" * ");
break;
case DIV:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" / ");
//System.out.print(" / ");
break;
}
a2 = print_indiv(buffer, a1);
Write(")");
//System.out.print(")");
return (a2);
}
public static char[] buffer = new char[MAX_LEN];
public char[] create_random_indiv(int depth) {
char[] ind;
int len;
len = grow(buffer, 0, MAX_LEN, depth);
while (len < 0) {
len = grow(buffer, 0, MAX_LEN, depth);
}
ind = new char[len];
System.arraycopy(buffer, 0, ind, 0, len);
return (ind);
}
public char[][] create_random_pop(int n, int depth, double[] fitness) {
char[][] pop = new char[n][];
int i;
for (i = 0; i < n; i++) {
pop[i] = create_random_indiv(depth);
fitness[i] = fitness_function(pop[i]);
}
return (pop);
}
public void stats(double[] fitness, char[][] pop, int gen) {
int i, best = rd.nextInt(POPSIZE);
int node_count = 0;
fbestpop = fitness[best];
favgpop = 0.0;
for (i = 0; i < POPSIZE; i++) {
node_count += traverse(pop[i], 0);
favgpop += fitness[i];
if (fitness[i] > fbestpop) {
best = i;
fbestpop = fitness[i];
}
}
avg_len = (double) node_count / POPSIZE;
favgpop /= POPSIZE;
Write("Generation=" + gen + " Avg Fitness=" + (-favgpop)
+ " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
+ "\nBest Individual: ");
//System.out.print("Generation=" + gen + " Avg Fitness=" + (-favgpop)
// + " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
// + "\nBest Individual: ");
print_indiv(pop[best], 0);
Write("\n");
//System.out.print("\n");
//System.out.flush();
}
public int tournament(double[] fitness, int tsize) {
int best = rd.nextInt(POPSIZE), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] > fbest) {
fbest = fitness[competitor];
best = competitor;
}
}
return (best);
}
public int negative_tournament(double[] fitness, int tsize) {
int worst = rd.nextInt(POPSIZE), i, competitor;
double fworst = 1e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] < fworst) {
fworst = fitness[competitor];
worst = competitor;
}
}
return (worst);
}
public char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = rd.nextInt(len1);
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start,
(xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring,
xo1start + (xo2end - xo2start),
(len1 - xo1end));
return (offspring);
}
public char[] mutation(char[] parent, double pmut) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < FSET_START) {
parentcopy[mutsite] = (char) rd.nextInt(varnumber + randomnumber);
} else {
switch (parentcopy[mutsite]) {
case ADD:
case SUB:
case MUL:
case DIV:
parentcopy[mutsite]
= (char) (rd.nextInt(FSET_END - FSET_START + 1)
+ FSET_START);
}
}
}
}
return (parentcopy);
}
public void print_parms() {
Write("-- TINY GP (Java version) --\n");
//System.out.print("-- TINY GP (Java version) --\n");
Write("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
+ "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
+ "\nCROSSOVER_PROB=" + CROSSOVER_PROB
+ "\nPMUT_PER_NODE=" + PMUT_PER_NODE
+ "\nMIN_RANDOM=" + minrandom
+ "\nMAX_RANDOM=" + maxrandom
+ "\nGENERATIONS=" + GENERATIONS
+ "\nTSIZE=" + TSIZE
+ "\n----------------------------------\n");
// System.out.print("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
// + "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
// + "\nCROSSOVER_PROB=" + CROSSOVER_PROB
// + "\nPMUT_PER_NODE=" + PMUT_PER_NODE
// + "\nMIN_RANDOM=" + minrandom
// + "\nMAX_RANDOM=" + maxrandom
// + "\nGENERATIONS=" + GENERATIONS
// + "\nTSIZE=" + TSIZE
// + "\n----------------------------------\n");
}
public tiny_gp(String fname, long s) {
fitness = new double[POPSIZE];
seed = s;
if (seed >= 0) {
rd.setSeed(seed);
}
setup_fitness(fname);
for (int i = 0; i < FSET_START; i++) {
x[i] = (maxrandom - minrandom) * rd.nextDouble() + minrandom;
}
pop = create_random_pop(POPSIZE, DEPTH, fitness);
}
public void evolve() {
int gen = 0, indivs, offspring, parent1, parent2, parent;
double newfit;
char[] newind;
print_parms();
stats(fitness, pop, 0);
for (gen = 1; gen < GENERATIONS; gen++) {
if (fbestpop > -1e-5) {
Write("PROBLEM SOLVED\n");
//System.out.print("PROBLEM SOLVED\n");
System.exit(0);
}
for (indivs = 0; indivs < POPSIZE; indivs++) {
if (rd.nextDouble() < CROSSOVER_PROB) {
parent1 = tournament(fitness, TSIZE);
parent2 = tournament(fitness, TSIZE);
newind = crossover(pop[parent1], pop[parent2]);
} else {
parent = tournament(fitness, TSIZE);
newind = mutation(pop[parent], PMUT_PER_NODE);
}
newfit = fitness_function(newind);
offspring = negative_tournament(fitness, TSIZE);
pop[offspring] = newind;
fitness[offspring] = newfit;
}
stats(fitness, pop, gen);
}
Write("PROBLEM *NOT* SOLVED\n");
//System.out.print("PROBLEM *NOT* SOLVED\n");
System.exit(1);
}
public void Write(String context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(context);
}
} catch (IOException ex) {
}
}
public void WriteDouble(double context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String ncontext = Double.toString(context);
bufferedWriter.write(ncontext);
}
} catch (IOException ex) {
}
}
};
The Functions Mapper file that uses the Tiny GP class file:
package function_mapper;
import javax.swing.JOptionPane;
import main.*;
public class Function_Mapper {
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog(null, "File Name", "Input Dialog", JOptionPane.INFORMATION_MESSAGE);
long s = -1;
if (args.length == 2) {
s = Integer.valueOf(args[0]).intValue();
fname = args[1];
}
if (args.length == 1) {
fname = args[0];
}
tiny_gp gp = new tiny_gp(fname, s);
gp.evolve();
}
}
Much help appreciated, thanks!
The Write method overwrites the contents of the file on each invocation. There are two ways to fix this.
An easier one, is to append file, instead of overwriting it. It could be achieved by passing append argument to the FileWriter (I simplified code a little bit along the way).
// true on the next line means "append"
try (Writer writer = new FileWriter("GP.txt", true)) {
writer.write(Double.toString(context));
} catch (IOException ex) {
}
A harder, but much fore efficient one is to openwriter in the constructor, use it in Write method, and close in the specially introduced close method of the tiny_gp.

Java - Reading files into array

I want to save a library for a small scale java application which stores technical manuals. Right now I am able to save the library to an external file but I am unable to load it back into the library itself, currently "-1" just gets printed to the console.
How can I solve this?
Here is my code:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
int x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
} else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
Here is also my library class:
package library;
import java.util.ArrayList;
public class Library {
public static int ManualChoice;
static String returnManualTitle;
static String status1 = "Available";
static String status2 = "Borrowed";
public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();
static void addManual(){
Manual newManual = new Manual();
newManual.createManual();
ManualList.add(newManual);
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Manual added to library!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
static void displayManualList(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
for (int i = 0; i < ManualList.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(ManualList.get(i).displayManual());
System.out.println("---------------------------------------------------------\n");
}
}
}
static void displayBorrowedManuals(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
for (int i = 0; i < borrowedManuals.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(borrowedManuals.get(i).displayManual());
System.out.println("---------------------------------------------------------");
}
}
}
public static void borrowManual(){
displayManualList();
ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));
borrowLoop:
while(Menu.menuChoice == 3){
if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice)){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n Manual borrowed!\n");
System.out.println("--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice){
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n "
+ " The Manual you wish to borrow is already on loan.");
System.out.println("\n--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualChoice > ManualList.size()-1){
System.out.println(Messages.noSuchManualMessage);
break borrowLoop;
}
if(ManualList.size() > 1){
displayManualList();
}
else if(ManualList.size() == 1){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
System.out.println("Please return the Manual within two weeks!\n");
displayManualList();
}
}
Menu.displayMenu();
}
static void returnManual(){
System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");
if(borrowedManuals.size() > 0){
for (int i = 0; i < borrowedManuals.size(); i++)
System.out.println(borrowedManuals.get(i).displayManual());
returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
}
int x = 0;
boolean serialExistance = false;
while (x < ManualList.size()){
if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle)){
ManualList.get(x).status = "Available";
ManualList.get(x).borrower = "N/A";
ManualList.get(x).borrowDate = "N/A";
ManualList.get(x).returnDate = "N/A";
int p = 0;
while (p < borrowedManuals.size()) {
Manual borrowed = borrowedManuals.get(p);
if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) {
borrowedManuals.remove(p);
break;
}
p++;
}
System.out.println(Messages.successReturnMessage);
serialExistance = true;
break;
}
x = x+1;
}
if(serialExistance == false){
boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
+"\n\nDo you want to try again? (Y/N):\n");
System.out.println("\n--------------------------------------------------------------------------");
if(repeatReturnManual){
returnManual();
}
}else if(serialExistance){
Menu.menuChoice = 8;
}
}
public static void removeManual(){
if(ManualList.size() >0){
displayManualList();
ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());
int p = 0;
while (p < borrowedManuals.size()){
if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle)){
borrowedManuals.remove(p);
}
}
ManualList.remove(ManualChoice);
System.out.print(Messages.successRemovedManualMessages);
Menu.menuChoice = 8;
}
}
static void emptyLibrary(){
System.out.println("\n WARNING!");
System.out.println("\n You have chosen to delete all Manuals in the library.\n");
System.out.println("--------------------------------------------------------------------------");
boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
System.out.println("\n--------------------------------------------------------------------------\n");
if(emptyLibraryChoice){
Library.ManualList.clear();
System.out.println(Messages.successEmptyLibraryMesssage);
System.out.println("--------------------------------------------------------------------------\n");
Menu.menuChoice = 8;
}
}
}
You are using ObjectInputStream not in the intended manner. The correct way would be like:
ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject(); // change Library to the type of object you are reading
System.out.println(x);
You probably need to change Library, but I could not find out, what type of object you are reading.

Encryption/Decryption in java

Hi i found some code after do some Google and i am using this code to Encrypt the string (witch i set as parameter in web-service)
and it's working fine, it's to hard for me to understand this code so put hole class.
public class RSA {
Vector<Object> vectEnc;
Object enc[];
private long P, Q;
private long N, M, E = 11;
private long D;
public RSA() {
P = 6151;
Q = 8807;
N = P * Q;
M = (P - 1) * (Q - 1);
E = 11;
D = 44310191;
vectEnc = new Vector<Object>();
}
public String doEncryption(String message) {
try {
String str = new BASE64Encoder().encode(message.getBytes("UTF-8"));
String encString = "";
for (int i = 0; i < str.length(); i += 3) {
String tempAsci = "1";
String tempStr;
for (int h = 0; h < 3; h++) {
int total = i + h;
if (total < str.length()) {
tempStr = String.valueOf((int) (str.subSequence(total,
total + 1).charAt(0)) - 30);
if (tempStr.length() < 2) {
tempStr = "0" + tempStr;
}
} else {
break;
}
tempAsci = tempAsci + tempStr;
}
vectEnc.add(tempAsci + "1");
}
enc = vectEnc.toArray();
vectEnc.removeAllElements();
for (int i = 0; i < enc.length; i++) {
long base = Long.parseLong(enc[i].toString());
long powMod = powMod(base, E, N);
encString = encString + String.valueOf(powMod) + " ";
}
return encString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String doDecryption(String codeMsg) {
String[] decryptArray = codeMsg.split(" ");
String decryptStr = "";
String originalStr = "";
for (int i = 0; i < decryptArray.length; i++) {
long base = Long.parseLong(decryptArray[i]);
long powMod = powMod(base, D, N);
String powModString = String.valueOf(powMod);
decryptStr = decryptStr
+ powModString.subSequence(1, powModString.length() - 1);
}
for (int i = 0; i < decryptStr.length(); i += 2) {
char ch = (char) (Integer.parseInt(decryptStr.subSequence(i, i + 2)
.toString()) + 30);
originalStr = originalStr + ch;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decBytes = null;
try {
decBytes = decoder.decodeBuffer(originalStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String decodeStr = new String(decBytes);
return decodeStr;
}
public long powMod(long base, long exp, long modula) {
long accum = 1;
int i = 0;
long base2 = base;
while ((exp >> i) > 0) {
if (((exp >> i) & 1) == 1) {
accum = mo((accum * base2), modula);
}
base2 = mo((base2 * base2), modula);
i++;
}
return accum;
}
public long mo(long g, long l) {
return (long) (g - (l * Math.floor(g / l)));
}
}
But the problem is when the String Length is more the 56 it throw the Exception Like
java.lang.NumberFormatException: For input string: "174-17-201"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.info.test.RSA.doEncryption(RSA.java:49)
at com.info.test.Test.main(Test.java:56)
i even no what is the algorithm is use by this code ,i do some Google and i found simple solution is make a part of string and do Encryption it Like this.
int MAX_LAN = 55;
List<String> splitEqually = splitEqually(string,MAX_LAN);
String encodeString = "";
for (int i = 0; i < splitEqually.size(); i++) {
encodeString +=rsa.doEncryption(splitEqually.get(i));
}
System.out.println(encodeString);
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
and it working fine , so is it proper method or not ??
I would strongly suggest using Java's built-in cryptographic libraries for this. Follow this series of articles on how to perform RSA encryption/decryption in Java:
http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml

Categories

Resources