Skip to content

Instantly share code, notes, and snippets.

@suwhs
Created December 3, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suwhs/069c992a33540a05718f to your computer and use it in GitHub Desktop.
Save suwhs/069c992a33540a05718f to your computer and use it in GitHub Desktop.
hyphenation rules downloiader
package ....;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import android.os.AsyncTask;
/**
* Created by igor n. boulliev on 22.11.15.
*/
public class HyphenationRulesDownloader {
private static final String TAG = "HyphenationRulesDownloader";
private static Set<String> mInDownloading = new HashSet<String>();
private static synchronized void onFinishDownload(String lang) {
mInDownloading.remove(lang);
}
private static synchronized boolean onStartDownload(String lang) {
if (mInDownloading.contains(lang)) return false;
mInDownloading.add(lang);
return true;
}
public static void Download(final Context context, final String lang, final Runnable onFinish) {
new AsyncTask<Void,Void,Void>() {
boolean isSuccess = false;
@SuppressLint("LongLogTag")
@Override
protected Void doInBackground(Void... params) {
if (!onStartDownload(lang)) return null;
try {
URL url = new URL("http://whs.su/bsapp/hr/"+lang+".hyphen.dat");
File lf = getLangFile(context, lang);
if (!lf.exists()) {
if (!lf.createNewFile()) {
Log.e(TAG, "could not create file");
return null;
}
}
FileOutputStream fos = new FileOutputStream(lf);
InputStream body = new BufferedInputStream(url.openStream());
byte data[] = new byte[32768];
long total = 0;
int count;
while ((count = body.read(data)) != -1) {
total += count;
// publishing the progress....
fos.write(data, 0, count);
}
fos.flush();
fos.close();
body.close();
isSuccess = true;
} catch (MalformedURLException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
onFinishDownload(lang);
if (onFinish!=null && isSuccess)
try {
onFinish.run();
} catch (Exception e) {
}
}
}.execute();
}
public static File getLangFile(Context context, String lang) throws IOException {
File dataFile = context.getFilesDir();
File hyphenrulesFile = new File(dataFile,"hr");
if (!hyphenrulesFile.exists()) {
if (!hyphenrulesFile.mkdirs()) {
throw new IOException("cannot create directory for hyphenation rules");
}
}
File langFile = new File(hyphenrulesFile,lang+".dat");
return langFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment