cannot find symbol: variable TestUtils - java

I have written a Java program that analyze .soft file of data on gene expressions and write it to txt
package il.ac.tau.cs.sw1.bioinformatics;
import org.apache.commons.math3.stat.inference.TestUtils;
import java.io.*;
import java.util.Arrays;
/**
*
* Gene Expression Analyzer
*
* Command line arguments:
* args[0] - GeoDatasetName: Gene expression dataset name (expects a corresponding
input file in SOFT format to exist in the local directory).
* args[1] - Label1: Label of the first sample subset
* args[2] - Label2: Label of the second sample subset
* args[3] - Alpha: T-test confidence level : only genes with pValue below this
threshold will be printed to output file
*
* Execution example: GeneExpressionAnalyzer GDS4085 "estrogen receptor-negative" "estrogen receptor-positive" 0.01
*
* #author software1-2014
*
*/
public class GeneExpressionAnalyzer {
public static void main(String args[]) throws IOException {
// Reads the dataset from a SOFT input file
String inputSoftFileName = args[0] + ".soft";
GeneExpressionDataset geneExpressionDataset = parseGeneExpressionFile (inputSoftFileName);
System.out.printf ("Gene expression dataset loaded from file %s. %n",inputSoftFileName);
System.out.printf("Dataset contains %d samples and %d gene probes.%n%n",geneExpressionDataset.samplesNumber, geneExpressionDataset.genesNumber);
// Writes the dataset to a tabular format
String tabularFileName = args[0] + "-Tabular.txt";
writeDatasetToTabularFile(geneExpressionDataset,tabularFileName);
System.out.printf ("Dataset saved to tabular file - %s.%n%n",tabularFileName);
// Identifies differentially expressed genes between two sample groups and writes the results to a text file
String label1 = args[1];
String label2 = args[2];
double alpha = Double.parseDouble(args[3]);
String diffGenesFileName = args[0] + "-DiffGenes.txt";
int numOfDiffGenes = writeTopDifferentiallyExpressedGenesToFile(diffGenesFileName,geneExpressionDataset, alpha, label1, label2);
System.out.printf ("%d differentially expressed genes identified using alpha of %f when comparing the two sample groups [%s] and [%s].%n",numOfDiffGenes, alpha, label1, label2);
System.out.printf ("Results saved to file %s.%n",diffGenesFileName);
}
private static float[] StringtoFloat(String[] temp) {
float[] array = new float[temp.length];
for (int i = 0; i < temp.length; i++){
array[i]= Float.parseFloat(temp[i]);
}
return array;
}
private static double[] CutToCounter(double[] array, int counter) {
if (array.length == counter){
return array;
}
double[] args = new double[counter+1];
for (int i = 0; i < args.length; i++){
args[i] = array[i];
}
return args;
}
private static int min(double[] pValues) {
double val = 2;
int index = -1;
for (int i = 0; i < pValues.length; i++){
if (pValues[i] < val && pValues[i] != 3.0){
val = pValues[i];
index = i;
}
}
return index;
}
private static String changeformat(float[] array) {
String[] args = new String[array.length];
for (int i = 0; i < array.length; i++){
args[i] = String.format("%.2f", array[i]);
}
return Arrays.toString(args);
}
/**
*
* parseGeneExpressionFile - parses the given SOFT file
*
*
* #param filename A gene expression file in SOFT format
* #return a GeneExpressionDataset object storing all data parsed from the input file
* #throws IOException
*/
public static GeneExpressionDataset parseGeneExpressionFile (String filename) throws IOException {
GeneExpressionDataset dataset = new GeneExpressionDataset();
BufferedReader buf = new BufferedReader(new FileReader(filename));
String line = buf.readLine();
String[] geneids = null;
String[] genesymbols = null;
float[][] datamatrix = null;
String[][] subsetinfo = new String[10][2];
String[][] subsetsample = new String[10][];
int i = 0;
int j = 0;
boolean bol = false;
while (line != null){
if (line.startsWith("!dataset_sample_count")){
dataset.samplesNumber = Integer.parseInt(line.substring(24));
}
else if (line.startsWith("!dataset_sample_count")){
dataset.genesNumber = Integer.parseInt(line.substring(25));
geneids = new String[dataset.genesNumber];
genesymbols = new String[dataset.genesNumber];
}
else if (line.startsWith("^SUBSET")){
subsetinfo[i][0] = line.substring(10);
i++;
}
else if (line.startsWith("!subset_sample_description")){
subsetinfo[i][1] = line.substring(22);
}
else if (line.startsWith("!subset_sample_id")){
subsetsample[i-1] = line.substring(20).split(",");
}
else if (line.startsWith("!dataset_table_begin")){
datamatrix = new float[dataset.genesNumber][dataset.samplesNumber];
}
else if (line.startsWith("ID_REF")){
String[] array1 = line.split("\t");
dataset.sampleIds = (String[]) Arrays.copyOfRange(array1, 2, array1.length);
bol = true;
}
else if (bol && !line.startsWith("!dataset_table_end")){
String[] array2 = line.split("\t");
geneids[j] = array2[0];
genesymbols[j] = array2[1];
String[] temp = (String[]) Arrays.copyOfRange(array2, 2, array2.length);
datamatrix[j] = StringtoFloat(temp);
j++;
}
}
buf.close();
dataset.geneIds = geneids;
dataset.geneSymbols = genesymbols;
dataset.dataMatrix = datamatrix;
String[] lables = new String[dataset.samplesNumber];
int k = 0;
for (String sample : dataset.sampleIds) {
for (int m = 0; m < subsetsample.length; m++) {
if (Arrays.binarySearch(subsetsample[m], sample) != -1) {
lables[k] = subsetsample[m][1];
k += 1;
} else {
continue;
}
}
}
dataset.labels = lables;
return dataset;
}
/**
* writeDatasetToTabularFile
* writes the dataset to a tabular text file
*
* #param geneExpressionDataset
* #param outputFilename
* #throws IOException
*/
public static void writeDatasetToTabularFile(GeneExpressionDataset geneExpressionDataset, String outputFilename) throws IOException {
File NewFile = new File(outputFilename);
BufferedWriter buf = new BufferedWriter(new FileWriter(NewFile));
String Lables = "\t" + "\t" + "\t" + "\t" + Arrays.toString(geneExpressionDataset.labels);
String Samples = "\t" + "\t" + "\t" + "\t" + Arrays.toString(geneExpressionDataset.sampleIds);
buf.write(Lables + "\r\n" + Samples + "\r\n");
for (int i = 0; i < geneExpressionDataset.genesNumber; i++){
buf.write(geneExpressionDataset.geneIds[i] + "\t"+ geneExpressionDataset.geneSymbols[i] + "\t" +
changeformat(geneExpressionDataset.dataMatrix[i]) + "\r\n");
}
buf.close();
}
/**
*
* writeTopDifferentiallyExpressedGenesToFile
*
* #param outputFilename
* #param geneExpressionDataset
* #param alpha
* #param label1
* #param label2
* #return numOfDiffGenes The number of differentially expressed genes detected, having p-value lower than alpha
* #throws IOException
*/
public static int writeTopDifferentiallyExpressedGenesToFile(String outputFilename,
GeneExpressionDataset geneExpressionDataset, double alpha,
String label1, String label2) throws IOException {
double pValues[] = new double[geneExpressionDataset.genesNumber];
int counter = 0;
for (int i = 0; i < pValues.length; i++){
double pval = calcTtest(geneExpressionDataset, i, label1, label2);
if (pval < alpha){
pValues[i] = pval;
counter++;
}
else{
continue;
}
}
File tofile = new File(outputFilename);
BufferedWriter buf = new BufferedWriter(new FileWriter(tofile));
int j = 0;
while (min(pValues) != -1){
String PVal = String.format("%.6f", pValues[min(pValues)]);
String gene_id = geneExpressionDataset.geneIds[min(pValues)];
String gene_symbol = geneExpressionDataset.geneSymbols[min(pValues)];
String line = String.valueOf(j) + "\t" + PVal + "\t" + gene_id + "\t" + gene_symbol;
buf.write(line + "\r\n");
pValues[min(pValues)] = 3.0;
j++;
}
buf.close();
return counter;
}
/**
*
* getDataEntriesForLabel
*
* Returns the entries in the 'data' array for which the corresponding entries in the 'labels' array equals 'label'
*
* #param data
* #param labels
* #param label
* #return
*/
public static double[] getDataEntriesForLabel(float[] data, String[] labels, String label) {
double[] array = new double[data.length];
int counter = 0;
for (int i = 0; i < data.length; i++){
if (labels[i].equals(label)){
array[counter] = data[i];
counter++;
}
else{
continue;
}
}return CutToCounter(array, counter);
}
/**
* calcTtest - returns a pValue for the t-Test
*
* Returns the p-value, associated with a two-sample, two-tailed t-test comparing the means of the input arrays
*
* //http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/stat/inference/TTest.html#tTest(double[], double[])
*
* #param geneExpressionDataset
* #param geneIndex
* #param label1
* #param label2
* #return
*/
private static double calcTtest(GeneExpressionDataset geneExpressionDataset, int geneIndex, String label1, String label2) {
double[] sample1 = getDataEntriesForLabel(geneExpressionDataset.dataMatrix[geneIndex], geneExpressionDataset.labels, label1);
double[] sample2 = getDataEntriesForLabel(geneExpressionDataset.dataMatrix[geneIndex], geneExpressionDataset.labels, label2);
return TestUtils.tTest(sample1, sample2);
}
/**
*
* GeneExpressionDataset
* A class representing a gene expression dataset
*
* #author software1-2014
*
*/
public static class GeneExpressionDataset {
public int samplesNumber; //number of dataset samples
public int genesNumber; // number of dataset gene probes
public String[] sampleIds; //sample ids
public String[] geneIds; //gene probe ids
public String[] geneSymbols; //gene symbols
public float[][] dataMatrix; //expression data matrix
public String[] labels; //sample labels
}
}
now, it won't compile and the error message is this:
"GeneExpressionAnalyzer.java:2: error: package org.apache.commons.math3.stat.inference does not exist
import org.apach.commons.math3.stat.interference.TestUtils;
GeneExpressionAnalyzer.java:277: error: cannot find symbol
return TestUtils.tTest;
symbol: variable TestUtils
location: class GeneExpressionAnalyzer
2 errors"
I don't get what went wrong, obviously i've added the .jar file that contains the path to TestUtils.
(here it is: http://apache.spd.co.il//commons/math/binaries/commons-math3-3.2-bin.zip)
any insights?

If you are working with eclipse,
Manually download the jar file from here
After that in eclipse open the package explorer -> right click on your project
Build Path -> Configure Build Path, A window will open.
Under the Libraries tab -> click Add External JARs. select the jar file you have downloaded Click Ok.
That's all. Now the problem might be gone

Does it work from the command line?
I've shortened your class to
import org.apache.commons.math3.stat.inference.TestUtils;
import java.io.*;
import java.util.Arrays;
public class Test {
public static void main(String args[]) throws IOException {
System.out.printf ("test...");
}
}
I copied the Test.java file and the commons-math3-3.2.jar to the same directory and here is my output from the command line:
C:\temp\test>dir
Répertoire de C:\temp\test
24/04/2014 14:41 <REP> .
24/04/2014 14:41 <REP> ..
24/04/2014 14:38 1 692 782 commons-math3-3.2.jar
24/04/2014 14:41 230 Test.java
2 fichier(s) 1 693 012 octets
2 Rép(s) 23 170 342 912 octets libres
C:\temp\test>javac Test.java
Test.java:1: package org.apache.commons.math3.stat.inference does not exist
import org.apache.commons.math3.stat.inference.TestUtils;
^
1 error
C:\temp\test>javac -cp commons-math3-3.2.jar Test.java
C:\temp\test>dir
Répertoire de C:\temp\test
24/04/2014 14:41 <REP> .
24/04/2014 14:41 <REP> ..
24/04/2014 14:38 1 692 782 commons-math3-3.2.jar
24/04/2014 14:41 500 Test.class
24/04/2014 14:41 230 Test.java

Related

How do I upload a file using the Java HttpServer API?

EDIT: I tried this using a multiple file upload, and I got 3 of 4 uploaded files, so it seems that the upload mechanism is only setting the offset too high for the first file.
I found a method for uploading files using the com.sun.net.httpserver library here, but it is not actually detecting any files from the form input. What it does is it finds the "starting point" of uploaded files, represented by List<Integer> offsets and then looks through the file to get bytes from it. The problem is that it sets each part of offsets as a number very close to the end of the form data, so nothing actually gets parsed. Here is my HttpHandler:
package app;
import com.sun.net.httpserver.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FormDataHandler implements HttpHandler {
#Override
public void handle(HttpExchange httpExchange) throws IOException {
Headers headers = httpExchange.getRequestHeaders();
String contentType = headers.getFirst("Content-Type");
if(contentType.startsWith("multipart/form-data")){
//found form data
String boundary = contentType.substring(contentType.indexOf("boundary=")+9);
// as of rfc7578 - prepend "\r\n--"
byte[] boundaryBytes = ("\r\n--" + boundary).getBytes(Charset.forName("UTF-8"));
byte[] payload = getInputAsBinary(httpExchange.getRequestBody());
ArrayList<MultiPart> list = new ArrayList<>();
List<Integer> offsets = searchBytes(payload, boundaryBytes, 0, payload.length - 1);
System.out.println(offsets);
for(int idx=0;idx<offsets.size();idx++){
int startPart = offsets.get(idx);
int endPart = payload.length;
if(idx<offsets.size()-1){
endPart = offsets.get(idx+1);
}
byte[] part = Arrays.copyOfRange(payload,startPart,endPart);
//look for header
int headerEnd = indexOf(part,"\r\n\r\n".getBytes(Charset.forName("UTF-8")),0,part.length-1);
/*This conditional is always false because headerEnd is not
found, due to part.length being to small, due to startPart
being too small, due to the current offset being to small*/
if(headerEnd>0) {
MultiPart p = new MultiPart();
byte[] head = Arrays.copyOfRange(part, 0, headerEnd);
String header = new String(head);
// extract name from header
int nameIndex = header.indexOf("\r\nContent-Disposition: form-data; name=");
if (nameIndex >= 0) {
int startMarker = nameIndex + 39;
//check for extra filename field
int fileNameStart = header.indexOf("; filename=");
if (fileNameStart >= 0) {
String filename = header.substring(fileNameStart + 11, header.indexOf("\r\n", fileNameStart));
p.filename = filename.replace('"', ' ').replace('\'', ' ').trim();
p.name = header.substring(startMarker, fileNameStart).replace('"', ' ').replace('\'', ' ').trim();
p.type = PartType.FILE;
} else {
int endMarker = header.indexOf("\r\n", startMarker);
if (endMarker == -1)
endMarker = header.length();
p.name = header.substring(startMarker, endMarker).replace('"', ' ').replace('\'', ' ').trim();
p.type = PartType.TEXT;
}
} else {
// skip entry if no name is found
continue;
}
// extract content type from header
int typeIndex = header.indexOf("\r\nContent-Type:");
if (typeIndex >= 0) {
int startMarker = typeIndex + 15;
int endMarker = header.indexOf("\r\n", startMarker);
if (endMarker == -1)
endMarker = header.length();
p.contentType = header.substring(startMarker, endMarker).trim();
}
//handle content
if (p.type == PartType.TEXT) {
//extract text value
byte[] body = Arrays.copyOfRange(part, headerEnd + 4, part.length);
p.value = new String(body);
} else {
//must be a file upload
p.bytes = Arrays.copyOfRange(part, headerEnd + 4, part.length);
}
list.add(p);
}
}
handle(httpExchange,list);
}else{
//if no form data is present, still call handle method
handle(httpExchange,null);
}
}
public void handle(HttpExchange he, List<MultiPart> parts) throws IOException {
OutputStream os = he.getResponseBody();
String response = "<h1>" + parts.size() + "</h1>";
he.sendResponseHeaders(200, response.length());
os.write(response.getBytes());
os.close();
}
public static byte[] getInputAsBinary(InputStream requestStream) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
byte[] buf = new byte[100000];
int bytesRead=0;
while ((bytesRead = requestStream.read(buf)) != -1){
//while (requestStream.available() > 0) {
// int i = requestStream.read(buf);
bos.write(buf, 0, bytesRead);
}
requestStream.close();
bos.close();
} catch (IOException e) {
}
return bos.toByteArray();
}
/**
* Search bytes in byte array returns indexes within this byte-array of all
* occurrences of the specified(search bytes) byte array in the specified
* range
* borrowed from https://github.com/riversun/finbin/blob/master/src/main/java/org/riversun/finbin/BinarySearcher.java
*
* #param srcBytes
* #param searchBytes
* #param searchStartIndex
* #param searchEndIndex
* #return result index list
*/
public List<Integer> searchBytes(byte[] srcBytes, byte[] searchBytes, int searchStartIndex, int searchEndIndex) {
final int destSize = searchBytes.length;
final List<Integer> positionIndexList = new ArrayList<Integer>();
int cursor = searchStartIndex;
while (cursor < searchEndIndex + 1) {
int index = indexOf(srcBytes, searchBytes, cursor, searchEndIndex);
if (index >= 0) {
positionIndexList.add(index);
cursor = index + destSize;
} else {
cursor++;
}
}
return positionIndexList;
}
/**
* Returns the index within this byte-array of the first occurrence of the
* specified(search bytes) byte array.<br>
* Starting the search at the specified index, and end at the specified
* index.
* borrowed from https://github.com/riversun/finbin/blob/master/src/main/java/org/riversun/finbin/BinarySearcher.java
*
* #param srcBytes
* #param searchBytes
* #param startIndex
* #param endIndex
* #return
*/
public int indexOf(byte[] srcBytes, byte[] searchBytes, int startIndex, int endIndex) {
if (searchBytes.length == 0 || (endIndex - startIndex + 1) < searchBytes.length) {
return -1;
}
int maxScanStartPosIdx = srcBytes.length - searchBytes.length;
final int loopEndIdx;
if (endIndex < maxScanStartPosIdx) {
loopEndIdx = endIndex;
} else {
loopEndIdx = maxScanStartPosIdx;
}
int lastScanIdx = -1;
label: // goto label
for (int i = startIndex; i <= loopEndIdx; i++) {
for (int j = 0; j < searchBytes.length; j++) {
if (srcBytes[i + j] != searchBytes[j]) {
continue label;
}
lastScanIdx = i + j;
}
if (endIndex < lastScanIdx || lastScanIdx - i + 1 < searchBytes.length) {
// it becomes more than the last index
// or less than the number of search bytes
return -1;
}
return i;
}
return -1;
}
public static class MultiPart {
public PartType type;
public String contentType;
public String name;
public String filename;
public String value;
public byte[] bytes;
}
public enum PartType{
TEXT,FILE
}
}
And here is my form:
<form action="http://localhost:8080/upl" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Does anybody know why this won't work? If not, is there a better option for HttpServer file uploads? I tried the Apache Commons API, but that didn't work either.

Problem with Abstract ArrayList and counting elements

I want to get a little help with a school assignment. I have a method that isn't acting the way I thought it would. I'm pretty sure the problem is in nlpClassify(), but I'm not entirely sure. Currently, clpClassify() will only print out 0s for the variables. Any suggestions are welcome.
public class TweetHandler implements TweetHandlerInterface {
private Scanner inFile = null;
private String tweet = null;
private String[] temp = null;
private int counter = 0;
List<AbstractTweet> tweetList = new ArrayList<AbstractTweet>();
List<AbstractTweet> dataList = new ArrayList<AbstractTweet>();
List<String[]> dataBaseList = new ArrayList<String[]>();
#Override
public List<AbstractTweet> loadTweetsFromText(String filePath) {
MainApp main = null;
try {
inFile = new Scanner ( new FileReader(filePath));
}
catch( FileNotFoundException er ){
System.err.println(er);
main.printMenu();
}
String line = null;
//String[] data = null;
//int counter = 0;
while ( inFile.hasNextLine() ) {
line = inFile.nextLine();
parseTweetLine(line);
counter++;
}
System.out.println("Reading tweets from file..."
+ "\n" + counter + " tweets read.");
inFile.close();
return tweetList;
}
#Override
public AbstractTweet parseTweetLine(String tweetLine) {
temp = tweetLine.split("\",\"");
tweet = temp[5];
if( temp.length > 6 ){
for( int i = 0; i < temp.length; i++ ){
tweet += " " + temp[i];
}
}
temp[0] = temp[0].replaceAll("\"","");
tweet = tweet.replaceAll("\\p{Punct}", "");
temp[5] = tweet;
int target = Integer.parseInt(temp[0]);
int id = Integer.parseInt(temp[1]);
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy");
Date date = new Date();
try{
date = format.parse(temp[2]);
}
catch( ParseException e ){
System.err.println("Error with date parsing. " + e);
}
String flag = temp[3];
String user = temp[4];
String text = temp[5];
Tweet tweets = new Tweet(target,id,date,flag,user,text);
return tweets;
}
/**
* calls classifyTweet
*/
public void nlpClassify(){ //prints out accuracy
System.out.println("Classifying tweets...");
counter = 0;
int correct = 0,
wrong = 0;
float accuracy = 0.0f;
AbstractTweet tweets;
for( int i = 0; i < tweetList.size(); i++ ){
tweets = tweetList.get(i);
tweets.setPredictedPolarity(classifyTweet(tweets));
int target = tweets.getTarget();
int polarity = tweets.getPredictedPolarity();
System.out.println("Target: " + target );
System.out.println("Prediction: " + polarity );
for( int j = 0; j < 75; j++ ){
System.out.print("=");
}
System.out.println();
if( target == polarity ){
correct++;
}
else{
wrong++;
}
counter++;
accuracy = ( correct / counter ) * 100.0f;
}
System.out.println( "Classified " + counter + " tweets." );
System.out.println( "Correct tweets: " + correct );
System.out.println( "Wrong tweets: " + wrong );
System.out.println( "Accuracy: " + accuracy );
}
#Override
public int classifyTweet(AbstractTweet tweet) {
int calcPolarity = SentimentAnalyzer.getParagraphSentiment( tweet.getText() );
tweet.setPredictedPolarity(calcPolarity);
return calcPolarity;
}
#Override
public void addTweetsToDB(List<AbstractTweet> tweets) {
System.out.println("Adding files to database... ");
int i = 0;
while( i < tweets.size()){
dataList.add(tweets.get(i));
i++;
}
}
#Override
public void deleteTweet(int id) {
int i = 0,
temp = 0;
Tweet obj = null;
while( i < dataList.size() ){
temp = obj.getId();
if( id == temp ){
dataList.remove(i);
--counter;
}
++i;
}
}
#Override
public void saveSerialDB() {
try{
FileOutputStream fileOut = new FileOutputStream("DB.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(dataList);
out.close();
fileOut.close();
}
catch( IOException e ){
e.printStackTrace();
}
}
#Override
public void loadSerialDB() {
try{
FileInputStream fileIn = new FileInputStream("DB.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
dataList = (List<AbstractTweet>)in.readObject();
in.close();
fileIn.close();
}
catch( Exception e ){
e.printStackTrace();
}
}
#Override
public List<AbstractTweet> searchByUser(String user) {
int i = 0;
String temp = null;
Tweet obj = null;
while( i < dataList.size() ){
temp = obj.getUser();
if( user.equals(temp) )
dataList.add(obj);
++i;
}
return dataList;
}
Ignore searchByUser(String user), I know it's wrong and haven't gotten around to fixing it. If you have suggestions for it, that's cool too.
Here is the interface.
public interface TweetHandlerInterface {
/**
* Loads tweets from a CSV text file.
* #param filePath The path to the CSV file.
* #return A list of tweets as objects.
*/
List<AbstractTweet> loadTweetsFromText(String filePath);
/**
* Parses a single line from the CSV file and returns a tweet as an object.
* #param tweetLine A string containing the contents of a single line in the CSV file.
* #return A tweet as an object.
*/
AbstractTweet parseTweetLine(String tweetLine);
/**
* Classifies a tweet as negative, neutral, or positive by using the text of the tweet.
* #param tweet A tweet object.
* #return 0 = negative, 2 = neutral, 4 = positive.
*/
int classifyTweet(AbstractTweet tweet);
/**
* Adds a list of new tweets to the existing database.
* #param tweets A list of tweet objects.
*/
void addTweetsToDB(List<AbstractTweet> tweets);
/**
* It deletes ad tweet from the database, given its id.
* #param id The id value of the tweet.
*/
void deleteTweet(int id);
/**
* Saves the database in the working directory as a serialized object.
*/
void saveSerialDB();
/**
* Loads tweet database.
*/
void loadSerialDB();
/**
* Searches the tweet database by user name. It returns a list of all tweets
* matching the given user name.
* #param user The user name to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByUser(String user);
/**
* Searches the tweet database for tweets posted on a given date.
* #param date The date to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByDate(Date date);
/**
* Searches the tweet database for tweets matching a given flag.
* #param flag The flag to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByFlag(String flag);
/**
* Searches the tweet database for tweets matching a given substring.
* #param substring The substring to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchBySubstring(String substring);
}
Here is my Main().
public class MainApp {
public static void main (String[] args){
TweetHandler handler = new TweetHandler();
MainApp obj = new MainApp();
Tweet tweetObj = null;
String choice;
do{
obj.printMenu();
System.out.print("Enter a choice from above: ");
Scanner inputConsole = new Scanner( System.in );
choice = inputConsole.next();
String filePath = null;
switch( choice ){
case "0":
System.exit(0);
break;
case "1":
Scanner file = new Scanner ( System.in );
System.out.print("Enter the input file path: ");
filePath = file.nextLine();
handler.loadTweetsFromText(filePath);
break;
case "2":
handler.classifyTweet(handler.parseTweetLine(filePath));
handler.nlpClassify();
break;
case "3":
System.out.println("Enter ID of the tweet you wish to change: ");
break;
case "4":
System.out.println("Adding tweets to database...");
handler.addTweetsToDB(handler.loadTweetsFromText(filePath));
break;
case "5":
Scanner removeChoice = new Scanner( System.in );
System.out.println("Enter ID of tweet you wish to delete: ");
int remove = removeChoice.nextInt();
handler.deleteTweet(remove);
break;
case "6":
Scanner searching = new Scanner( System.in );
System.out.println("Search by: 1 User, 2 Date, 3 Flag, 4 Substring.");
int search = searching.nextInt();
switch(search){
case 1:
case 2:
case 3:
case 4:
}
break;
}
} while ( !"0".equals(choice) );
}
void printMenu(){
System.out.println("0. Exit program.\n"
+ "1. Load new tweet text file.\n"
+ "2. Classify tweets using NLP library and report accuracy.\n"
+ "3. Manually change tweet class label.\n"
+ "4. Add new tweets to database.\n"
+ "5. Delete tweet from database (given its id).\n"
+ "6. Search tweets by user, date, flag, or a matching substring.\n");
}
}
You loop for with tweetList.size(). You can print out tweetList.size() to see the value. I guess it's 0. I didn't see any tweetList.add(obj) in your code. So tweetList is empty all the time.

Split .srt file into equal chunks

I am new to this and i need to split Srt(subtitle file) into multiple chunks.
For example: if i have subtitle file of a video(60 minutes). Then the subtitle file should split into 6 subtitle files having each subtitle file of 10 minutes.
i.e 6 X 10 = 60 Minutes
Need to divide into 6 chunks irrespective of minutes.
Using these each subtitle time/duration, i have to split the video into same chunks.
I am trying this code, can u please help me out how can i calculate the time and divide into chunks,
I am able to achieve how many minutes of chuck i needed.But stuck in how to read upto that chunck minutes from source file and create a new file .Then how to start the next chunk from the next 10 minutes from the source file.
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
/**
* The class SyncSRTSubtitles reads a subtitles .SRT file and offsets all the
* timestamps with the same specific value in msec.
*
* The format of the .SRT file is like this:
*
* 123
* 00:11:23,456 --> 00:11:25,234
* subtitle #123 text here
*
*
* #author Sorinel CRISTESCU
*/
public class SyncSRTSubtitles {
/**
* Entry point in the program.
*
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
/* INPUT: offset value: negative = less (-) ... positive = more (+). */
long delta = (22 * 1000L + 000); /* msec */
/* INPUT: source & destination files */
String srcFileNm = "/Users/meh/Desktop/avatar.srt";
String destFileNm = "/Users/meh/Desktop/avatar1.srt";
/* offset algorithm: START */
File outFile = new File(destFileNm);
outFile.createNewFile();
FileWriter ofstream = new FileWriter(outFile);
BufferedWriter out = new BufferedWriter(ofstream);
/* Open the file that is the first command line parameter */
FileInputStream fstream = new FileInputStream(srcFileNm);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// List<String> doc = IOUtils.readLines(in, StandardCharsets.UTF_8);
String strEnd = null;
long diff = 0;
String line;
String startTS1;
try (Stream<String> lines = Files.lines(Paths.get(srcFileNm))) {
line = lines.skip(1).findFirst().get();
String[] atoms = line.split(" --> ");
startTS1 = atoms[0];
}
System.out.println("bolo:" +line);
System.out.println("startTS1:" +startTS1);
String startTS = null;
String endTS = null;
/* Read File Line By Line */
while ((strLine = br.readLine()) != null) {
String[] atoms = strLine.split(" --> ");
if (atoms.length == 1) {
//out.write(strLine + "\n");
}
else {
startTS = atoms[0];
endTS = atoms[1];
// out.write(offsetTime(startTS, delta) + " --> "
// + offsetTime(endTS, delta) + "\n");
strEnd = endTS;
}
}
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Date parsedendDate = dateFormat.parse(strEnd);
Date parsedStartDate = dateFormat.parse(startTS1);
diff = parsedendDate.getTime() - parsedStartDate.getTime();
} catch(Exception e) { //this generic but you can control another types of exception
// look the origin of excption
}
System.out.println("strEnd");
System.out.println(strEnd);
/* Close the input streams */
in.close();
out.close();
System.out.println(diff);
long diff1 =diff/6;
System.out.println(diff1);
long diff2= (diff1*6);
System.out.println(diff2);
System.out.println((diff / 3600000) + " hour/s " + (diff % 3600000) / 60000 + " minutes");
System.out.println((diff1 / 3600000) + " hour/s " + (diff1 % 3600000) / 60000 + " minutes");
System.out.println((diff2 / 3600000) + " hour/s " + (diff2 % 3600000) / 60000 + " minutes");
/* offset algorithm: END */
System.out.println("DONE! Check the rsult oin the file: " + destFileNm);
}
/**
* Computes the timestamp offset.
*
* #param ts
* String value of the timestamp in format: "hh:MM:ss,mmm"
* #param delta
* long value of the offset in msec (positive or negative).
* #return String with the new timestamp representation.
*/
private static String offsetTime(String ts, long delta) {
long tsMsec = 0;
String atoms[] = ts.split("\\,");
if (atoms.length == 2) {
tsMsec += Integer.parseInt(atoms[1]);
}
atoms = atoms[0].split(":");
tsMsec += Integer.parseInt(atoms[2]) * 1000L; /* seconds */
tsMsec += Integer.parseInt(atoms[1]) * 60000L; /* minutes */
tsMsec += Integer.parseInt(atoms[0]) * 3600000L; /* hours */
tsMsec += delta; /* here we do the offset. */
long h = tsMsec / 3600000L;
System.out.println(h);
String result = get2digit(h, 2) + ":";
System.out.println(result);
long r = tsMsec % 3600000L;
System.out.println(r);
long m = r / 60000L;
System.out.println(m);
result += get2digit(m, 2) + ":";
System.out.println(result);
r = r % 60000L;
System.out.println(r);
long s = r / 1000L;
result += get2digit(s, 2) + ",";
result += get2digit(r % 1000L, 3);
System.out.println(result);
return result;
}
/**
* Gets the string representation of the number, adding the prefix '0' to
* have the required length.
*
* #param n
* long number to convert to string.
* #param digits
* int number of digits required.
* #return String with the required length string (3 for digits = 3 -->
* "003")
*/
private static String get2digit(long n, int digits) {
String result = "" + n;
while (result.length() < digits) {
result = "0" + result;
}
return result;
}
}
Please suggest me how can i achieve this?
You will need to parse the file twice:
once to read the last end time
second time to process all lines and
generate output files.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class SplitSRTFiles {
/**
* Splits a SRT file in multiple files each containing an equal time duration.
* #param args
* [0] number of wanted chunks
* [1] source file name
* #throws IOException
*/
public static void main(String[] args) throws IOException {
int nrOfChunks = Integer.parseInt(args[0]);
File srtFile = new File(args[1]);
System.out.println("Splitting "+srtFile.getAbsolutePath()+" into "+nrOfChunks+" files.");
List<String> srcLines = FileUtils.readLines(srtFile);
long fileEndTime = lastEndTime(srcLines);
long msecsPerChunkFile = fileEndTime / nrOfChunks;
int destFileCounter = 1;
String[] fileNameParts = srtFile.getName().split("\\.");
File outFile = new File(fileNameParts[0] + destFileCounter + "." + fileNameParts[1]);
System.out.println("Writing to "+outFile.getAbsolutePath());
outFile.createNewFile();
FileWriter ofstream = new FileWriter(outFile);
BufferedWriter out = new BufferedWriter(ofstream);
for (String line : srcLines) {
String[] atoms = line.split(" --> ");
if (atoms.length > 1) {
long startTS = toMSec(atoms[0]);
// check if start time of this subtitle is after the current
// chunk
if (startTS > msecsPerChunkFile * destFileCounter) {
// close existing file ...
out.close();
ofstream.close();
// ... and start a new file
destFileCounter++;
outFile = new File(srtFile.getParent(), fileNameParts[0] + destFileCounter + "." + fileNameParts[1]);
System.out.println("Writing to "+outFile.getAbsolutePath());
outFile.createNewFile();
ofstream = new FileWriter(outFile);
out = new BufferedWriter(ofstream);
}
}
out.write(line + "/n");
}
out.close();
ofstream.close();
System.out.println("Done.");
}
/**
* Calculates the time in msec of the end time of the last subtitle of the
* file
*
* #param lines
* read from file
* #return end time in milliseconds of the last subtitle
*/
public static long lastEndTime(List lines) throws IOException {
String endTS = null;
for (String line : lines) {
String[] atoms = line.split(" --> ");
if (atoms.length > 1) {
endTS = atoms[1];
}
}
return endTS == null ? 0L : toMSec(endTS);
}
public static long toMSec(String time) {
long tsMsec = 0;
String atoms[] = time.split("\\,");
if (atoms.length == 2) {
tsMsec += Integer.parseInt(atoms[1]);
}
atoms = atoms[0].split(":");
tsMsec += Integer.parseInt(atoms[2]) * 1000L; /* seconds */
tsMsec += Integer.parseInt(atoms[1]) * 60000L; /* minutes */
tsMsec += Integer.parseInt(atoms[0]) * 3600000L; /* hours */
return tsMsec;
}
}
I have figured out a way to divide the file into chunks,
public static void main(String args[]) throws IOException {
String FilePath = "/Users/meh/Desktop/escapeplan.srt";
FileInputStream fin = new FileInputStream(FilePath);
System.out.println("size: " +fin.getChannel().size());
long abc = 0l;
abc = (fin.getChannel().size())/3;
System.out.println("6: " +abc);
System.out.println("abc: " +abc);
//FilePath = args[1];
File filename = new File(FilePath);
long splitFileSize = 0,bytefileSize=0;
if (filename.exists()) {
try {
//bytefileSize = Long.parseLong(args[2]);
splitFileSize = abc;
Splitme spObj = new Splitme();
spObj.split(FilePath, (long) splitFileSize);
spObj = null;
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("File Not Found....");
}
}
public void split(String FilePath, long splitlen) {
long leninfile = 0, leng = 0;
int count = 1, data;
try {
File filename = new File(FilePath);
InputStream infile = new BufferedInputStream(new FileInputStream(filename));
data = infile.read();
System.out.println("data");
System.out.println(data);
while (data != -1) {
filename = new File("/Users/meh/Documents/srt" + count + ".srt");
//RandomAccessFile outfile = new RandomAccessFile(filename, "rw");
OutputStream outfile = new BufferedOutputStream(new FileOutputStream(filename));
while (data != -1 && leng < splitlen) {
outfile.write(data);
leng++;
data = infile.read();
}
leninfile += leng;
leng = 0;
outfile.close();
changeTimeStamp(filename, count);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
}

I am trying to write the result of the dql queries into a separate CSV file using dfc coding.

i have attached screen shot of the resultant CSV file
I am trying to write the result of the dql queries into a separate CSV file using dfc coding. but the result of the first record is printing twice in the resultant sheet.
public class ChkGroupExistence {
/**
* #param args
*/
private static Properties queryProp;
//private static Properties configProp;
IDfSession sess = null;
public ChkGroupExistence() {
System.out.println("Loading Properties..");
LoadProps loadProp = LoadProps.getInstance();
queryProp = loadProp.getQueryProp();
//configProp = loadProp.getConfigProp();
List<String> proj_list = new ArrayList<String>();
List<String> grp_list = new ArrayList<String>();
List<String> acl_list = new ArrayList<String>();
HashMap<String, String> projList_Map = new HashMap<String, String>();
IDfCollection projId_coll = null;
IDfCollection grp_coll = null;
//IDfCollection chk_coll = null;
//IDfCollection acl_coll = null;
String grpqry = null;
String chkqry = null;
//String getACLQuery = null;
int j=0;
CreateSession ifcDocsDfSession = new CreateSession();
try {
sess = ifcDocsDfSession.getSession();
DfLogger.info(this, "Session Created ::" + sess.getSessionId(),
null, null);
} catch (DfException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String qry = queryProp
.getProperty(IdocsConstants.PROJECT_ID);
try {
CSVWriter csvwriter=new CSVWriter(new FileWriter(new File("C:\\WBG\\IFCTools\\cs_log.csv")));
projId_coll = Util.executeQuery(sess, qry, IDfQuery.READ_QUERY);
while (projId_coll.next()) {
proj_list.add(projId_coll.getString("project_id"));
}
System.out.println("List of Project ::"+proj_list.size());
String tempQuery=queryProp.getProperty(IdocsConstants.P_GROUP_EXIST);
//String tempQuery1=queryProp.getProperty(IdocsConstants.P_GROUP_VERIFY);
//String tempQuery2 = queryProp.getProperty(IdocsConstants.P_GETACL);
List<String[]> csvList=new ArrayList<String[]>();
List<String[]> titleList = new ArrayList<String[]>();
String[] projList;
String[] titleString;
titleString = new String[3];
titleString[0]="ProjectId/Institutionnbr";
titleString[1]="GroupName";
titleString[2]="ACL Name";
titleList.add(titleString);
csvwriter.writeAll(titleList);
for(int i = 0; i <proj_list.size();i++ ) {
//grpqry = tempQuery+proj_list.get(i) + "_ed_off_grp'" ;
grpqry = MessageFormat.format(tempQuery,proj_list.get(i));
//chkqry = queryProp.getProperty(IdocsConstants.P_GROUP_VERIFY);
//System.out.println(grpqry);
//getACLQuery = MessageFormat.format(tempQuery2, proj_list.get(i));
//System.out.println(getACLQuery);
//System.out.println("grp_coll query is executing....");
grp_coll = Util.executeQuery(sess, grpqry, IDfQuery.READ_QUERY);
//System.out.println("verification query is executing.....");
//chk_coll = Util.executeQuery(sess, chkqry, IDfQuery.READ_QUERY);
//acl_coll = Util.executeQuery(sess, getACLQuery, IDfQuery.READ_QUERY);
if (grp_coll!=null && grp_coll.next()) {
String grpName = grp_coll.getString("group_name");
grp_list.add(grpName);
System.out.println("Got group for "+proj_list.get(i)+" :: "+grpName);
projList=new String[3];
projList[0]=proj_list.get(i);
projList[1]=grpName;
//System.out.println(grpName);
projList_Map.put(proj_list.get(i),grp_list.get(j));
j++;
System.out.println(projList_Map.size());
if(chkqry == null){
//System.out.println("group names are adding to the list.....");
//grp_list.add(grpName);
String acl_name = queryProp.getProperty(IdocsConstants.P_GETACL);
acl_list.add(acl_name);
projList[2]=acl_name;
}
csvList.add(projList);
csvwriter.writeAll(csvList);
}
}
System.out.println("Project List is loading....");
Set<String> keySet = projList_Map.keySet();
System.out.println(grp_list);
System.out.println(acl_list);
for(String set : keySet) {
System.out.println(set + " : " +projList_Map.get(set));
}
csvwriter.close();
} catch (DfException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
ChkGroupExistence chkexist = new ChkGroupExistence();
}
}
CSVWriter.java
public class CSVWriter {
/**
* Default Delimiter will be used if not given.
*/
private static final char DEF_DELIM = ',';
/**
* Default Quote Character will be used if not given.
*/
private static final char DEF_QUOTE_CHAR = '"';
/**
* Default End of Line Character.
*/
private static final char DEFAULT_EOL = '\n';
/**
* Contains the Delimtter.
*/
private char delimiter;
/**
* Contains the Quote character.
*/
private char quotechar;
/**
* String contains the End of the line character.
*/
private char cLineEnd;
/**
* Instance Variable to hold Write Object.
*/
private Writer rawWriter;
/**
* Instance variable to hold PrintWriter object
*/
private PrintWriter pw;
/**
* Constructor to take File Writer as Input.
*
* #param writer
* File Writer
*/
public CSVWriter(Writer writer) {
this(writer, DEF_DELIM);
}
/**
* Constructor to take File Writer and Delimiter as Input.
*
* #param writer
* File Writer
* #param delim
* Delimiter
*/
public CSVWriter(Writer writer, char delim) {
this(writer, delim, DEF_QUOTE_CHAR);
}
/**
* Constructor to take File Writer, Delimiter and Quote Character as Input.
*
* #param writer
* File Writer
* #param delim
* Delimiter
* #param quote
* Quote Character
*/
public CSVWriter(Writer writer, char delim, char quote) {
this(writer, delim, quote, DEFAULT_EOL);
}
/**
* Constructor to take File Writer, Delimiter, Quote Character and End of
* Line feed as Input.
*
* #param writer
* File Writer
* #param delim
* Delimiter
* #param quote
* #param sEOL
*/
public CSVWriter(Writer writer, char delim, char quote, char sEOL) {
rawWriter = writer;
pw = new PrintWriter(writer);
delimiter = delim;
quotechar = quote;
cLineEnd = sEOL;
}
/**
* Method takes List as input and writes values into the CSV file.
*
* #param list
* List of Cell values.
*/
public void writeAll(List list) {
String sRow[];
for (Iterator iter = list.iterator(); iter.hasNext(); writeNext(sRow)) {
sRow = (String[]) iter.next();
}
}
/**
* Method that takes String[] as input and writes each and every cell.
*
* #param sRow
* String[]
*/
private void writeNext(String sRow[]) {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < sRow.length; i++) {
if (i != 0) {
stringbuffer.append(delimiter);
}
String s = sRow[i];
if (s == null) {
continue;
}
if (quotechar != 0) {
stringbuffer.append(quotechar);
}
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if (c == quotechar) {
stringbuffer.append(DEF_QUOTE_CHAR).append(c);
continue;
}
if (c == DEF_QUOTE_CHAR) {
stringbuffer.append(DEF_QUOTE_CHAR).append(c);
} else {
stringbuffer.append(c);
}
}
if (quotechar != 0) {
stringbuffer.append(quotechar);
}
}
stringbuffer.append(cLineEnd);
pw.write(stringbuffer.toString());
}
/**
* Method that closed the Print Writer. Only when this method is called, the
* CSV file will be saved.
*
* #throws IOException
*/
public void close() throws IOException {
pw.flush();
pw.close();
rawWriter.close();
}
Probably because you're including a repeating attribute in your query.
Tip: I tend to include the object ID for reference and debugging when I do this.
You can also insert a "DISTINCT" keyword into your query when including these repeating attributes.
The reason they act like this is the nature of the data model: all repeating attributes are stored in the same table - so when one of these attributes contains multiple values a query could return multiple rows when querying another repeating attribute. In this case a SELECT DISTINCT would do the trick.
You can also play around with the DQL hint ENABLE(ROW_BASED) if you are joining repeating attribute with single value attributes.
Happy coding!

Wordsearch puzzle nullpointerexception on array

Am getting a java.lang.NullPointerException on an array I have initialized and I can't quite figure it out what am doing wrong. The error is occuring at line 371.
Below is the code of the parent class followed by the class initializng the letterArray ArrayList:
package wordsearch;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/**
* Main class of Puzzle Program
* #author mungaialex
*
*/
public class WordSearchPuzzle extends JFrame {
private static final long serialVersionUID = 1L;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
static JButton[][] grid; //names the grid of buttons
GridLayout myGridLayout = new GridLayout(1,2,3,3);
/**Array to hold wordList*/
ArrayList<String> wordList;
JButton btnCheck, btnClear;
/** Panel to hold Components to the left*/
JPanel leftSidePanel;
/** Panel to hold components to the right*/
JPanel rightSidePanel;
/**Panel to hold word List*/
JPanel wordListPanel;
/**Panel to hold grid buttons*/
JPanel gridPanel;
/**Panel to hold clear button and check button*/
JPanel buttonsPanel;
/**Panel to hold output textarea*/
JPanel bottomPanel;
private JLabel[] wordListComponents;
#SuppressWarnings("rawtypes")
List puzzleLines;
//Grid Size
private final int ROWS = 20;
private final int COLS = 20;
/** Output Area of system*/
private JTextArea txtOutput;
/**Scrollpane for Output area*/
private JScrollPane scptxtOutput;
private Object[] theWords;
public String wordFromChars = new String();
/** the matrix of the letters */
private char[][] letterArray = null;
/**
* Constructor for WordSearchPuzzle
* #param wordListFile File Containing words to Search for
* #param wordSearhPuzzleFile File Containing the puzzle
*/
public WordSearchPuzzle(String wordSearchFile,String wordsListFile) throws IOException {
FileIO io = new FileIO(wordSearchFile,wordsListFile,grid);
wordList = io.loadWordList();
theWords = wordList.toArray();
addComponentsToPane();
buildWordListPanel();
buildBottomPanel();
io.loadPuzleFromFile();
//Override System.out
PrintStream stream = new PrintStream(System.out) {
#Override
public void print(String s) {
txtOutput.append(s + "\n");
txtOutput.setCaretPosition(txtOutput.getText().length());
}
};
System.setOut(stream);
System.out.print("MESSAGES");
}
/**
* Constructor two
*/
public WordSearchPuzzle() {
}
/**
* Gets the whole word of buttons clicked
* #return
* Returns whole Word
*/
public String getSelectedWord() {
return wordFromChars;
}
/**
* Adds word lists to Panel on the left
*/
private void buildWordListPanel() {
leftSidePanel.setBackground(Color.WHITE);
// Build the word list
wordListComponents = new JLabel[wordList.size()];
wordListPanel = new JPanel(new GridLayout(25, 1));
wordListPanel.setBackground(Color.white);
//Loop through list of words
for (int i = 0; i < this.wordList.size(); i++) {
String word = this.wordList.get(i).toUpperCase();
wordListComponents[i] = new JLabel(word);
wordListComponents[i].setForeground(Color.BLUE);
wordListComponents[i].setHorizontalAlignment(SwingConstants.LEFT);
wordListPanel.add(wordListComponents[i]);
}
leftSidePanel.add(wordListPanel,BorderLayout.WEST);
}
/**
* Adds an output area to the bottom of
*/
private void buildBottomPanel() {
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
txtOutput = new JTextArea();
txtOutput.setEditable(false);
txtOutput.setRows(5);
scptxtOutput = new JScrollPane(txtOutput);
bottomPanel.add(txtOutput,BorderLayout.CENTER);
bottomPanel.add(scptxtOutput,BorderLayout.SOUTH);
rightSidePanel.add(bottomPanel,BorderLayout.CENTER);
}
/**
* Initialize Components
*/
public void addComponentsToPane() {
// buttonsPanel = new JPanel(new BorderLayout(3,5)); //Panel to hold Buttons
buttonsPanel = new JPanel(new GridLayout(3,1));
leftSidePanel = new JPanel(new BorderLayout());
rightSidePanel = new JPanel(new BorderLayout());
btnCheck = new JButton("Check Word");
btnCheck.setActionCommand("Check");
btnCheck.addActionListener(new ButtonClickListener());
btnClear = new JButton("Clear Selection");
btnClear.setActionCommand("Clear");
btnClear.addActionListener(new ButtonClickListener());
buttonsPanel.add(btnClear);//,BorderLayout.PAGE_START);
buttonsPanel.add(btnCheck);//,BorderLayout.PAGE_END);
leftSidePanel.add(buttonsPanel,BorderLayout.SOUTH);
this.getContentPane().add(leftSidePanel,BorderLayout.LINE_START);
gridPanel = new JPanel();
gridPanel.setLayout(myGridLayout);
myGridLayout.setRows(20);
myGridLayout.setColumns(20);
grid = new JButton[ROWS][COLS]; //allocate the size of grid
//theBoard = new char[ROWS][COLS];
for(int Row = 0; Row < grid.length; Row++){
for(int Column = 0; Column < grid[Row].length; Column++){
grid[Row][Column] = new JButton();//Row + 1 +", " + (Column + 1));
grid[Row][Column].setActionCommand(Row + "," + Column);
grid[Row][Column].setActionCommand("gridButton");
grid[Row][Column].addActionListener(new ButtonClickListener());
gridPanel.add(grid[Row][Column]);
}
}
rightSidePanel.add(gridPanel,BorderLayout.NORTH);
this.getContentPane().add(rightSidePanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
try {
if (args.length !=2) { //Make sure we have both the puzzle file and word list file
JOptionPane.showMessageDialog(null, "One or All Files are Missing");
} else { //Files Found
WordSearchPuzzle puzzle = new WordSearchPuzzle(args[0],args[1]);
puzzle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
puzzle.setSize(new Dimension(1215,740));
//Display the window.
puzzle.setLocationRelativeTo(null); // Center frame on screen
puzzle.setResizable(false); //Set the form as not resizable
puzzle.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public int solvePuzzle( ){
int matches = 0;
for( int r = 0; r < ROWS; r++ )
for( int c = 0; c < COLS; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
return matches;
}
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta ){
String charSequence = "";
int numMatches = 0;
int searchResult;
FileIO io = new FileIO();
charSequence += io.theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < ROWS && j < COLS;
i += rowDelta, j += colDelta )
{
charSequence += io.theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
{
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
}
}
return numMatches;
}
private static int prefixSearch( Object [ ] a, String x ) {
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
}
class ButtonClickListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = ((JButton)e.getSource()).getActionCommand();
if (command == "Clear") {
//Enable the buttons that have been disabled and not form a whole word
//JOptionPane.showMessageDialog(null, "Cooming Soon");
for (String word : wordList) {
System.out.print(word);
}
} else if (command == "Check") {
String selectedWord = getSelectedWord();
if (!selectedWord.equals("")){
System.out.print("Selected word is " + getSelectedWord());
//First check if selected word exits in wordList
if (ifExists(selectedWord)) {
if(searchWord(selectedWord)){
JOptionPane.showMessageDialog(null, "Success");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "[" + selectedWord + "] " +
"Does Not Belong to Word list");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "No Buttons on Grid have been clicked");
}
} else if (command == "gridButton") {
getSelectedCharacter(e);
((JButton)e.getSource()).setEnabled(false);
}
}
/**
* Gets the character of each button and concatenates each character to form a whole word
* #param e The button that received the Click Event
* #return Whole word
*/
private String getSelectedCharacter (ActionEvent e) {
String character;
character = ((JButton) e.getSource()).getText();
wordFromChars = wordFromChars + character;
return wordFromChars;
}
}
/**
* Checks if selected word is among in wordlist
* #param selectedWord
* #return The word to search for
*/
private boolean ifExists(String selectedWord) {
if (wordList.contains(selectedWord)) {
return true;
}
return false;
}
public boolean searchWord(String word) {
if (!wordList.contains(word)) {
return false;
}
//int index = wordList.indexOf(word);
Line2D.Double line = new Line2D.Double();
//System.out.print("LetterArray is " + letterArray.length);
for (int x = 0; x < letterArray.length; x++) {
for (int y = 0; y < letterArray[x].length; y++) {
// save start point
line.x1 = y; // (y + 1) * SCALE_INDEX_TO_XY;
line.y1 = x; // (x + 1) * SCALE_INDEX_TO_XY;
int pos = 0; // current letter position
if (letterArray[x][y] == word.charAt(pos)) {
// first letter correct -> check next
pos++;
if (pos >= word.length()) {
// word is only one letter long
// double abit = SCALE_INDEX_TO_XY / 3;
line.x2 = y; // (y + 1) * SCALE_INDEX_TO_XY + abit;
line.y2 = x; // (x + 1) * SCALE_INDEX_TO_XY + abit;
return true;
}
// prove surrounding letters:
int[] dirX = { 1, 1, 0, -1, -1, -1, 0, 1 };
int[] dirY = { 0, -1, -1, -1, 0, 1, 1, 1 };
for (int d = 0; d < dirX.length; d++) {
int dx = dirX[d];
int dy = dirY[d];
int cx = x + dx;
int cy = y + dy;
pos = 1; // may be greater if already search in another
// direction from this point
if (insideArray(cx, cy)) {
if (letterArray[cx][cy] == word.charAt(pos)) {
// 2 letters correct
// -> we've got the direction
pos++;
cx += dx;
cy += dy;
while (pos < word.length() && insideArray(cx, cy)
&& letterArray[cx][cy] == word.charAt(pos)) {
pos++;
cx += dx;
cy += dy;
}
if (pos == word.length()) {
// correct end if found
cx -= dx;
cy -= dy;
pos--;
}
if (insideArray(cx, cy) && letterArray[cx][cy] == word.charAt(pos)) {
// we've got the end point
line.x2 = cy; // (cy + 1) *
// SCALE_INDEX_TO_XY;
line.y2 = cx; // (cx + 1) *
// SCALE_INDEX_TO_XY;
/*
* System.out.println(letterArray[x][y] +
* " == " + word.charAt(0) + " (" + line.x1
* + "," + line.y1 + ") ->" + " (" + line.x2
* + "," + line.y2 + "); " + " [" + (line.x1
* / SCALE_INDEX_TO_XY) + "," + (line.y1 /
* SCALE_INDEX_TO_XY) + "] ->" + " [" +
* (line.x2 / SCALE_INDEX_TO_XY) + "." +
* (line.y2 / SCALE_INDEX_TO_XY) + "]; ");
*/
//result[index] = line;
// found
return true;
}
// else: try next occurence
}
}
}
}
}
}
return false;
}
private boolean insideArray(int x, int y) {
boolean insideX = (x >= 0 && x < letterArray.length);
boolean insideY = (y >= 0 && y < letterArray[0].length);
return (insideX && insideY);
}
public void init(char[][] letterArray) {
try {
for (int i = 0; i < letterArray.length; i++) {
for (int j = 0; j < letterArray[i].length; j++) {
char ch = letterArray[i][j];
if (ch >= 'a' && ch <= 'z') {
letterArray[i][j] = Character.toUpperCase(ch);
}
}
}
} catch (Exception e){
System.out.println(e.toString());
}
//System.out.println("It is " + letterArray.length);
this.letterArray = letterArray;
}
}
Here is class initializing the letterArray array:
package wordsearch;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
/**
* Reads wordlist file and puzzle file
* #author mungaialex
*
*/
public class FileIO {
String _puzzleFile, _wordListFile;
/**ArrayList to hold words*/
ArrayList<String> wordList;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
List puzzleLines;
JButton[][] _grid;
char theBoard[][];
private final int _rows = 20;
private final int _columns = 20;
WordSearchPuzzle pz = new WordSearchPuzzle();
/**
* Default Constructor
* #param puzzleFile
* #param wordListFile
*/
public FileIO(String puzzleFile, String wordListFile,JButton grid[][]){
_puzzleFile = new String(puzzleFile);
_wordListFile = new String(wordListFile);
_grid = pz.grid;
}
public FileIO() {
}
/**
* Reads word in the wordlist file and adds them to an array
* #param wordListFilename
* File Containing Words to Search For
* #throws IOException
*/
protected ArrayList<String> loadWordList()throws IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(_wordListFile));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != WORDLISTCOLS) {
JOptionPane.showMessageDialog(null, "Error: only one word per line allowed in the word list",
"WordSearch Puzzle: Invalid Format", row);//, JOptionPane.OK_CANCEL_OPTION);
//"Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok.toUpperCase());
line = reader.readLine();
row++;
}
reader.close();
return wordList;
}
/**
* Reads the puzzle file line by by line
* #param wordSearchFilename
* The file containing the puzzle
* #throws IOException
*/
protected void loadPuzleFromFile() throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(_puzzleFile));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
puzzleLines = new ArrayList<String>();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
sb.append(line);
sb.append('\n');
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
WordSearchPuzzle.grid[row][col].setText(tok);
pz.grid[row][col].setForeground(Color.BLACK);
pz.grid[row][col].setHorizontalAlignment(SwingConstants.CENTER);
puzzleLines.add(tok);
col++;
}
line = reader.readLine();
row++;
theBoard = new char[_rows][_columns];
Iterator itr = puzzleLines.iterator();
for( int r = 0; r < _rows; r++ )
{
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toUpperCase().toCharArray( );
}
}
String[] search = sb.toString().split("\n");
initLetterArray(search);
reader.close();
}
protected void initLetterArray(String[] letterLines) {
char[][] array = new char[letterLines.length][];
System.out.print("Letter Lines are " +letterLines.length );
for (int i = 0; i < letterLines.length; i++) {
letterLines[i] = letterLines[i].replace(" ", "").toUpperCase();
array[i] = letterLines[i].toCharArray();
}
System.out.print("Array inatoshana ivi " + array.length);
pz.init(array);
}
}
Thanks in advance.
Here it is!
char[][] array = new char[letterLines.length][];
You are only initializing one axis.
When you pass this array to init() and set this.letterArray = letterArray;, the letterArray is also not fully initialized.
Try adding a length to both axes:
char[][] array = new char[letterLines.length][LENGTH];
first you will handle the NullPoinetrException , the code is
if( letterArray != null){
for (int x = 0; x < letterArray.length; x++)
{
..........
............
}
}

Categories