Example usage for java.util Vector addElement

List of usage examples for java.util Vector addElement

Introduction

In this page you can find the example usage for java.util Vector addElement.

Prototype

public synchronized void addElement(E obj) 

Source Link

Document

Adds the specified component to the end of this vector, increasing its size by one.

Usage

From source file:de.mango.business.GoogleSearchProvider.java

public Vector<String> search(String query, int count, int page) {
    Vector<String> results = new Vector<String>();
    // Prepare the query
    try {//from w ww . j av a2  s.c o  m
        query = "http://ajax.googleapis.com/ajax/services/search/images?" + GoogleSearchProvider.searchArguments
                + this.hostLanguage + "&q="
                + URLEncoder.encode(
                        GoogleSearchProvider.restrictToOpenClipart ? query + GoogleSearchProvider.openClipart
                                : query,
                        "UTF-8")
                + "&start=";
    } catch (UnsupportedEncodingException e) {
        if (DEBUG) {
            Log.w(TAG, "Unsupported Encoding Exception:" + e.getMessage());
            Log.w(TAG, Log.getStackTraceString(e));
        }
        return results;
    }

    // start argument to pass to google
    int firstindex = count * page;
    // count of results to skip before adding them to the result array
    int skip = 0;
    // start indices > 56 are skipped by Google, so we
    // ask for results from 56, but skip the unwanted $skip indices
    if (firstindex > 63)
        return results;
    if (firstindex > 56) {
        skip = firstindex - 56;
        firstindex = 56;
    }

    boolean readMore = true; // do we need more queries and are they
    // possible?
    while (readMore) {
        // add start index to the query
        String currentQuery = query + firstindex;
        if (DEBUG)
            Log.d(TAG, "Searching: " + currentQuery);
        try {
            // prepare the connection
            URL url = new URL(currentQuery);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", GoogleSearchProvider.refererUrl);

            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.connect();

            // receive the results
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            // parse the results
            JSONObject json = new JSONObject(builder.toString());
            int responseStatus = json.getInt("responseStatus");
            if (responseStatus == 200)// successful search
            {
                json = json.getJSONObject("responseData");
                JSONArray res = json.getJSONArray("results");
                if (res.length() == 0)
                    return results;
                String s;
                int limit = Math.min(res.length(), count - results.size() + skip);
                for (int i = skip; i < limit; i++) {
                    s = res.getJSONObject(i).getString("unescapedUrl");
                    if (s != null)
                        results.addElement(s);
                }
                // see if there are "more Results"
                JSONObject cursor = json.getJSONObject("cursor");
                JSONArray pages = cursor.getJSONArray("pages");
                int pageCount = pages.length();
                int currentPageIndex = cursor.getInt("currentPageIndex");
                this.moreResults = readMore = (pageCount - 1) > currentPageIndex;
            } else {
                if (DEBUG)
                    Log.w(TAG, "Goole Search Error (Code " + responseStatus + "):"
                            + json.getString("responseDetails"));
                this.moreResults = readMore = false;// prevent for (;;) loop
                // on errors
            }
        } catch (MalformedURLException e) {
            if (DEBUG) {
                Log.w(TAG, "MalformedURLException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (IOException e) {
            if (DEBUG) {
                Log.w(TAG, "IOException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        } catch (JSONException e) {
            if (DEBUG) {
                Log.w(TAG, "JSONException:" + e.getMessage());
                Log.w(TAG, Log.getStackTraceString(e));
            }
            this.moreResults = readMore = false;
        }

        // read more only if we can read more AND want to have more
        readMore = readMore && results.size() < count;
        if (readMore) {
            firstindex += 8;
            if (firstindex > 56)// the last pages always need to start
            // querying at index 56 (or google returns
            // errors)
            {
                skip = firstindex - 56;
                firstindex = 56;
            }
        }
    }
    return results;
}

From source file:com.duroty.application.mail.manager.MailManager.java

/**
 * DOCUMENT ME!/*w  ww.  ja  va  2  s  .  c  o  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param user DOCUMENT ME!
 * @param mid DOCUMENT ME!
 * @param midReferences DOCUMENT ME!
 * @param date DOCUMENT ME!
 * @param beforeSent DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private Vector readReference(Session hsession, Users user, String mid, String midReferences, Date date1,
        boolean beforeSent, boolean isHtml, boolean displayImages) {
    Vector references = new Vector();
    ByteArrayOutputStream baos = null;

    try {
        Locale locale = new Locale(user.getUseLanguage());
        TimeZone timeZone = TimeZone.getDefault();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance(timeZone, locale);
        calendar.setTime(now);

        SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale);
        SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale);

        Criteria crit = hsession.createCriteria(Message.class);
        crit.add(Restrictions.not(Restrictions.eq("mesName", mid)));
        crit.add(Restrictions.eq("mesReferences", midReferences));
        crit.add(Restrictions.eq("users", user));
        crit.add(Restrictions.not(Restrictions.eq("mesBox", this.folderSpam)));
        crit.add(Restrictions.not(Restrictions.eq("mesBox", this.folderTrash)));
        crit.add(Restrictions.not(Restrictions.eq("mesBox", FOLDER_DELETE)));

        if (beforeSent) {
            crit.add(Restrictions.le("mesDate", date1));
        } else {
            crit.add(Restrictions.gt("mesDate", date1));
        }

        crit.addOrder(Order.asc("mesDate"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Message message = (Message) scroll.get(0);

            message.setMesRecent(false);
            hsession.update(message);
            hsession.flush();

            MessageObj obj = new MessageObj(message.getMesName());

            obj.setBox(message.getMesBox());

            obj.setFrom(message.getMesFrom());
            obj.setTo(message.getMesTo());
            obj.setReplyTo(message.getMesReplyTo());
            obj.setCc(message.getMesCc());

            if ((message.getAttachments() != null) && (message.getAttachments().size() > 0)) {
                obj.setHasAttachment(true);

                Set set = message.getAttachments();
                Iterator it = set.iterator();
                Vector attachments = new Vector();

                while (it.hasNext()) {
                    Attachment attachment = (Attachment) it.next();
                    AttachmentObj attachmentObj = new AttachmentObj();
                    attachmentObj.setIdint(attachment.getAttPart());
                    attachmentObj.setName(attachment.getAttName());

                    int size = attachment.getAttSize();
                    size /= 1024;

                    if (size > 1024) {
                        size /= 1024;
                        attachmentObj.setSize(size + " MB");
                    } else {
                        attachmentObj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
                    }

                    String extension = (String) this.extensions.get(attachment.getAttContentType());

                    if (StringUtils.isBlank(extension)) {
                        extension = "generic";
                    }

                    attachmentObj.setExtension(extension);

                    attachmentObj.setContentType(attachment.getAttContentType());
                    attachments.addElement(attachmentObj);
                    obj.setAttachments(attachments);
                }
            } else {
                obj.setHasAttachment(false);
            }

            int size = message.getMesSize();
            size /= 1024;

            if (size > 1024) {
                size /= 1024;
                obj.setSize(size + " MB");
            } else {
                obj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
            }

            if (message.getMesBox().equals(folderSent)) {
                try {
                    obj.setEmail(message.getMesTo());
                } catch (Exception e) {
                    obj.setEmail("unknown to");
                }
            } else {
                obj.setEmail(message.getMesFrom());
            }

            Date date = message.getMesDate();

            if (date != null) {
                Calendar calendar2 = Calendar.getInstance(timeZone, locale);
                calendar2.setTime(date);

                if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))
                        && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH))
                        && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) {
                    obj.setDateStr(formatter2.format(calendar2.getTime()));
                } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
                    obj.setDateStr(formatter1.format(calendar2.getTime()));
                } else {
                    obj.setDateStr(formatter3.format(calendar2.getTime()));
                }
            }

            obj.setDate(date);

            if (message.getLabMeses() != null) {
                Iterator it = message.getLabMeses().iterator();
                StringBuffer label = new StringBuffer();

                while (it.hasNext()) {
                    if (label.length() > 0) {
                        label.append(", ");
                    }

                    LabMes labMes = (LabMes) it.next();
                    label.append(labMes.getId().getLabel().getLabName());
                }

                obj.setLabel(label.toString());
            }

            try {
                if (StringUtils.isBlank(message.getMesSubject())) {
                    obj.setSubject("(no subject)");
                } else {
                    obj.setSubject(message.getMesSubject());
                }
            } catch (Exception ex) {
                obj.setSubject("(no subject)");
            }

            if (message.isMesFlagged()) {
                obj.setFlagged(true);
            } else {
                obj.setFlagged(false);
            }

            if (message.isMesRecent()) {
                obj.setRecent(true);
            } else {
                obj.setRecent(false);
            }

            String priority = "normal";

            if (MessageUtilities.isHighPriority(message.getMesHeaders())) {
                priority = "high";
            } else if (MessageUtilities.isLowPriority(message.getMesHeaders())) {
                priority = "low";
            }

            obj.setPriority(priority);

            String body = message.getMesBody();

            if (!StringUtils.isBlank(body)) {
                obj.setBody(bodyCleaner(body, displayImages));
            } else {
                obj.setBody("");
            }

            references.addElement(obj);
        }

        scroll.close();
    } catch (Exception ex) {
        return null;
    } finally {
        IOUtils.closeQuietly(baos);
    }

    if (references.size() <= 0) {
        return null;
    }

    return references;
}

From source file:focusedCrawler.util.parser.PaginaURL.java

/**
 * Este metodo adiciona um termo na lista de termos com suas posicoes
 * e' dado tambem uma posicao do termo./*from w ww.  java  2  s .c o  m*/
 * E' usado quando a pagina e' construida
 */
protected void adicionaTermoPosicao(String termo, int pos) {
    if (noindex) {
        return;
    }

    if (palavra_posicoes == null) {
        palavra_posicoes = new Hashtable();
    }

    termo = termo.toLowerCase();
    boolean dominio = termo.startsWith("#") && termo.endsWith("#");
    if (!irrelevante(termo) || dominio) {
        Vector posicoes = (Vector) palavra_posicoes.get(termo);

        if (posicoes == null) {
            if (!irrelevante(termo)) {
                posicoes = new Vector();

                palavra_posicoes.put(termo, posicoes);
                posicoes.addElement(new Integer(pos));
            }
        } else {
            posicoes.addElement(new Integer(pos));
        }
    }

}

From source file:focusedCrawler.util.parser.PaginaURL.java

/**
 * Este metodo adiciona um termo na lista de termos com suas posicoes
 * e' dado tambem uma posicao do termo./*from w  w  w  . j  av a  2 s. com*/
 * E' usado quando a pagina e' construida
 */
protected void adicionaTermoMetaPosicao(String termo, int pos) {
    if (noindex) {
        return;
    }

    if (palavra_posicoes_meta == null) {
        palavra_posicoes_meta = new Hashtable();
    }

    termo = termo.toLowerCase();

    Vector posicoesMeta = (Vector) palavra_posicoes_meta.get(termo);

    if (posicoesMeta == null) {
        if (!irrelevante(termo)) {
            posicoesMeta = new Vector();

            palavra_posicoes_meta.put(termo, posicoesMeta);
            posicoesMeta.addElement(new Integer(pos));
        }
    } else {
        posicoesMeta.addElement(new Integer(pos));
    }
}

From source file:com.duroty.application.admin.manager.AdminManager.java

/**
 * DOCUMENT ME!//from   w  ww . j av a 2 s  . com
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public SearchUsersObj allUsers(Session hsession, int page, int byPage) throws Exception {
    SearchUsersObj searchUsersObj = new SearchUsersObj();
    Vector users = new Vector();

    try {
        Criteria crit = hsession.createCriteria(Users.class);
        searchUsersObj.setHits(crit.list().size());

        crit = hsession.createCriteria(Users.class);
        crit.setFirstResult(page * byPage);
        crit.setMaxResults(byPage);
        crit.addOrder(Order.asc("useName"));

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Users user = (Users) scroll.get(0);

            UserObj obj = new UserObj();

            obj.setActive(user.isUseActive());
            obj.setEmail(user.getUseEmail());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            obj.setHtmlMessages(mailPreferences.isMaprHtmlMessage());
            obj.setIdint(user.getUseIdint());
            obj.setLanguage(user.getUseLanguage());
            obj.setMessagesByPage(mailPreferences.getMaprMessagesByPage());
            obj.setName(user.getUseName());
            obj.setPassword(user.getUsePassword());
            obj.setQuotaSize(mailPreferences.getMaprQuotaSize());
            obj.setRegisterDate(user.getUseRegisterDate());

            Integer[] roles = new Integer[user.getUserRoles().size()];

            if (roles.length > 0) {
                it = user.getUserRoles().iterator();

                int i = 0;

                while (it.hasNext()) {
                    UserRole userRole = (UserRole) it.next();
                    roles[i] = new Integer(userRole.getId().getRoles().getRolIdint());
                    i++;
                }
            }

            obj.setRoles(roles);

            obj.setSignature(mailPreferences.getMaprSignature());

            if (mailPreferences.getMaprSpamTolerance() == 100) {
                obj.setSpamTolerance(true);
            } else {
                obj.setSpamTolerance(false);
            }

            obj.setUsername(user.getUseUsername());
            obj.setVacationBody(mailPreferences.getMaprVacationBody());
            obj.setVacationSubject(mailPreferences.getMaprVacationSubject());
            obj.setVactionActive(mailPreferences.isMaprVacationActive());

            int usedQuotaSize = getUsedQuotaSize(hsession, user);
            usedQuotaSize /= 1024;

            if (usedQuotaSize > 1024) {
                usedQuotaSize /= 1024;
                obj.setUsedQuota(usedQuotaSize + " MB");
            } else {
                obj.setUsedQuota(((usedQuotaSize > 0) ? (usedQuotaSize + "") : "<1") + " kB");
            }

            users.addElement(obj);
        }

        searchUsersObj.setUsers(users);

        return searchUsersObj;
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.ViewServiceSpring#getAllViewComponents4Status(java.lang.Integer, int)
 *///ww  w .  j a  v  a 2s.c  o m
@Override
protected ViewComponentValue[] handleGetAllViewComponents4Status(Integer viewDocumentId, int status)
        throws Exception {
    try {
        Vector<ViewComponentValue> vec = new Vector<ViewComponentValue>();
        Collection<ViewComponentHbm> coll = super.getViewComponentHbmDao().findByStatus(viewDocumentId, status);
        Iterator<ViewComponentHbm> it = coll.iterator();
        ViewComponentValue viewDao;
        ViewComponentHbm view;
        while (it.hasNext()) {
            view = it.next();
            if (!view.isRoot()) {
                viewDao = view.getDeployDao();
                viewDao.setPath2Unit(this.getParents4View(view));
                vec.addElement(viewDao);
            }
        }
        return vec.toArray(new ViewComponentValue[0]);
    } catch (Exception e) {
        throw new UserException(e.getMessage());
    }
}

From source file:com.duroty.application.mail.manager.PreferencesManager.java

/**
 * DOCUMENT ME!/*from   ww  w.j a v  a 2 s . c  o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws ManagerException DOCUMENT ME!
 */
public SearchContactsObj getContacts(Session hsession, String repositoryName, int page, int byPage, int order,
        String extra) throws Exception {
    Vector contacts = new Vector();

    SearchContactsObj sobj = new SearchContactsObj();

    try {
        Criteria crit = hsession.createCriteria(Contact.class);
        crit.add(Restrictions.isNotNull("conSentDate"));
        crit.add(Restrictions.isNotNull("conReceivedDate"));
        crit.add(Restrictions.eq("users", getUser(hsession, repositoryName)));

        int hits = crit.list().size();

        sobj.setHits(hits);

        crit = hsession.createCriteria(Contact.class);
        crit.add(Restrictions.isNotNull("conSentDate"));
        crit.add(Restrictions.isNotNull("conReceivedDate"));
        crit.add(Restrictions.eq("users", getUser(hsession, repositoryName)));
        crit.setFirstResult(page * byPage);
        crit.setMaxResults(byPage);

        switch (order) {
        case ORDER_BY_EMAIL:
            crit.addOrder(Order.asc("conEmail"));

            break;

        case ORDER_BY_FREQUENCY_SENT:
            crit.addOrder(Order.desc("conCount"));

            break;

        case ORDER_BY_FREQUENCY_RECEIVED:
            crit.addOrder(Order.desc("conCount"));

            break;

        default:
            crit.addOrder(Order.desc("conCount"));

            break;
        }

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            Contact contact = (Contact) scroll.get(0);

            ContactObj obj = new ContactObj();
            obj.setIdint(contact.getConIdint());
            obj.setName(contact.getConName());
            obj.setEmail(contact.getConEmail());

            if (!StringUtils.isBlank(contact.getConDescription())) {
                obj.setDescription(contact.getConDescription().replaceAll("\n", "\\\\n")
                        .replaceAll("\r", "\\\\r").replaceAll("'", "''"));
            }

            contacts.addElement(obj);
        }

        sobj.setContacts(contacts);

        return sobj;
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.PreferencesManager.java

/**
 * DOCUMENT ME!/*from ww  w. jav  a2s.co m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param byPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param extra DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public SearchGroupsObj getGroups(Session hsession, String repositoryName, int page, int byPage, int order,
        String extra) throws Exception {
    Vector contacts = new Vector();

    SearchGroupsObj sobj = new SearchGroupsObj();

    try {
        Criteria crit = hsession.createCriteria(ContactList.class);
        crit.add(Restrictions.eq("users", getUser(hsession, repositoryName)));

        int hits = crit.list().size();

        sobj.setHits(hits);

        crit = hsession.createCriteria(ContactList.class);
        crit.add(Restrictions.eq("users", getUser(hsession, repositoryName)));
        crit.addOrder(Order.asc("coliName"));

        if (byPage > 0) {
            crit.setFirstResult(page * byPage);
            crit.setMaxResults(byPage);
        }

        ScrollableResults scroll = crit.scroll();

        while (scroll.next()) {
            ContactList contactList = (ContactList) scroll.get(0);

            ContactListObj obj = new ContactListObj();
            obj.setIdint(contactList.getColiIdint());
            obj.setName(contactList.getColiName());

            Set set = contactList.getConColis();

            StringBuffer emails = new StringBuffer();

            if (set != null) {
                Iterator it = set.iterator();

                while (it.hasNext()) {
                    ConColi conColi = (ConColi) it.next();
                    Contact contact = conColi.getId().getContact();

                    if (emails.length() > 0) {
                        emails.append(", ");
                    }

                    String name = "";

                    if (!StringUtils.isBlank(contact.getConName())) {
                        name = contact.getConName().replaceAll("'", "\\\\'") + " ";
                    }

                    emails.append(name + "<" + contact.getConEmail() + ">");
                }

                if (emails.length() > 0) {
                    obj.setEmails(emails.toString() + ", ");
                }
            }

            contacts.addElement(obj);
        }

        sobj.setGroups(contacts);

        return sobj;
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.bookmark.manager.BookmarkManager.java

/**
 * DOCUMENT ME!/* w  w  w  .  ja  v a  2s . co  m*/
 *
 * @param repositoryName DOCUMENT ME!
 * @param token DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param messagesByPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param orderType DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws BookmarkException DOCUMENT ME!
 * @throws SearchException DOCUMENT ME!
 */
public SearchObj search(String repositoryName, String token, int page, int messagesByPage, int order,
        String orderType, boolean isNotebook) throws BookmarkException {
    String lucenePath = "";

    if (!defaultLucenePath.endsWith(File.separator)) {
        lucenePath = defaultLucenePath + File.separator + repositoryName + File.separator
                + Constants.BOOKMARK_LUCENE_BOOKMARK;
    } else {
        lucenePath = defaultLucenePath + repositoryName + File.separator + Constants.BOOKMARK_LUCENE_BOOKMARK;
    }

    Searcher searcher = null;
    SearchObj searchObj = new SearchObj();
    Highlighter highlighter = null;

    try {
        searcher = BookmarkIndexer.getSearcher(lucenePath);

        Query query = null;
        Hits hits = null;

        if (StringUtils.isBlank(token)) {
            if (isNotebook) {
                query = SimpleQueryParser.parse("notebook:true", new KeywordAnalyzer());
            } else {
                query = new MatchAllDocsQuery();
            }

            hits = searcher.search(query, new Sort(new SortField[] { SortField.FIELD_SCORE,
                    new SortField(Field_insert_date, SortField.STRING, true) }));
        } else {
            query = SimpleQueryParser.parse(token, analyzer);

            StringBuffer buffer = new StringBuffer();

            if (isNotebook) {
                buffer.append("(" + query.toString() + ") AND ");

                QueryParser parser = new QueryParser(Field_notebook, new KeywordAnalyzer());
                parser.setDefaultOperator(Operator.AND);

                Query aux = parser.parse(String.valueOf(true));

                buffer.append("(" + aux.toString() + ") ");
            }

            if (buffer.length() > 0) {
                QueryParser parser = new QueryParser("", new WhitespaceAnalyzer());
                query = parser.parse(buffer.toString());
            }

            hits = searcher.search(query);
        }

        Date searchStart = new Date();

        Date searchEnd = new Date();

        //time in seconds
        double time = ((double) (searchEnd.getTime() - searchStart.getTime())) / (double) 1000;

        int hitsLength = hits.length();

        if (hitsLength <= 0) {
            return null;
        }

        int start = page * messagesByPage;
        int end = start + messagesByPage;

        if (end > 0) {
            end = Math.min(hitsLength, end);
        } else {
            end = hitsLength;
        }

        if (start > end) {
            throw new SearchException("Search index of bound. start > end");
        }

        Vector bookmarks = new Vector();

        for (int j = start; j < end; j++) {
            Document doc = hits.doc(j);

            if (doc != null) {
                LuceneBookmark luceneBookmark = new LuceneBookmark(doc);

                SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<b>", "</b>");
                highlighter = new Highlighter(formatter, new QueryScorer(query));
                highlighter.setTextFragmenter(new SimpleFragmenter(150));

                BookmarkObj bookmarkObj = new BookmarkObj();
                bookmarkObj.setCacheDate(luceneBookmark.getCacheDate());
                bookmarkObj.setComments(luceneBookmark.getComments());
                bookmarkObj.setContents(luceneBookmark.getCotents());
                bookmarkObj.setDepth(luceneBookmark.getDepth());
                bookmarkObj.setFlagged(luceneBookmark.isFlagged());
                bookmarkObj.setIdint(luceneBookmark.getIdint());
                bookmarkObj.setInsertDate(luceneBookmark.getInsertDate());
                bookmarkObj.setKeywords(luceneBookmark.getKeywords());
                bookmarkObj.setNotebook(luceneBookmark.isNotebook());
                bookmarkObj.setParent(Long.parseLong(luceneBookmark.getParent()));
                bookmarkObj.setTitle(luceneBookmark.getTitle());
                bookmarkObj.setTitleHighlight(luceneBookmark.getTitle());
                bookmarkObj.setUrl(luceneBookmark.getUrl());

                String contents = luceneBookmark.getCotents();
                String hcontents = null;

                if ((contents != null) && (!contents.trim().equals(""))) {
                    contents = contents.replaceAll("\\s+", " ");

                    TokenStream tokenStream = analyzer.tokenStream(Field_contents, new StringReader(contents));
                    hcontents = highlighter.getBestFragment(tokenStream, contents);

                    if (hcontents != null) {
                        contents = hcontents;
                    } else {
                        contents = null;
                    }
                }

                bookmarkObj.setContentsHighlight(contents);

                String title = luceneBookmark.getTitle();
                String htitle = null;

                if ((title != null) && (!title.trim().equals(""))) {
                    title = title.replaceAll("\\s+", " ");

                    TokenStream tokenStream = analyzer.tokenStream(Field_title, new StringReader(title));
                    htitle = highlighter.getBestFragment(tokenStream, title);

                    if (htitle != null) {
                        title = htitle;
                    }
                }

                bookmarkObj.setTitleHighlight(title);

                bookmarks.addElement(bookmarkObj);
            }
        }

        searchObj.setHits(hitsLength);
        searchObj.setTime(time);
        searchObj.setBookmarks(bookmarks);
    } catch (Exception ex) {
        throw new SearchException(ex);
    } finally {
    }

    return searchObj;
}

From source file:alter.vitro.vgw.wsiadapter.WsiUberDustCon.java

private Vector<String> DEBUG_offline_getFaultyNodes() {

    String responseBodyFromHttpNodesGetStr = WsiUberDustCon.DEBUG_OFFLINE_STR_NODE_GETRESTSTATUS;
    String responseBodyFromHttpNodes_STATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_GETRESTSTATUS_RAW;
    String responseBodyFromHttpNodes_ADMINSTATUS_Get = WsiUberDustCon.DEBUG_OFFLINE_STR_BODY_ADMINSTATUS;

    Vector<String> retVec = new Vector<String>();
    // direct for test http://uberdust.cti.gr/rest/sendCommand/destination/urn:wisebed:ctitestbed:0x42f/payload/7f,69,70,1,$1,1
    try {// w w w  . java2s.  co m

        String[] faultyNodeUrnsLinesInUberdust = responseBodyFromHttpNodes_ADMINSTATUS_Get.split("\\r?\\n");
        int totalfaultyNodeUrnsLinesInUberdust = faultyNodeUrnsLinesInUberdust.length;
        for (String afaultyNodeUrnLineInUberdust : faultyNodeUrnsLinesInUberdust) {
            String[] afaultyNodeUrnTokens = afaultyNodeUrnLineInUberdust.split("\\t");
            // [0] has the urn
            if (afaultyNodeUrnTokens != null && afaultyNodeUrnTokens.length > 0
                    && !afaultyNodeUrnTokens[0].isEmpty()) {
                retVec.addElement(afaultyNodeUrnTokens[0]);
                //      logger.debug("Adding faulty node:: "+afaultyNodeUrnTokens[0]);
            }

        }
    } catch (Exception e) {
        logger.debug(e.getMessage());
    }
    return retVec;
}