1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package androidx.work.integration.testapp.sherlockholmes;
17
18import android.support.annotation.NonNull;
19import android.util.Log;
20
21import androidx.work.Data;
22import androidx.work.Worker;
23import androidx.work.integration.testapp.db.TestDatabase;
24import androidx.work.integration.testapp.db.WordCount;
25
26import java.io.DataInputStream;
27import java.io.FileInputStream;
28import java.io.IOException;
29import java.util.ArrayList;
30import java.util.Collections;
31import java.util.HashMap;
32import java.util.List;
33import java.util.Map;
34
35/**
36 * A Worker that combines the word counts of various works and outputs them.
37 */
38public class TextReducingWorker extends Worker {
39
40    private static final String INPUT_FILE = "input_file";
41
42    private Map<String, Integer> mWordCount = new HashMap<>();
43
44    @Override
45    public @NonNull Result doWork() {
46        Data input = getInputData();
47        String[] inputFiles = input.getStringArray(INPUT_FILE);
48        if (inputFiles == null) {
49            throw new IllegalArgumentException();
50        }
51
52        for (int i = 0; i < inputFiles.length; ++i) {
53            FileInputStream fileInputStream = null;
54            DataInputStream dataInputStream = null;
55            try {
56                fileInputStream = getApplicationContext().openFileInput(inputFiles[i]);
57                dataInputStream = new DataInputStream(fileInputStream);
58                while (dataInputStream.available() > 0) {
59                    String word = dataInputStream.readUTF();
60                    int count = dataInputStream.readInt();
61                    if (mWordCount.containsKey(word)) {
62                        count += mWordCount.get(word);
63                    }
64                    mWordCount.put(word, count);
65                }
66            } catch (IOException e) {
67                return Result.FAILURE;
68            } finally {
69                if (dataInputStream != null) {
70                    try {
71                        dataInputStream.close();
72                    } catch (IOException e) {
73                        // Do nothing.
74                    }
75                }
76                if (fileInputStream != null) {
77                    try {
78                        fileInputStream.close();
79                    } catch (IOException e) {
80                        // Do nothing.
81                    }
82                }
83            }
84        }
85
86        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(mWordCount.size());
87        sortedList.addAll(mWordCount.entrySet());
88        Collections.sort(sortedList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
89
90        TestDatabase db = TestDatabase.getInstance(getApplicationContext());
91        db.beginTransaction();
92        try {
93            for (Map.Entry<String, Integer> entry : sortedList) {
94                WordCount wc = new WordCount();
95                wc.mWord = entry.getKey();
96                wc.mCount = entry.getValue();
97                db.getWordCountDao().insertWordCount(wc);
98            }
99            db.setTransactionSuccessful();
100        } finally {
101            db.endTransaction();
102        }
103
104        Log.d("Reduce", "Reduction finished");
105        return Result.SUCCESS;
106    }
107}
108