Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.rickendirk.rsgwijzigingen.ZoekService.java

private ArrayList<String> checkerClusters() {
    ArrayList<String> tempList = new ArrayList<>();
    //String van klas halen uit SP
    String klasTextS = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
            .getString("pref_klas", "");
    String url = "http://www.rsgtrompmeesters.nl/roosters/roosterwijzigingen/Lijsterbesstraat/subst_001.htm";
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    //Clusters ophalen uit SP
    ArrayList<String> clusters = new ArrayList<>();
    for (int a = 1; a < 15; a++) {
        //String initializen, anders kan hij hem niet toevoegen
        String clusterLowCase = "";
        String cluster = sp.getString("pref_cluster" + a, "");
        //If om nullpointer te voorkomen
        if (!cluster.equals("")) {
            clusterLowCase = cluster.substring(0, 1).toLowerCase() + cluster.substring(1);
        }/*from ww w .j av  a2 s.c  om*/
        clusters.add(clusterLowCase);
    }

    //Lege clusters weghalen uit arraylist TODO: Kijken of singleton werkt/wat het is
    clusters.removeAll(Collections.singleton(""));
    //Er moeten wel clusters zijn ingevoerd: Zo nee, komt AlertDialog via onPostExecute
    if (clusters.isEmpty()) {
        tempList.add("geenClusters");
        return tempList;
    }
    //Checken of klas niet leeg is
    if (klasTextS.equals("")) {
        tempList.add("geenKlas");
        return tempList;
    }
    //Eerste teken klas mag geen letter zijn
    if (Character.isLetter(klasTextS.charAt(0))) {
        tempList.add("EersteTekenLetter");
        return tempList;
    }
    //String opsplitsen in 2 delen, om naar hoofdletters te converteren
    char charcijfer = klasTextS.charAt(0);
    String klascijfer = String.valueOf(charcijfer);
    char charafdeling = klasTextS.charAt(1);
    String klasafdelingBig = String.valueOf(charafdeling).toUpperCase();
    //Onderstaand voor hoofdlettercorrectie
    String klasCorrect; //KlasCorrect is klas na hoofdlettercorrectie
    switch (klasTextS.length()) {
    case 2:
        klasCorrect = klascijfer + klasafdelingBig;
        break;
    case 3:
        char klasabc = klasTextS.charAt(2);
        String klasabcSmall = String.valueOf(klasabc).toLowerCase();
        klasCorrect = klascijfer + klasafdelingBig + klasabcSmall;
        break;
    case 4:
        char klasafdeling2 = klasTextS.charAt(2);
        String klasafdeling2Big = String.valueOf(klasafdeling2).toUpperCase();
        klasabc = klasTextS.charAt(3);
        klasabcSmall = String.valueOf(klasabc).toLowerCase();

        klasCorrect = klascijfer + klasafdelingBig + klasafdeling2Big + klasabcSmall;
        break;
    default:
        tempList.add("klasMeerDan4Tekens");
        return tempList;
    }
    //Try en catch in het geval dat de internetverbinding mist
    try {
        Document doc = Jsoup.connect(url).get();
        Elements tables = doc.select("table");
        if (tables.size() < 1) {
            //Geen geschikte tabel aanwezig
            tempList.add("geenTabel");
            return tempList;
        }
        Element table = tables.get(1);
        Elements rows = table.select("tr");
        //Eerste loop is om 2e loop te herhalen voor iedere cluster, tweede loop
        //doorzoekt dan op zowel klas als cluster
        for (int b = 0; b < clusters.size(); b++) {
            for (int i = 2; i < rows.size(); i++) {
                Element row = rows.get(i);
                Elements cols = row.select("td");

                if (cols.get(0).text().contains(klasCorrect) && cols.get(2).text().contains(clusters.get(b))) {
                    String vakOud = Jsoup.parse(cols.get(2).toString()).text();
                    String docentOud = Jsoup.parse(cols.get(3).toString()).text();
                    String vakNieuw = Jsoup.parse(cols.get(4).toString()).text();
                    String docentNieuw = Jsoup.parse(cols.get(5).toString()).text();
                    //If in geval van uitval, else ingeval van wijziging
                    if (Jsoup.parse(cols.get(6).toString()).text().contains("--")) {
                        //2 opties: wordt verplaatst of valt uit
                        if (Jsoup.parse(cols.get(8).toString()).text().contains("Uitval")) {
                            String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                    + Jsoup.parse(cols.get(2).toString()).text() + " valt uit";
                            tempList.add(wijziging);
                        } else {
                            //Uur wordt verplaatst
                            String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                    + "wordt verplaatst naar " + Jsoup.parse(cols.get(8).toString()).text();
                            tempList.add(wijziging);
                        }
                    } else if (vakOud.equals(vakNieuw) && docentOud.equals(docentNieuw)) {
                        String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur " + vakOud
                                + " wordt verplaatst naar " + Jsoup.parse(cols.get(6).toString()).text();
                        tempList.add(wijziging);
                    } else {
                        String wijzigingKaal =
                                // Voegt alle kolommen samen tot 1 string
                                // .text() zorgt voor leesbare text
                                // Spaties voor leesbaarheid
                                Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                        + Jsoup.parse(cols.get(2).toString()).text() + " "
                                        + Jsoup.parse(cols.get(3).toString()).text() + " wordt "
                                        + Jsoup.parse(cols.get(4).toString()).text() + " "
                                        + Jsoup.parse(cols.get(5).toString()).text() + " in "
                                        + Jsoup.parse(cols.get(6).toString()).text();

                        //ipv en naar bevatten een "/" ivm uren (ma 12-04 / 4)
                        String ipv = "";
                        if (Jsoup.parse(cols.get(7).toString()).text().contains("/")) {
                            ipv = "ipv " + Jsoup.parse(cols.get(7).toString()).text();
                        }
                        String naar = "";
                        if (Jsoup.parse(cols.get(8).toString()).text().contains("/")) {
                            naar = "naar " + Jsoup.parse(cols.get(8).toString()).text() + " ";
                        }
                        String vervangingsTekst = "";
                        //&nbsp; staat in lege cell, encoding enz, zie volgende link:
                        // http://stackoverflow.com/questions/26837034/how-to-tell-if-a-html-table-has-an-empty-cell-nbsp-using-jsoup
                        if (cols.size() > 9) {
                            if (!Jsoup.parse(cols.get(9).toString()).text().equals("\u00a0")) {
                                vervangingsTekst = "(" + Jsoup.parse(cols.get(9).toString()).text() + ")";
                            }
                        }
                        String wijziging = wijzigingKaal + " " + ipv + " " + naar + " " + vervangingsTekst;
                        tempList.add(wijziging);
                    }

                }
                //Geen wijzigingen pas bij laatste rij en de laatste cluster
                if (i == rows.size() - 1 && b == clusters.size() - 1) {
                    //Checken of tempList leeg is, zo ja 1 ding toevoegen
                    if (tempList.isEmpty()) {
                        tempList.add("Er zijn geen wijzigingen");
                    }
                    //Dag waarvoor wijzigingen zijn ophalen
                    Element dag = doc.select("body > div > div:nth-child(2) > p > b > span").first();
                    //Compatibiliteit met andere opmaak, om NPE te voorkomen
                    if (dag == null) {
                        dag = doc.select("body > center:nth-child(2) > div").first();
                    }
                    String dagStr = dag.text().toLowerCase();
                    // Woorden staan verkeerd om: omwisselen
                    int indexVanSpatie = dagStr.indexOf(" ");
                    String datum = dagStr.substring(0, indexVanSpatie);
                    String rest = dagStr.substring(indexVanSpatie + 1);
                    String dagGoed = rest + " " + datum;
                    tempList.add(dagGoed);

                    //Stand ophalen: staat in 1e tabel van HTML
                    Element tableDate = doc.select("table").get(0);
                    String dateFullText = tableDate.getElementsContainingOwnText("Stand:").text();
                    //Deel achter "Stand:" pakken
                    String FullTextSplit[] = dateFullText.split("Stand:");
                    tempList.add(FullTextSplit[1]);
                    return tempList;

                }
            }
        }
    } catch (java.io.IOException e) {
        //Error toevoegen aan tempList, dat wordt weergegeven in messagebox
        tempList.clear();
        tempList.add("verbindFout");
        return tempList;
    }
    //Zover hoort de method NOOIT te komen
    tempList.add("andereFout");
    return tempList;
}

From source file:base.BasePlayer.FileRead.java

void getVariantWindow(String chrom, int start, int end) {
    try {//from  ww  w .  java  2s. c o m
        FileRead.lastpos = 0;
        removeNonListVariants();
        removeBedLinks();

        for (int i = 0; i < Control.controlData.fileArray.size(); i++) {
            Control.controlData.fileArray.get(i).controlled = false;
        }
        readFiles = true;
        head.putNext(null);
        current = head;
        cancelvarcount = false;
        cancelfileread = false;

        Main.drawCanvas.loadingtext = "Loading variants...";
        for (int i = 0; i < Main.samples; i++) {
            if (cancelvarcount || cancelfileread) {
                cancelFileRead();
                break;
            }
            if (Main.drawCanvas.sampleList.get(i).getTabixFile() == null
                    || Main.drawCanvas.sampleList.get(i).multipart) {
                continue;
            }
            current = head;

            getVariants(chrom, start, end, Main.drawCanvas.sampleList.get(i));

        }
        readFiles = false;
        annotate();

        if (Control.controlData.controlsOn) {
            Control.applyControl();
        }
        Main.bedCanvas.intersected = false;
        if (bigcalc) {
            Main.drawCanvas.calcClusters(FileRead.head);
        } else {
            Main.drawCanvas.calcClusters(FileRead.head, 1);
        }

        if (Main.bedCanvas.bedOn) {
            //VarNode current = FileRead.head.getNext();

            /*while(current != null) {   
                       
               current.bedhit = true;   
               current = current.getNext();
            }*/
            ArrayList<BedTrack> bigs = new ArrayList<BedTrack>();
            int smalls = 0;
            for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {
                if (!Main.bedCanvas.bedTrack.get(i).small
                        || Main.bedCanvas.bedTrack.get(i).getZoomlevel() != null) {
                    if (Main.bedCanvas.bedTrack.get(i).intersect) {
                        bigs.add(Main.bedCanvas.bedTrack.get(i));
                        Main.bedCanvas.bedTrack.get(i).intersect = false;
                    }
                } else {
                    if (Main.bedCanvas.bedTrack.get(i).intersect) {
                        smalls++;
                    }
                }
            }
            if (smalls == 0) {
                VarNode current = FileRead.head.getNext();
                while (current != null) {

                    current.bedhit = true;
                    current = current.getNext();
                }
            }
            for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {
                Main.bedCanvas.bedTrack.get(i).used = false;
                if (Main.bedCanvas.bedTrack.get(i).small
                        && Main.bedCanvas.bedTrack.get(i).getZoomlevel() == null) {
                    if (Main.bedCanvas.bedTrack.get(i).intersect && !Main.bedCanvas.bedTrack.get(i).loading) {
                        Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(),
                                FileRead.head.getNext());
                    } else if (Main.bedCanvas.bedTrack.get(i).intersect
                            && Main.bedCanvas.bedTrack.get(i).loading) {
                        Main.bedCanvas.bedTrack.get(i).waiting = true;
                    }
                }
                //else if(Main.bedCanvas.bedTrack.get(i).intersect) {   

                /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i));
                annotator.annotateVars();            */
                //   }
            }
            if (bigs.size() > 0) {
                for (int i = 0; i < bigs.size(); i++) {
                    bigs.get(i).intersect = true;
                    BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i));
                    annotator.annotateVars();
                }
                bigs.clear();
            }
            Main.bedCanvas.intersected = true;
            if (FileRead.bigcalc) {
                Main.drawCanvas.calcClusters(FileRead.head);
            } else {
                Main.drawCanvas.calcClusters(FileRead.head, 1);

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

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;//  w  ww . java  2 s.c  o m
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

public void editDirFilterDlg(final SyncTaskItem sti, final String prof_master,
        final ArrayList<String> dir_filter, final NotifyEvent p_ntfy) {
    ArrayList<FilterListItem> filterList = new ArrayList<FilterListItem>();
    final AdapterFilterList filterAdapter;

    // ??/*from   ww w .j  a va2 s .  co  m*/
    final Dialog dialog = new Dialog(mContext);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setContentView(R.layout.filter_list_dlg);

    LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.filter_select_edit_view);
    ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color);

    final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.filter_select_edit_title_view);
    final TextView title = (TextView) dialog.findViewById(R.id.filter_select_edit_title);
    title_view.setBackgroundColor(mGp.themeColorList.dialog_title_background_color);
    title.setTextColor(mGp.themeColorList.text_color_dialog_title);

    filterAdapter = new AdapterFilterList(mContext, R.layout.filter_list_item_view, filterList);
    final ListView lv = (ListView) dialog.findViewById(R.id.filter_select_edit_listview);

    for (int i = 0; i < dir_filter.size(); i++) {
        String inc = dir_filter.get(i).substring(0, 1);
        String filter = dir_filter.get(i).substring(1, dir_filter.get(i).length());
        boolean b_inc = false;
        if (inc.equals(SMBSYNC_PROF_FILTER_INCLUDE))
            b_inc = true;
        filterAdapter.add(new FilterListItem(filter, b_inc));
    }
    if (filterAdapter.getCount() == 0)
        filterAdapter.add(new FilterListItem(mContext.getString(R.string.msgs_filter_list_no_filter), false));
    lv.setAdapter(filterAdapter);
    lv.setScrollingCacheEnabled(false);
    lv.setScrollbarFadingEnabled(false);

    title.setText(mContext.getString(R.string.msgs_filter_list_dlg_dir_filter));
    final TextView dlg_msg = (TextView) dialog.findViewById(R.id.filter_select_edit_msg);
    final Button dirbtn = (Button) dialog.findViewById(R.id.filter_select_edit_dir_btn);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);

    final EditText et_filter = (EditText) dialog.findViewById(R.id.filter_select_edit_new_filter);
    final Button addbtn = (Button) dialog.findViewById(R.id.filter_select_edit_add_btn);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.filter_select_edit_cancel_btn);
    final Button btn_ok = (Button) dialog.findViewById(R.id.filter_select_edit_ok_btn);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> items, View view, int idx, long id) {
            FilterListItem fli = filterAdapter.getItem(idx);
            if (fli.getFilter().startsWith("---") || fli.isDeleted())
                return;
            // ????????
            editDirFilter(idx, filterAdapter, fli, fli.getFilter());
        }
    });

    // Add?
    et_filter.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() != 0) {
                if (isFilterExists(s.toString().trim(), filterAdapter)) {
                    String mtxt = mContext.getString(R.string.msgs_filter_list_duplicate_filter_specified);
                    dlg_msg.setText(String.format(mtxt, s.toString().trim()));
                    addbtn.setEnabled(false);
                    dirbtn.setEnabled(true);
                    btn_ok.setEnabled(true);
                } else {
                    dlg_msg.setText("");
                    addbtn.setEnabled(true);
                    dirbtn.setEnabled(false);
                    btn_ok.setEnabled(false);
                }
            } else {
                addbtn.setEnabled(false);
                dirbtn.setEnabled(true);
                btn_ok.setEnabled(true);
            }
            //            et_filter.setText(s);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    addbtn.setEnabled(false);
    addbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dlg_msg.setText("");
            String newfilter = et_filter.getText().toString();
            if (isFilterExists(newfilter, filterAdapter)) {
                String mtxt = mContext.getString(R.string.msgs_filter_list_duplicate_filter_specified);
                dlg_msg.setText(String.format(mtxt, newfilter));
                return;
            }
            dlg_msg.setText("");
            et_filter.setText("");
            if (filterAdapter.getItem(0).getFilter().startsWith("---"))
                filterAdapter.remove(filterAdapter.getItem(0));
            filterAdapter.add(new FilterListItem(newfilter, true));
            filterAdapter.setNotifyOnChange(true);
            filterAdapter.sort(new Comparator<FilterListItem>() {
                @Override
                public int compare(FilterListItem lhs, FilterListItem rhs) {
                    return lhs.getFilter().compareToIgnoreCase(rhs.getFilter());
                };
            });
            dirbtn.setEnabled(true);
            btn_ok.setEnabled(true);
        }
    });
    // Directory?
    //      if (getProfileType(prof_master,prof_dapter).equals("L")) {
    //         if (!mGp.externalStorageIsMounted) dirbtn.setEnabled(false);
    //      } else if (getProfileType(prof_master,prof_dapter).equals("R")) {
    //         if (util.isRemoteDisable()) dirbtn.setEnabled(false);
    //      } else dirbtn.setEnabled(false);
    dirbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            NotifyEvent ntfy = new NotifyEvent(mContext);
            //Listen setRemoteShare response 
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(Context arg0, Object[] arg1) {
                    dlg_msg.setText("");
                }

                @Override
                public void negativeResponse(Context arg0, Object[] arg1) {
                    if (arg1 != null)
                        dlg_msg.setText((String) arg1[0]);
                    else
                        dlg_msg.setText("");
                }
            });
            listDirFilter(sti, prof_master, dir_filter, filterAdapter, ntfy);
        }
    });

    // CANCEL?
    btn_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
            //            glblParms.profileListView.setSelectionFromTop(currentViewPosX,currentViewPosY);
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btn_cancel.performClick();
        }
    });
    // OK?
    btn_ok.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
            dir_filter.clear();
            if (filterAdapter.getCount() > 0) {
                for (int i = 0; i < filterAdapter.getCount(); i++) {
                    if (!filterAdapter.getItem(i).isDeleted()
                            && !filterAdapter.getItem(i).getFilter().startsWith("---")) {
                        String inc = SMBSYNC_PROF_FILTER_EXCLUDE;
                        if (filterAdapter.getItem(i).getInc())
                            inc = SMBSYNC_PROF_FILTER_INCLUDE;
                        dir_filter.add(inc + filterAdapter.getItem(i).getFilter());
                    }

                }
            }
            p_ntfy.notifyToListener(true, null);
        }
    });
    //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
    //      dialog.setCancelable(false);
    dialog.show();

}

From source file:com.krawler.spring.hrms.common.hrmsCommonController.java

public ModelAndView exportUserInfo(HttpServletRequest request, HttpServletResponse response) {
    KwlReturnObject kmsg = null;/*from  w w w.j av a2  s  .  c  o m*/
    JSONObject jobj = new JSONObject();
    JSONArray jarr = new JSONArray();
    JSONObject countobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    try {
        String Searchjson = request.getParameter("searchJson");
        String appendCase = "and";
        String companyid = sessionHandlerImplObj.getCompanyid(request);
        String lid = StringUtil.checkForNull(request.getParameter("lid"));
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        ArrayList filter_names = new ArrayList(
                Arrays.asList("ua.user.company.companyID", "ua.user.deleteflag"));
        ArrayList filter_values = new ArrayList(Arrays.asList(companyid, 0));
        requestParams.put("ss", StringUtil.checkForNull(request.getParameter("ss")));
        requestParams.put("allflag", true);
        requestParams.put("searchcol", new String[] { "u.firstName", "u.lastName", "ua.department.value",
                "ua.designationid.value", "ua.role.name", "u.emailID" });
        if (request.getParameter("combo") != null) {
            requestParams.put("combo", request.getParameter("combo"));
        } else {
            requestParams.put("combo", "");
        }
        StringUtil.checkpaging(requestParams, request);
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        if (!StringUtil.isNullOrEmpty(request.getParameter("stdate"))) {
            filter_names.add(">=emp.joindate");
            filter_values.add(new Date(df.format(new Date(request.getParameter("stdate")))));
            filter_names.add("<=emp.joindate");
            filter_values.add(new Date(df.format(new Date(request.getParameter("enddate")))));
        }

        if (!StringUtil.isNullOrEmpty(Searchjson)) {
            getMyAdvanceSearchparams(Searchjson, filter_names);
            insertParamAdvanceSearchString(filter_values, Searchjson);
        }
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_values", filter_values);

        kmsg = hrmsCommonDAOObj.getUserDetailsHrms(requestParams);
        List lst = kmsg.getEntityList();
        jarr = kwlCommonTablesDAOObj.getDetailsJson(lst, 0, "com.krawler.common.admin.User");

        int count = 0;
        for (int ctr = 0; ctr < jarr.length(); ctr++) {
            jobj = jarr.getJSONObject(ctr);
            Object[] row = (Object[]) lst.get(ctr);
            User u = (User) jobj.get("instance");
            Useraccount ua = (Useraccount) kwlCommonTablesDAOObj
                    .getObject("com.krawler.common.admin.Useraccount", row[0].toString());
            if (row[1] != null) {
                Empprofile e = (Empprofile) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.ess.Empprofile",
                        row[1].toString());
                if (!StringUtil.isNullOrEmpty(e.getStatus())) {
                    jobj.put("status", messageSource.getMessage("hrms.administration." + e.getStatus(), null,
                            e.getStatus(), RequestContextUtils.getLocale(request)));
                } else {
                    jobj.put("status", messageSource.getMessage("hrms.administration.Pending", null, "Pending",
                            RequestContextUtils.getLocale(request)));
                }
                jobj.put("dob", e.getDoB() == null ? "" : e.getDoB());
                jobj.put("gender", e.getGender() == null ? "" : e.getGender());
                jobj.put("bloodgrp", e.getBloodgrp() == null ? "" : e.getBloodgrp());
                jobj.put("fathername", e.getFathername() == null ? "" : e.getFathername());
                jobj.put("mothername", e.getMothername() == null ? "" : e.getMothername());
                jobj.put("passportno", e.getPassportno() == null ? "" : e.getPassportno());
                jobj.put("joindate", e.getJoindate() == null ? "" : e.getJoindate());
                jobj.put("confirmdate", e.getConfirmdate() == null ? "" : e.getConfirmdate());
                jobj.put("middlename", e.getMiddlename() == null ? "" : e.getMiddlename());
                jobj.put("keyskills", e.getKeyskills() == null ? "" : e.getKeyskills());
                jobj.put("wkstarttime", e.getWkstarttime() == null ? "" : e.getWkstarttime());
                jobj.put("wkendtime", e.getWkendtime() == null ? "" : e.getWkendtime());
                jobj.put("weekoff", e.getWeekoff() == null ? "" : e.getWeekoff());
                jobj.put("pannumber", e.getPanno() == null ? "" : e.getPanno());
                jobj.put("updatedon", e.getUpdated_on() == null ? "" : e.getUpdated_on());
            } else {
                jobj.put("status", messageSource.getMessage("hrms.recruitment.InComplete", null, "Incomplete",
                        RequestContextUtils.getLocale(request)));
                jobj.put("dob", "");
                jobj.put("gender", "");
                jobj.put("bloodgrp", "");
                jobj.put("fathername", "");
                jobj.put("mothername", "");
                jobj.put("passportno", "");
                jobj.put("joindate", "");
                jobj.put("confirmdate", "");
                jobj.put("middlename", "");
                jobj.put("keyskills", "");
                jobj.put("wkstarttime", "");
                jobj.put("wkendtime", "");
                jobj.put("weekoff", "");
            }
            jobj.put("department", (ua.getDepartment() == null ? "" : ua.getDepartment().getId()));
            jobj.put("departmentname", (ua.getDepartment() == null ? "" : ua.getDepartment().getValue()));
            jobj.put("role", (ua.getRole() == null ? "" : ua.getRole().getID()));
            String name = "";
            if (ua.getRole() != null && ua.getRole().getCompany() != null) {
                name = ua.getRole().getName();
            } else {
                name = messageSource.getMessage("hrms.common.role." + ua.getRole().getID(), null,
                        ua.getRole().getName(), RequestContextUtils.getLocale(request));
            }
            jobj.put("rolename", (ua.getRole() == null ? "" : name));
            jobj.put("username", u.getUserLogin().getUserName());
            jobj.put("fullname", u.getFirstName() + " " + (u.getLastName() == null ? "" : u.getLastName()));
            jobj.put("lastlogin",
                    (u.getUserLogin().getLastActivityDate() == null ? ""
                            : sessionHandlerImplObj.getDateFormatter(request)
                                    .format(u.getUserLogin().getLastActivityDate())));
            jobj.put("designation", ua.getDesignationid() == null ? "" : ua.getDesignationid().getValue());
            jobj.put("designationid", ua.getDesignationid() == null ? "" : ua.getDesignationid().getId());
            jobj.put("templateid", ua.getTemplateid() != null ? ua.getTemplateid() : "");
            jobj.put("salary", ua.getSalary() != null ? ua.getSalary() : "");
            jobj.put("accno", ua.getAccno() != null ? ua.getAccno() : "");
            jobj.put("createdon", ua.getUser().getCreatedon() != null ? ua.getUser().getCreatedon() : "");
            requestParams.clear();
            requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
            requestParams.put("empid", ua.getEmployeeid());
            KwlReturnObject result;
            //                KwlReturnObject result = profileHandlerDAOObj.getEmpidFormatEdit(requestParams);
            if (ua.getEmployeeIdFormat() == null) {
                jobj.put("employeeid", ua.getEmployeeid() == null ? ""
                        : profileHandlerDAOObj.getEmpidFormatEdit(requestParams).getEntityList().get(0));
            } else {
                requestParams.put("standardEmpId", profileHandlerDAOObj.getEmpidFormatEdit(requestParams)
                        .getEntityList().get(0).toString());
                requestParams.put("employeeIdFormat", ua.getEmployeeIdFormat());
                jobj.put("employeeid", profileHandlerDAOObj.getNewEmployeeIdFormat(requestParams));
            }
            requestParams.clear();
            filter_names.add("assignemp.userID");
            filter_values.add(u.getUserID());

            filter_names.add("managerstatus");
            filter_values.add(1);

            requestParams.put("filter_names",
                    Arrays.asList("assignemp.userID", "managerstatus", "assignman.deleteflag"));
            requestParams.put("filter_values", Arrays.asList(u.getUserID(), 1, 0));

            result = hrmsCommonDAOObj.getAssignmanager(requestParams);
            List lst1 = result.getEntityList();
            Iterator itr1 = lst1.iterator();

            if (itr1.hasNext()) {
                String manager = "";
                while (itr1.hasNext()) {
                    Assignmanager asm = (Assignmanager) itr1.next();
                    if (asm.getAssignman() != null) {
                        jobj.append("managerid", asm.getAssignman().getUserID());
                        manager += asm.getAssignman().getFirstName() + " " + asm.getAssignman().getLastName()
                                + ",";
                    }
                }
                jobj.put("manager", manager.substring(0, manager.length() - 1));
            } else {
                jobj.put("manager", " ");
                jobj.put("managerid", " ");
            }

            requestParams.clear();
            filter_names.clear();
            filter_values.clear();
            filter_names.add("employee.userID");
            filter_values.add(u.getUserID());

            filter_names.add("reviewer.deleteflag");
            filter_values.add(0);

            filter_names.add("reviewerstatus");
            filter_values.add(1);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getAssignreviewer(requestParams);
            lst1 = result.getEntityList();
            itr1 = lst1.iterator();
            if (itr1.hasNext()) {
                String reviewer = "";
                while (itr1.hasNext()) {
                    Assignreviewer rev = (Assignreviewer) itr1.next();
                    if (rev.getReviewer() != null) {
                        jobj.append("reviewerid", rev.getReviewer().getUserID());
                        reviewer += rev.getReviewer().getFirstName() + " " + rev.getReviewer().getLastName()
                                + ",";
                    }
                }
                jobj.put("reviewer", reviewer.substring(0, reviewer.length() - 1));
            } else {
                jobj.put("reviewer", " ");
                jobj.put("reviewerid", " ");
            }

            jarr.put(ctr, jobj);
            count++;
        }

        countobj.put("data", jarr);
        countobj.put("count", kmsg.getRecordTotalCount());
        exportDAOImplObj.processRequest(request, response, countobj);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

From source file:com.datatorrent.stram.engine.GenericNode.java

/**
 * Originally this method was defined in an attempt to implement the interface Runnable.
 *
 * Note that activate does not return as long as there is useful workload for the node.
 *//*from   ww  w  .ja v  a2 s.co m*/
@Override
@SuppressWarnings({ "SleepWhileInLoop", "UseSpecificCatch", "BroadCatchBlock", "TooBroadCatch" })
public final void run() {
    doCheckpoint = false;

    final long maxSpinMillis = context.getValue(OperatorContext.SPIN_MILLIS);
    long spinMillis = 0;
    final boolean handleIdleTime = operator instanceof IdleTimeHandler;
    int totalQueues = inputs.size();
    int regularQueues = totalQueues;
    // regularQueues is the number of queues that are not connected to a DelayOperator
    for (String portName : inputs.keySet()) {
        if (isInputPortConnectedToDelayOperator(portName)) {
            regularQueues--;
        }
    }

    ArrayList<Map.Entry<String, SweepableReservoir>> activeQueues = new ArrayList<>();
    activeQueues.addAll(inputs.entrySet());

    int expectingBeginWindow = activeQueues.size();
    int receivedEndWindow = 0;
    long firstWindowId = -1;

    calculateNextCheckpointWindow();

    TupleTracker tracker;
    LinkedList<TupleTracker> resetTupleTracker = new LinkedList<TupleTracker>();
    try {
        do {
            Iterator<Map.Entry<String, SweepableReservoir>> buffers = activeQueues.iterator();
            activequeue: while (buffers.hasNext()) {
                Map.Entry<String, SweepableReservoir> activePortEntry = buffers.next();
                SweepableReservoir activePort = activePortEntry.getValue();
                Tuple t = activePort.sweep();
                if (t != null) {
                    spinMillis = 0;
                    boolean delay = (operator instanceof Operator.DelayOperator);
                    long windowAhead = 0;
                    if (delay) {
                        windowAhead = WindowGenerator.getAheadWindowId(t.getWindowId(), firstWindowMillis,
                                windowWidthMillis, 1);
                    }
                    switch (t.getType()) {
                    case BEGIN_WINDOW:
                        if (expectingBeginWindow == totalQueues) {
                            // This is the first begin window tuple among all ports
                            if (isInputPortConnectedToDelayOperator(activePortEntry.getKey())) {
                                // We need to wait for the first BEGIN_WINDOW from a port not connected to DelayOperator before
                                // we can do anything with it, because otherwise if a CHECKPOINT tuple arrives from
                                // upstream after the BEGIN_WINDOW tuple for the next window from the delay operator, it would end
                                // up checkpointing in the middle of the window.  This code is assuming we have at least one
                                // input port that is not connected to a DelayOperator, and we might have to change this later.
                                // In the future, this condition will not be needed if we get rid of the CHECKPOINT tuple.
                                continue;
                            }
                            activePort.remove();
                            expectingBeginWindow--;
                            receivedEndWindow = 0;
                            currentWindowId = t.getWindowId();
                            if (delay) {
                                if (WindowGenerator.getBaseSecondsFromWindowId(windowAhead) > t
                                        .getBaseSeconds()) {
                                    // Buffer server code strips out the base seconds from BEGIN_WINDOW and END_WINDOW tuples for
                                    // serialization optimization.  That's why we need a reset window here to tell the buffer
                                    // server we are having a new baseSeconds now.
                                    Tuple resetWindowTuple = new ResetWindowTuple(windowAhead);
                                    for (int s = sinks.length; s-- > 0;) {
                                        sinks[s].put(resetWindowTuple);
                                    }
                                    controlTupleCount++;
                                }
                                t.setWindowId(windowAhead);
                            }
                            for (int s = sinks.length; s-- > 0;) {
                                sinks[s].put(t);
                            }
                            controlTupleCount++;

                            context.setWindowsFromCheckpoint(nextCheckpointWindowCount--);

                            if (applicationWindowCount == 0) {
                                insideWindow = true;
                                operator.beginWindow(currentWindowId);
                            }
                        } else if (t.getWindowId() == currentWindowId) {
                            activePort.remove();
                            expectingBeginWindow--;
                        } else {
                            buffers.remove();
                            String port = activePortEntry.getKey();
                            if (PROCESSING_MODE == ProcessingMode.AT_MOST_ONCE) {
                                if (t.getWindowId() < currentWindowId) {
                                    /*
                                     * we need to fast forward this stream till we find the current
                                     * window or the window which is bigger than the current window.
                                     */

                                    /* lets move the current reservoir in the background */
                                    Sink<Object> sink = activePort.setSink(Sink.BLACKHOLE);
                                    deferredInputConnections.add(0,
                                            new DeferredInputConnection(port, activePort));

                                    /* replace it with the reservoir which blocks the tuples in the past */
                                    WindowIdActivatedReservoir wiar = new WindowIdActivatedReservoir(port,
                                            activePort, currentWindowId);
                                    wiar.setSink(sink);
                                    inputs.put(port, wiar);
                                    activeQueues.add(new AbstractMap.SimpleEntry<String, SweepableReservoir>(
                                            port, wiar));
                                    break activequeue;
                                } else {
                                    expectingBeginWindow--;
                                    if (++receivedEndWindow == totalQueues) {
                                        processEndWindow(null);
                                        activeQueues.addAll(inputs.entrySet());
                                        expectingBeginWindow = activeQueues.size();
                                        break activequeue;
                                    }
                                }
                            } else {
                                logger.error(
                                        "Catastrophic Error: Out of sequence {} tuple {} on port {} while expecting {}",
                                        t.getType(), Codec.getStringWindowId(t.getWindowId()), port,
                                        Codec.getStringWindowId(currentWindowId));
                                System.exit(2);
                            }
                        }
                        break;

                    case END_WINDOW:
                        buffers.remove();
                        if (t.getWindowId() == currentWindowId) {
                            activePort.remove();
                            endWindowDequeueTimes.put(activePort, System.currentTimeMillis());
                            if (++receivedEndWindow == totalQueues) {
                                assert (activeQueues.isEmpty());
                                if (delay) {
                                    t.setWindowId(windowAhead);
                                }
                                processEndWindow(t);
                                activeQueues.addAll(inputs.entrySet());
                                expectingBeginWindow = activeQueues.size();
                                break activequeue;
                            }
                        }
                        break;

                    case CHECKPOINT:
                        activePort.remove();
                        long checkpointWindow = t.getWindowId();
                        if (lastCheckpointWindowId < checkpointWindow) {
                            dagCheckpointOffsetCount = 0;
                            if (PROCESSING_MODE == ProcessingMode.EXACTLY_ONCE) {
                                lastCheckpointWindowId = checkpointWindow;
                            } else if (!doCheckpoint) {
                                if (checkpointWindowCount == 0) {
                                    checkpoint(checkpointWindow);
                                    lastCheckpointWindowId = checkpointWindow;
                                } else {
                                    doCheckpoint = true;
                                }
                            }
                            if (!delay) {
                                for (int s = sinks.length; s-- > 0;) {
                                    sinks[s].put(t);
                                }
                                controlTupleCount++;
                            }
                        }
                        break;

                    case RESET_WINDOW:
                        /**
                         * we will receive tuples which are equal to the number of input streams.
                         */
                        activePort.remove();
                        if (isInputPortConnectedToDelayOperator(activePortEntry.getKey())) {
                            break; // breaking out of the switch/case
                        }

                        buffers.remove();
                        int baseSeconds = t.getBaseSeconds();
                        tracker = null;
                        for (Iterator<TupleTracker> trackerIterator = resetTupleTracker
                                .iterator(); trackerIterator.hasNext();) {
                            tracker = trackerIterator.next();
                            if (tracker.tuple.getBaseSeconds() == baseSeconds) {
                                break;
                            }
                        }

                        if (tracker == null) {
                            tracker = new TupleTracker(t, regularQueues);
                            resetTupleTracker.add(tracker);
                        }
                        int trackerIndex = 0;
                        while (trackerIndex < tracker.ports.length) {
                            if (tracker.ports[trackerIndex] == null) {
                                tracker.ports[trackerIndex++] = activePort;
                                break;
                            } else if (tracker.ports[trackerIndex] == activePort) {
                                break;
                            }

                            trackerIndex++;
                        }

                        if (trackerIndex == regularQueues) {
                            Iterator<TupleTracker> trackerIterator = resetTupleTracker.iterator();
                            while (trackerIterator.hasNext()) {
                                if (trackerIterator.next().tuple.getBaseSeconds() <= baseSeconds) {
                                    trackerIterator.remove();
                                }
                            }
                            if (!delay) {
                                for (int s = sinks.length; s-- > 0;) {
                                    sinks[s].put(t);
                                }
                                controlTupleCount++;
                            }
                            if (!activeQueues.isEmpty()) {
                                // make sure they are all queues from DelayOperator
                                for (Map.Entry<String, SweepableReservoir> entry : activeQueues) {
                                    if (!isInputPortConnectedToDelayOperator(entry.getKey())) {
                                        assert (false);
                                    }
                                }
                                activeQueues.clear();
                            }
                            activeQueues.addAll(inputs.entrySet());
                            expectingBeginWindow = activeQueues.size();

                            if (firstWindowId == -1) {
                                if (delay) {
                                    for (int s = sinks.length; s-- > 0;) {
                                        sinks[s].put(t);
                                    }
                                    controlTupleCount++;
                                    // if it's a DelayOperator and this is the first RESET_WINDOW (start) or END_STREAM
                                    // (recovery), fabricate the first window
                                    fabricateFirstWindow((Operator.DelayOperator) operator, windowAhead);
                                }
                                firstWindowId = t.getWindowId();
                            }
                            break activequeue;
                        }
                        break;

                    case END_STREAM:
                        activePort.remove();
                        buffers.remove();
                        if (firstWindowId == -1) {
                            // this is for recovery from a checkpoint for DelayOperator
                            if (delay) {
                                // if it's a DelayOperator and this is the first RESET_WINDOW (start) or END_STREAM (recovery),
                                // fabricate the first window
                                fabricateFirstWindow((Operator.DelayOperator) operator, windowAhead);
                            }
                            firstWindowId = t.getWindowId();
                        }
                        for (Iterator<Entry<String, SweepableReservoir>> it = inputs.entrySet().iterator(); it
                                .hasNext();) {
                            Entry<String, SweepableReservoir> e = it.next();
                            if (e.getValue() == activePort) {
                                if (!descriptor.inputPorts.isEmpty()) {
                                    descriptor.inputPorts.get(e.getKey()).component.setConnected(false);
                                }
                                it.remove();

                                /* check the deferred connection list for any new port that should be connected here */
                                Iterator<DeferredInputConnection> dici = deferredInputConnections.iterator();
                                while (dici.hasNext()) {
                                    DeferredInputConnection dic = dici.next();
                                    if (e.getKey().equals(dic.portname)) {
                                        connectInputPort(dic.portname, dic.reservoir);
                                        dici.remove();
                                        activeQueues.add(
                                                new AbstractMap.SimpleEntry<>(dic.portname, dic.reservoir));
                                        break activequeue;
                                    }
                                }

                                break;
                            }
                        }

                        /**
                         * We are not going to receive begin window on this ever!
                         */
                        expectingBeginWindow--;

                        /**
                         * Since one of the operators we care about it gone, we should relook at our ports.
                         * We need to make sure that the END_STREAM comes outside of the window.
                         */
                        regularQueues--;
                        totalQueues--;

                        boolean break_activequeue = false;
                        if (regularQueues == 0) {
                            alive = false;
                            break_activequeue = true;
                        } else if (activeQueues.isEmpty()) {
                            assert (!inputs.isEmpty());
                            processEndWindow(null);
                            activeQueues.addAll(inputs.entrySet());
                            expectingBeginWindow = activeQueues.size();
                            break_activequeue = true;
                        }

                        /**
                         * also make sure that we update the reset tuple tracker if this stream had delivered any reset tuples.
                         * Check all the reset buffers to see if current input port has already delivered reset tuple. If it has
                         * then we are waiting for something else to deliver the reset tuple, so just clear current reservoir
                         * from the list of tracked reservoirs. If the current input port has not delivered the reset tuple, and
                         * it's the only one which has not, then we consider it delivered and release the reset tuple downstream.
                         */
                        Tuple tuple = null;
                        for (Iterator<TupleTracker> trackerIterator = resetTupleTracker
                                .iterator(); trackerIterator.hasNext();) {
                            tracker = trackerIterator.next();

                            trackerIndex = 0;
                            while (trackerIndex < tracker.ports.length) {
                                if (tracker.ports[trackerIndex] == activePort) {
                                    SweepableReservoir[] ports = new SweepableReservoir[regularQueues];
                                    System.arraycopy(tracker.ports, 0, ports, 0, trackerIndex);
                                    if (trackerIndex < regularQueues) {
                                        System.arraycopy(tracker.ports, trackerIndex + 1, ports, trackerIndex,
                                                tracker.ports.length - trackerIndex - 1);
                                    }
                                    tracker.ports = ports;
                                    break;
                                } else if (tracker.ports[trackerIndex] == null) {
                                    if (trackerIndex == regularQueues) { /* regularQueues is already adjusted above */
                                        if (tuple == null
                                                || tuple.getBaseSeconds() < tracker.tuple.getBaseSeconds()) {
                                            tuple = tracker.tuple;
                                        }

                                        trackerIterator.remove();
                                    }
                                    break;
                                } else {
                                    tracker.ports = Arrays.copyOf(tracker.ports, regularQueues);
                                }

                                trackerIndex++;
                            }
                        }

                        /*
                         * Since we were waiting for a reset tuple on this stream, we should not any longer.
                         */
                        if (tuple != null && !delay) {
                            for (int s = sinks.length; s-- > 0;) {
                                sinks[s].put(tuple);
                            }
                            controlTupleCount++;
                        }

                        if (break_activequeue) {
                            break activequeue;
                        }
                        break;

                    default:
                        throw new UnhandledException("Unrecognized Control Tuple",
                                new IllegalArgumentException(t.toString()));
                    }
                }
            }

            if (activeQueues.isEmpty() && alive) {
                logger.error("Catastrophic Error: Invalid State - the operator blocked forever!");
                System.exit(2);
            } else {
                boolean need2sleep = true;
                for (Map.Entry<String, SweepableReservoir> cb : activeQueues) {
                    need2sleep = cb.getValue().isEmpty();
                    if (!need2sleep) {
                        spinMillis = 0;
                        break;
                    }
                }

                if (need2sleep) {
                    if (handleIdleTime && insideWindow) {
                        ((IdleTimeHandler) operator).handleIdleTime();
                    } else {
                        Thread.sleep(spinMillis);
                        spinMillis = Math.min(maxSpinMillis, spinMillis + 1);
                    }
                }
            }
        } while (alive);
    } catch (ShutdownException se) {
        logger.debug("Shutdown requested by the operator when alive = {}.", alive);
        alive = false;
    } catch (Throwable cause) {
        synchronized (this) {
            if (alive) {
                DTThrowable.rethrow(cause);
            }
        }

        Throwable rootCause = cause;
        while (rootCause != null) {
            if (rootCause instanceof InterruptedException) {
                break;
            }
            rootCause = rootCause.getCause();
        }

        if (rootCause == null) {
            DTThrowable.rethrow(cause);
        } else {
            logger.debug("Ignoring InterruptedException after shutdown", cause);
        }
    }

    /**
     * TODO: If shutdown and inside window provide alternate way of notifying the operator in such ways
     * TODO: as using a listener callback
     */
    if (insideWindow && !shutdown) {
        operator.endWindow();
        endWindowEmitTime = System.currentTimeMillis();
        if (++applicationWindowCount == APPLICATION_WINDOW_COUNT) {
            applicationWindowCount = 0;
        }

        if (++checkpointWindowCount == CHECKPOINT_WINDOW_COUNT) {
            checkpointWindowCount = 0;
            if (doCheckpoint || PROCESSING_MODE == ProcessingMode.EXACTLY_ONCE) {
                checkpoint(currentWindowId);
            }
        }

        ContainerStats.OperatorStats stats = new ContainerStats.OperatorStats();
        fixEndWindowDequeueTimesBeforeDeactivate();
        reportStats(stats, currentWindowId);
        stats.metrics = collectMetrics();
        handleRequests(currentWindowId);
    }

}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * @param toSync// w ww  .  j a  va2  s  . c om
 * @param account
 * @param extras
 * @param provider
 * @param syncResult
 * @return true if the item was sync'd successfully. Soft errors will cause this to return
 *         false.
 * @throws RemoteException
 * @throws SyncException
 * @throws JSONException
 * @throws IOException
 * @throws NetworkProtocolException
 * @throws NoPublicPath
 * @throws OperationApplicationException
 * @throws InterruptedException
 */
public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException,
        NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException {

    String pubPath = null;

    //
    // Handle http or https uris separately. These require the
    // destination uri.
    //
    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        pubPath = toSync.toString();

        if (!extras.containsKey(EXTRA_DESTINATION_URI)) {
            throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs");
        }
        toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI));
    }

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);

    // skip any items already sync'd
    if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) {
        if (DEBUG) {
            Log.d(TAG, "not syncing " + toSync + " as it's been updated recently");
        }
        syncResult.stats.numSkippedEntries++;
        return false;
    }

    // the sync map will convert the json data to ContentValues
    final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync);

    final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build();

    final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>();
    final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>();
    final LinkedList<String> cpoPubUris = new LinkedList<String>();

    //
    // first things first, upload any content that needs to be
    // uploaded.
    //

    try {
        uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult);

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // this should ensure that all items have a pubPath when we
        // query it below.

        if (pubPath == null) {
            // we should avoid calling this too much as it
            // can be expensive
            pubPath = MediaProvider.getPublicPath(mContext, toSync);
        }
    } catch (final NoPublicPath e) {
        // TODO this is a special case and this is probably not the best place to handle this.
        // Ideally, this should be done in such a way as to reduce any extra DB queries -
        // perhaps by doing a join with the parent.
        if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) {
            if (DEBUG) {
                Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first");
            }
            syncResult.stats.numSkippedEntries++;
            return false;
        }

        // if it's an item, we can handle it.
        if (isDir) {
            throw e;
        }
    }

    if (pubPath == null) {

        // this should have been updated already by the initial
        // upload, so something must be wrong
        throw new SyncException("never got a public path for " + toSync);
    }

    if (DEBUG) {
        Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync="
                + manualSync + ",...)");
        Log.d(TAG, "pubPath: " + pubPath);
    }

    final long request_time = System.currentTimeMillis();

    HttpResponse hr = mNetworkClient.get(pubPath);

    final long response_time = System.currentTimeMillis();

    // the time compensation below allows a time-based synchronization to function even if the
    // local clock is entirely wrong. The server's time is extracted using the Date header and
    // all are compared relative to the respective clock reference. Any data that's stored on
    // the mobile should be stored relative to the local clock and the server will respect the
    // same.
    long serverTime;

    try {
        serverTime = getServerTime(hr);
    } catch (final DateParseException e) {
        Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e);
        serverTime = System.currentTimeMillis();
    }

    // TODO check out
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
    final long response_delay = response_time - request_time;
    if (DEBUG) {
        Log.d(TAG, "request took " + response_delay + "ms");
    }
    final long localTime = request_time;

    // add this to the server time to get the local time
    final long localOffset = (localTime - serverTime);

    if (Math.abs(localOffset) > 30 * 60 * 1000) {
        Log.w(TAG, "local clock is off by " + localOffset + "ms");
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    final HttpEntity ent = hr.getEntity();

    String selection;
    String selectionInverse;
    String[] selectionArgs;

    if (isDir) {

        final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();

        final int len = ja.length();
        selectionArgs = new String[len];

        // build the query to see which items are already in the
        // database
        final StringBuilder sb = new StringBuilder();

        sb.append("(");

        for (int i = 0; i < len; i++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime);

            syncStatuses.put(syncStatus.remote, syncStatus);

            selectionArgs[i] = syncStatus.remote;

            // add in a placeholder for the query
            sb.append('?');
            if (i != (len - 1)) {
                sb.append(',');
            }

        }
        sb.append(")");

        final String placeholders = sb.toString();
        selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders;
        selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders;
    } else {

        final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();
        final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime);

        syncStatuses.put(syncStatus.remote, syncStatus);

        selection = JsonSyncableItem._PUBLIC_URI + "=?";
        selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?";
        selectionArgs = new String[] { syncStatus.remote };
    }

    // first check without the querystring. This will ensure that we
    // properly mark things that we already have in the database.
    final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs,
            null);

    // these items are on both sides
    try {
        final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int idCol = check.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = check.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = check.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            itemStatus.state = SyncState.BOTH_UNKNOWN;

            itemStatus.local = localUri;

            // make the status searchable by both remote and
            // local uri
            syncStatuses.put(localUri.toString(), itemStatus);
        }
    } finally {
        check.close();
    }

    Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null);

    // these items are on both sides
    try {
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE);
        final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE);
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = c.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = c.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE
                    || itemStatus.state == SyncState.NOW_UP_TO_DATE) {
                if (DEBUG) {
                    Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date.");
                }
                continue;
            }

            itemStatus.local = localUri;

            // make the status searchable by both remote and local uri
            syncStatuses.put(localUri.toString(), itemStatus);

            // last modified as stored in the DB, in phone time
            final long itemLocalModified = c.getLong(localModifiedCol);

            // last modified as stored in the DB, in server time
            final long itemServerModified = c.getLong(serverModifiedCol);
            final long localAge = localTime - itemLocalModified;

            final long remoteAge = serverTime - itemStatus.remoteModifiedTime;

            final long ageDifference = Math.abs(localAge - remoteAge);

            // up to date, as far remote -> local goes
            if (itemServerModified == itemStatus.remoteModifiedTime) {
                itemStatus.state = SyncState.ALREADY_UP_TO_DATE;
                if (DEBUG) {
                    Log.d(TAG, pubUri + " is up to date.");
                }

                // need to download
            } else if (localAge > remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms older ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); updating local copy...");
                }

                itemStatus.state = SyncState.REMOTE_DIRTY;

                final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri);

                // update this so it's in the local timescale
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE,
                        JsonSyncableItem._CREATED_DATE, localOffset);
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                        JsonSyncableItem._MODIFIED_DATE, localOffset);

                b.withValues(itemStatus.remoteCVs);
                b.withExpectedCount(1);

                cpo.add(b.build());
                cpoPubUris.add(pubUri);

                syncResult.stats.numUpdates++;

                // need to upload
            } else if (localAge < remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms newer ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); publishing to server...");
                }
                itemStatus.state = SyncState.LOCAL_DIRTY;

                mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap));
            }

            mLastUpdated.markUpdated(localUri);

            syncResult.stats.numEntries++;
        } // end for
    } finally {

        c.close();
    }

    /*
     * Apply updates in bulk
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "applying " + cpo.size() + " bulk updates...");
        }

        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "Done applying updates. Running postSync handler...");
        }

        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i));
            if (ss == null) {
                Log.e(TAG, "can't get sync status for " + res.uri);
                continue;
            }
            syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
        }

        if (DEBUG) {
            Log.d(TAG, "done running postSync handler.");
        }

        cpo.clear();
        cpoPubUris.clear();
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    /*
     * Look through the SyncState.state values and find ones that need to be stored.
     */

    for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        final String pubUri = entry.getKey();
        final SyncStatus status = entry.getValue();
        if (status.state == SyncState.REMOTE_ONLY) {
            if (DEBUG) {
                Log.d(TAG, pubUri + " is not yet stored locally, adding...");
            }

            // update this so it's in the local timescale
            correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE,
                    JsonSyncableItem._CREATED_DATE, localOffset);
            correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                    JsonSyncableItem._MODIFIED_DATE, localOffset);

            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync);
            b.withValues(status.remoteCVs);

            cpo.add(b.build());
            cpoPubUris.add(pubUri);
            syncResult.stats.numInserts++;

        }
    }

    /*
     * Execute the content provider operations in bulk.
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "bulk inserting " + cpo.size() + " items...");
        }
        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "applyBatch completed. Processing results...");
        }

        int successful = 0;
        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            if (res.uri == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "result from content provider bulk operation returned null");
                continue;
            }
            final String pubUri = cpoPubUris.get(i);
            final SyncStatus ss = syncStatuses.get(pubUri);

            if (ss == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i));
                continue;
            }

            ss.local = res.uri;
            if (DEBUG) {
                Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri);
            }

            syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
            successful++;
        }
        if (DEBUG) {
            Log.d(TAG, successful + " batch inserts successfully applied.");
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "no updates to perform.");
        }
    }

    /**
     * Look through all the items that we didn't already find on the server side, but which
     * still have a public uri. They should be checked to make sure they're not deleted.
     */
    c = provider.query(toSync, SYNC_PROJECTION,
            ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"),
            selectionArgs, null);

    try {
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);

        cpo.clear();

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            final String pubUri = c.getString(pubUriCol);
            SyncStatus ss = syncStatuses.get(pubUri);

            final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))
                    : toSync;

            if (ss == null) {
                ss = syncStatuses.get(item.toString());
            }

            if (DEBUG) {
                Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath
                        + "), but appears to be a child of " + toSync);

                if (ss != null) {
                    Log.d(TAG, "found sync status for " + item + ": " + ss);
                }
            }

            if (ss != null) {
                switch (ss.state) {
                case ALREADY_UP_TO_DATE:
                case NOW_UP_TO_DATE:
                    if (DEBUG) {
                        Log.d(TAG, item + " is already up to date. No need to see if it was deleted.");
                    }
                    continue;

                case BOTH_UNKNOWN:
                    if (DEBUG) {
                        Log.d(TAG,
                                item + " was found on both sides, but has an unknown sync status. Skipping...");
                    }
                    continue;

                default:

                    Log.w(TAG, "got an unexpected state for " + item + ": " + ss);
                }

            } else {
                ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY);
                ss.local = item;

                hr = mNetworkClient.head(pubUri);

                switch (hr.getStatusLine().getStatusCode()) {
                case 200:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 200");
                    }
                    ss.state = SyncState.BOTH_UNKNOWN;
                    break;

                case 404:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally...");
                    }
                    ss.state = SyncState.DELETED_REMOTELY;
                    final ContentProviderOperation deleteOp = ContentProviderOperation
                            .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)))
                            .build();
                    cpo.add(deleteOp);

                    break;

                default:
                    syncResult.stats.numIoExceptions++;
                    Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine());
                }
            }
            syncStatuses.put(pubUri, ss);
        } // for cursor

        if (cpo.size() > 0) {
            final ContentProviderResult[] results = provider.applyBatch(cpo);

            for (final ContentProviderResult result : results) {
                if (result.count != 1) {
                    throw new SyncException("Error deleting item");
                }
            }
        }

    } finally {
        c.close();
    }

    syncStatuses.clear();

    mLastUpdated.markUpdated(toSync);

    return true;
}

From source file:base.BasePlayer.FileRead.java

public void changeChrom(String chrom) {

    try {//from  www.j av a  2s  . c o  m

        nobeds = false;
        cancelfileread = false;
        if (!search) {
            FileRead.novars = false;
        }
        try {
            Main.drawCanvas.loading("Loading annotation...");

            Main.drawCanvas.splits.get(0).setGenes(getExons(chrom));

            Main.chromDraw.updateExons = true;
            Main.chromDraw.repaint();

        } catch (Exception e) {
            ErrorLog.addError(e.getStackTrace());
            e.printStackTrace();
        }

        Main.drawCanvas.ready("Loading annotation...");
        ArrayList<BedTrack> bigs = new ArrayList<BedTrack>();
        if (Main.bedCanvas.bedTrack.size() > 0) {

            Main.drawCanvas.loading("Loading BED-files...");
            Main.bedCanvas.bedOn = true;
            boolean ison = false;
            for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {
                if (Main.bedCanvas.bedTrack.get(i).intersect) {

                    ison = true;
                    break;
                }
            }
            if (!ison) {
                Main.bedCanvas.bedOn = false;
            }
            //if(search) {            

            for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {

                Main.bedCanvas.bedTrack.get(i).used = false;

                if (Main.bedCanvas.bedTrack.get(i).small
                        && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) {

                    Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1,
                            Main.drawCanvas.splits.get(0).chromEnd);

                } else {
                    if (search && searchEnd - searchStart < Settings.windowSize) {
                        Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), searchStart, searchEnd);
                    } else {
                        if (Main.bedCanvas.bedTrack.get(i).small) {
                            Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1,
                                    Main.drawCanvas.splits.get(0).chromEnd);
                        }
                    }
                }
                if (Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small
                        || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null)) {
                    Main.bedCanvas.bedTrack.get(i).intersect = false;

                    bigs.add(Main.bedCanvas.bedTrack.get(i));
                }
                if (nobeds) {
                    Main.drawCanvas.ready("Loading BED-files...");

                    return;
                }

            }
        }

        /*   }
           else {
                      
                      
              for(int i = 0; i< Main.bedCanvas.bedTrack.size(); i++) {
                         
                 Main.bedCanvas.bedTrack.get(i).used = false;
                         
                 if(Main.bedCanvas.bedTrack.get(i).small && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) {         
                  
          Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd);
                              
                 }
                 else {
                  
             Main.bedCanvas.getBEDfeatures(Main.bedCanvas.bedTrack.get(i), 1, Main.drawCanvas.splits.get(0).chromEnd);
                  
                 }
                 if(Main.bedCanvas.bedTrack.get(i).intersect && (!Main.bedCanvas.bedTrack.get(i).small || Main.bedCanvas.bedTrack.get(i).getBBfileReader() != null))  {
          Main.bedCanvas.bedTrack.get(i).intersect = false;
                  
          bigs.add(Main.bedCanvas.bedTrack.get(i));
                 }
                 if(nobeds) {
          Main.drawCanvas.ready("Loading BED-files...");
                  
          return;
                 }
                         
              }
           }
           */
        //}

        Main.drawCanvas.ready("Loading BED-files...");

        if (novars) {
            Main.drawCanvas.variantsStart = 0;
            Main.drawCanvas.variantsEnd = 0;

        } else {
            changing = true;
        }

        if (Main.varsamples > 0 && !novars && !bigcalc) {
            removeNonListVariants();
            removeBedLinks();

            Main.drawCanvas.loading("Loading variants...");
            head.putNext(null);
            current = FileRead.head;
            if (FileRead.head.getPosition() > 0) {
                FileRead.head = new VarNode(0, (byte) 0, "N", 0, 0, false, (float) 0, (float) 0, null, null,
                        null, null, null);
            }
            Main.drawCanvas.current = head;
            Main.chromDraw.varnode = null;
            Main.chromDraw.vardraw = null;

            for (int i = 0; i < Main.samples; i++) {
                if (nobeds) {
                    return;
                }
                if (cancelfileread || !Main.drawCanvas.loading) {

                    cancelFileRead();
                    break;
                }
                if (Main.drawCanvas.sampleList.get(i).getTabixFile() == null
                        || Main.drawCanvas.sampleList.get(i).multipart) {
                    continue;
                }

                if (search) {

                    getVariants(chrom, FileRead.searchStart, FileRead.searchEnd,
                            Main.drawCanvas.sampleList.get(i));
                } else {

                    getVariants(chrom, 0, Main.drawCanvas.splits.get(0).chromEnd,
                            Main.drawCanvas.sampleList.get(i));
                }

            }

            annotate();

            if (Main.drawCanvas.annotationOn) {
                SampleDialog.checkAnnotation();
            }

            Main.drawCanvas.loading("Applying controls...");
            if (Control.controlData.controlsOn) {
                Control.applyControl();
            }
            Main.drawCanvas.ready("Applying controls...");
            readFiles = false;
            Main.bedCanvas.intersected = false;
            if (bigcalc) {
                Main.drawCanvas.calcClusters(FileRead.head);
            } else {
                Main.drawCanvas.calcClusters(FileRead.head);

            }

            if (Main.bedCanvas.bedOn) {

                Main.drawCanvas.loadingtext = "Annotating variants";
                int smalls = 0;
                for (int i = 0; i < Main.bedCanvas.bedTrack.size(); i++) {
                    if (Main.bedCanvas.bedTrack.get(i).small
                            && Main.bedCanvas.bedTrack.get(i).getBBfileReader() == null) {
                        if (Main.bedCanvas.bedTrack.get(i).intersect
                                && !Main.bedCanvas.bedTrack.get(i).loading) {
                            smalls++;
                            Main.bedCanvas.annotate(Main.bedCanvas.bedTrack.get(i).getHead(),
                                    FileRead.head.getNext());
                            Main.bedCanvas.intersected = true;

                        } else if (Main.bedCanvas.bedTrack.get(i).intersect
                                && Main.bedCanvas.bedTrack.get(i).loading) {
                            Main.bedCanvas.bedTrack.get(i).waiting = true;
                        }
                    }
                    //else if(Main.bedCanvas.bedTrack.get(i).intersect) {   
                    //bigs.add(Main.bedCanvas.bedTrack.get(i));
                    /*BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(Main.bedCanvas.bedTrack.get(i));
                    annotator.annotateVars();                  
                    Main.bedCanvas.intersected = true;                  */
                    //}
                }
                if (smalls == 0) {
                    VarNode current = FileRead.head.getNext();
                    while (current != null) {

                        current.bedhit = true;
                        current = current.getNext();
                    }
                }
                for (int i = 0; i < bigs.size(); i++) {

                    bigs.get(i).intersect = true;
                    BedCanvas.Annotator annotator = Main.bedCanvas.new Annotator(bigs.get(i));
                    annotator.annotateVars();
                    Main.bedCanvas.intersected = true;
                }
                bigs.clear();
            }

            if (FileRead.bigcalc) {
                Main.drawCanvas.calcClusters(FileRead.head);
            } else {
                Main.drawCanvas.calcClusters(FileRead.head);

            }
        }

        Draw.updatevars = true;
        Main.drawCanvas.ready("Loading variants...");
        if (!Main.drawCanvas.loading) {
            Draw.calculateVars = true;
        }
        if (novars) {
            Main.drawCanvas.variantsStart = 0;
            Main.drawCanvas.variantsEnd = Main.drawCanvas.splits.get(0).chromEnd;
        }

        search = false;
        changing = false;
        current = null;
        Main.chromDraw.updateExons = true;
        Main.chromDraw.repaint();

    } catch (Exception e) {
        e.printStackTrace();
        ErrorLog.addError(e.getStackTrace());
        changing = false;
    }

    Main.drawCanvas.loadbarAll = 0;
    Main.drawCanvas.loadBarSample = 0;
    Main.drawCanvas.repaint();
}

From source file:base.BasePlayer.FileRead.java

java.util.ArrayList<java.util.Map.Entry<Integer, Byte>> getMismatches(SAMRecord samRecord, Reads readClass,
        double[][] coverageArray, SplitClass split) {

    if (readClass == null) {
        sample.resetreadHash();/*from   www .j  a v a  2s. co  m*/
    }
    java.util.ArrayList<java.util.Map.Entry<Integer, Byte>> mismatches = null;
    String MD = samRecord.getStringAttribute("MD");
    String SA = samRecord.getStringAttribute("SA");
    if (samRecord.getReadBases().length == 0) {
        return null;
    }
    try {

        if (MD == null) {

            if (readClass.sample.MD) {
                readClass.sample.MD = false;
            }
        }

        if ((readClass.sample.MD || MD != null) && (samRecord.getCigarString().contains("S")
                && Settings.softClips == 0)/* && ((!samRecord.getCigarString().contains("S") && SA == null) || SA !=null)*/) {

            if (!readClass.sample.MD) {
                readClass.sample.MD = true;
            }

            java.util.ArrayList<java.util.Map.Entry<Integer, Integer>> insertions = null;
            int softstart = 0;
            if (samRecord.getCigarLength() > 1) {

                readstart = samRecord.getUnclippedStart();
                if (readClass.getCoverageStart() > readstart) {
                    return null;
                }
                readpos = 0;
                for (int i = 0; i < samRecord.getCigarLength(); i++) {
                    element = samRecord.getCigar().getCigarElement(i);
                    if (element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH) == 0) {
                        for (int r = readpos; r < readpos + element.getLength(); r++) {
                            try {
                                coverageArray[((readstart + r) - readClass.getCoverageStart())][0]++;
                            } catch (Exception e) {
                                //TODO
                            }
                            try {
                                if (coverageArray[((readstart + r)
                                        - readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) {
                                    readClass.setMaxcoverage(
                                            coverageArray[((readstart + r) - readClass.getCoverageStart())][0]);

                                }
                            } catch (Exception e) {
                                //TODO
                            }
                            mispos++;
                        }

                        readpos += element.getLength();
                    } else if (element.getOperator().compareTo(CigarOperator.DELETION) == 0) {
                        for (int d = 0; d < element.getLength(); d++) {
                            readClass.getCoverages()[(readstart + readpos + d)
                                    - readClass.getCoverageStart()][Main.baseMap.get((byte) 'D')]++;

                        }
                        readpos += element.getLength();
                    } else if (element.getOperator().compareTo(CigarOperator.INSERTION) == 0) {
                        if (insertions == null) {
                            insertions = new java.util.ArrayList<java.util.Map.Entry<Integer, Integer>>();
                        }
                        java.util.Map.Entry<Integer, Integer> ins = new java.util.AbstractMap.SimpleEntry<>(
                                readpos, element.getLength());
                        insertions.add(ins);
                        readClass.getCoverages()[(readstart + readpos)
                                - readClass.getCoverageStart()][Main.baseMap.get((byte) 'I')]++;

                        mispos += element.getLength();

                    } else if (element.getOperator().compareTo(CigarOperator.SOFT_CLIP) == 0) {

                        if (i == 0 && SA == null) {
                            softstart = element.getLength();
                        }

                        if (Settings.softClips == 1) {
                            for (int r = readpos; r < readpos + element.getLength(); r++) {
                                if (SA == null) {
                                    coverageArray[((readstart + r) - readClass.getCoverageStart())][0]++;
                                }
                                mispos++;
                            }
                            readpos += element.getLength();

                        } else {
                            if (i == 0) {

                                readstart = samRecord.getAlignmentStart();

                                mispos += element.getLength();
                            }
                        }

                    } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP) == 0) {
                        if (i == 0) {
                            readstart = samRecord.getAlignmentStart();
                        }
                    } else if (element.getOperator().compareTo(CigarOperator.SKIPPED_REGION) == 0) {
                        readpos += element.getLength();
                    }
                }
            } else {
                readstart = samRecord.getUnclippedStart();

                for (int i = 0; i < samRecord.getReadLength(); i++) {
                    try {
                        if (readClass.getCoverageStart() > readstart) {
                            break;
                        }
                        coverageArray[(readstart + i) - readClass.getCoverageStart()][0]++;

                        if (coverageArray[(samRecord.getUnclippedStart() - readClass.getCoverageStart())
                                + i][0] > readClass.getMaxcoverage()) {
                            readClass.setMaxcoverage(
                                    coverageArray[(samRecord.getUnclippedStart() - readClass.getCoverageStart())
                                            + i][0]);
                        }
                    } catch (Exception e) {
                        ErrorLog.addError(e.getStackTrace());
                        e.printStackTrace();
                        FileRead.cancelreadread = true;
                        break;
                    }
                }
            }
            if (MD != null) {
                try {
                    Integer.parseInt(MD);
                    return null;
                } catch (Exception ex) {

                    readstart = samRecord.getAlignmentStart() - softstart;

                    char[] chars = MD.toCharArray();
                    String bases = samRecord.getReadString();
                    String qualities = samRecord.getBaseQualityString();

                    if (SA == null) {
                        softstart = 0;
                    }

                    int readpos = softstart;
                    int mispos = softstart;

                    int add = 0;
                    int digitpointer = 0, insertionpointer = 0;
                    boolean first = true;

                    for (int i = 0; i < chars.length; i++) {
                        try {
                            if (insertions != null) {
                                if (insertionpointer < insertions.size()
                                        && insertions.get(insertionpointer).getKey() <= readpos) {
                                    while (insertionpointer < insertions.size()
                                            && insertions.get(insertionpointer).getKey() <= readpos) {
                                        mispos += insertions.get(insertionpointer).getValue();
                                        insertionpointer++;
                                    }
                                }
                            }
                            if (Character.isDigit(chars[i])) {
                                digitpointer = i + 1;
                                while (digitpointer < chars.length && Character.isDigit(chars[digitpointer])) {
                                    digitpointer++;
                                }

                                if (digitpointer == chars.length) {

                                    if ((mispos + Integer.parseInt(MD.substring(i, digitpointer))) > samRecord
                                            .getReadLength()) {
                                        if (!first) {
                                            break;
                                        }
                                        first = false;
                                        readpos = 0;
                                        mispos = 0;
                                        i = -1;
                                        digitpointer = 0;
                                        insertionpointer = 0;
                                        mismatches.clear();
                                        continue;
                                    }

                                    break;
                                } else {
                                    add = Integer.parseInt(MD.substring(i, digitpointer));
                                    readpos += add;
                                    mispos += add;
                                }
                                i = digitpointer - 1;
                            } else if (chars[i] != '^') {

                                if (mismatches == null) {
                                    mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer, Byte>>();
                                }

                                readClass.getCoverages()[(readstart + readpos)
                                        - readClass.getCoverageStart()][Main.baseMap
                                                .get((byte) bases.charAt(mispos))]++;

                                if (samRecord.getBaseQualityString().length() != 1
                                        && (int) qualities.charAt(mispos)
                                                - readClass.sample.phred < Settings.baseQ) {

                                    java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                            readpos, (byte) Character.toLowerCase(bases.charAt(mispos)));
                                    mismatches.add(mismatch);
                                } else {

                                    java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                            readpos, (byte) bases.charAt(mispos));
                                    mismatches.add(mismatch);
                                }
                                mispos++;
                                readpos++;
                            } else {

                                digitpointer = i + 1;

                                while (!Character.isDigit(chars[digitpointer])) {
                                    digitpointer++;
                                    readpos++;
                                }

                                i = digitpointer - 1;
                            }
                        } catch (Exception exc) {
                            if (!first) {
                                break;
                            }
                            first = false;
                            readpos = 0;
                            mispos = 0;
                            i = -1;
                            digitpointer = 0;
                            insertionpointer = 0;
                            mismatches.clear();
                        }
                    }
                }
            }
        } else {
            /*if(split.getReference() == null) {
                       
               readClass.setReference(new ReferenceSeq(splitIndex.chrom,start-500, end+500, Main.referenceFile));
               }*/
            //timecounter = 0;
            /*while(splitIndex.getReadReference() == null) {
               Thread.sleep(100);
               timecounter++;
               if(timecounter > 20) {
                  break;
               }
            }
            Thread.sleep(0);
            */
            //   if(splitIndex.getReadReference() == null) {
            //splitIndex.setReference(new ReferenceSeq(splitIndex.chrom,startpos-searchwindow-1,  endpos+searchwindow +200, Main.referenceFile));
            //   return null;
            //}
            if (samRecord.getCigarLength() > 1) {
                readstart = samRecord.getUnclippedStart();
                readpos = 0;
                mispos = 0;
                /*if(readClass.getCoverageStart()>readstart) {
                   return null;
                }*/
                if (mismatches == null) {
                    mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer, Byte>>();
                }

                for (int i = 0; i < samRecord.getCigarLength(); i++) {
                    element = samRecord.getCigar().getCigarElement(i);
                    if (element.getOperator().compareTo(CigarOperator.MATCH_OR_MISMATCH) == 0) {
                        for (int r = readpos; r < readpos + element.getLength(); r++) {
                            if (((readstart + r) - split.getReadReference().getStartPos()
                                    - 1) > split.getReadReference().getSeq().length - 1) {
                                split.getReadReference().append(samRecord.getUnclippedEnd() + 1000);
                            }
                            if (((readstart + r) - split.getReadReference().getStartPos() - 1) < 0) {
                                split.getReadReference().appendToStart(samRecord.getUnclippedStart() - 1000);
                            }
                            try {

                                if (samRecord.getReadBases()[mispos] != split.getReadReference()
                                        .getSeq()[((readstart + r) - split.getReadReference().getStartPos()
                                                - 1)]) {
                                    readClass.getCoverages()[(readstart + r)
                                            - readClass.getCoverageStart()][Main.baseMap
                                                    .get((byte) samRecord.getReadBases()[mispos])]++;

                                    if (samRecord.getBaseQualityString().length() != 1
                                            && (int) samRecord.getBaseQualityString().charAt(mispos)
                                                    - readClass.sample.phred < Settings.baseQ) {

                                        java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                                r, (byte) Character
                                                        .toLowerCase((char) samRecord.getReadBases()[mispos]));
                                        mismatches.add(mismatch);
                                    } else {

                                        java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                                r, samRecord.getReadBases()[mispos]);
                                        mismatches.add(mismatch);
                                    }
                                }
                            } catch (Exception e) {
                                System.out.println(samRecord.getReadBases().length);
                                e.printStackTrace();
                            }
                            try {
                                coverageArray[((readstart + r) - readClass.getCoverageStart())][0]++;

                                if (coverageArray[((readstart + r)
                                        - readClass.getCoverageStart())][0] > readClass.getMaxcoverage()) {
                                    readClass.setMaxcoverage(
                                            coverageArray[((readstart + r) - readClass.getCoverageStart())][0]);
                                }
                            } catch (Exception e) {
                                //TODO

                            }
                            mispos++;
                        }

                        readpos += element.getLength();
                    } else if (element.getOperator().compareTo(CigarOperator.DELETION) == 0) {
                        //      readWidth+=element.getLength();                  
                        for (int d = 0; d < element.getLength(); d++) {
                            readClass.getCoverages()[(readstart + readpos + d)
                                    - readClass.getCoverageStart()][Main.baseMap.get((byte) 'D')]++;

                        }
                        readpos += element.getLength();
                    } else if (element.getOperator().compareTo(CigarOperator.INSERTION) == 0) {
                        readClass.getCoverages()[(readstart + readpos)
                                - readClass.getCoverageStart()][Main.baseMap.get((byte) 'I')]++;
                        mispos += element.getLength();

                    } else if (element.getOperator().compareTo(CigarOperator.SOFT_CLIP) == 0) {
                        if (Settings.softClips == 1) {

                            for (int r = readpos; r < readpos + element.getLength(); r++) {
                                if (((readstart + r) - split.getReadReference().getStartPos()
                                        - 1) > split.getReadReference().getSeq().length - 1) {
                                    split.getReadReference().append(samRecord.getUnclippedEnd() + 1000);
                                }
                                if (((readstart + r) - splitIndex.getReadReference().getStartPos() - 1) < 0) {
                                    split.getReadReference()
                                            .appendToStart(samRecord.getUnclippedStart() - 1000);
                                }
                                /*   if(((readstart+r)-readClass.reference.getStartPos()-1) < 0) {
                                   continue;
                                }*/
                                if (samRecord.getReadBases()[mispos] != split.getReadReference()
                                        .getSeq()[((readstart + r) - split.getReadReference().getStartPos()
                                                - 1)]) {
                                    if (SA == null) {

                                        readClass.getCoverages()[(readstart + r)
                                                - readClass.getCoverageStart()][Main.baseMap
                                                        .get(samRecord.getReadBases()[mispos])]++;
                                    }
                                    if (mismatches == null) {
                                        mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer, Byte>>();
                                    }
                                    java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                            r, samRecord.getReadBases()[mispos]);
                                    mismatches.add(mismatch);
                                }
                                if (SA == null) {
                                    coverageArray[((readstart + r) - readClass.getCoverageStart())][0]++;
                                }
                                mispos++;
                            }
                            readpos += element.getLength();

                        } else {
                            if (i == 0) {

                                readpos += element.getLength();
                                mispos += element.getLength();

                            }
                        }

                    } else if (element.getOperator().compareTo(CigarOperator.HARD_CLIP) == 0) {
                        if (i == 0) {
                            readstart = samRecord.getAlignmentStart();
                        }
                    } else if (element.getOperator().compareTo(CigarOperator.SKIPPED_REGION) == 0) {
                        readpos += element.getLength();
                        //         this.readWidth+=element.getLength();
                    }
                }
            } else {
                readstart = samRecord.getUnclippedStart();
                /*if(readClass.getCoverageStart()>readstart) {
                   return null;
                }*/
                if ((samRecord.getUnclippedEnd() - split.getReadReference().getStartPos()
                        - 1) > split.getReadReference().getSeq().length - 1) {
                    split.getReadReference().append(samRecord.getUnclippedEnd() + 100);
                }
                if ((samRecord.getUnclippedStart() - split.getReadReference().getStartPos() - 1) < 0) {
                    split.getReadReference().appendToStart(samRecord.getUnclippedStart() - 100);
                }

                for (int r = 0; r < samRecord.getReadLength(); r++) {
                    try {

                        if (samRecord.getReadBases()[r] != split.getReadReference()
                                .getSeq()[((readstart + r) - split.getReadReference().getStartPos() - 1)]) {

                            if ((readstart + r) - readClass.getCoverageStart() < readClass.getCoverages().length
                                    - 1) {
                                readClass.getCoverages()[(readstart + r)
                                        - readClass.getCoverageStart()][Main.baseMap
                                                .get(samRecord.getReadBases()[r])]++;
                                if (mismatches == null) {
                                    mismatches = new java.util.ArrayList<java.util.Map.Entry<Integer, Byte>>();
                                }
                                java.util.Map.Entry<Integer, Byte> mismatch = new java.util.AbstractMap.SimpleEntry<>(
                                        r, samRecord.getReadBases()[r]);
                                mismatches.add(mismatch);
                            }
                        }
                        try {

                            coverageArray[(readstart + r) - readClass.getCoverageStart()][0]++;
                        } catch (Exception e) {
                            //TODO
                            //e.printStackTrace();
                            continue;
                        }
                        if (coverageArray[(samRecord.getUnclippedStart() - readClass.getCoverageStart())
                                + r][0] > readClass.getMaxcoverage()) {
                            readClass.setMaxcoverage(
                                    coverageArray[(samRecord.getUnclippedStart() - readClass.getCoverageStart())
                                            + r][0]);
                        }
                    } catch (Exception e) {

                        ErrorLog.addError(e.getStackTrace());
                        e.printStackTrace();
                        return mismatches;

                    }
                }

            }
        }
    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }
    return mismatches;
}