Example usage for java.lang ClassCastException printStackTrace

List of usage examples for java.lang ClassCastException printStackTrace

Introduction

In this page you can find the example usage for java.lang ClassCastException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:playground.benjamin.scenarios.zurich.analysis.charts.BkChartWriter.java

public static void writeChartDataToFile(String filename, JFreeChart chart) {
    filename += ".txt";
    try {/* w ww. j a  va2 s  .  c  o m*/
        BufferedWriter writer = IOUtils.getBufferedWriter(filename);
        try { /*read "try" as if (plot instanceof XYPlot)*/
            XYPlot xy = chart.getXYPlot();
            String yAxisLabel = xy.getRangeAxis().getLabel();

            String xAxisLabel = "";
            if (xy.getDomainAxis() != null) {
                xAxisLabel = xy.getDomainAxis().getLabel();
            }
            String header = xAxisLabel + "\t " + yAxisLabel;
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < xy.getDatasetCount(); i++) {
                XYDataset xyds = xy.getDataset(i);
                for (int seriesIndex = 0; seriesIndex < xyds.getSeriesCount(); seriesIndex++) {
                    writer.newLine();
                    writer.write("Series " + "'" + xyds.getSeriesKey(seriesIndex).toString());
                    writer.write("'");
                    writer.newLine();
                    int items = xyds.getItemCount(seriesIndex);
                    for (int itemsIndex = 0; itemsIndex < items; itemsIndex++) {
                        Number xValue = xyds.getX(seriesIndex, itemsIndex);
                        Number yValue = xyds.getY(seriesIndex, itemsIndex);
                        writer.write(xValue.toString());
                        writer.write("\t");
                        writer.write(yValue.toString());
                        writer.newLine();
                    }
                }
            }
            System.out.println("Table written to : " + filename + "\n"
                    + "==================================================");

        } catch (ClassCastException e) { //else instanceof CategoryPlot
            log.info("caught class cast exception, trying to write CategoryPlot");
            CategoryPlot cp = chart.getCategoryPlot();
            String header = "CategoryRowKey \t CategoryColumnKey \t CategoryRowIndex \t CategoryColumnIndex \t Value";
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < cp.getDatasetCount(); i++) {
                CategoryDataset cpds = cp.getDataset(i);
                for (int rowIndex = 0; rowIndex < cpds.getRowCount(); rowIndex++) {
                    for (int columnIndex = 0; columnIndex < cpds.getColumnCount(); columnIndex++) {
                        Number value = cpds.getValue(rowIndex, columnIndex);
                        writer.write(cpds.getRowKey(rowIndex).toString());
                        writer.write("\t");
                        writer.write(cpds.getColumnKey(columnIndex).toString());
                        writer.write("\t");
                        writer.write(Integer.toString(rowIndex));
                        writer.write("\t");
                        writer.write(Integer.toString(columnIndex));
                        writer.write("\t");
                        writer.write(value.toString());
                        writer.newLine();
                    }
                }
            }

        }
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.excel.DBExcelUtility.java

private String getRowXMLData(HSSFSheet hssfsheet, String sheetName, int row, int colcount, String prefix,
        String coltype[]) {//from w  w  w  .j av a2 s . com
    StringBuffer sb = new StringBuffer();
    Object cdata = null;
    int column = 0;

    try {

        for (int i = 0; i < colcount; i++) {
            column = (short) (dataStart_column + i);
            cdata = ExcelUtility.getObject(hssfsheet, row, (short) column);

            //sb.append("(AV=" + cdata + "," + cdata.toString().length() + ")");
            if (cdata != null && cdata.toString().length() != 0) {
                if (coltype[i].equalsIgnoreCase(DataType.TYPE_STRING)) {
                    sb.append("<" + prefix + ">" + (String) cdata + "</" + prefix + ">");
                } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_INTEGER)) {
                    Integer idata = ExcelUtility.getInteger(hssfsheet, row, (short) (dataStart_column + i));

                    sb.append("<" + prefix + ">" + idata + "</" + prefix + ">");
                } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DOUBLE)) {
                    Double ddata = ExcelUtility.getDouble(hssfsheet, row, (short) (dataStart_column + i));

                    sb.append("<" + prefix + ">" + ddata + "</" + prefix + ">");
                } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_BOOLEAN)) {
                    Boolean bdata = ExcelUtility.getBoolean(hssfsheet, row, (short) (dataStart_column + i));

                    sb.append("<" + prefix + ">" + bdata + "</" + prefix + ">");
                } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DATE)) {
                    Date dtval = ExcelUtility.getDate(hssfsheet, row, (short) (dataStart_column + i));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    StringBuffer dtString = new StringBuffer();
                    String dt = sdf.format(dtval);

                    //System.out.println("dtval = " + dtval);
                    //System.out.println("dt = " + dtString.toString());
                    sb.append("<" + prefix + ">" + dt + "</" + prefix + ">");
                }
            } else {
                sb.append("<none/>");
            }
        }
        return sb.toString();
    } catch (ClassCastException ce) {
        ce.printStackTrace();
        throw new ClassCastException("There is a type problem in the excel worksheet on Sheet='" + sheetName
                + "', and Cell(" + (row + 1) + "," + (column + 1) + ")" + "\n" + ce.getMessage());
    }
}

From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java

/**
 * Saves the content node to the favorites area of the sdcard
 * /*from   w  w w  .  j  a v  a2  s . c  o  m*/
 * @param position
 */
public void toggleFavorite(int position) {
    final Context context = getContext();
    final CMISPreferencesManager prefsMgr = CMISPreferencesManager.getInstance();
    final NodeRef ref = getItem(position);
    final Set<NodeRef> favorites = prefsMgr.getFavorites(context);

    if (favorites.contains(ref)) {
        favorites.remove(ref);
        prefsMgr.storeFavorites(context, favorites);

        if (mFavoritesView) {
            remove(ref);
            notifyDataSetChanged();
        }
    } else {
        try {
            downloadContent(ref, new Handler() {
                public void handleMessage(Message msg) {
                    boolean done = msg.getData().getBoolean("done");
                    if (done) {
                        dismissProgressDlg();
                        File file = null;
                        try {
                            file = (File) mDlThread.getResult();
                        } catch (ClassCastException e) {
                            e.printStackTrace();
                        }

                        if (file != null) {
                            favorites.add(ref);
                            prefsMgr.storeFavorites(context, favorites);
                        }
                    } else {
                        int value = msg.getData().getInt("progress");
                        if (value > 0) {
                            mProgressDlg.setProgress(value);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.manzdagratiano.gobbledygook.Gobbledygook.java

/**
 * @brief   //w w  w.  j ava2 s . com
 * @return  
 */
private Attributes getAttributes(View view) {
    EditText domainField = (EditText) findViewById(R.id.domain);
    EditText iterationsField = (EditText) findViewById(R.id.iterations);
    EditText truncationField = (EditText) findViewById(R.id.truncation);

    String domain = domainField.getText().toString();
    Integer iterations = null;
    try {
        iterations = ((0 == iterationsField.getText().toString().trim().length())
                ? Attributes.DEFAULT_ITERATIONS
                : Integer.parseInt(iterationsField.getText().toString()));
    } catch (ClassCastException e) {
        Log.e(Env.LOG_CATEGORY, "ERROR: Caught " + e);
        e.printStackTrace();
        iterations = Attributes.DEFAULT_ITERATIONS;
    }

    Integer truncation = null;
    try {
        truncation = ((0 == truncationField.getText().toString().trim().length()) ? Attributes.NO_TRUNCATION
                : Integer.parseInt(truncationField.getText().toString()));
    } catch (ClassCastException e) {
        Log.e(Env.LOG_CATEGORY, "ERROR: Caught " + e);
        e.printStackTrace();
        truncation = Attributes.NO_TRUNCATION;
    }

    Attributes attributes = new Attributes(domain, iterations, truncation);

    return attributes;
}

From source file:playground.dgrether.analysis.charts.utils.DgChartWriter.java

public static void writeChartDataToFile(String filename, JFreeChart chart) {
    filename += ".txt";
    try {//from  w  w w . j a v  a  2s  .  c  o m
        BufferedWriter writer = IOUtils.getBufferedWriter(filename);
        try { /*read "try" as if (plot instanceof XYPlot)*/
            XYPlot xy = chart.getXYPlot();
            String yAxisLabel = xy.getRangeAxis().getLabel();

            String xAxisLabel = "";
            if (xy.getDomainAxis() != null) {
                xAxisLabel = xy.getDomainAxis().getLabel();
            }
            String header = "#" + xAxisLabel + "\t " + yAxisLabel;
            writer.write(header);
            writer.newLine();
            //write the header
            writer.write("#");
            for (int i = 0; i < xy.getDatasetCount(); i++) {
                XYDataset xyds = xy.getDataset(i);
                int seriesIndex = 0;
                int maxItems = 0;
                int seriesCount = xyds.getSeriesCount();
                while (seriesIndex < seriesCount) {
                    writer.write("Series " + xyds.getSeriesKey(seriesIndex).toString());
                    if (seriesIndex < seriesCount - 1) {
                        writer.write("\t \t");
                    }
                    if (xyds.getItemCount(seriesIndex) > maxItems) {
                        maxItems = xyds.getItemCount(seriesIndex);
                    }
                    seriesIndex++;
                }
                writer.newLine();

                //write the data
                Number xValue, yValue = null;
                for (int itemsIndex = 0; itemsIndex < maxItems; itemsIndex++) {
                    for (int seriesIdx = 0; seriesIdx < seriesCount; seriesIdx++) {
                        if (seriesIdx < xyds.getSeriesCount() && itemsIndex < xyds.getItemCount(seriesIdx)) {
                            xValue = xyds.getX(seriesIdx, itemsIndex);
                            yValue = xyds.getY(seriesIdx, itemsIndex);
                            if (xValue != null && yValue != null) {
                                writer.write(xValue.toString());
                                writer.write("\t");
                                writer.write(yValue.toString());
                                if (seriesIdx < seriesCount - 1) {
                                    writer.write("\t");
                                }
                            }
                        }
                    }
                    writer.newLine();
                }
            }
        } catch (ClassCastException e) { //else instanceof CategoryPlot
            log.info("Due to a caught class cast exception, it should be a CategoryPlot");
            CategoryPlot cp = chart.getCategoryPlot();
            String header = "# CategoryRowKey \t CategoryColumnKey \t CategoryRowIndex \t CategoryColumnIndex \t Value";
            writer.write(header);
            writer.newLine();
            for (int i = 0; i < cp.getDatasetCount(); i++) {
                CategoryDataset cpds = cp.getDataset(i);
                for (int rowIndex = 0; rowIndex < cpds.getRowCount(); rowIndex++) {
                    for (int columnIndex = 0; columnIndex < cpds.getColumnCount(); columnIndex++) {
                        Number value = cpds.getValue(rowIndex, columnIndex);
                        writer.write(cpds.getRowKey(rowIndex).toString());
                        writer.write("\t");
                        writer.write(cpds.getColumnKey(columnIndex).toString());
                        writer.write("\t");
                        writer.write(Integer.toString(rowIndex));
                        writer.write("\t");
                        writer.write(Integer.toString(columnIndex));
                        writer.write("\t");
                        writer.write(value.toString());
                        writer.newLine();
                    }
                }
            }

        }
        writer.close();
        log.info("Chart data written to: " + filename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.example.office365sample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // inflate views and set initial state
    btnSendMessage = (Button) findViewById(R.id.button_sendSelectedMessage);
    btnSendMessage.setEnabled(false);/*from   w  w w.ja v  a  2  s .c  om*/
    listViewMessages = (ListView) findViewById(R.id.listview_Messages);
    listViewMessages.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    Configuration.setServerBaseUrl(Constants.RESOURCE_ID + Constants.ODATA_ENDPOINT);
    AuthenticationSettings.INSTANCE.setSecretKey(Constants.STORAGE_KEY);

    listViewMessages.setAdapter(
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[] { "Loading..." }));

    btnSendMessage.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(View v) {
            IMessage selectedMessage;
            int position = listViewMessages.getCheckedItemPosition();
            Log.i(TAG, "Selected Item: " + position);
            try {
                selectedMessage = ((ArrayAdapter<IMessage>) listViewMessages.getAdapter()).getItem(position);
            } catch (ClassCastException e) {
                Log.i(TAG, "Adapter not set properly");
                throw e;
            }

            Log.i(TAG, "Sending message: " + selectedMessage.getSubject() + "\nto: "
                    + selectedMessage.getToRecipients());
            Futures.addCallback(selectedMessage.sendAsync(), new FutureCallback<Void>() {
                @Override
                public void onFailure(Throwable t) {
                    t.printStackTrace();
                }

                @Override
                public void onSuccess(Void result) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    readMessages();
                }
            });

        }
    });

    doLogin();
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * This used to be a VIP methods for muse. Now superseded by Searcher.java for ePADD.
 * handle query for term, sentiment, person, attachment, docNum, timeCluster
 * etc//  w  w w  .  jav  a 2s  . c  o m
 * note: date range selection is always ANDed
 * if only_apply_to_filtered_docs, looks at emailDocs, i.e. ones selected by
 * the current filter (if there is one)
 * if !only_apply_to_filtered_docs, looks at all docs in archive
 * note: only_apply_to_filtered_docs == true is not honored by lucene lookup
 * by term (callers need to filter by themselves)
 * note2: performance can be improved. e.g., if in AND mode, searches that
 * iterate through documents such as
 * selectDocByTag, getBlobsForAttachments, etc., can take the intermediate
 * resultDocs rather than allDocs.
 * set intersection/union can be done in place to the intermediate
 * resultDocs rather than create a new collection.
 * getDocsForAttachments can be called on the combined result of attachments
 * and attachmentTypes search, rather than individually.
 * note3: should we want options to allow user to choose whether to search
 * only in emails, only in attachments, or both?
 * also, how should we allow variants in combining multiple conditions.
 * there will be work in UI too.
 * note4: the returned resultBlobs may not be tight, i.e., it may include
 * blobs from docs that are not in the returned resultDocs.
 * but for docs that are in resultDocs, it should not include blobs that are
 * not hitting.
 * these extra blobs will not be seen since we only use this info for
 * highlighting blobs in resultDocs.
 */
public static Pair<Collection<Document>, Collection<Blob>> selectDocsWithHighlightAttachments(
        HttpServletRequest request, HttpSession session, boolean only_apply_to_filtered_docs,
        boolean or_not_and) throws UnsupportedEncodingException {
    // below are all the controls for selecting docs 
    String term = request.getParameter("term"); // search term
    String[] contact_ids = request.getParameterValues("contact");
    String[] persons = request.getParameterValues("person");
    String[] attachments = request.getParameterValues("attachment"); // actual attachment name

    String[] attachment_extensions = request.getParameterValues("attachment_extension");

    {
        // if attachment_types specified, parse them and add the values in them to attachment_extensions also
        // types are higher level (video, audio, etc.) and map to more than 1 extension
        String[] attachment_types = request.getParameterValues("attachment_type"); // will be something like ["pdf,doc", "ppt,pptx,key"]
        if (!Util.nullOrEmpty(attachment_types)) {
            // assemble all extensions in a list first
            List<String> list = new ArrayList<>();
            if (!Util.nullOrEmpty(attachment_extensions))
                list.addAll(Arrays.asList(attachment_extensions));

            for (String s : attachment_types)
                list.addAll(Util.tokenize(s, ","));
            // trim all spaces, then convert back to array
            list = list.stream().map(s -> s.trim()).collect(Collectors.toList());
            attachment_extensions = list.toArray(new String[list.size()]);
        }
    }

    String datasetId = request.getParameter("datasetId");
    String[] docIds = request.getParameterValues("docId");
    String[] folders = request.getParameterValues("folder");
    String sortByStr = request.getParameter("sort_by");
    Indexer.SortBy sortBy = Indexer.SortBy.RELEVANCE;
    if (!Util.nullOrEmpty(sortByStr)) {
        if ("relevance".equals(sortByStr.toLowerCase()))
            sortBy = Indexer.SortBy.RELEVANCE;
        else if ("recent".equals(sortByStr.toLowerCase()))
            sortBy = Indexer.SortBy.RECENT_FIRST;
        else if ("chronological".equals(sortByStr.toLowerCase()))
            sortBy = Indexer.SortBy.CHRONOLOGICAL_ORDER;
        else {
            log.warn("Unknown sort by option: " + sortBy);
        }
    }

    // compute date requirements. start/end_date are in yyyy/mm/dd format
    int yy = -1, end_yy = -1, mm = -1, end_mm = -1, dd = -1, end_dd = -1;

    String start_date = request.getParameter("start_date");
    if (!Util.nullOrEmpty(start_date)) {
        String[] ss = start_date.split("/");
        if (ss.length > 0) {
            yy = Util.getIntParam(ss[0], -1);
        }
        if (ss.length > 1) {
            mm = Util.getIntParam(ss[1], -1);
        }
        if (ss.length > 2) {
            dd = Util.getIntParam(ss[2], -1);
        }
    }

    String end_date = request.getParameter("end_date");
    if (!Util.nullOrEmpty(end_date)) {
        String[] ss = end_date.split("/");
        if (ss.length > 0) {
            end_yy = Util.getIntParam(ss[0], -1);
        }
        if (ss.length > 1) {
            end_mm = Util.getIntParam(ss[1], -1);
        }
        if (ss.length > 2) {
            end_dd = Util.getIntParam(ss[2], -1);
        }
    }

    //key to large array of docids in session
    //it possible to pass this array as the get request parameter, but is not scalable due to the post and get size limits of tomcat
    String dIdLKey = request.getParameter("dIdLKey");
    if (dIdLKey != null) {
        try {
            Set<String> docIdsLot = (Set<String>) session.getAttribute(dIdLKey);
            Set<String> dIds = new HashSet<String>();
            if (docIds != null)
                for (String docId : docIds)
                    dIds.add(docId);

            if (docIdsLot != null)
                for (String dId : docIdsLot)
                    dIds.add(dId);
            docIds = dIds.toArray(new String[dIds.size()]);
            //System.err.println("Found docIds in the session... read "+docIds.length+" docIds");
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }
    String tag = request.getParameter("annotation"); // only one tag supported right now, will revisit if needed

    String[] directions = request.getParameterValues("direction");
    Set<String> directionsSet = new LinkedHashSet<String>();
    if (directions != null)
        for (String d : directions)
            directionsSet.add(d);
    boolean direction_in = directionsSet.contains("in");
    boolean direction_out = directionsSet.contains("out");

    String[] sentiments = request.getParameterValues("sentiment");
    int cluster = HTMLUtils.getIntParam(request, "timeCluster", -1);
    /** usually, there is 1 time cluster per month */

    Set<String> foldersSet = new LinkedHashSet<String>();
    if (folders != null)
        for (String f : folders)
            foldersSet.add(f);

    // a little bit of an asymmetry here, only one groupIdx is considered, can't be multiple
    int groupIdx = HTMLUtils.getIntParam(request, "groupIdx", Integer.MAX_VALUE);
    Archive archive = JSPHelper.getArchive(session);
    AddressBook addressBook = archive.addressBook;
    GroupAssigner groupAssigner = archive.groupAssigner;
    BlobStore attachmentsStore = archive.blobStore;

    Collection<Document> allDocs = getAllDocsAsSet(session, only_apply_to_filtered_docs);
    if (Util.nullOrEmpty(allDocs))
        return new Pair<Collection<Document>, Collection<Blob>>(new ArrayList<Document>(),
                new ArrayList<Blob>());

    //why are there two vars for sentiment and content indexer repns?
    //      Indexer sentiIndexer, indexer;
    //      indexer = sentiIndexer = archive.indexer;

    // the raw request param val is in 8859 encoding, interpret the bytes as utf instead

    /**
     * there is a little overlap between datasetId and docForDocIds.
     * probably datasetIds can be got rid of?
     */
    List<Document> docsForGroup = null, docsForDateRange = null, docsForNumbers = null, docsForFolder = null,
            docsForDirection = null, docsForCluster = null, docsForDocIds = null;
    Collection<Document> docsForTerm = null, docsForPersons = null, docsForSentiments = null, docsForTag = null,
            docsForAttachments = null, docsForAttachmentTypes = null, docsForDoNotTransfer = null,
            docsForTransferWithRestrictions = null, docsForReviewed = null, docsForRegex = null;
    Collection<Blob> blobsForAttachments = null, blobsForAttachmentTypes = null, blobsForTerm = null;

    if (!Util.nullOrEmpty(term)) {
        term = JSPHelper.convertRequestParamToUTF8(term);
        if (isRegexSearch(request)) {
            docsForTerm = new LinkedHashSet<Document>(IndexUtils.selectDocsByRegex(archive, allDocs, term));
            // TODO: regex search in attachments is not implemented yet
        } else {
            Indexer.QueryType qt = null;
            String searchType = request.getParameter("searchType");
            if ("correspondents".equals(searchType))
                qt = Indexer.QueryType.CORRESPONDENTS;
            else if ("subject".equals(searchType))
                qt = Indexer.QueryType.SUBJECT;
            else if ("original".equals(searchType))
                qt = Indexer.QueryType.ORIGINAL;
            else if ("regex".equals(searchType))
                qt = Indexer.QueryType.REGEX;
            else
                qt = Indexer.QueryType.FULL;

            Indexer.QueryOptions options = new Indexer.QueryOptions();
            options.setQueryType(qt);
            options.setSortBy(sortBy);

            docsForTerm = archive.docsForQuery(term, options);
            // also search blobs and merge result, but not for subject/corr. search
            if (!"correspondents".equals(searchType) && !"subject".equals(searchType)) {
                blobsForTerm = archive.blobsForQuery(term);
                Set<Document> blobDocsForTerm = (Set<Document>) EmailUtils
                        .getDocsForAttachments((Collection) allDocs, blobsForTerm);
                log.info("Blob docs for term: " + term + ", " + blobDocsForTerm.size() + ", blobs: "
                        + blobsForTerm.size());
                docsForTerm = Util.setUnion(docsForTerm, blobDocsForTerm);
            }
        }
    }

    if ("true".equals(request.getParameter("sensitive"))) {
        Indexer.QueryType qt = null;
        qt = Indexer.QueryType.PRESET_REGEX;
        docsForRegex = archive.docsForQuery(cluster, qt);
    }

    if (foldersSet.size() > 0) {
        docsForFolder = new ArrayList<Document>();
        for (Document d : allDocs) {
            EmailDocument ed = (EmailDocument) d;
            if (foldersSet.contains(ed.folderName))
                docsForFolder.add(ed);
        }
    }

    if ((direction_in || direction_out) && addressBook != null) {
        docsForDirection = new ArrayList<Document>();
        for (Document d : allDocs) {
            EmailDocument ed = (EmailDocument) d;
            int sent_or_received = ed.sentOrReceived(addressBook);
            if (direction_in)
                if (((sent_or_received & EmailDocument.RECEIVED_MASK) != 0) || sent_or_received == 0) // if sent_or_received == 0 => we neither directly recd. nor sent it (e.g. it could be received on a mailing list). so count it as received.
                    docsForDirection.add(ed);
            if (direction_out && (sent_or_received & EmailDocument.SENT_MASK) != 0)
                docsForDirection.add(ed);
        }
    }

    String doNotTransfer = request.getParameter("doNotTransfer");
    if (!Util.nullOrEmpty(doNotTransfer)) {
        boolean val = "true".equals(doNotTransfer);
        docsForDoNotTransfer = new LinkedHashSet<Document>();
        for (Document d : allDocs) {
            EmailDocument ed = (EmailDocument) d;
            if (ed.doNotTransfer == val)
                docsForDoNotTransfer.add(ed);
        }
    }

    String transferWithRestrictions = request.getParameter("transferWithRestrictions");
    if (!Util.nullOrEmpty(transferWithRestrictions)) {
        boolean val = "true".equals(transferWithRestrictions);
        docsForTransferWithRestrictions = new LinkedHashSet<Document>();
        for (Document d : allDocs) {
            EmailDocument ed = (EmailDocument) d;
            if (ed.transferWithRestrictions == val)
                docsForTransferWithRestrictions.add(ed);
        }
    }

    String reviewed = request.getParameter("reviewed");
    if (!Util.nullOrEmpty(reviewed)) {
        boolean val = "true".equals(reviewed);
        docsForReviewed = new LinkedHashSet<Document>();
        for (Document d : allDocs) {
            EmailDocument ed = (EmailDocument) d;
            if (ed.reviewed == val)
                docsForReviewed.add(ed);
        }
    }

    if (sentiments != null && sentiments.length > 0) {
        Lexicon lex = (Lexicon) getSessionAttribute(session, "lexicon");
        docsForSentiments = lex.getDocsWithSentiments(sentiments, archive.indexer, allDocs, cluster,
                request.getParameter("originalContentOnly") != null, sentiments);
    }

    // if (!Util.nullOrEmpty(tag))
    if (tag != null) // note: explicitly allowing tag=<empty> as a way to specify no tag.
    {
        docsForTag = Document.selectDocByTag(allDocs, tag, true);
    }
    if (cluster >= 0) {
        docsForCluster = new ArrayList<>(archive.docsForQuery(null, cluster, Indexer.QueryType.FULL)); // null for term returns all docs in cluster
    }

    if (persons != null || contact_ids != null) {
        persons = JSPHelper.convertRequestParamsToUTF8(persons);
        docsForPersons = IndexUtils.selectDocsByAllPersons(addressBook, (Collection) allDocs, persons,
                Util.toIntArray(contact_ids));
    }

    //Some docs with faulty date are assigned 1960/01/01
    if (end_yy >= 0 && yy >= 0) // date range
    {
        docsForDateRange = (List) IndexUtils.selectDocsByDateRange((Collection) allDocs, yy, mm, dd, end_yy,
                end_mm, end_dd);
        log.info("Found " + docsForDateRange.size() + " docs in range: [" + yy + "/" + mm + "/" + dd + " - ["
                + end_yy + "/" + end_mm + "/" + end_dd + "]");
    } else if (yy >= 0) // single month or year
    {
        docsForDateRange = IndexUtils.selectDocsByDateRange((Collection) allDocs, yy, mm, dd);
        log.info("Found " + docsForDateRange.size() + " docs beyond " + yy + "/" + mm + "/" + dd);
    }

    if (groupIdx != Integer.MAX_VALUE) {
        if (groupIdx >= groupAssigner.getSelectedGroups().size())
            groupIdx = -1; // must be the "None" group
        docsForGroup = (List) IndexUtils.getDocsForGroupIdx((Collection) allDocs, addressBook, groupAssigner,
                groupIdx);
    }

    if (!Util.nullOrEmpty(attachments)) {
        attachments = JSPHelper.convertRequestParamsToUTF8(attachments);
        blobsForAttachments = IndexUtils.getBlobsForAttachments(allDocs, attachments, attachmentsStore);
        docsForAttachments = (Set<Document>) EmailUtils.getDocsForAttachments((Collection) allDocs,
                blobsForAttachments);
    }

    if (!Util.nullOrEmpty(attachment_extensions)) {
        attachment_extensions = JSPHelper.convertRequestParamsToUTF8(attachment_extensions);
        blobsForAttachmentTypes = IndexUtils.getBlobsForAttachmentTypes(allDocs, attachment_extensions);
        docsForAttachmentTypes = (Set<Document>) EmailUtils.getDocsForAttachments((Collection) allDocs,
                blobsForAttachmentTypes);
    }

    if (!Util.nullOrEmpty(docIds)) {
        docsForDocIds = new ArrayList<>();
        for (String id : docIds) {
            Document d = archive.docForId(id);
            if (d != null)
                docsForDocIds.add(d);
        }
    }

    if (datasetId != null) {
        // note: these docNums have nothing to do with docIds of the docs.
        // they are just indexes into a dataset, which is a collection of docs from the result of some search.
        DataSet dataset = (DataSet) getSessionAttribute(session, datasetId);
        if (dataset != null)

        {
            String[] docNumbers = request.getParameterValues("docNum");
            if (docNumbers == null)
                docsForNumbers = dataset.getDocs();
            else
                docsForNumbers = (List) IndexUtils.getDocNumbers(dataset.getDocs(), docNumbers);
        }
    }

    // apply the OR or AND of the filters
    boolean initialized = false;
    List<Document> resultDocs;
    List<Blob> resultBlobs;

    // if its an AND selection, and we are applying only to filtered docs, start with it and intersect with the docs for each facet.
    // otherwise, start with nothing as an optimization, since there's no need to intersect with it.
    // the docs for each facet will always be a subset of archive's docs.
    if (only_apply_to_filtered_docs && !or_not_and && allDocs != null) {
        initialized = true;
        resultDocs = new ArrayList<>(allDocs);
    } else
        resultDocs = new ArrayList<>();

    if (docsForTerm != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForTerm);
        } else
            resultDocs.retainAll(docsForTerm);
    }

    if (docsForRegex != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForRegex);
        } else
            resultDocs.retainAll(docsForRegex);
    }

    if (docsForSentiments != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForSentiments);
        } else
            resultDocs = Util.listIntersection(resultDocs, docsForSentiments);
    }
    if (docsForTag != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForTag);
        } else
            resultDocs = Util.listIntersection(resultDocs, docsForTag);
    }

    if (docsForCluster != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForCluster);
        } else
            resultDocs.retainAll(docsForCluster);
    }

    if (docsForDocIds != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForDocIds);
        } else
            resultDocs.retainAll(docsForDocIds);
    }

    if (docsForPersons != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForPersons);
        } else
            resultDocs = Util.listIntersection(resultDocs, docsForPersons);
    }

    if (docsForDateRange != null) {
        // if (!initialized || or_not_and)
        // note: date range selection is always ANDed, regardless of or_not_and
        if (!initialized) {
            initialized = true;
            resultDocs.addAll(docsForDateRange);
        } else
            resultDocs.retainAll(docsForDateRange);
    }
    if (docsForFolder != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForFolder);
        } else
            resultDocs.retainAll(docsForFolder);
    }

    if (docsForDirection != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForDirection);
        } else
            resultDocs.retainAll(docsForDirection);
    }

    if (docsForDoNotTransfer != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForDoNotTransfer);
        } else
            resultDocs.retainAll(docsForDoNotTransfer);
    }

    if (docsForTransferWithRestrictions != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForTransferWithRestrictions);
        } else
            resultDocs.retainAll(docsForTransferWithRestrictions);
    }

    if (docsForReviewed != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForReviewed);
        } else
            resultDocs.retainAll(docsForReviewed);
    }

    if (docsForGroup != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForGroup);
        } else
            resultDocs.retainAll(docsForGroup);
    }

    if (docsForAttachments != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForAttachments);
        } else
            resultDocs.retainAll(docsForAttachments);
    }

    if (docsForAttachmentTypes != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForAttachmentTypes);
        } else
            resultDocs.retainAll(docsForAttachmentTypes);
    }

    if (docsForNumbers != null) {
        if (!initialized || or_not_and) {
            initialized = true;
            resultDocs.addAll(docsForNumbers);
        } else
            resultDocs.retainAll(docsForNumbers);
    }

    if (!initialized) {
        if (cluster >= 0)
            resultDocs = new ArrayList<Document>(archive.docsForQuery(null, cluster, Indexer.QueryType.FULL)); // means all docs in cluster x
        else {
            resultDocs = new ArrayList<Document>();
            resultDocs.addAll(allDocs); // if no filter, all docs are selected
        }
    }

    // compute resultBlobs
    if (or_not_and) {
        resultBlobs = Util.listUnion(blobsForAttachments, blobsForAttachmentTypes);
        resultBlobs = Util.listUnion(resultBlobs, blobsForTerm);
    } else {
        resultBlobs = Util.listIntersection(blobsForAttachments, blobsForAttachmentTypes);
        resultBlobs = Util.listIntersection(resultBlobs, blobsForTerm);
    }

    // we need to sort again if needed. by default, we're here assuming relevance based sort.
    // can't rely on indexer sort.
    // for 2 reasons:
    // 1. blobs vs. docs may not be sorted by date as they are retrieved separately from the index.
    // 2. there may be no search term -- the user can use this as a way to list all docs, but may still want sort by time
    if (sortBy == Indexer.SortBy.CHRONOLOGICAL_ORDER)
        Collections.sort(resultDocs);
    else if (sortBy == Indexer.SortBy.RECENT_FIRST) {
        Collections.sort(resultDocs);
        Collections.reverse(resultDocs);
    }

    return new Pair<Collection<Document>, Collection<Blob>>(resultDocs, resultBlobs);
}

From source file:com.ovrhere.android.careerstack.ui.MainActivity.java

@SuppressWarnings("unchecked")
@Override//from  www  .  j  av  a 2s  .  c  o  m
protected void onCreate(Bundle savedInstanceState) {
    setThemeByIntent();
    super.onCreate(savedInstanceState);
    getSupportFragmentManager().addOnBackStackChangedListener(this);

    if (PreferenceUtils.isFirstRun(this)) {
        PreferenceUtils.setToDefault(this);
    }
    prefs = PreferenceUtils.getPreferences(this);
    //checks and, if necessary, restarts activity for theme
    checkThemePref();

    setContentView(R.layout.activity_main);

    tabletMessage = (TextView) findViewById(R.id.careerstack_main_text_job_description_message);

    if (savedInstanceState == null) {
        loadFragment(new MainFragment(), TAG_MAIN_FRAG, false);
        actionBarTitle = getString(R.string.app_name);

    } else {
        try {
            currSearchBarState = savedInstanceState.getBundle(KEY_CURRENT_SEARCH_BAR_STATE);

            if (savedInstanceState.getStringArrayList(KEY_FRAG_TAG_TACK) != null) {
                fragTagStack.addAll(savedInstanceState.getStringArrayList(KEY_FRAG_TAG_TACK));
            }

            if (savedInstanceState.getString(KEY_ACTIONBAR_TITLE) != null) {
                actionBarTitle = savedInstanceState.getString(KEY_ACTIONBAR_TITLE);
            }
            reattachLastFragment();

            if (savedInstanceState.getSerializable(KEY_FRAG_SAVED_STATES) != null) {
                try {
                    fragSavedStates.putAll((Map<? extends String, ? extends Bundle>) savedInstanceState
                            .getSerializable(KEY_FRAG_SAVED_STATES));
                } catch (ClassCastException e) {
                }
            }

        } catch (Exception e) {
            if (DEBUG) {
                Log.e(CLASS_NAME, "Should not be having an error here: " + e);
                e.printStackTrace();
            }
        }
    }

    getSupportActionBar().setTitle(actionBarTitle);

}

From source file:de.nava.informa.utils.FeedManagerEntry.java

/**
 * Loads the channel and sets up the time to expire
 *
 * @param uri The location for the rss file
 * @return The Channel//from  w  w w . j  a  va  2 s . c o  m
 * @throws FeedManagerException If the feed specified by <code>uri</code> is invalid
 */
private FeedIF retrieveFeed(String uri) throws FeedManagerException {
    try {
        URL urlToRetrieve = new URL(uri);

        URLConnection conn = null;
        try {
            conn = urlToRetrieve.openConnection();

            if (conn instanceof HttpURLConnection) {

                HttpURLConnection httpConn = (HttpURLConnection) conn;

                httpConn.setInstanceFollowRedirects(true); // not needed, default ?

                //    Hack for User-Agent : problem for
                // http://www.diveintomark.org/xml/rss.xml
                HttpHeaderUtils.setUserAgent(httpConn, "Informa Java API");

                logger.debug("retr feed at url " + uri + ": ETag" + HttpHeaderUtils.getETagValue(httpConn)
                        + " if-modified :" + HttpHeaderUtils.getLastModified(httpConn));

                // get initial values for cond. GET in updateChannel
                this.httpHeaders.setETag(HttpHeaderUtils.getETagValue(httpConn));
                this.httpHeaders.setIfModifiedSince(HttpHeaderUtils.getLastModified(httpConn));
            }
        } catch (java.lang.ClassCastException e) {
            logger.warn("problem cast to HttpURLConnection " + uri, e);
            throw new FeedManagerException(e);
        } catch (NullPointerException e) {
            logger.error("problem NPE " + uri + " conn=" + conn, e);
            throw new FeedManagerException(e);
        }

        ChannelIF channel = FeedParser.parse(getChannelBuilder(), conn.getInputStream());
        this.timeToExpire = getTimeToExpire(channel);
        this.feed = new Feed(channel);

        Date currDate = new Date();
        this.feed.setLastUpdated(currDate);
        this.feed.setDateFound(currDate);
        this.feed.setLocation(urlToRetrieve);
        logger.info("feed retrieved " + uri);

    } catch (IOException e) {
        logger.error("IOException " + feedUri + " e=" + e);
        e.printStackTrace();
        throw new FeedManagerException(e);
    } catch (ParseException e) {
        e.printStackTrace();
        throw new FeedManagerException(e);
    }

    return this.feed;
}

From source file:org.mitre.eren.model.ModelManager.java

/**
 * Convert the message into a string and then parse it using the abdera parser.
 * Is there a simpler way to do this?/*  w ww. j a v a  2 s .  co m*/
 * @param edxl
 * @param outgoing
 */
private void attachMessage(EDXLDistribution edxl, Node outgoing) {

    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        LSSerializer writer = impl.createLSSerializer();
        String str = writer.writeToString(outgoing);

        Abdera abdera = new Abdera();
        Parser parser = abdera.getParser();
        Document<Feed> feed_doc = parser.parse(new StringReader(str));
        ExtensibleElement content = feed_doc.getRoot();

        ContentObject co = edxl.addContentObject();
        XmlContent xc = co.setXmlContent();
        EmbeddedXMLContent exc = xc.addEmbeddedXMLContent();

        exc.addExtension(content);
    } catch (ClassCastException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}