1 package org.apache.maven.archiva.web.action;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import java.net.MalformedURLException;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.List;
29 import org.apache.archiva.indexer.search.RepositorySearch;
30 import org.apache.archiva.indexer.search.RepositorySearchException;
31 import org.apache.archiva.indexer.search.SearchFields;
32 import org.apache.archiva.indexer.search.SearchResultHit;
33 import org.apache.archiva.indexer.search.SearchResultLimits;
34 import org.apache.archiva.indexer.search.SearchResults;
35 import org.apache.commons.collections.CollectionUtils;
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
38 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
39 import org.apache.maven.archiva.database.ArchivaDAO;
40 import org.apache.maven.archiva.database.ArtifactDAO;
41 import org.apache.maven.archiva.database.Constraint;
42 import org.apache.maven.archiva.database.constraints.ArtifactsByChecksumConstraint;
43 import org.apache.maven.archiva.security.AccessDeniedException;
44 import org.apache.maven.archiva.security.ArchivaSecurityException;
45 import org.apache.maven.archiva.security.ArchivaXworkUser;
46 import org.apache.maven.archiva.security.PrincipalNotFoundException;
47 import org.apache.maven.archiva.security.UserRepositories;
49 import com.opensymphony.xwork2.ActionContext;
50 import com.opensymphony.xwork2.Preparable;
51 import org.apache.maven.archiva.common.utils.VersionUtil;
52 import org.apache.maven.archiva.database.constraints.UniqueVersionConstraint;
53 import org.apache.struts2.ServletActionContext;
54 import org.springframework.web.context.WebApplicationContext;
55 import org.springframework.web.context.support.WebApplicationContextUtils;
58 * Search all indexed fields by the given criteria.
60 * @plexus.component role="com.opensymphony.xwork2.Action" role-hint="searchAction" instantiation-strategy="per-lookup"
62 public class SearchAction
63 extends PlexusActionSupport
70 private ArchivaConfiguration archivaConfiguration;
72 private Map<String, ManagedRepositoryConfiguration> managedRepositories;
77 * @plexus.requirement role-hint="jdo"
79 private ArchivaDAO dao;
84 private SearchResults results;
89 private UserRepositories userRepositories;
94 private ArchivaXworkUser archivaXworkUser;
96 private static final String RESULTS = "results";
98 private static final String ARTIFACT = "artifact";
100 private List databaseResults;
102 private int currentPage = 0;
104 private int totalPages;
106 private boolean searchResultsOnly;
108 private String completeQueryString;
110 private static final String COMPLETE_QUERY_STRING_SEPARATOR = ";";
112 private List<String> managedRepositoryList;
114 private String groupId;
116 private String artifactId;
118 private String version;
120 private String className;
122 private int rowCount = 30;
124 private String repositoryId;
126 private boolean fromFilterSearch;
128 private boolean filterSearch = false;
130 private boolean fromResultsPage;
132 private RepositorySearch nexusSearch;
134 private Map<String, String> searchFields;
136 public boolean isFromResultsPage()
138 return fromResultsPage;
141 public void setFromResultsPage( boolean fromResultsPage )
143 this.fromResultsPage = fromResultsPage;
146 public boolean isFromFilterSearch()
148 return fromFilterSearch;
151 public void setFromFilterSearch( boolean fromFilterSearch )
153 this.fromFilterSearch = fromFilterSearch;
156 public void prepare()
158 managedRepositoryList = new ArrayList<String>();
159 managedRepositoryList = getObservableRepos();
161 if ( managedRepositoryList.size() > 0 )
163 managedRepositoryList.add( "all" );
166 searchFields = new HashMap<String, String>();
167 searchFields.put( "groupId", "Group ID" );
168 searchFields.put( "artifactId", "Artifact ID" );
169 searchFields.put( "version", "Version" );
170 searchFields.put( "className", "Class/Package Name" );
171 searchFields.put( "rowCount", "Row Count" );
173 super.clearErrorsAndMessages();
177 private void clearSearchFields()
188 // advanced search MRM-90 -- filtered search
189 public String filteredSearch()
190 throws MalformedURLException
192 if ( ( groupId == null || "".equals( groupId ) ) &&
193 ( artifactId == null || "".equals( artifactId ) ) && ( className == null || "".equals( className ) ) &&
194 ( version == null || "".equals( version ) ) )
196 addActionError( "Advanced Search - At least one search criteria must be provided." );
200 fromFilterSearch = true;
202 if ( CollectionUtils.isEmpty( managedRepositoryList ) )
204 return GlobalResults.ACCESS_TO_NO_REPOS;
207 SearchResultLimits limits = new SearchResultLimits( currentPage );
208 limits.setPageSize( rowCount );
209 List<String> selectedRepos = new ArrayList<String>();
211 if ( repositoryId == null || StringUtils.isBlank( repositoryId ) ||
212 "all".equals( StringUtils.stripToEmpty( repositoryId ) ) )
214 selectedRepos = getObservableRepos();
218 selectedRepos.add( repositoryId );
221 if ( CollectionUtils.isEmpty( selectedRepos ) )
223 return GlobalResults.ACCESS_TO_NO_REPOS;
226 SearchFields searchFields =
227 new SearchFields( groupId, artifactId, version, null, className, selectedRepos );
229 // TODO: add packaging in the list of fields for advanced search (UI)?
232 results = getNexusSearch().search( getPrincipal(), searchFields, limits );
234 catch ( RepositorySearchException e )
236 addActionError( e.getMessage() );
240 if ( results.isEmpty() )
242 addActionError( "No results found" );
246 totalPages = results.getTotalHits() / limits.getPageSize();
248 if ( ( results.getTotalHits() % limits.getPageSize() ) != 0 )
250 totalPages = totalPages + 1;
253 for (SearchResultHit hit : results.getHits())
255 final String version = hit.getVersion();
258 hit.setVersion(VersionUtil.getBaseVersion(version));
265 public String quickSearch()
266 throws MalformedURLException
268 /* TODO: give action message if indexing is in progress.
269 * This should be based off a count of 'unprocessed' artifacts.
270 * This (yet to be written) routine could tell the user that X (unprocessed) artifacts are not yet
271 * present in the full text search.
274 assert q != null && q.length() != 0;
276 fromFilterSearch = false;
278 SearchResultLimits limits = new SearchResultLimits( currentPage );
280 List<String> selectedRepos = getObservableRepos();
281 if ( CollectionUtils.isEmpty( selectedRepos ) )
283 return GlobalResults.ACCESS_TO_NO_REPOS;
288 if( searchResultsOnly && !completeQueryString.equals( "" ) )
290 results = getNexusSearch().search( getPrincipal(), selectedRepos, q, limits, parseCompleteQueryString() );
294 completeQueryString = "";
295 results = getNexusSearch().search( getPrincipal(), selectedRepos, q, limits, null );
298 catch ( RepositorySearchException e )
300 addActionError( e.getMessage() );
304 if ( results.isEmpty() )
306 addActionError( "No results found" );
310 totalPages = results.getTotalHits() / limits.getPageSize();
312 if( (results.getTotalHits() % limits.getPageSize()) != 0 )
314 totalPages = totalPages + 1;
316 // TODO: filter / combine the artifacts by version? (is that even possible with non-artifact hits?)
318 /* I don't think that we should, as I expect us to utilize the 'score' system in lucene in
319 * the future to return relevant links better.
320 * I expect the lucene scoring system to take multiple hits on different areas of a single document
321 * to result in a higher score.
325 if( !isEqualToPreviousSearchTerm( q ) )
327 buildCompleteQueryString( q );
330 //Lets get the versions for the artifact we just found and display them
331 //Yes, this is in the lucene index but its more challenging to get them out when we are searching by project
333 // TODO: do we still need to do this? all hits are already filtered in the NexusRepositorySearch
334 // before being returned as search results
335 for ( SearchResultHit resultHit : results.getHits() )
337 final List<String> versions =
338 dao.query( new UniqueVersionConstraint( getObservableRepos(), resultHit.getGroupId(),
339 resultHit.getArtifactId() ) );
340 if ( versions != null && !versions.isEmpty() )
342 resultHit.setVersion( null );
343 resultHit.setVersions( filterTimestampedSnapshots( versions ) );
351 * Remove timestamped snapshots from versions
353 private static List<String> filterTimestampedSnapshots(List<String> versions)
355 final List<String> filtered = new ArrayList<String>();
356 for (final String version : versions)
358 final String baseVersion = VersionUtil.getBaseVersion(version);
359 if (!filtered.contains(baseVersion))
361 filtered.add(baseVersion);
367 public String findArtifact()
370 // TODO: give action message if indexing is in progress
372 if ( StringUtils.isBlank( q ) )
374 addActionError( "Unable to search for a blank checksum" );
378 Constraint constraint = new ArtifactsByChecksumConstraint( q );
380 ArtifactDAO artifactDao = dao.getArtifactDAO();
381 databaseResults = artifactDao.queryArtifacts( constraint );
383 if ( databaseResults.isEmpty() )
385 addActionError( "No results found" );
389 if ( databaseResults.size() == 1 )
391 // 1 hit? return it's information directly!
398 public String doInput()
403 private String getPrincipal()
405 return archivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
408 private List<String> getObservableRepos()
412 return userRepositories.getObservableRepositoryIds( getPrincipal() );
414 catch ( PrincipalNotFoundException e )
416 getLogger().warn( e.getMessage(), e );
418 catch ( AccessDeniedException e )
420 getLogger().warn( e.getMessage(), e );
422 catch ( ArchivaSecurityException e )
424 getLogger().warn( e.getMessage(), e );
426 return Collections.emptyList();
429 private void buildCompleteQueryString( String searchTerm )
431 if ( searchTerm.indexOf( COMPLETE_QUERY_STRING_SEPARATOR ) != -1 )
433 searchTerm = StringUtils.remove( searchTerm, COMPLETE_QUERY_STRING_SEPARATOR );
436 if ( completeQueryString == null || "".equals( completeQueryString ) )
438 completeQueryString = searchTerm;
442 completeQueryString = completeQueryString + COMPLETE_QUERY_STRING_SEPARATOR + searchTerm;
446 private List<String> parseCompleteQueryString()
448 List<String> parsedCompleteQueryString = new ArrayList<String>();
449 String[] parsed = StringUtils.split( completeQueryString, COMPLETE_QUERY_STRING_SEPARATOR );
450 CollectionUtils.addAll( parsedCompleteQueryString, parsed );
452 return parsedCompleteQueryString;
455 private boolean isEqualToPreviousSearchTerm( String searchTerm )
457 if ( !"".equals( completeQueryString ) )
459 String[] parsed = StringUtils.split( completeQueryString, COMPLETE_QUERY_STRING_SEPARATOR );
460 if ( StringUtils.equalsIgnoreCase( searchTerm, parsed[parsed.length - 1] ) )
474 public void setQ( String q )
479 public SearchResults getResults()
484 public List getDatabaseResults()
486 return databaseResults;
489 public void setCurrentPage( int page )
491 this.currentPage = page;
494 public int getCurrentPage()
499 public int getTotalPages()
504 public void setTotalPages( int totalPages )
506 this.totalPages = totalPages;
509 public boolean isSearchResultsOnly()
511 return searchResultsOnly;
514 public void setSearchResultsOnly( boolean searchResultsOnly )
516 this.searchResultsOnly = searchResultsOnly;
519 public String getCompleteQueryString()
521 return completeQueryString;
524 public void setCompleteQueryString( String completeQueryString )
526 this.completeQueryString = completeQueryString;
529 public ArchivaConfiguration getArchivaConfiguration()
531 return archivaConfiguration;
534 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
536 this.archivaConfiguration = archivaConfiguration;
539 public Map<String, ManagedRepositoryConfiguration> getManagedRepositories()
541 return getArchivaConfiguration().getConfiguration().getManagedRepositoriesAsMap();
544 public void setManagedRepositories( Map<String, ManagedRepositoryConfiguration> managedRepositories )
546 this.managedRepositories = managedRepositories;
549 public String getGroupId()
554 public void setGroupId( String groupId )
556 this.groupId = groupId;
559 public String getArtifactId()
564 public void setArtifactId( String artifactId )
566 this.artifactId = artifactId;
569 public String getVersion()
574 public void setVersion( String version )
576 this.version = version;
579 public int getRowCount()
584 public void setRowCount( int rowCount )
586 this.rowCount = rowCount;
589 public boolean isFilterSearch()
594 public void setFilterSearch( boolean filterSearch )
596 this.filterSearch = filterSearch;
599 public String getRepositoryId()
604 public void setRepositoryId( String repositoryId )
606 this.repositoryId = repositoryId;
609 public List<String> getManagedRepositoryList()
611 return managedRepositoryList;
614 public void setManagedRepositoryList( List<String> managedRepositoryList )
616 this.managedRepositoryList = managedRepositoryList;
619 public String getClassName()
624 public void setClassName( String className )
626 this.className = className;
629 public RepositorySearch getNexusSearch()
631 // no need to do this when wiring is already in spring
632 if( nexusSearch == null )
634 WebApplicationContext wac =
635 WebApplicationContextUtils.getRequiredWebApplicationContext( ServletActionContext.getServletContext() );
636 nexusSearch = ( RepositorySearch ) wac.getBean( "nexusSearch" );
641 public void setNexusSearch( RepositorySearch nexusSearch )
643 this.nexusSearch = nexusSearch;
646 public ArchivaDAO getDao()
651 public void setDao( ArchivaDAO dao )
656 public UserRepositories getUserRepositories()
658 return userRepositories;
661 public void setUserRepositories( UserRepositories userRepositories )
663 this.userRepositories = userRepositories;
666 public ArchivaXworkUser getArchivaXworkUser()
668 return archivaXworkUser;
671 public void setArchivaXworkUser( ArchivaXworkUser archivaXworkUser )
673 this.archivaXworkUser = archivaXworkUser;
676 public Map<String, String> getSearchFields()
681 public void setSearchFields( Map<String, String> searchFields )
683 this.searchFields = searchFields;