Below is my code, I'm not understanding the cause of the "ECHONEST api 4 NULL pointer exception":
package com.main;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.echonest.api.v4.EchoNestAPI;
import com.echonest.api.v4.EchoNestException;
import com.echonest.api.v4.Track;
import com.echonest.api.v4.TrackAnalysis;
public class SongAnalysis {
private static final String API_KEY = "14CPBOK0IFN0HRC0R";
public String getTempo(String fileName){
return null;
}
public static void main (String [] args)throws EchoNestException, IOException{
EchoNestAPI echoNest = new EchoNestAPI(API_KEY);
File file = new File("C:\\Users\\wooh\\workspace\\SongAnalysis\\songs\\b.mp3");
Track track = echoNest.uploadTrack(file,false );
track.waitForAnalysis(30000);
TrackAnalysis a = track.getAnalysis();
System.out.println("Tempo" + a.getTempo());
}
}
The likely occurrences of your NPE are:
echoNest is null.
track is null.
a is null.
You would want to pinpoint the specific location that your NullPointerException occurs, then ensure that when you instantiate the object, the object you need is being returned.
Related
I am working on a project involving Hadoop and Mahout libraries. I have to use SequenceFile.Writer to write data to a file but I am getting a nullpointer exception when I am trying to use SequenceFile. To better understand my problem I have written a test code which is re-creating the problem and also the error message. I am also adding the code to generate the sample data.
Here first I am generating a sample data based on some distribution in the MyUtil class. Then passing the sample data to do canopy clustering(in the test Class) using Mahout's canopy clustering library. Then trying to write the centriods produced by the canopy clustering algorithm to a file using the SequenceFile.Writer. This is where I am getting the null pointer exception(When Creating the Sequence File Writer)
Thanks in advance for your help.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.mahout.clustering.canopy.Canopy;
import org.apache.mahout.clustering.canopy.CanopyClusterer;
import org.apache.mahout.clustering.canopy.CanopyDriver;
import org.apache.mahout.common.distance.EuclideanDistanceMeasure;
import org.apache.mahout.math.Vector;
public class Test {
public static void main(String[] args) throws IOException{
List<Vector> sampleData = new ArrayList<Vector>();
MyUtil.generateSamples(sampleData, 400, 1, 1, 2);
MyUtil.generateSamples(sampleData, 400, 1, 0, .5);
MyUtil.generateSamples(sampleData, 400, 0, 2, .1);
#SuppressWarnings("deprecation")
List<Canopy> canopies = CanopyClusterer.createCanopies(sampleData,
new EuclideanDistanceMeasure(), 3.0, 1.5);
Configuration conf = new Configuration();
File testData = new File("testData/points");
if(!testData.exists()){
testData.mkdir();
}
Path path = new Path("testData/points/file1");
SequenceFile.Writer writer = SequenceFile.createWriter(conf,
SequenceFile.Writer.file(path),
SequenceFile.Writer.keyClass(LongWritable.class),
SequenceFile.Writer.valueClass(Text.class));
for(Canopy canopy: canopies){
System.out.println("Canopy ID: "+canopy.getId()+" centers "+
canopy.getCenter().toString());
writer.append(new LongWritable(canopy.getId()),
new Text(canopy.getCenter().toString()));
}
writer.close();
}
}
MyUtil.generateSamples is just generating the sample data(I have also added the code below). And the error message the above code is throwing is
Exception in thread "main" java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1010)
at org.apache.hadoop.util.Shell.runCommand(Shell.java:445)
at org.apache.hadoop.util.Shell.run(Shell.java:418)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:650)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:739)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:722)
at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:633)
at org.apache.hadoop.fs.FilterFileSystem.setPermission(FilterFileSystem.java:467)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:456)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:424)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:906)
at org.apache.hadoop.io.SequenceFile$Writer.<init>(SequenceFile.java:1071)
at org.apache.hadoop.io.SequenceFile$RecordCompressWriter.<init>(SequenceFile.java:1371)
at org.apache.hadoop.io.SequenceFile.createWriter(SequenceFile.java:272)
at Test.main(Test.java:39)
To Generate the sample data
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.random.Normal;
public class MyUtil {
public static void generateSamples(List<Vector> vectors, int num,
double mx, double my, double sd){
Normal xDist = new Normal(mx, sd);
Normal yDist = new Normal(my, sd);
for(int i=0; i<num; i++){
vectors.add(new DenseVector(new double[]{xDist.sample(), yDist.sample()}));
}
}
}
}
I'm trying to mock an external library, however the actual object created in APKDecompiler is being used, instead of the mock object.
Test code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import APKDecompiler;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.*;
import java.io.File;
import java.io.IOException;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Dex2jar.class})
public class TestAPKDecompiler {
//As this only uses external libraries, I will only test that they are called correctly by mocking them.
#Test
public void testAPKDecompiler() {
try {
File testFile = new File("ApkExtractor/src/test/resources/testApp.jar");
String expectedDirectory = testFile.getAbsolutePath().substring(0, testFile.getAbsolutePath().length() - 4);
mockStatic(Dex2jar.class);
Dex2jar mockApkToProcess = createMock(Dex2jar.class);
Decompiler mockDecompiler = createNiceMockAndExpectNew(Decompiler.class);
expect(Dex2jar.from(testFile)).andStubReturn(mockApkToProcess);
mockApkToProcess.to(new File(expectedDirectory + ".jar"));
expectLastCall();
PowerMock.expectNew(Decompiler.class).andReturn(mockDecompiler).anyTimes();
expect(mockDecompiler.decompileToDir(expectedDirectory + ".jar", expectedDirectory)).andReturn(0);
replay(mockApkToProcess);
PowerMock.replay(mockDecompiler);
replayAll();
String actualDirectory = APKDecompiler.decompileAPKToDirectory(testFile);
verify(mockApkToProcess);
verify(mockDecompiler);
verifyAll();
assertEquals(expectedDirectory, actualDirectory);
testFile.delete();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Class code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import jd.core.DecompilerException;
import java.io.File;
import java.io.IOException;
public class APKDecompiler {
public static String decompileAPKToDirectory(File filename) throws IOException, DecompilerException {
String filenameWithoutFileExtension = filename.getAbsolutePath().substring(0, filename.getAbsolutePath().length() - 4);
Dex2jar apkToProcess = Dex2jar.from(filename);
File jar = new File(filenameWithoutFileExtension + ".jar");
apkToProcess.to(jar);
Decompiler decompiler = new Decompiler();
decompiler.decompileToDir(filenameWithoutFileExtension + ".jar", filenameWithoutFileExtension);
return filenameWithoutFileExtension;
}
I've tried this and I haven't had any luck. EasyMock: Mocked object is calling actual method
I get a FileNotFoundException when decompiler.decompileToDir is called, which shouldn't happen as I should be mocking the class.
Any help would be greatly appreciated.
The answer was I didn't include the class i was testing in the #PrepareForTest annotation.
#PrepareForTest({APKDecompiler.class, Dex2jar.class, Decompiler.class})
In the book Beginning Android 4 games development by Mario Zechner and Robert Green I am following along to start making a game of my own. We create a framework for the game first and then implement it into one class, and I got one error which I could not figure out. The error occured when I tried to instantiate something from a class called AndroidFileIO.
This is how the book describes how to instantiate it:
FileIO fileIO
fileIO = new AndroidFileIO(getAssets());
and the class it gets it from is:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Environment;
import android.preference.PreferenceManager;
import com.example.android4gamedevtut.FileIO;
public class AndroidFileIO implements FileIO{
Context context;
AssetManager assets;
String externalStoragePath;
public AndroidFileIO(Context assetManager) {
this.context = assetManager;
this.assets = assetManager.getAssets();
this.externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator;
}
#Override
public InputStream readAsset(String fileName) throws IOException {
return assets.open(fileName);
}
#Override
public InputStream readFile(String fileName) throws IOException {
return new FileInputStream(externalStoragePath + fileName);
}
#Override
public OutputStream writeFile(String fileName) throws IOException {
return new FileOutputStream(externalStoragePath + fileName);
}
public SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
The error that is stopping me is saying "The constructor AndroidFileIO(AssetManager) is undefined" and eclipses suggests too fixes to the problem. The first being to "change the constructor AndroidFileIO(Context) to AndroidFileIO(AssetManager)" and the second being "create a constructor AndroidFileIO(AssetManager)". Please answer this question in simple terms I am very new to java.
you should use
fileIO = new AndroidFileIO(this);
instead of getAsset();
refer to line 54 in https://code.google.com/p/beginning-android-games-2/source/browse/trunk/ch09-jumper/src/com/badlogic/androidgames/framework/impl/GLGame.java?r=4
I'm new with the Jahmm package, also I'm new with Java.
I'm having an error in KMeansLearner that says
Incompatible Types List<ObservationVector> cannot be converted to
List<? extends Observation Vector>
What does this mean? I have only observation vectors until now, and I declared it on headers. Can please anyone can tell how do I fix this? And if I want to use a <ObservationReal>, how does it affects the code?
Here is my code:
package jahmm;
import be.ac.ulg.montefiore.run.jahmm.*;
import be.ac.ulg.montefiore.run.jahmm.ForwardBackwardCalculator;
import be.ac.ulg.montefiore.run.jahmm.Hmm;
import be.ac.ulg.montefiore.run.jahmm.KMeansCalculator;
import be.ac.ulg.montefiore.run.jahmm.ObservationVector;
import be.ac.ulg.montefiore.run.jahmm.ObservationVector;
import be.ac.ulg.montefiore.run.jahmm.OpdfDiscrete;
import be.ac.ulg.montefiore.run.jahmm.OpdfMultiGaussian;
import be.ac.ulg.montefiore.run.jahmm.ViterbiCalculator;
import be.ac.ulg.montefiore.run.jahmm.draw.GenericHmmDrawerDot;
import be.ac.ulg.montefiore.run.jahmm.io.ObservationReader;
import be.ac.ulg.montefiore.run.jahmm.io.ObservationSequencesReader;
import be.ac.ulg.montefiore.run.jahmm.io.ObservationVectorReader;
import be.ac.ulg.montefiore.run.jahmm.learn.KMeansLearner;
import be.ac.ulg.montefiore.run.jahmm.learn.BaumWelchLearner;
import be.ac.ulg.montefiore.run.jahmm.learn.BaumWelchScaledLearner;
import be.ac.ulg.montefiore.run.jahmm.toolbox.MarkovGenerator;
import be.ac.ulg.montefiore.run.jahmm.ObservationReal;
import be.ac.ulg.montefiore.run.jahmm.OpdfInteger;
import java.io.*;
import java.lang.*;
import java.util.*;
/**
*
* #author
*/
public class Jahmm {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//Instances instances;
Reader reader;
int i, j, k;
try{
//String filename = argv[0];
String filex="dta_eat.seq";
//filex = "Desktop\R\dt_junto.csv";
String csvFileToRead = filex;
reader = new FileReader(filex);
List<ObservationVector> sequences =
ObservationSequencesReader.readSequence(new ObservationVectorReader(),
reader);
reader.close();
OpdfMultiGaussianFactory gMix = new OpdfMultiGaussianFactory(3);
KMeansLearner<ObservationVector> kml;
kml = new KMeansLearner<ObservationVector>(6,
gMix, sequences);
Hmm<ObservationVector> initHmm = kml.iterate();
//Hmm<ObservationVector> fittedHmm = kml.learn();
//Hmm<ObservationVector> initHmm = kml.iterate();
} catch(Exception e){
e.printStackTrace();
}
}
}
I'll really would appreciate your help.
you get List of Lists:
Reader reader = new FileReader("vectors.seq");
List<List<ObservationVector>> v = ObservationSequencesReader.
readSequences(new ObservationVectorReader(2), reader);
reader.close();
See this example.
I am trying to write an arraylist string list to a file. The arraylist string is actually a string converted from twitter JSON and I am trying to write the tweet text into the file.
However, I keep getting this error:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at kr.ac.uos.datamining.test.main(test.java:32)
The code for the whole class are below:
package kr.ac.uos.datamining;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.uos.datamining.JSONParser;
import kr.ac.uos.datamining.Tweet;
import kr.ac.uos.datamining.User;
public class test {
public static List <String> list = new ArrayList<String>();
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException, SQLException {
JSONParser j = new JSONParser(new File("D:/curl-7.32.0/samsunggalaxy-01-23-2014.txt"));
ArrayList<Tweet> tweets = j.getTweets();
for(Tweet tweet : tweets){
list.add(tweet.getText());
}
FileWriter writer = new FileWriter("D:/samsunggalaxy.txt");
for (String tweet: list) {
Line 32 writer.write(tweet);
}
writer.close();
}
}
Since it is said as Unknown Source, is it the problem with the String tweet: list line?
I tried to change it to String str: list but its not working as well
The only way that you got a NullPoineterException is that your text is null, so validate what you want to write before writing it.
for (String tweet: list) {
if(tweet != null || !tweet.equals("")) {
writer.write(tweet);
}
}
Seems one of your tweet objects is null. This is the problem here.
It seems the String tweet is null, so I'd check your Tweet.getText() method to ensure it never returns null.