Example usage for java.util ArrayList contains

List of usage examples for java.util ArrayList contains

Introduction

In this page you can find the example usage for java.util ArrayList contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:net.phyloviz.mstsstatistics.Runner.java

private double calcNumberMSTs(List edgesList, GOeBurstResult sgr) {

    Collections.sort(edgesList);/* ww  w.jav  a 2 s.com*/

    double nmsts = 0;

    int mapid;

    //Passo 1 - Descobrir o MaxId Inicial
    int maxid = findMaxId(edgesList);
    SparseDoubleMatrix2D matrix = new SparseDoubleMatrix2D(maxid + 1, maxid + 1);
    matrix.assign(0);

    DisjointSet ds = new DisjointSet(maxid);

    int[] map = new int[maxid + 1];
    for (int i = 0; i <= maxid; i++) {
        map[i] = i;
    }

    int[] mapaux = new int[maxid + 1];
    for (int i = 0; i <= maxid; i++) {
        mapaux[i] = -1;
    }

    //Passo 2 - Varrer arcos do nivel L, preenchendo a matriz
    Iterator<EdgeMST> eIter = edgesList.iterator();

    EdgeMST e = eIter.next();
    int level = (e != null) ? e.getLevel() : 1;

    ArrayList<Integer> vaux = new ArrayList<Integer>(maxid + 1);

    int prev = 0;
    int now = 0;

    while (true) {
        if (e != null && e.getLevel() == level) {
            int u = e.getSource();
            int v = e.getDest();
            if (!vaux.contains(u)) {
                vaux.add(u);
            }
            if (!vaux.contains(v)) {
                vaux.add(v);
            }
            //Preenchimento da Matriz
            int s = map[u];
            int d = map[v];

            matrix.setQuick(s, d, matrix.getQuick(s, d) - 1);
            matrix.setQuick(d, s, matrix.getQuick(d, s) - 1);
            matrix.setQuick(s, s, matrix.getQuick(s, s) + 1);
            matrix.setQuick(d, d, matrix.getQuick(d, d) + 1);

            if (!ds.sameSet(u, v)) {
                ds.unionSet(u, v);
            }

            now++;

            try {
                e = eIter.next();
            } catch (NoSuchElementException ex) {
                e = null;
            }

        } else if (prev != now) {
            mapid = 0;
            for (int i = 0; i <= maxid; i++) {
                int setid = ds.findSet(i);
                if (mapaux[setid] == -1) {
                    mapaux[setid] = mapid;
                    mapaux[i] = mapid;
                    mapid++;
                } else {
                    mapaux[i] = mapaux[setid];
                }
            }

            ArrayList[] calcDet = new ArrayList[mapid];
            for (int i = 0; i < calcDet.length; i++) {
                calcDet[i] = new ArrayList<Integer>();
            }

            for (int i = 0; i < vaux.size(); i++) {
                if (!calcDet[mapaux[vaux.get(i)]].contains(map[vaux.get(i)])) {
                    calcDet[mapaux[vaux.get(i)]].add(map[vaux.get(i)]);
                }
            }

            sgr.getPanel().appendWithDate("Level " + level + "\n");

            double[] calcNMstsDet = new double[mapid];
            for (int i = 0; i < calcDet.length; i++) {

                if (!calcDet[i].isEmpty()) {

                    int[] vgraph = new int[calcDet[i].size()];
                    ArrayList<Integer> graph = (ArrayList<Integer>) calcDet[i];
                    Iterator<Integer> gIter = graph.iterator();
                    int index = 0;
                    while (gIter.hasNext()) {
                        vgraph[index++] = gIter.next();
                    }

                    double det = 0.0;
                    LUDecomposition tempMax = new LUDecomposition(
                            (matrix.viewSelection(ArrayUtils.subarray(vgraph, 0, vgraph.length - 1),
                                    ArrayUtils.subarray(vgraph, 0, vgraph.length - 1))));
                    DoubleMatrix2D max = tempMax.getU();
                    System.out.println(max.rows());
                    for (int k = 0; k < max.rows(); k++) {
                        det += Math.log10(Math.abs(max.get(k, k)));
                    }

                    if (det == 0) {
                        det = 1;
                    }

                    sgr.getPanel().append("View: " + Arrays.toString(vgraph) + "\n");
                    sgr.getPanel().append("Det: " + det + "\n");
                    sgr.getPanel().flush();

                    calcNMstsDet[i] = det;
                    nmsts = nmsts + det;

                }
            }

            calcEdgesNMSTs(edgesList, prev, now, map, mapaux, calcDet, matrix, calcNMstsDet);

            prev = now;
            if (e == null) {
                break;
            }

            matrix = new SparseDoubleMatrix2D(mapid, mapid);
            matrix.assign(0);
            map = mapaux;
            mapaux = new int[maxid + 1];
            for (int i = 0; i <= maxid; i++) {
                mapaux[i] = -1;
            }
            //Passa para o nvel seguinte
            level++;
            vaux = new ArrayList<Integer>(mapid);
        } else { // Se prev==now a lista  vazia e passamos para o nvel seguinte
            level++;
        }
    }

    return nmsts;
}

From source file:net.fenyo.gnetwatch.activities.MergeQueue.java

final void mergeEventsOfTarget(final Target target, final String event_type, final Long s,
        final EventGeneric ev_first) {
    if (ev_first == null)
        return;//from  w ww.j  a v a 2 s  .  c o  m

    final org.hibernate.Query query = getGUI().getSynchro().getSessionFactory().getCurrentSession()
            .createQuery("from EventGeneric as ev " + "where ev.eventList = :event_list "
                    + "and ev.date < :stop_date " + "and ev.merged != :s order by ev.date asc")
            .setString("event_list", target.getEventLists().get(event_type).getId().toString()).setLong("s", s)
            .setString("stop_date", ev_first.getDate().toString());
    //    log.debug("stop date : " + ev_first.getDate().toString());
    final List<EventGeneric> results = query.list();
    if (results.size() > 0) {
        EventGeneric prev_event = null;
        final ArrayList<EventGeneric> events = new ArrayList<EventGeneric>();
        for (final EventGeneric event : results) {
            event.setMerged(s);
            if (prev_event != null) {
                if (event.getDate().getTime()
                        - event.getDate().getTime() % (s * 1000) == prev_event.getDate().getTime()
                                - prev_event.getDate().getTime() % (s * 1000)) {
                    if (!events.contains(prev_event))
                        events.add(prev_event);
                    if (!events.contains(event))
                        events.add(event);
                } else {
                    if (events.size() > 0)
                        mergeEventsChunk(events, new java.util.Date(events.get(0).getDate().getTime()
                                - events.get(0).getDate().getTime() % (s * 1000) + s * 500));
                    events.clear();
                    events.add(event);
                }
            }
            prev_event = event;
        }
        if (events.size() > 0)
            mergeEventsChunk(events, new java.util.Date(events.get(0).getDate().getTime()
                    - events.get(0).getDate().getTime() % (s * 1000) + s * 500));
        events.clear();
    }
}

From source file:com.fujitsu.dc.test.jersey.ODataCommon.java

/**
 * $link???.// w w  w  .ja v a  2  s  .  c o m
 * @param json ?
 * @param uri uri?
 */
public static void checkLinResponseBody(final JSONObject json, final ArrayList<String> uri) {
    String value;
    JSONObject jsonResult;

    // results
    JSONArray results = (JSONArray) ((JSONObject) json.get("d")).get("results");

    assertEquals(uri.size(), results.size());
    for (Object result : results) {
        jsonResult = (JSONObject) result;
        value = (String) jsonResult.get("uri");
        assertTrue("expected uri doesn't contain [" + value + "]", uri.contains(value));
    }
}

From source file:fr.cirad.mgdb.exporting.markeroriented.GFFExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }//www .  j av  a  2 s. c o m
        }

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);
    ArrayList<String> individualList = new ArrayList<String>();
    for (int i = 0; i < sampleIDs.size(); i++) {
        Individual individual = individuals.get(i);
        if (!individualList.contains(individual.getId())) {
            individualList.add(individual.getId());
        }
    }

    String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".gff3"));
    String header = "##gff-version 3" + LINE_SEPARATOR;
    zos.write(header.getBytes());

    TreeMap<String, String> typeToOntology = new TreeMap<String, String>();
    typeToOntology.put(Type.SNP.toString(), "SO:0000694");
    typeToOntology.put(Type.INDEL.toString(), "SO:1000032");
    typeToOntology.put(Type.MIXED.toString(), "SO:0001059");
    typeToOntology.put(Type.SYMBOLIC.toString(), "SO:0000109");
    typeToOntology.put(Type.MNP.toString(), "SO:0001059");

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    short nProgress = 0, nPreviousProgress = 0;
    long nLoadedMarkerCount = 0;

    while (markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
        LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                mongoTemplate, sampleIDs, currentMarkers, true,
                null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
        for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
        {
            Comparable variantId = variant.getId();
            List<String> variantDataOrigin = new ArrayList<String>();

            Map<String, Integer> gqValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, Integer> dpValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
            List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":");
            if (chromAndPos.size() == 0)
                LOG.warn("Chromosomal position not found for marker " + variantId);
            // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR);
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(variantId);
                if (syn != null)
                    variantId = syn;
            }

            Collection<VariantRunData> runs = variantsAndRuns.get(variant);
            if (runs != null)
                for (VariantRunData run : runs)
                    for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                        SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                        String individualId = individuals
                                .get(sampleIDs.indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                .getId();

                        Integer gq = null;
                        try {
                            gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ);
                        } catch (Exception ignored) {
                        }
                        if (gq != null && gq < nMinimumGenotypeQuality)
                            continue;

                        Integer dp = null;
                        try {
                            dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP);
                        } catch (Exception ignored) {
                        }
                        if (dp != null && dp < nMinimumReadDepth)
                            continue;

                        String gtCode = sampleGenotype.getCode();
                        List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                        if (storedIndividualGenotypes == null) {
                            storedIndividualGenotypes = new ArrayList<String>();
                            individualGenotypes.put(individualId, storedIndividualGenotypes);
                        }
                        storedIndividualGenotypes.add(gtCode);
                    }

            zos.write((chromAndPos.get(0) + "\t" + StringUtils.join(variantDataOrigin, ";") /*source*/ + "\t"
                    + typeToOntology.get(variant.getType()) + "\t" + Long.parseLong(chromAndPos.get(1)) + "\t"
                    + Long.parseLong(chromAndPos.get(1)) + "\t" + "." + "\t" + "+" + "\t" + "." + "\t")
                            .getBytes());
            Comparable syn = markerSynonyms == null ? null : markerSynonyms.get(variant.getId());
            zos.write(("ID=" + variant.getId() + ";" + (syn != null ? "Name=" + syn + ";" : "") + "alleles="
                    + StringUtils.join(variant.getKnownAlleleList(), "/") + ";" + "refallele="
                    + variant.getKnownAlleleList().get(0) + ";").getBytes());

            for (int j = 0; j < individualList
                    .size(); j++ /* we use this list because it has the proper ordering*/) {

                NumberFormat nf = NumberFormat.getInstance(Locale.US);
                nf.setMaximumFractionDigits(4);
                HashMap<String, Integer> compt1 = new HashMap<String, Integer>();
                int highestGenotypeCount = 0;
                int sum = 0;

                String individualId = individualList.get(j);
                List<String> genotypes = individualGenotypes.get(individualId);
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes

                String mostFrequentGenotype = null;
                if (genotypes != null)
                    for (String genotype : genotypes) {
                        if (genotype.length() == 0)
                            continue; /* skip missing genotypes */

                        int count = 0;
                        for (String t : variant.getAllelesFromGenotypeCode(genotype)) {
                            for (String t1 : variant.getKnownAlleleList()) {
                                if (t.equals(t1) && !(compt1.containsKey(t1))) {
                                    count++;
                                    compt1.put(t1, count);
                                } else if (t.equals(t1) && compt1.containsKey(t1)) {
                                    if (compt1.get(t1) != 0) {
                                        count++;
                                        compt1.put(t1, count);
                                    } else
                                        compt1.put(t1, count);
                                } else if (!(compt1.containsKey(t1))) {
                                    compt1.put(t1, 0);
                                }
                            }
                        }
                        for (int countValue : compt1.values()) {
                            sum += countValue;
                        }

                        int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                        if (gtCount > highestGenotypeCount) {
                            highestGenotypeCount = gtCount;
                            mostFrequentGenotype = genotype;
                        }
                        genotypeCounts.put(genotype, gtCount);
                    }

                List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>()
                        : variant.getAllelesFromGenotypeCode(mostFrequentGenotype);

                if (alleles.size() != 0) {
                    zos.write(("acounts=" + individualId + ":").getBytes());

                    for (String knowAllelesCompt : compt1.keySet()) {
                        zos.write(
                                (knowAllelesCompt + " " + nf.format(compt1.get(knowAllelesCompt) / (float) sum)
                                        + " " + compt1.get(knowAllelesCompt) + " ").getBytes());
                    }
                    zos.write((alleles.size() + ";").getBytes());
                }
                if (genotypeCounts.size() > 1) {
                    Comparable sVariantId = markerSynonyms != null ? markerSynonyms.get(variant.getId())
                            : variant.getId();
                    warningFileWriter.write("- Dissimilar genotypes found for variant "
                            + (sVariantId == null ? variant.getId() : sVariantId) + ", individual "
                            + individualId + ". Exporting most frequent: " + StringUtils.join(alleles, ",")
                            + "\n");
                }
            }
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            //            if (nProgress%5 == 0)
            //               LOG.info("========================= exportData: " + nProgress + "% =========================" + (System.currentTimeMillis() - before)/1000 + "s");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:formatter.handler.get.FormatterGetHandler.java

/**
 * Turn a list of corcode names into an actual list of corcodes
 * @param names the docids of the corcodes
 * @param styleNames an array of style names to augment
 * @param text the text of the version/*from  w ww  . j av a  2s .c  o  m*/
 * @return an array of actual corcodes
 * @throws FormatterException 
 */
String[] fetchCorcodes(ArrayList names, ArrayList styleNames, String text) throws FormatterException {
    ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < names.size(); i++) {
        EcdosisVersion hv = doGetResourceVersion(Database.CORCODE, (String) names.get(i), version1);
        if (!styleNames.contains(hv.getStyle()))
            styleNames.add(hv.getStyle());
        list.add(new String(hv.getVersion()));
    }
    // add selections
    if (selections != null && selections.length() > 0)
        list.add(selectionsToCorcode(text));
    String[] corcodes = new String[list.size()];
    list.toArray(corcodes);
    return corcodes;
}

From source file:MSUmpire.SeqUtility.ShuffledSeqGen.java

private String shuffle(String s) {
    ArrayList<Character> list = new ArrayList<>();
    ArrayList<Integer> KRP = new ArrayList<>();
    for (int i = 0; i < s.length(); i++) {
        //            if(i>0 && s.charAt(i) == 'P' &&(s.charAt(i-1) == 'K' || s.charAt(i-1) == 'R')){
        //                KRP.add(i);
        //            }
        if (s.charAt(i) == 'K' || s.charAt(i) == 'R' || s.charAt(i) == 'P') {
            KRP.add(i);/*from   w  ww  . ja v a  2 s  . com*/
        } else {
            list.add(s.charAt(i));
        }
    }
    Collections.shuffle(list);
    String shuffledSeq = "";

    int offset = 0;
    for (int i = 0; i < s.length(); i++) {
        if (KRP.contains(i)) {
            shuffledSeq += String.valueOf(s.charAt(i));
            offset++;
        } else {
            shuffledSeq += String.valueOf(list.get(i - offset));
        }
    }
    return shuffledSeq;
}

From source file:gov.nih.nci.cabig.caaers.web.study.SolicitedAdverseEventTab.java

protected void retainOnlyTheseEpochsInStudy(HttpServletRequest request, Study study, String[] epoch_orders) {
    try {//from w  ww.j av a  2s  . co m
        ArrayList<String> unDeletedEpochs = new ArrayList<String>();

        for (String epoch_order : epoch_orders) {
            unDeletedEpochs.add(epoch_order);
        }

        List<Epoch> all_epochs = study.getActiveEpochs();
        java.util.Iterator<Epoch> iterator = all_epochs.iterator();

        while (iterator.hasNext()) {
            Epoch epoch = iterator.next();
            if (!unDeletedEpochs.contains(String.valueOf(epoch.getEpochOrder()))) {
                epoch.retire();
                //                    int count = 0;
                //                    if (epoch.getId() != null)
                //                        count = epochDao.getCountReportingPeriodsByEpochId(epoch.getId());
                //
                //                    // System.out.println("This epoch is assigned to (" + count + ") Reporting Periods.");
                //                    if (count == 0) iterator.remove(); else {
                //                        request.setAttribute("statusMessage", "wrongEpochDelete");
                //                    }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

public ArrayList<String> getAllAvalDate() {
    ArrayList<String> list = new ArrayList<String>();
    String q = "SELECT * FROM " + LocalTransformationDB.TABLE_DATE_TO_TRAFFIC + " ORDER BY "
            + LocalTransformationDB.COLUMN_DATE_ID + ";";
    Cursor cursor = database.rawQuery(q, null);
    if (cursor.moveToFirst()) {
        do {/*  w  ww. j a va  2  s  . c o m*/
            String date = cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_DATE_TEXT));
            if (!list.contains(date))
                list.add(date);
        } while (cursor.moveToNext());
    }
    cursor.close();

    Collections.sort(list, new Comparator<String>() {

        @Override
        public int compare(String arg0, String arg1) {
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            int compareResult = 0;
            try {
                Date arg0Date = format.parse(arg0);
                Date arg1Date = format.parse(arg1);
                compareResult = arg0Date.compareTo(arg1Date);
            } catch (ParseException e) {
                e.printStackTrace();
                compareResult = arg0.compareTo(arg1);
            }
            return compareResult;
        }
    });

    for (String s : list) {
        Log.e(TAG, "AvalDate:" + s);
    }
    return list;
}

From source file:com.chiorichan.scheduler.ChioriScheduler.java

public List<ChioriTask> getPendingTasks() {
    final ArrayList<ChioriTask> truePending = new ArrayList<ChioriTask>();
    for (ChioriTask task = head.getNext(); task != null; task = task.getNext()) {
        if (task.getTaskId() != -1) {
            // -1 is special code
            truePending.add(task);/*from w ww  . ja v a2  s  .co  m*/
        }
    }

    final ArrayList<ChioriTask> pending = new ArrayList<ChioriTask>();
    for (ChioriTask task : runners.values()) {
        if (task.getPeriod() >= -1L) {
            pending.add(task);
        }
    }

    for (final ChioriTask task : truePending) {
        if (task.getPeriod() >= -1L && !pending.contains(task)) {
            pending.add(task);
        }
    }
    return pending;
}

From source file:com.nononsenseapps.notepad.sync.SyncAdapter.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w. j  av a 2 s.co  m*/
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);

    // Only sync if it has been enabled by the user, and account is selected
    // Issue on reinstall where account approval is remembered by system
    if (settings.getBoolean(SyncPrefs.KEY_SYNC_ENABLE, false)
            && !settings.getString(SyncPrefs.KEY_ACCOUNT, "").isEmpty()
            && account.name.equals(settings.getString(SyncPrefs.KEY_ACCOUNT, ""))) {

        if (SYNC_DEBUG_PRINTS)
            Log.d(TAG, "onPerformSync");
        Intent i = new Intent(SYNC_STARTED);
        mContext.sendBroadcast(i);
        // For later
        Intent doneIntent = new Intent(SYNC_FINISHED);
        doneIntent.putExtra(SYNC_RESULT, ERROR);

        // Initialize necessary stuff
        GoogleDBTalker dbTalker = new GoogleDBTalker(account.name, provider);
        GoogleAPITalker apiTalker = new GoogleAPITalker();

        try {
            boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE,
                    NOTIFY_AUTH_FAILURE);

            if (connected) {
                if (SYNC_DEBUG_PRINTS)
                    Log.d(TAG, "We got an authToken atleast");

                try {
                    // FIrst of all, we need the latest updated time later.
                    // So
                    // save
                    // that for now.
                    // This is the latest time we synced
                    String lastUpdate = dbTalker.getLastUpdated(account.name);
                    //String lastUpdate = settings.getString(PREFS_LAST_SYNC_DATE, null);
                    // Get the latest hash value we saw on the server
                    String localEtag = settings.getString(PREFS_LAST_SYNC_ETAG, "");

                    // Prepare lists for items
                    ArrayList<GoogleTaskList> listsToSaveToDB = new ArrayList<GoogleTaskList>();
                    HashMap<GoogleTaskList, ArrayList<GoogleTask>> tasksInListToSaveToDB = new HashMap<GoogleTaskList, ArrayList<GoogleTask>>();

                    HashMap<Long, ArrayList<GoogleTask>> tasksInListToUpload = new HashMap<Long, ArrayList<GoogleTask>>();
                    HashMap<Long, ArrayList<GoogleTask>> allTasksInList = new HashMap<Long, ArrayList<GoogleTask>>();

                    // gets all tasks in one query
                    ArrayList<GoogleTask> allTasks = dbTalker.getAllTasks(allTasksInList, tasksInListToUpload);

                    ArrayList<GoogleTaskList> listsToUpload = new ArrayList<GoogleTaskList>();
                    ArrayList<GoogleTaskList> allLocalLists = new ArrayList<GoogleTaskList>();

                    // gets all lists in one query
                    dbTalker.getAllLists(allLocalLists, listsToUpload);

                    // Get the current hash value on the server and all
                    // remote
                    // lists if upload is not true

                    String serverEtag = apiTalker.getModifiedLists(localEtag, allLocalLists, listsToSaveToDB);

                    // IF the tags match, then nothing has changed on
                    // server.
                    if (localEtag.equals(serverEtag)) {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Etags match, nothing to download");
                    } else {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Etags dont match, downloading new tasks");
                        // Download tasks which have been updated since last
                        // time
                        for (GoogleTaskList list : listsToSaveToDB) {
                            if (list.id != null && !list.id.isEmpty()) {
                                if (SYNC_DEBUG_PRINTS)
                                    Log.d(TAG, "Saving remote modified tasks for: " + list.id);
                                tasksInListToSaveToDB.put(list,
                                        list.downloadModifiedTasks(apiTalker, allTasks, lastUpdate));
                            }
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Getting stuff we want to upload");
                    // Get stuff we would like to upload to server
                    // In case of lists, locally modified versions always
                    // wins
                    // in
                    // conflict, so nothing more to do

                    for (GoogleTaskList list : allLocalLists) {
                        ArrayList<GoogleTask> moddedTasks = tasksInListToUpload.get(list.dbId);
                        if (moddedTasks != null && !moddedTasks.isEmpty()) {
                            // There are some tasks here which we want to
                            // upload
                            if (SYNC_DEBUG_PRINTS)
                                Log.d(TAG, "List id " + list.dbId + ", Locally modified tasks found: "
                                        + moddedTasks.size());

                            // Now we need to handle possible conflicts in
                            // the
                            // tasks. But this has already been sorted when
                            // we
                            // downloaded them
                            // For any task which exists in stuffToSaveToDB,
                            // we
                            // should not upload it
                            // Iterate over a clone to avoid concurrency
                            // problems since we will be modifying
                            // the list during iteration
                            for (GoogleTask moddedTask : (ArrayList<GoogleTask>) moddedTasks.clone()) {
                                ArrayList<GoogleTask> tasksToBeSaved = tasksInListToSaveToDB.get(list);
                                if (tasksToBeSaved != null && tasksToBeSaved.contains(moddedTask)) {
                                    if (SYNC_DEBUG_PRINTS)
                                        Log.d(TAG,
                                                "This modified task was newer on server, removing from upload list: "
                                                        + moddedTask.title);
                                    moddedTasks.remove(moddedTask);
                                }
                                // In the case that a task has been deleted
                                // before it was synced the first time
                                // We should definitely not sync it. Only
                                // delete
                                // it later
                                if (moddedTask.deleted == 1
                                        && (moddedTask.id == null || moddedTask.id.isEmpty())) {
                                    moddedTasks.remove(moddedTask);
                                }
                            }
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Uploading lists");
                    // First thing we want to do is upload stuff, because
                    // some
                    // values are updated then
                    boolean uploadedStuff = false;
                    // Start with lists
                    for (GoogleTaskList list : listsToUpload) {
                        GoogleTaskList result = apiTalker.uploadList(list);
                        uploadedStuff = true;
                        if (result != null) {
                            // Make sure that local version is the same as
                            // server's
                            for (GoogleTaskList localList : allLocalLists) {
                                if (result.equals(localList)) {
                                    localList.title = result.title;
                                    localList.id = result.id;
                                    result.dbId = localList.dbId;
                                    break;
                                }
                            }
                            listsToSaveToDB.add(result);
                        }
                    }

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Uploading tasks");
                    // Right, now upload tasks
                    for (GoogleTaskList list : allLocalLists) {
                        ArrayList<GoogleTask> tasksToUpload = tasksInListToUpload.get(list.dbId);
                        if (tasksToUpload != null) {
                            for (GoogleTask task : tasksToUpload) {
                                GoogleTask result = apiTalker.uploadTask(task, list);
                                uploadedStuff = true;
                                // Task now has relevant fields set. Add to
                                // DB-list
                                if (tasksInListToSaveToDB.get(list) == null)
                                    tasksInListToSaveToDB.put(list, new ArrayList<GoogleTask>());
                                tasksInListToSaveToDB.get(list).add(result);
                            }
                        }
                    }

                    // Finally, get the updated etag from the server and
                    // save.
                    // Only worth doing if we actually uploaded anything
                    // Also, only do this if we are doing a full sync
                    String currentEtag = serverEtag;
                    if (uploadedStuff) {
                        currentEtag = apiTalker.getEtag();
                        //lastUpdate = dbTalker.getLastUpdated(account.name);
                    }

                    settings.edit().putString(PREFS_LAST_SYNC_ETAG, currentEtag)
                            //.putString(PREFS_LAST_SYNC_DATE, lastUpdate)
                            .commit();

                    // Now, set sorting values.
                    for (GoogleTaskList list : tasksInListToSaveToDB.keySet()) {
                        if (SYNC_DEBUG_PRINTS)
                            Log.d(TAG, "Setting position values in: " + list.id);
                        ArrayList<GoogleTask> tasks = tasksInListToSaveToDB.get(list);
                        if (tasks != null) {
                            if (SYNC_DEBUG_PRINTS)
                                Log.d(TAG, "Setting position values for #tasks: " + tasks.size());
                            ArrayList<GoogleTask> allListTasks = allTasksInList.get(list.dbId);
                            list.setSortingValues(tasks, allListTasks);
                        }
                    }

                    // Save to database in a single transaction
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Save stuff to DB");
                    dbTalker.SaveToDatabase(listsToSaveToDB, tasksInListToSaveToDB);
                    // Commit it
                    ContentProviderResult[] result = dbTalker.apply();

                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "Sync Complete!");
                    doneIntent.putExtra(SYNC_RESULT, SUCCESS);

                } catch (ClientProtocolException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "ClientProtocolException: " + e.getLocalizedMessage());
                } catch (JSONException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "JSONException: " + e.getLocalizedMessage());
                } catch (IOException e) {
                    syncResult.stats.numIoExceptions++;
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "IOException: " + e.getLocalizedMessage());
                } catch (RemoteException e) {
                    if (SYNC_DEBUG_PRINTS)
                        Log.d(TAG, "RemoteException: " + e.getLocalizedMessage());
                } catch (OperationApplicationException e) {
                    Log.d(TAG, "Joined operation failed: " + e.getLocalizedMessage());
                } catch (ClassCastException e) {
                    // GetListofLists will cast this if it returns a string. It should not return a string
                    // but it did...
                    Log.d(TAG, "ClassCastException: " + e.getLocalizedMessage());
                }

            } else {
                // return real failure
                if (SYNC_DEBUG_PRINTS)
                    Log.d(TAG, "Could not get authToken. Reporting authException");
                syncResult.stats.numAuthExceptions++;
                doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL);
            }

        } finally {
            // This must always be called or we will leak resources
            if (apiTalker != null) {
                apiTalker.closeClient();
            }

            mContext.sendBroadcast(doneIntent);

            if (SYNC_DEBUG_PRINTS)
                Log.d(TAG, "SyncResult: " + syncResult.toDebugString());
        }
    }
}