Subversion Repositories bacoAlunos

Rev

Rev 1306 | Rev 1312 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.srusources;

import pt.utl.ist.berserk.logic.serviceManager.IService;
import pt.estgp.estgweb.services.common.*;
import pt.estgp.estgweb.services.common.impl.DefaultSearchResults;
import pt.estgp.estgweb.services.common.impl.DefaultResult;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.views.SruSourceView;
import pt.estgp.estgweb.domain.views.SruSourceCollectionView;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.utils.RoleManager;
import pt.estgp.estgweb.utils.Dom4jUtil;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.estgp.estgweb.Globals;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.analysis.Analyzer;
import org.dom4j.Document;
import org.dom4j.XPath;
import org.dom4j.Element;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.URLEncoder;
import java.net.URL;

/*
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
 *
 *
 * Created at 17/Out/2003 , 23:45:24
 *
 */

/**
 * @author Jorge Machado
 *         <p/>
 *         <p/>
 *         Created at 17/Out/2003 , 23:45:24
 */

public class SruSourcesCommonServices extends MultipleSearchResults implements IService, IModuleCommonServices
{

    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(SruSourcesCommonServices.class);


    public int countSearch(1.5.0/docs/api/java/lang/String.html">String search, SearchTypeEnum searchType, UserSession userSession)
    {
        return 0;
    }

    public List<ISearchResults> searchList(1.5.0/docs/api/java/lang/String.html">String moduleInternalKey, 1.5.0/docs/api/java/lang/String.html">String search, SearchTypeEnum searchType, int page, int maxResults, UserSession userSession)
    {
        return searchList(moduleInternalKey, null, search, searchType, page, maxResults, userSession);
    }

    public List<ISearchResults> searchList(1.5.0/docs/api/java/lang/String.html">String moduleInternalKey, 1.5.0/docs/api/java/lang/String.html">String from, 1.5.0/docs/api/java/lang/String.html">String search, SearchTypeEnum searchType, int page, int maxResults, UserSession userSession)
    {
        boolean containsSpecialChars = false;

        if(!QueryLanguageChars.isValid(search))
            return null;
        if(QueryLanguageChars.containsSpecialNotUsual(search))
        {
            containsSpecialChars = true;
        }

//        if(searchType == SearchTypeEnum.ExactPhrase && search.indexOf("AND") < 0)
//            search = "\"" + search + "\"";
//        if(searchType == SearchTypeEnum.AllWords && search)
//        search = search.replace("(","\\(").replace(")","\\)").replace("[","\\[").replace("]","\\]").replace("{","\\{").replace("}","\\}").replace(":","\\:").replace("^","\\^");
        List<ISearchResults> searchResults = new ArrayList<ISearchResults>();

        if(userSession.getUser() == null)
            return searchResults;

        //obtain source, in case of internal key means hat we are in the presence of a page search
        List<SruSource> sruSources;
        List<SruSourceView> admitedSources;
        if(moduleInternalKey == null)
        {
            sruSources = DaoFactory.getSruSourceDaoImpl().findAll();
        }
        else
        {
            long sourceId = 1.5.0/docs/api/java/lang/Long.html">Long.parseLong(moduleInternalKey);
            SruSource sruSource = DaoFactory.getSruSourceDaoImpl().load(sourceId);
            sruSources = new ArrayList<SruSource>();
            sruSources.add(sruSource);
        }


        //filtering the admited sources
        admitedSources = new ArrayList<SruSourceView>();
        for(SruSource source: sruSources)
        {
            List<SruSourceCollection> admitedCollections = new ArrayList<SruSourceCollection>();

            for(SruSourceCollection sruSourceCollection : source.getCollections())
            {
                if(sruSourceCollection.getAdmitedRoles() == null || sruSourceCollection.getAdmitedRoles().trim().length() == 0 || RoleManager.hasRole(userSession.getUser(), RoleManager.getRolesFromSerial(sruSourceCollection.getAdmitedRoles())))
                {
                    admitedCollections.add(sruSourceCollection);
                }
            }
            if(admitedCollections.size() > 0)
            {
                SruSourceView sruSourceView = new SruSourceView(source,admitedCollections);
                admitedSources.add(sruSourceView);
            }
        }

        if(admitedSources.size() > 0)
        {
            for(SruSourceView sruSourceView: admitedSources)
            {
                DefaultSearchResults searchResultsSource = new DefaultSearchResults();
                searchResultsSource.setResults(new ArrayList<IResult>());
                searchResultsSource.setModuleInternalKey("" + sruSourceView.getId());
                searchResultsSource.setModule(ModuleEnum.SruSource);
                searchResultsSource.setDescription(sruSourceView.getName());
                try
                {
                    1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder collectionQuery = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
                    1.5.0/docs/api/java/lang/String.html">String appender = "";
                    for(SruSourceCollectionView collectionView: sruSourceView.getCollections())
                    {
                        collectionQuery.append(appender).append(sruSourceView.getCollectionField()).append(":\"" + collectionView.getCollection() + "\"");
                        appender = " OR ";
                    }
                    1.5.0/docs/api/java/lang/String.html">String finalQuery = "(" + collectionQuery.toString() + ") AND (" + search + ")";
                    logger.info("Sru server " + sruSourceView.getName() + " final query: " + finalQuery);
                    1.5.0/docs/api/java/lang/String.html">String service = "getSRUResponseWithThisQueryPhraseBoost";
                    if(containsSpecialChars)
                        service = "getSRUResponseWithThisQuery";
                    1.5.0/docs/api/java/lang/String.html">String sruRequest = sruSourceView.getUrl() +  "?query=" + 1.5.0/docs/api/java/net/URLEncoder.html">URLEncoder.encode(finalQuery,"UTF-8") + "&verb=" + service + "&startRecord=" + ((page*maxResults)+1) + "&maximumRecords=" + maxResults;
                    1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(sruRequest);
                    5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(url);

                    Map<String,String> namespaces = new HashMap<String,String>();
                    namespaces.put("files","http://www.estgp.pt/sru/solrFilesManager");
                    namespaces.put("srw","http://www.loc.gov/zing/srw/");

                    1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathNumberOfRecords = dom.createXPath("//srw:numberOfRecords");
                    xPathNumberOfRecords.setNamespaceURIs(namespaces);
                    5+0%2Fdocs%2Fapi+Element">Element numberOfRecords = (5+0%2Fdocs%2Fapi+Element">Element) xPathNumberOfRecords.selectSingleNode(dom);
                    if(numberOfRecords == null)
                        continue;
                    searchResultsSource.setTotalResults(1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(numberOfRecords.getTextTrim()));

                    1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathRecords = dom.createXPath("//files:doc");
                    xPathRecords.setNamespaceURIs(namespaces);
                    List<Element> docs = xPathRecords.selectNodes(dom);
                    for(5+0%2Fdocs%2Fapi+Element">Element doc: docs)
                    {
                        1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileRelativePath = dom.createXPath("./files:fileRelativePath");
                        xPathFileRelativePath.setNamespaceURIs(namespaces);
                        5+0%2Fdocs%2Fapi+Object">Object fileRelativePath = xPathFileRelativePath.selectSingleNode(doc);

                        1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileName = dom.createXPath("./files:fileName");
                        xPathFileName.setNamespaceURIs(namespaces);
                        5+0%2Fdocs%2Fapi+Element">Element fileName = (5+0%2Fdocs%2Fapi+Element">Element) xPathFileName.selectSingleNode(doc);

                        1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileSize = dom.createXPath("./files:fileSizeKB");
                        xPathFileSize.setNamespaceURIs(namespaces);
                        5+0%2Fdocs%2Fapi+Element">Element fileSizeKB = (5+0%2Fdocs%2Fapi+Element">Element) xPathFileSize.selectSingleNode(doc);

                        1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileType = dom.createXPath("./files:fileType");
                        xPathFileType.setNamespaceURIs(namespaces);
                        5+0%2Fdocs%2Fapi+Element">Element fileType = (5+0%2Fdocs%2Fapi+Element">Element) xPathFileType.selectSingleNode(doc);

                        1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileDateLastModified = dom.createXPath("./files:fileDateLastModified");
                        xPathFileDateLastModified.setNamespaceURIs(namespaces);
                        5+0%2Fdocs%2Fapi+Element">Element fileDateLastModified = (5+0%2Fdocs%2Fapi+Element">Element) xPathFileDateLastModified.selectSingleNode(doc);
                        if(fileRelativePath != null )
                        {
                            1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFileUrl = dom.createXPath("./files:url");
                            xPathFileUrl.setNamespaceURIs(namespaces);
                            5+0%2Fdocs%2Fapi+Object">Object fileUrl =  xPathFileUrl.selectSingleNode(doc);
                            if(fileUrl != null)
                            {

                                DefaultResult defaultResult = new DefaultResult();
                                1.5.0/docs/api/java/lang/String.html">String relativePathStr = ((5+0%2Fdocs%2Fapi+Element">Element)fileRelativePath).getText();
                                defaultResult.setTitle(fileName.getText());
                                defaultResult.setSizeKb(fileSizeKB.getTextTrim());
                                defaultResult.setDirectory(relativePathStr);




                                defaultResult.setDate(fileDateLastModified.getTextTrim());
                                defaultResult.setMime(fileType.getTextTrim());
//                            defaultResult.setSubTitle(courseUnit.getCourseName());
//                            defaultResult.setSubTitleKey(false);
//                            defaultResult.setText(courseUnit.getObjectives());
                                1.5.0/docs/api/java/lang/String.html">String urlStr = ((5+0%2Fdocs%2Fapi+Element">Element)fileUrl).getTextTrim();
                                1.5.0/docs/api/java/lang/String.html">String[] pathItems = relativePathStr.trim().split("\\\\");
                                1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder pathBuidler = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
                                for(1.5.0/docs/api/java/lang/String.html">String item: pathItems)
                                {
                                    if(item.trim().length() > 0)
                                        pathBuidler.append("/").append(1.5.0/docs/api/java/net/URLEncoder.html">URLEncoder.encode(item,"ISO-8859-1").replace("+","%20"));
                                }
                                urlStr = urlStr.substring(0,urlStr.length() - (relativePathStr.length())) + pathBuidler.toString();


                                defaultResult.setUrl(urlStr);

                                defaultResult.setAbsoluteUrl(true);

                                1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathCollection = dom.createXPath("./files:collection");
                                xPathFileUrl.setNamespaceURIs(namespaces);
                                5+0%2Fdocs%2Fapi+Element">Element collection  = (5+0%2Fdocs%2Fapi+Element">Element) xPathCollection.selectSingleNode(doc);
                                defaultResult.setSubTitle(formatSubtitle(relativePathStr,collection.getTextTrim()));


                                1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFragment = dom.createXPath("./files:snippet/files:fragment");
                                xPathFragment.setNamespaceURIs(namespaces);
                                List<Element> fragments  = (List<Element>) xPathFragment.selectNodes(doc);
                                if(fragments != null)
                                {
                                    defaultResult.setBestFragments("");
                                    for(5+0%2Fdocs%2Fapi+Element">Element fragment: fragments)
                                    {
                                        defaultResult.setBestFragments(defaultResult.getBestFragments() + " ... " + fragment.getTextTrim().replace("<em>","<b><i>").replace("</em>","</i></b>"));
                                    }
                                }
                                searchResultsSource.addResult(defaultResult);
                            }
                            else
                                logger.warn("File retured from SRU without filePath query:" + search + " page:" + page + " path:" + ((5+0%2Fdocs%2Fapi+Element">Element)fileRelativePath).getText() );
                        }
                        else
                            logger.warn("File retured from SRU without filePath query:" + search + " page:" + page);
                    }

                    /*Facets*/
                    List<IFacet> facets = new ArrayList<IFacet>();
                    1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFacets = dom.createXPath("//files:facet");
                    xPathFacets.setNamespaceURIs(namespaces);
                    List<Element> facetsElems = xPathFacets.selectNodes(dom);
                    for(5+0%2Fdocs%2Fapi+Element">Element facetElem: facetsElems)
                    {
                        DefaultFacet defaultFacet = new DefaultFacet();
                        defaultFacet.setLabels(new ArrayList<IFacetLabel>());
                        defaultFacet.setIndex(facetElem.attribute("name").getValue());
                        if(!defaultFacet.getIndex().equals("dir") && !defaultFacet.getIndex().equals("facetDir"))
                        {
                            1.5.0/docs/api/javax/xml/xpath/XPath.html">XPath xPathFacetLabel = dom.createXPath("./files:facetLabel");
                            xPathFacetLabel.setNamespaceURIs(namespaces);
                            List<Element> facetLabelElems = xPathFacetLabel.selectNodes(facetElem);

                            for(5+0%2Fdocs%2Fapi+Element">Element facetLabelElem: facetLabelElems)
                            {
                                DefaultFacetLabel facetLabel = new DefaultFacetLabel();
                                facetLabel.setOccurrences(1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(facetLabelElem.attribute("ocurr").getValue()));
                                facetLabel.setLabel(facetLabelElem.getTextTrim());
                                if(facetLabel.getOccurrences() > 0)
                                    defaultFacet.getLabels().add(facetLabel);
                            }
                            if(defaultFacet.getLabels().size()>0)
                                facets.add(defaultFacet);
                        }
                    }
                    if(facets.size() > 0)
                        searchResultsSource.setFacets(facets);
                }
                catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
                {
                    logger.error(e,e);
                }

                if(searchResultsSource.getResults() != null && searchResultsSource.getResults().size() > 0)
                    searchResults.add(searchResultsSource);
            }
        }
        return searchResults;
    }




    static HashMap<String, Pattern> patterns = new HashMap<String,Pattern>();
    private 1.5.0/docs/api/java/lang/String.html">String formatSubtitle(1.5.0/docs/api/java/lang/String.html">String path, 1.5.0/docs/api/java/lang/String.html">String collection)
    {
        path = path.trim();
        if(path.startsWith("\\") || path.startsWith("/"))
            path = path.substring(1);
        List<String> regexProps = ConfigProperties.getListProperties("srusource.path.condition.pattern");
        for(1.5.0/docs/api/java/lang/String.html">String regexProp: regexProps)
        {
            1.5.0/docs/api/java/lang/String.html">String id = regexProp.substring(regexProp.lastIndexOf("."));
            1.5.0/docs/api/java/lang/String.html">String patternStr = ConfigProperties.getProperty(regexProp);

            1.5.0/docs/api/java/lang/String.html">String template = ConfigProperties.getProperty("srusource.path.condition.template" + id);
            1.5.0/docs/api/java/util/regex/Pattern.html">Pattern pattern = patterns.get(patternStr);
            if(pattern == null)
            {
                pattern = 1.5.0/docs/api/java/util/regex/Pattern.html">Pattern.compile(patternStr);
                patterns.put(patternStr,pattern);
            }
            1.5.0/docs/api/java/util/regex/Matcher.html">Matcher matcher = pattern.matcher(path);
            if(matcher.find())
            {
                1.5.0/docs/api/java/lang/String.html">String[]  paths = path.split("[\\\\]");
                template = template.replace("@collection@", collection);
                return java.text.1.5.0/docs/api/java/text/MessageFormat.html">MessageFormat.format(template,paths);
            }
        }
        return "(" + collection + ")";
    }



    public int countToDo(UserSession userSession)
    {
        return 0;
    }

    public IToDoCat getToDo(UserSession userSession)
    {
        return null;
    }

    public List<IToDo> getAllToDos(UserSession userSession)
    {
        return null;
    }/*This method is invoked from object creation*/

    public void adviseNew(DomainObject object)
    {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void adviseUpdate(DomainObject object)
    {
        //To change body of implemented methods use File | Settings | File Templates.
    }




}