java.io.FileNotFoundExceptionis thrown for unknown reason - java

Problem solved!!! I've transfered the whole folder from desktop under c:\ and for some reason it is working
I've a very weird scenario.
I try to run my partner's version which is fully working without any exceptions in his computer- it is the same project..
Any ideas?
Relevant code added..
public class DJ implements Runnable
{
private static final int k_SoundLoop = 500;
private static final int k_NumberOfSong = 2;
private static final int k_CairoTrainSong = 0;
private static final int k_MachineSong = 1;
private ArrayList<Clip> m_Records = new ArrayList<Clip>();
private int m_CurrentRecored = 0;
private Thread m_MusicThread = null;
private AppletContext m_AppletContext;
//java.net.URL m_CodeBase;
//AppletContext ac;
public DJ()
{
try
{
createClip(getClass().getResource("/Music/train.au"));
createClip(getClass().getResource("/Music/machine.au"));
}
catch (Exception ex)
{
Logger.getLogger(DJ.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void createClip(URL i_SoundFileURL) throws Exception
{
File soundFile = new File(i_SoundFileURL.getFile());
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
m_Records.add(clip);
}
public void play()
{
m_Records.get(m_CurrentRecored).loop(k_SoundLoop);
}
public void play(int i_RecoredNumber)
{
stopCurrentClipIfNeeded();
m_CurrentRecored = i_RecoredNumber;
m_Records.get(m_CurrentRecored).start();
}
public void stop()
{
stopCurrentClipIfNeeded();
m_CurrentRecored = 0;
}
public void stop(int i_RecordNumber)
{
m_Records.get(i_RecordNumber).stop();
}
public void Next()
{
stopCurrentClipIfNeeded();
m_CurrentRecored = ((m_CurrentRecored+1)%k_NumberOfSong);
m_Records.get(m_CurrentRecored).start();
}
private void stopCurrentClipIfNeeded()
{
if (m_Records.get(m_CurrentRecored).isRunning())
{
m_Records.get(m_CurrentRecored).stop();
}
}
public boolean IsRunning()
{
return m_Records.get(m_CurrentRecored).isRunning();
}
public void CloseRecoredSet()
{
for (Clip clip : m_Records)
{
clip.close();
}
}
#Override
public void run()
{
m_Records.get(m_CurrentRecored).start();
}
}
Thanks
I'm consistently getting this:
08/10/2011 23:47:48 LogicEngine.DJ <init>
SEVERE: null
java.io.FileNotFoundException: C:\Users\Dan\Desktop\CairoNightTrain\CairoNightTrain\CairoNightTrainClient\src\Music\train.au (‏‏System can not find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at com.sun.media.sound.WaveFileReader.getAudioInputStream(WaveFileReader.java:205)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1162)
at LogicEngine.DJ.createClip(DJ.java:56)
at LogicEngine.DJ.<init>(DJ.java:42)
at GUI.JPanelGameApplet$1.run(JPanelGameApplet.java:63)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:199)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatc

C:\Users\Dan\Desktop\CairoNightTrain\CairoNightTrain\CairoNightTrainClient\src\Music\train.au
Is your friend called Dan by any chance? It can't find this file. I think it's pretty clear?
What does this print?
File file = new File("/Music/train.au");
String absolutePathOfFile = file.getAbsolutePath();
System.out.println(" The absolute path is " + absolutePathOfFile);

Related

How can I use the Observer Pattern for file monitoring with threads?

I am trying to implement the observer pattern to a game i have made. When a villain is created in the battle-zone file using threads, I would like to use the observer pattern to create a hero using threads and add it to the same file. The villians and heroes are created using the factory method pattern. I am unsure of where to go with regards to linking my HeroCreationMain class to the observer pattern classes.
Villian Creation
public class VillianCreationMain {
private static Villian villian;
public static void main(String[] args, int userInput) throws IOException {
String fileName = null;
Random randomVillian = new Random();
int amountOfVillians = userInput;
if (amountOfVillians < 7) {
for (int x = 0; x < amountOfVillians; x++) {
int randomGenerator = randomVillian.nextInt(6);
for (int i = 0; i < 5; i++) {
if (randomGenerator == 0 ) {
setVillian(new FlyingVillian());
}
else if (randomGenerator == 1) {
setVillian(new StrongVillian());
}
else if (randomGenerator == 2) {
setVillian(new FastVillian());
}
else if (randomGenerator == 3) {
setVillian(new SmartVillian());
}
else if (randomGenerator == 4) {
setVillian(new FireVillian());
}
else if (randomGenerator == 5) {
setVillian(new IceVillian());
}
try {
writeToFile(getVillian(), i, fileName);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
VillianThreads t1 = new VillianThreads(VillianCreationMain.getVillian());
t1.start();
}
}
else {
System.out.println("Please enter a value of less than 7");
}
}
public static void writeToFile(Villian villian, int amountOfVillians, String fileName) throws IOException {
for(int x = 0; x < amountOfVillians; x++) {
// String parsedInt = Integer.toString(x);
fileName = "battle-zone.ser";
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(file);
oos.writeObject(villian);
file.close();
oos.close();
}
}
public static Villian getVillian() {
return villian;
}
public static void setVillian(Villian villian) {
VillianCreationMain.villian = villian;
}
}
Hero Creation
public class HeroCreationMain {
private static Hero hero = null;
public static void main(String[] Hero) {
EnemyStatus enemyStatus = new EnemyStatus();
VillianObserver observer1 = new VillianObserver(enemyStatus);
}
public static void readFile() throws IOException, ClassNotFoundException {
#SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream (new FileInputStream("battle-zone.ser"));
Villian targetVillian = (Villian) ois.readObject();
System.out.println(targetVillian + " is being attacked by a hero!");
}
public static Hero getHero() {
return hero;
}
public static void setHero(Hero hero) {
HeroCreationMain.hero = hero;
}
}
Observer
public interface Observer {
public void update(boolean enemyPresent);
}
public interface Subject {
public void register(Observer o);
public void unregister(Observer o);
public void notifyObserver();
}
Observable
public class VillianObserver implements Observer {
private boolean enemyPresent;
private static int heroIDTracker;
private int heroID;
private Subject villianObserver;
public VillianObserver(Subject villianObserver) {
this.villianObserver = villianObserver;
this.heroID = ++heroIDTracker;
System.out.println("New Observer " + this.heroID);
villianObserver.register(this);
}
#Override
public void update(boolean enemyPresent) {
this.enemyPresent = enemyPresent;
printResult();
}
public void printResult() {
System.out.println(heroID + " " + enemyPresent);
}
}
Enemy Status
import java.util.ArrayList;
public class EnemyStatus implements Subject {
private ArrayList<Observer> observers;
private boolean enemyPresent;
public EnemyStatus() {
// Creates an ArrayList to hold all observers
observers = new ArrayList<Observer>();
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
// Get the index of the observer to delete
int heroIndex = observers.indexOf(deleteObserver);
// Print out message (Have to increment index to match
System.out.println("Observer " + (heroIndex+1) + " deleted");
// Removes observer from the ArrayList
observers.remove(heroIndex);
}
#Override
public void notifyObserver() {
for(Observer observer : observers) {
observer.update(enemyPresent);
}
}
public void setEnemyStatus(boolean enemyPresent) {
this.enemyPresent = enemyPresent;
notifyObserver();
}
}
JNotify is the Java library to observe file changes on the file system.
One piece of advice: Object(Input/Output)Streams are easy when you're just getting started but they lead you down a path of ruin. Objects get so easily BadVersion'ed. Object files are also relatively hard to inspect using a text editor. I'd advise you to try using a different data format (like JSON) instead.

Thread that terminates after webservice return executed?

My problem is that the web service returns a value of the static variable response in the recognition class before the thread updates its value (not up to date value)
here is my web service :
#GET
#Produces("application/json")
public synchronized String returnTitle() {
String result="init value";
Recognition recognition = new Recognition();
FutureTask<String> future = new FutureTask(recognition);
future.run();
System.out.println("result0 = "+result);
try{
System.out.println("result = "+result);
result = future.get();
System.out.println("result1 = "+result);
}catch (Exception e){e.printStackTrace();}
return "<h1>hello</h1> "+ Recognition.response;
}
This class contains the static variable called response that well be returned by the web service.
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
import com.bitsinharmony.recognito.MatchResult;
public class Recognition implements Callable<String>{
public static String response =""; // The variable to return by the web service.
#Override
public String call() throws Exception {
response= "";
if (!Ressources.isInitilalized){ // if the initialization of training data is not done yet.
Ressources.init(); // initialize training data
Ressources.isInitilalized= true; //changing the boolean variable to know that inisialization has been done next execution
}
final JavaSoundRecorder recorder = new JavaSoundRecorder(); // Class used to record voice from microphone and save it to .wav file.
Thread stopper = new Thread(new Runnable() { // Thread that sleeps 5000 ms then stops recording.
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recorder.finish(); // after timer finished stop recording
try{
File file20 = new File("C:\\RecordAudio.wav");
List<MatchResult<String>> matches = Ressources.recognito.identify(file20);
MatchResult<String> match = matches.get(0);
//file20.delete();
System.out.println(match.getKey() + " " + match.getLikelihoodRatio());
response = match.getKey()+" "+match.getLikelihoodRatio()+"\n";// say for which user the sound recorded belongs with witch probability.
}catch (Exception e){}
}
});
stopper.start(); // start the thread
// start recording
recorder.start(); // start recording
return response;
}
}
This class contains static resources to train the model of speaker identification :
import java.io.File;
import com.bitsinharmony.recognito.Recognito;
public class Ressources {
public static String response = "hello : ";
public final static File file0 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\silence12.wav");
public final static File file00 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\noise12.wav");
public final static File file1 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\dhia12.wav");
public final static File file30 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\dhia30.wav");
public final static File file2 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\dhia2.wav");
public final static File file3 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\obama1.wav");
public final static File file4 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\obama2.wav");
public final static File file5 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\obama3.wav");
public final static File file6 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\reagan1.wav");
public final static File file7 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\reagan2.wav");
public final static File file8 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\reagan3.wav");
public final static File file9 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\georgebush1.wav");
public final static File file10 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\georgebush2.wav");
public final static File file11 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\georgebush3.wav");
public final static File file12 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\georgebush4.wav");
public final static File file13 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\carter1.wav");
public final static File file14 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\carter2.wav");
public final static File file15 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\clinton1.wav");
public final static File file16 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\clinton2.wav");
public final static File file17 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\huyan1.wav");
public final static File file18 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\huyan2.wav");
public final static File file19 = new File("C:\\Users\\dsghaier\\Desktop\\Records\\huyan3.wav");
public static Recognito<String> recognito = new Recognito<String>(16000.0f);
public static boolean isInitilalized = false;
public static void init(){
try{
recognito.createVoicePrint("Dhia", file1);
//recognito.mergeVoiceSample("Dhia", file2);
//recognito.mergeVoiceSample("Dhia", file30);
recognito.createVoicePrint("Obama", file3);
//recognito.mergeVoiceSample("Obama", file4);
//recognito.mergeVoiceSample("Obama", file5);
recognito.createVoicePrint("Reagan", file6);
//recognito.mergeVoiceSample("Reagan", file7);
//recognito.mergeVoiceSample("Reagan", file8);
recognito.createVoicePrint("George Bush", file9);
//recognito.mergeVoiceSample("George Bush", file10);
//recognito.mergeVoiceSample("George Bush", file11);
//recognito.mergeVoiceSample("George Bush", file12);
recognito.createVoicePrint("Carter", file13);
//recognito.mergeVoiceSample("Carter", file14);
//recognito.createVoicePrint("Clinton", file15);
//recognito.mergeVoiceSample("Clinton", file16);
//recognito.createVoicePrint("Huyan", file17);
//recognito.mergeVoiceSample("Huyan", file18);
//recognito.mergeVoiceSample("Huyan", file19);
//recognito.createVoicePrint("Silence", file0);
//recognito.createVoicePrint("Noise", file00);
// ********************************
}catch (Exception e){e.printStackTrace();}
isInitilalized = true;
}
}
And finally this class is used to record sound and save it into a .wav file :
import javax.sound.sampled.*;
import java.io.*;
/**
* A sample program is to demonstrate how to record sound in Java
* author: www.codejava.net
*/
public class JavaSoundRecorder {
// record duration, in milliseconds
static final long RECORD_TIME = 500;
// path of the wav file
File wavFile = new File("C:/RecordAudio.wav");
// format of audio file
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
// the line from which audio data is captured
TargetDataLine line;
/**
* Defines an audio format
*/
AudioFormat getAudioFormat() {
float sampleRate = 16000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
channels, signed, bigEndian);
return format;
}
/**
* Captures the sound and record into a WAV file
*/
public void start() {
try {
AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// checks if system supports the data line
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start(); // start capturing
// System.out.println("Start capturing...");
AudioInputStream ais = new AudioInputStream(line);
// System.out.println("Start recording...");
// start recording
AudioSystem.write(ais, fileType, wavFile);
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Closes the target data line to finish capturing and recording
*/
public void finish() {
line.stop();
line.close();
// System.out.println("Finished");
}
}
Maybe you should just initialize your static variable.
Initializing and declaring a variable is not the same:
Initializing : int a = 0;
Declaring : int a;
If this is not what you are looking for, maybe you might be a bit more specific and show us an error message

JAVA - Sounds not playing after jar exported

I have the problem that after i export my java project no sound is playing.
I searched in the internet and i found that:
Main.class.getResourceAsStream("fileloc");solves that problem
But my class uses this..
Where is the problem?
public class Sounds {
private static Clip eat;
public static Clip collect;
private static Clip lsd;
private static AudioInputStream inputStream;
private static FloatControl gainControl;
public static void getSounds(){
try{
eat = getClip("/sound/collect/eat.wav");
collect = getClip("/sound/collect/collect.wav");
lsd = getClip("/sound/LSD.wav");
} catch(LineUnavailableException | UnsupportedAudioFileException| IOException e){
e.printStackTrace();
}
}
private static Clip getClip(String loc) throws LineUnavailableException, UnsupportedAudioFileException, IOException{
Clip c = AudioSystem.getClip();
inputStream = AudioSystem.getAudioInputStream(Spielfeld.class.getResourceAsStream(loc));
c.open(inputStream);
gainControl = (FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(+6.0f);
c.setMicrosecondPosition(0);
return c;
}
public static void playSound(final String url) {
switch(url){
case "collect/collect.wav": collect.start(); collect.setMicrosecondPosition(0); break;
case "collect/eat.wav": eat.start(); eat.setMicrosecondPosition(0); break;
case "LSD.wav": lsd.start(); lsd.setMicrosecondPosition(0); break;
}
}
}
Thank you for your help
No sound after export to jar
Thank you trinityalps ;) (https://stackoverflow.com/users/5012832/trinityalps)

The method getApplication() is undefined for the type (my class)

I am using a global variables "GlobalVariables" in a separated class and I am try to use it in the following code but it is always gives me the error :
The method getApplication() is undefined for the type UploadPicture
I tried the following but still have error:
((GlobalVariables) this.getApplication()).set_FileUploading(false);
The qustion was already asked here but unfortunatlly all the answors didn't work with me and gave me same error! any suggestion please?
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath, File file) {
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
return 500;
}
#Override
public void onProgress(long bytes, long total) {
//publishProgress(bytes);
}
}
);
if (mRequest != null) {
mRequest.upload();
((GlobalVariables) UploadPicture.this.getApplication()).set_FileUploading(false);
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
Edit: I am adding now my "VariableGlobales" calss:
public class GlobalVariables extends Application {
private Boolean _IsIOIORunning=false;
private Boolean _FileUploading=false;
public Boolean get_IsIOIORunning()
{
return _IsIOIORunning;
}
public void set_IsIOIORunning(Boolean _IsIOIORunning)
{
this._IsIOIORunning = _IsIOIORunning;
}
public Boolean get_FileUploading()
{
return _FileUploading;
}
public void set_FileUploading(Boolean _FileUploading)
{
this._FileUploading = _FileUploading;
}
It's normal UploadPicture doesn't extend GlobalVariables but it extend AsyncTask.
That it's my "GlobalVariables "
public class AppInfo extends Application {
private static Context context;
private static String user;
public void onCreate(){
super.onCreate();
AppInfo.context = getApplicationContext();
user = null;
}
public static Context getAppContext() {return AppInfo.context;}
public static String getUser() {return user;}
public static void setUser(String user) {AppInfo.user = user;}
}
And I call it everywhere like that:
AppInfo.getUser();
Edit:
GlobalVariables should use static method and variables:
public class GlobalVariables extends Application {
private static Boolean _IsIOIORunning=false;
private static Boolean _FileUploading=false;
public static Boolean get_IsIOIORunning() {
return _IsIOIORunning;
}
public static void set_IsIOIORunning(Boolean _IsIOIORunning) {
GlobalVariables._IsIOIORunning = _IsIOIORunning;
}
public static Boolean get_FileUploading(){
return _FileUploading;
}
public static void set_FileUploading(Boolean _FileUploading){
GlobalVariables._FileUploading = _FileUploading;
}
}

Thread does not run

I have some places in a excel file, each of the point have a lng and lat coordinate.
Now I try to create a static Map for each point using the google map static map api.
And I have Two component, a parser and a loader.
The Parser is used to read the excel file while the loaded is used to load tiles.
And I make the loader run in a seprate Thread.
public class Parser {
private static Parser instance;
private StaticMapLoader loader;
private Parser(StaticMapLoader loader) {
this.loader = loader;
}
public synchronized static Parser getInstance(StaticMapLoader loader) {
if (instance == null) {
instance = new Parser(loader);
}
return instance;
}
public void parse(String path) {
List<Branch> result = new ArrayList<Branch>();
InputStream inp;
try {
inp = new FileInputStream(path);
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum();
for(Row r : sheet.getRows){
loader.addTask(r.type,r.name,r.x,r.y);
}
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Branch bc = new Branch("网点1", null, null);
return result;
}
}
Loader:
public class StaticMapLoader extends Thread {
private final static Logger log = Logger.getLogger(StaticMapLoader.class);
private List<Task> tasks = new ArrayList<Task>();
private String tilePath;
private boolean running = false;
public StaticMapLoader(String saveDir) {
this.tilePath = saveDir;
}
#Override
public void run() {
while (running) {
log.debug("run " + tasks.size());
if (tasks.size() > 0) {
Task t = tasks.get(0);
if (t != null && t.status == Status.waiting) {
tasks.remove(0);
t.status = Status.running;
downLoad(t);
}
}
}
}
private void downLoad(Task t) {
log.debug(String.format("load data for " + t.toString()));
//down tiles and save
t.status=Status.success;
}
public void addTask(String type, String name, double x, double y) {
log.debug(String.format("add task of :%s,%s", type, name));
tasks.add(new Task(type,name,x,y));
}
public void startRunning() {
running = true;
this.start();
}
public void stopRunning() {
running = false;
this.interrupt();
}
class Task {
Status status = Status.waiting;
String type, name;
double x,y;
Task(String type, String name, double x,double y) {
this.type = type;
this.name = name;
this.xian = xian;
this.x = x;
this.y = y;
}
}
enum Status {
waiting, running, fail, success
}
}
The process is rather simple, the StaticMapLoader have a field of ArrayList. While the Parser parse a record(place), it will be thrown to the list.
And the loader will iterator the list and download the data.
However I meet a strange problem here:
#Override
public void run() {
while (running) {
log.debug("run " + tasks.size());
if (tasks.size() > 0) {
Task t = tasks.get(0);
if (t != null && t.status == Status.waiting) {
tasks.remove(0);
t.status = Status.running;
downLoad(t);
}
}
}
}
The above codes runs, and I will get the logs like this:
run 1
add task of ..
run 2
add task of ...
However , if I comment the log line, the downLoad will be never called, I will get:
run 1
run 2
......
It seems that this may be caused by the Thread , do I miss anything?
BTW, the above codes ran inside the HttpServlet context, and I start them like this:
#Override
public void init() throws ServletException {
super.init();
try {
URL fileUrl = getServletContext().getResource(getInitParameter("xlsxFile"));
URL tilePath = getServletContext().getResource(getInitParameter("tilePath"));
StaticMapLoader loader = new StaticMapLoader(tilePath.getPath());
loader.startRunning();
Parser.getInstance(loader).parse(fileUrl.getPath());
} catch (MalformedURLException e) {
}
}

Categories