Search in sources :

Example 16 with AnyMemoDBOpenHelper

use of org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper in project AnyMemo by helloworld1.

the class QATxtImporter method convert.

public void convert(String src, String dest) throws Exception {
    if (!new File(dest).exists()) {
        amFileUtil.createDbFileWithDefaultSettings(new File(dest));
    }
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(dest);
    try {
        final CardDao cardDao = helper.getCardDao();
        BufferedReader txtfile = new BufferedReader(new FileReader(src));
        String line;
        int count = 0;
        List<Card> cardList = new LinkedList<Card>();
        boolean isQ = false;
        StringBuffer qBuf = null;
        StringBuffer aBuf = null;
        while ((line = txtfile.readLine()) != null) {
            /* remove BOM */
            line = line.replace("\uFEFF", "");
            String head = "";
            if (line.length() >= 2) {
                head = line.substring(0, 2);
            }
            if (line.equals("")) {
                continue;
            } else if (head.equals("Q:")) {
                if (isQ == true) {
                    /* next line */
                    qBuf.append("<br />" + line.replaceAll("Q:\\s*", ""));
                } else {
                    isQ = true;
                    /* Save item when the Q is after A
                         * because it is a new item */
                    if (count != 0) {
                        Card card = new Card();
                        card.setQuestion(qBuf.toString());
                        card.setAnswer(aBuf.toString());
                        card.setCategory(new Category());
                        card.setLearningData(new LearningData());
                        cardList.add(card);
                    }
                    count += 1;
                    qBuf = new StringBuffer();
                    qBuf.append(line.replaceAll("Q:\\s*", ""));
                }
            } else if (head.equals("A:")) {
                if (isQ == true) {
                    isQ = false;
                    aBuf = new StringBuffer();
                    aBuf.append(line.replaceAll("A:\\s*", ""));
                } else {
                    aBuf.append("<br />" + line.replaceAll("A:\\s*", ""));
                }
            } else {
                if (isQ) {
                    qBuf.append("<br />" + line);
                } else {
                    aBuf.append("<br />" + line);
                }
            }
        }
        /* Last item need to be added manually */
        count += 1;
        Card card = new Card();
        card.setQuestion(qBuf.toString());
        card.setAnswer(aBuf.toString());
        card.setCategory(new Category());
        card.setLearningData(new LearningData());
        cardList.add(card);
        txtfile.close();
        cardDao.createCards(cardList);
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
}
Also used : Category(org.liberty.android.fantastischmemo.entity.Category) LinkedList(java.util.LinkedList) Card(org.liberty.android.fantastischmemo.entity.Card) AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File) LearningData(org.liberty.android.fantastischmemo.entity.LearningData) CardDao(org.liberty.android.fantastischmemo.dao.CardDao)

Example 17 with AnyMemoDBOpenHelper

use of org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper in project AnyMemo by helloworld1.

the class CellsDBConverter method convertCellsToDb.

/* cardCells contains the question, answer, category and note
     * category and note is optionally.
     * learningDataCells contains all necessary learning data.
     * If learningDataCells, new learning data is used.
     * dbPath is the place to store converted database
     */
public void convertCellsToDb(Cells cardCells, Cells learningDataCells, String dbPath) throws IOException {
    int numberOfRows = cardCells.getRowCounts();
    int numberOfLearningDataRows = 0;
    if (learningDataCells != null) {
        numberOfLearningDataRows = learningDataCells.getRowCounts();
    }
    // We ignore the header row
    List<Card> cardList = new ArrayList<Card>(numberOfRows + 1);
    for (int i = 1; i < numberOfRows; i++) {
        List<String> row = cardCells.getRow(i);
        Card card = new Card();
        Category category = new Category();
        if (row.size() == 0) {
            Log.w(TAG, "Each row in spreadsheet should have at least 2 column: question and answer. Row number: " + i);
        }
        if (row.size() >= 1) {
            card.setQuestion(row.get(0));
        }
        if (row.size() >= 2) {
            card.setAnswer(row.get(1));
        }
        if (row.size() >= 3) {
            category.setName(row.get(2));
        }
        if (row.size() >= 4) {
            card.setNote(row.get(3));
        }
        // This can't be null because numberOfLearningDataRows is 0
        // if learningDataCells is 0.
        LearningData learningData;
        if (i < numberOfLearningDataRows) {
            learningData = getLearningDataFromRow(learningDataCells.getRow(i));
        } else {
            learningData = new LearningData();
        }
        card.setCategory(category);
        card.setLearningData(learningData);
        cardList.add(card);
    }
    if (cardList.size() == 0) {
        throw new IOException("Wrong spreadsheet format. The spreadsheet should contain at least 1 worksheet with at least 2 columns of questions and answers.");
    }
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(mContext, dbPath);
    try {
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
}
Also used : AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) Category(org.liberty.android.fantastischmemo.entity.Category) ArrayList(java.util.ArrayList) IOException(java.io.IOException) LearningData(org.liberty.android.fantastischmemo.entity.LearningData) CardDao(org.liberty.android.fantastischmemo.dao.CardDao) Card(org.liberty.android.fantastischmemo.entity.Card)

Example 18 with AnyMemoDBOpenHelper

use of org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper in project AnyMemo by helloworld1.

the class QuizletDownloadHelper method downloadCardset.

/**
 * Download cardsets list from Quizlet and save to a db file
 *
 * @param setId
 *            cardset ID
 * @param authToken
 *            oauth token
 * @return The path of saved db file
 * @throws IOException
 *             IOException If http response code is not 2xx
 * @throws JSONException
 *             If the response is invalid JSON
 */
public String downloadCardset(String setId, String authToken) throws IOException, JSONException {
    URL url;
    // needs authtoken
    if (authToken != null) {
        url = new URL(AMEnv.QUIZLET_API_ENDPOINT + "/sets/" + setId);
    } else {
        String urlString = String.format(AMEnv.QUIZLET_API_ENDPOINT + "/sets/" + "%1$s?client_id=%2$s", URLEncoder.encode(setId, "UTF-8"), URLEncoder.encode(AMEnv.QUIZLET_CLIENT_ID, "UTF-8"));
        url = new URL(urlString);
    }
    String response = makeApiCall(url, authToken);
    JSONObject rootObject = new JSONObject(response);
    JSONArray flashcardsArray = rootObject.getJSONArray("terms");
    int termCount = rootObject.getInt("term_count");
    boolean hasImage = rootObject.getBoolean("has_images");
    List<Card> cardList = new ArrayList<Card>(termCount);
    // handle image
    String dbname = downloaderUtils.validateDBName(rootObject.getString("title")) + ".db";
    String imagePath = AMEnv.DEFAULT_IMAGE_PATH + dbname + "/";
    if (hasImage) {
        FileUtils.forceMkdir(new File(imagePath));
    }
    for (int i = 0; i < flashcardsArray.length(); i++) {
        JSONObject jsonItem = flashcardsArray.getJSONObject(i);
        String question = jsonItem.getString("term");
        String answer = jsonItem.getString("definition");
        // Download images, ignore image downloading error.
        try {
            if (jsonItem.has("image") && !jsonItem.isNull("image") && hasImage) {
                JSONObject imageItem = jsonItem.getJSONObject("image");
                String imageUrl = imageItem.getString("url");
                String downloadFilename = Uri.parse(imageUrl).getLastPathSegment();
                downloaderUtils.downloadFile(imageUrl, imagePath + downloadFilename);
                answer += "<br /><img src=\"" + downloadFilename + "\"/>";
            }
        } catch (Exception e) {
            Log.e(TAG, "Error downloading image.", e);
        }
        Card card = new Card();
        card.setQuestion(question);
        card.setAnswer(answer);
        card.setCategory(new Category());
        card.setLearningData(new LearningData());
        cardList.add(card);
    }
    /* Make a valid dbname from the title */
    String dbpath = AMEnv.DEFAULT_ROOT_PATH;
    String fullpath = dbpath + dbname;
    amFileUtil.deleteFileWithBackup(fullpath);
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(fullpath);
    try {
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);
        long count = helper.getCardDao().getTotalCount(null);
        if (count <= 0L) {
            throw new RuntimeException("Downloaded empty db.");
        }
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
    return fullpath;
}
Also used : Category(org.liberty.android.fantastischmemo.entity.Category) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) URL(java.net.URL) JSONException(org.json.JSONException) IOException(java.io.IOException) Card(org.liberty.android.fantastischmemo.entity.Card) AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) JSONObject(org.json.JSONObject) File(java.io.File) LearningData(org.liberty.android.fantastischmemo.entity.LearningData) CardDao(org.liberty.android.fantastischmemo.dao.CardDao)

Example 19 with AnyMemoDBOpenHelper

use of org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper in project AnyMemo by helloworld1.

the class SupermemoXMLImporter method convert.

@Override
public void convert(String src, String dest) throws Exception {
    URL mXMLUrl = new URL("file:///" + src);
    cardList = new LinkedList<Card>();
    System.setProperty("org.xml.sax.driver", "org.xmlpull.v1.sax2.Driver");
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(mXMLUrl.openStream()));
    if (!new File(dest).exists()) {
        amFileUtil.createDbFileWithDefaultSettings(new File(dest));
    }
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(dest);
    try {
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
}
Also used : InputSource(org.xml.sax.InputSource) AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) SAXParser(javax.xml.parsers.SAXParser) File(java.io.File) URL(java.net.URL) XMLReader(org.xml.sax.XMLReader) CardDao(org.liberty.android.fantastischmemo.dao.CardDao) Card(org.liberty.android.fantastischmemo.entity.Card) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 20 with AnyMemoDBOpenHelper

use of org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper in project AnyMemo by helloworld1.

the class CSVExporter method convert.

@Override
public void convert(String src, String dest) throws Exception {
    new File(dest).delete();
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(src);
    final CardDao cardDao = helper.getCardDao();
    final CategoryDao categoryDao = helper.getCategoryDao();
    CSVWriter writer;
    if (separator == null) {
        writer = new CSVWriter(new FileWriter(dest));
    } else {
        writer = new CSVWriter(new FileWriter(dest), separator);
    }
    try {
        final List<Card> cardList = cardDao.queryForAll();
        // Populate all category field in a transaction.
        categoryDao.callBatchTasks(new Callable<Void>() {

            public Void call() throws Exception {
                for (Card c : cardList) {
                    categoryDao.refresh(c.getCategory());
                }
                return null;
            }
        });
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
        if (cardList.size() == 0) {
            throw new IOException("Can't retrieve cards for database: " + src);
        }
        String[] entries = new String[4];
        for (Card card : cardList) {
            entries[0] = card.getQuestion();
            entries[1] = card.getAnswer();
            entries[2] = card.getCategory().getName();
            entries[3] = card.getNote();
            writer.writeNext(entries);
        }
    } finally {
        writer.close();
    }
}
Also used : CategoryDao(org.liberty.android.fantastischmemo.dao.CategoryDao) FileWriter(java.io.FileWriter) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) IOException(java.io.IOException) Card(org.liberty.android.fantastischmemo.entity.Card) AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) File(java.io.File) CardDao(org.liberty.android.fantastischmemo.dao.CardDao)

Aggregations

AnyMemoDBOpenHelper (org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper)32 CardDao (org.liberty.android.fantastischmemo.dao.CardDao)28 Card (org.liberty.android.fantastischmemo.entity.Card)28 File (java.io.File)13 Category (org.liberty.android.fantastischmemo.entity.Category)11 CategoryDao (org.liberty.android.fantastischmemo.dao.CategoryDao)10 LearningDataDao (org.liberty.android.fantastischmemo.dao.LearningDataDao)9 LearningData (org.liberty.android.fantastischmemo.entity.LearningData)9 IOException (java.io.IOException)6 URL (java.net.URL)5 FileWriter (java.io.FileWriter)4 ArrayList (java.util.ArrayList)4 SmallTest (androidx.test.filters.SmallTest)3 BufferedWriter (java.io.BufferedWriter)3 PrintWriter (java.io.PrintWriter)3 SAXParser (javax.xml.parsers.SAXParser)3 SAXParserFactory (javax.xml.parsers.SAXParserFactory)3 Test (org.junit.Test)3 InputSource (org.xml.sax.InputSource)3 XMLReader (org.xml.sax.XMLReader)3