Пример #1
0
  public void init(Request request, Response response) {
    RequestData data = monitor.current();
    if (data == null) {
      // will happen in cases where the filter is not active
      return;
    }

    data.setCategory(Category.REST);
    if (request.getResourceRef() != null) {
      String resource = request.getResourceRef().getLastSegment();
      resource = FilenameUtils.getBaseName(resource);
      data.getResources().add(resource);
    }
    monitor.update();
  }
Пример #2
0
 @Override
 protected void afterHandle(Request request, Response response) {
   String callback = request.getResourceRef().getQueryAsForm().getFirstValue("callback");
   if (callback != null) {
     StringBuilder stringBuilder = new StringBuilder(callback);
     stringBuilder.append("(");
     Representation representation = response.getEntity();
     if (representation != null) {
       try {
         InputStream inputStream = representation.getStream();
         if (inputStream != null) {
           ByteArrayOutputStream out = new ByteArrayOutputStream();
           byte[] bytes = new byte[0x10000];
           int length;
           while ((length = inputStream.read(bytes)) > 0) {
             out.write(bytes, 0, length);
           }
           stringBuilder.append(out.toString("UTF-8"));
         }
       } catch (IOException e) {
         List<String> details = new ArrayList<String>();
         details.add(e.getMessage());
         ServiceException serviceException =
             new ServiceException(
                 new ServiceError(
                     (Status.SERVER_ERROR_INTERNAL.getCode()), "Internal Server Error", details));
         response.setEntity(serviceException);
       }
     }
     stringBuilder.append(")");
     response.setEntity(new StringRepresentation(stringBuilder.toString(), MediaType.TEXT_PLAIN));
   }
 }
  protected String buildUploadFailedHtmlResponse(Throwable t, Request request, Response response) {
    try {
      handleException(request, response, t);
    } catch (ResourceException e) {
      getLogger().debug("Got error while uploading artifact", t);

      StringBuffer resp = new StringBuffer();
      resp.append("<html>");
      resp.append("<body>");
      resp.append("<error>" + e.getMessage() + "</error>");
      resp.append("</body>");
      resp.append("</html>");

      String forceSuccess = request.getResourceRef().getQueryAsForm().getFirstValue("forceSuccess");

      if (!"true".equals(forceSuccess)) {
        response.setStatus(e.getStatus());
      }

      return resp.toString();
    }

    // We have an error at this point, can't get here
    return null;
  }
Пример #4
0
  public void doGet(Request req, Response resp) throws RestletException {

    String taskIds = null;
    try {
      taskIds = URLDecoder.decode((String) req.getAttributes().get("taskids"), "UTF-8");
    } catch (UnsupportedEncodingException uee) {
      log.error("Exception type = " + uee.getClass().getName() + " msg = " + uee.getMessage());
      throw new RestletException(uee.getMessage(), Status.SERVER_ERROR_INTERNAL);
    }

    ArrayList<GWCTaskStatus> taskList = new ArrayList<GWCTaskStatus>();
    seeder.getStorageBroker().getTasks(taskIds, taskList);

    List<String> segments = req.getResourceRef().getSegments();
    String reqAction = segments.get(segments.size() - 2);
    if (reqAction.equalsIgnoreCase("seedprogress")) {
      handleProgress(req, resp, taskList);
    } else if (reqAction.equalsIgnoreCase("seedcancel")) {
      handleCancel(req, resp, taskList);
    } else {
      String msg = "Unsupported action: " + reqAction;
      log.error(msg);
      throw new RestletException(msg, Status.CLIENT_ERROR_NOT_FOUND);
    }
  }
 @Override
 public Resource findTarget(Request request, Response response) {
   if (request.getResourceRef().getLastSegment().endsWith(".ftl")) {
     return new FreemarkerTemplateResource(request, response, catalog);
   } else {
     return new FreemarkerTemplateListResource(getContext(), request, response, catalog);
   }
 }
Пример #6
0
  public TestResource(Context context, Request request, Response response) {
    super(context, request, response);

    patientId = request.getResourceRef().getQueryAsForm().getFirstValue("patientId");

    // This representation has only one type of representation.
    getVariants().add(new Variant(MediaType.APPLICATION_JSON));
    context.getClientDispatcher();
  }
  protected Model getPom(Variant variant, Request request, Response response)
      throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    // TODO: enable only one section retrieval of POM, ie. only mailing lists, or team members

    String groupId = form.getFirstValue("g");

    String artifactId = form.getFirstValue("a");

    String version = form.getFirstValue("v");

    String repositoryId = form.getFirstValue("r");

    if (groupId == null || artifactId == null || version == null || repositoryId == null) {
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    ArtifactStoreRequest gavRequest =
        getResourceStoreRequest(
            request, false, repositoryId, groupId, artifactId, version, null, null, "pom");

    try {
      MavenRepository mavenRepository = getMavenRepository(repositoryId);

      ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper();

      InputStream pomContent = null;

      InputStreamReader ir = null;

      Model pom = null;

      try {
        StorageFileItem file = helper.retrieveArtifactPom(gavRequest);

        pomContent = file.getInputStream();

        MavenXpp3Reader reader = new MavenXpp3Reader();

        ir = new InputStreamReader(pomContent);

        pom = reader.read(ir);
      } finally {
        IOUtil.close(pomContent);

        IOUtil.close(ir);
      }

      return pom;

    } catch (Exception e) {
      handleException(request, response, e);
    }

    return null;
  }
Пример #8
0
  public MailActionResource(Context context, Request request, Response response) {
    super(context, request, response);

    try {
      String query = request.getResourceRef().getQueryAsForm().getQueryString();
      //      System.out.println("query: "+query);
      if (checkApiCaller(query) != true) {
        getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
        return;
      }

    } catch (Exception e) {
      getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
      return;
    }

    setModifiable(true);
    setAvailable(true);
    allowPut();

    final Method httpMethod = request.getMethod();
    Logger.getLogger(MailActionResource.class.getName())
        .log(Level.INFO, "httpMethod: " + httpMethod);

    try {
      userId = request.getResourceRef().getQueryAsForm().getFirstValue("userId");
      action = request.getResourceRef().getQueryAsForm().getFirstValue("action");
      Logger.getLogger(MailActionResource.class.getName()).log(Level.INFO, userId);
      Logger.getLogger(MailActionResource.class.getName()).log(Level.INFO, action);

      //            fromUser=request.getResourceRef().getQueryAsForm().getFirstValue("fromUser");
      //
      // fromUserProvider=request.getResourceRef().getQueryAsForm().getFirstValue("fromUserProvider");
      //            toUser=request.getResourceRef().getQueryAsForm().getFirstValue("toUser");
      //
      // toUserProvider=request.getResourceRef().getQueryAsForm().getFirstValue("toUserProvider");
      //            subject=request.getResourceRef().getQueryAsForm().getFirstValue("subject");
      //            message=request.getResourceRef().getQueryAsForm().getFirstValue("message");
    } catch (Exception e) {
      // don't care
    }

    getVariants().add(new Variant(MediaType.APPLICATION_JSON));
  }
Пример #9
0
  public MedicationsResource(Context context, Request request, Response response) {
    super(context, request, response);

    try {
      String query = request.getResourceRef().getQueryAsForm().getQueryString();

      //      System.out.println("query: "+query);
      if (checkApiCaller(query) != true) {
        getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);

        return;
      }

    } catch (Exception e) {
      getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, e);

      return;
    }

    // This representation has only one type of representation.
    getVariants().add(new Variant(MediaType.APPLICATION_JSON));

    String apikey = request.getResourceRef().getQueryAsForm().getFirstValue("apiKey");

    if (apikey != null) {
      this.apiKey = apikey;
    }

    patientId = this.getParameter(request, "patientId", "");
    fromDate = this.getDateParameter(request, "fromDate", "Patient", "Medications", "Begin");
    toDate = this.getDateParameter(request, "toDate", "Patient", "Medications", "End");

    jsonRequestString =
        "{getMedicationFacts:{criteria:{queryId:\"20100411011010\",\"senderId\":\"Adapter Assembly Service\",\"interactionId\":\"QUPC_IN043100UV\",\"triggerEventCode\":\"QUPC_TE043100UV0\",\"patientId\":\""
            + patientId
            + "\",\"careProvisionCode\":\"HISTMEDLIST\",\"careRecordStartTimePeriod\":\""
            + fromDate
            + "\",\"careRecordEndTimePeriod\":\""
            + toDate
            + "\"}}}";
  }
  private boolean isAllTasks(Request request) {
    Form form = request.getResourceRef().getQueryAsForm();

    if (form != null) {
      String result = form.getFirstValue("allTasks");

      if (result != null) {
        return result.equalsIgnoreCase("true");
      }
    }

    return false;
  }
  @Override
  public Representation handleGet(Request request, Response response, Session session)
      throws ResourceException {
    if (request.getResourceRef().getPath().endsWith("image.png")) {
      return new InputRepresentation(
          getClass().getResourceAsStream("sis-video.png"), MediaType.IMAGE_PNG);
    }

    String url = SIS.get().getSettings(getContext()).getProperty(SOURCE_KEY);
    if (url == null) throw new ResourceException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);

    final Request extReq = new Request(Method.GET, url);
    final Response extResp = getContext().getClientDispatcher().handle(extReq);

    if (!extResp.getStatus().isSuccess())
      throw new ResourceException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);

    final Document respDoc = getEntityAsDocument(extResp.getEntity());

    final List<VideoSource> list = new ArrayList<VideoSource>();
    final NodeList nodes = respDoc.getDocumentElement().getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      if ("entry".equals(node.getNodeName())) {
        VideoSource video = new VideoSource();
        video.setImage("/sources/youtube/featured/image.png");
        NodeCollection children = new NodeCollection(node.getChildNodes());
        for (Node child : children) {
          if ("title".equals(child.getNodeName())) video.setTitle(child.getTextContent());
          else if ("content".equals(child.getNodeName())) video.setCaption(child.getTextContent());
          else if ("link".equals(child.getNodeName())) {
            if ("alternate".equals(BaseDocumentUtils.impl.getAttribute(child, "rel"))) {
              Reference videoRef =
                  new Reference(BaseDocumentUtils.impl.getAttribute(child, "href"));
              String videoID = videoRef.getQueryAsForm().getFirstValue("v");
              if (videoID == null) video.setUrl(BaseDocumentUtils.impl.getAttribute(child, "href"));
              else video.setUrl("http://www.youtube.com/embed/" + videoID);
            }
          }
        }
        list.add(video);
      }
    }

    final StringBuilder out = new StringBuilder();
    out.append("<root>");
    for (VideoSource source : list) out.append(source.toXML());
    out.append("</root>");

    return new StringRepresentation(out.toString(), MediaType.TEXT_XML);
  }
  // CLEAN
  public String getRestRepoRemoteStatus(
      ProxyRepository repository, Request request, Response response) throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    boolean forceCheck = form.getFirst("forceCheck") != null;

    RemoteStatus rs =
        repository.getRemoteStatus(
            new ResourceStoreRequest(RepositoryItemUid.PATH_ROOT), forceCheck);

    if (RemoteStatus.UNKNOWN.equals(rs)) {
      // set status to ACCEPTED, since we have incomplete info
      response.setStatus(Status.SUCCESS_ACCEPTED);
    }

    return rs == null ? null : rs.toString();
  }
Пример #13
0
  /**
   * The default handler. It simply extracts the requested file name and gets the file's InputStream
   * from Nexus instance. If Nexus finds the file appropriate, the handler wraps it into InputStream
   * representation and ships it as "text/plain" media type, otherwise HTTP 404 is returned.
   *
   * @param fileName The file name to retrieve (as defined in the log list resource response).
   */
  @Override
  @GET
  @ResourceMethodSignature(
      pathParams = {@PathParam(LogsPlexusResource.FILE_NAME_KEY)},
      output = Object.class)
  public Object get(Context context, Request request, Response response, Variant variant)
      throws ResourceException {
    String logFile = request.getAttributes().get(FILE_NAME_KEY).toString();

    Form params = request.getResourceRef().getQueryAsForm();

    String fromStr = params.getFirstValue("from");

    String countStr = params.getFirstValue("count");

    long from = 0;

    long count = Long.MAX_VALUE;

    if (!StringUtils.isEmpty(fromStr)) {
      from = Long.valueOf(fromStr);
    }

    if (!StringUtils.isEmpty(countStr)) {
      count = Long.valueOf(countStr);
    }

    NexusStreamResponse result;
    try {
      result = logManager.getApplicationLogAsStream(logFile, from, count);
    } catch (IOException e) {
      throw new ResourceException(e);
    }

    if (result != null) {
      return new InputStreamRepresentation(
          MediaType.valueOf(result.getMimeType()), result.getInputStream());
    } else {
      getLogger().warn("Log file not found, filename=" + logFile);

      throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Log file not found");
    }
  }
  protected RepositoryTargetResource getNexusToRestResource(Target target, Request request) {
    RepositoryTargetResource resource = new RepositoryTargetResource();

    resource.setId(target.getId());

    resource.setName(target.getName());

    resource.setResourceURI(request.getResourceRef().getPath());

    resource.setContentClass(target.getContentClass().getId());

    List<String> patterns = new ArrayList<String>(target.getPatternTexts());

    for (String pattern : patterns) {
      resource.addPattern(pattern);
    }

    return resource;
  }
Пример #15
0
  @Override
  public void performService(Request request, Response response) {
    try {
      String username = request.getChallengeResponse().getIdentifier();

      if (username == null || username.equals("")) {
        response.setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      } else if (request.getMethod().equals(Method.GET)) {
        String id = (String) request.getAttributes().get("id");
        String ret = null;

        try {
          if (id == null) ret = getAssessments(request, username);
          else
            ret =
                AssessmentIO.readAssessmentAsString(
                    vfs, id, (String) request.getAttributes().get("type"), username);

          if (ret != null) {
            response.setEntity(ret, MediaType.TEXT_XML);
            response.setStatus(Status.SUCCESS_OK);
          } else response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        } catch (IOException e) {
          e.printStackTrace();
          response.setStatus(Status.SERVER_ERROR_INTERNAL);
        }
      } else if (request.getMethod().equals(Method.PUT)) {
        try {
          putAssessment(request, response, username);
        } catch (Throwable e) {
          e.printStackTrace();
        }
      } else if (request.getMethod().equals(Method.POST)) {
        String action = request.getResourceRef().getQueryAsForm().getFirstValue("action");
        if (action == null) {
          postAssessment(request, response, username);
        } else if (action.equalsIgnoreCase("fetch")) {
          try {
            String ret = getAssessments(request, username);

            if (ret != null) {
              response.setEntity(ret, MediaType.TEXT_XML);
              response.setStatus(Status.SUCCESS_OK);
            } else response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
          } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
          }
        } else if (action.equalsIgnoreCase("batch")) {
          String ret = batchCreate(request, username);

          if (ret != null) {
            response.setEntity(ret, MediaType.TEXT_XML);
            response.setStatus(Status.SUCCESS_OK);
          } else {
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
          }
        }
      } else if (request.getMethod().equals(Method.DELETE)) {
        if (request.getResourceRef().getPath().startsWith("assessmentsByTaxon")) {
          String taxonID = (String) request.getAttributes().get("id");
          String type = (String) request.getAttributes().get("type");
          deleteAssessmentsForTaxon(taxonID, type, username, request, response);
        } else {
          String id = (String) request.getAttributes().get("id");
          String type = (String) request.getAttributes().get("type");
          deleteAssessment(request, response, id, type, username);
        }
      } else {
        response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
      }
    } catch (Exception e) {
      e.printStackTrace();
      response.setStatus(Status.SERVER_ERROR_INTERNAL);
    }
  }
Пример #16
0
  @Override
  public Object get(Context context, Request request, Response response, Variant variant)
      throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    String loggerName = form.getFirstValue("loggerName");
    String level = form.getFirstValue("level");
    String message = form.getFirstValue("message");
    String exceptionType = form.getFirstValue("exceptionType");
    String exceptionMessage = form.getFirstValue("exceptionMessage");

    if (message == null) {
      message = "A log message at " + new Date();
    }

    Throwable exception = null;
    if (exceptionType != null || exceptionMessage != null) {
      if (exceptionMessage == null) {
        exceptionMessage = "An exception thrown at " + new Date();
      }
      exception = new Exception(exceptionMessage);
      if (exceptionType != null) {
        try {
          exception =
              (Throwable)
                  this.getClass()
                      .getClassLoader()
                      .loadClass(exceptionType)
                      .getConstructor(String.class)
                      .newInstance(exceptionMessage);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    Logger logger;
    if (loggerName == null) {
      logger = LoggerFactory.getLogger(this.getClass());
    } else {
      logger = LoggerFactory.getLogger(loggerName);
    }

    if (level == null) {
      level = "INFO";
    }
    if (level.equalsIgnoreCase("trace")) {
      if (exception == null) {
        logger.trace(message);
      } else {
        logger.trace(message, exception);
      }
    } else if (level.equalsIgnoreCase("debug")) {
      if (exception == null) {
        logger.debug(message);
      } else {
        logger.debug(message, exception);
      }
    } else if (level.equalsIgnoreCase("warn")) {
      if (exception == null) {
        logger.warn(message);
      } else {
        logger.warn(message, exception);
      }
    } else if (level.equalsIgnoreCase("error")) {
      if (exception == null) {
        logger.error(message);
      } else {
        logger.error(message, exception);
      }
    } else {
      if (exception == null) {
        logger.info(message);
      } else {
        logger.info(message, exception);
      }
    }

    response.setStatus(Status.SUCCESS_OK);
    return "OK";
  }
  protected Object getContent(
      Variant variant, boolean redirectTo, Request request, Response response)
      throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    String groupId = form.getFirstValue("g");

    String artifactId = form.getFirstValue("a");

    String version = form.getFirstValue("v");

    String packaging = form.getFirstValue("p");

    String classifier = form.getFirstValue("c");

    String repositoryId = form.getFirstValue("r");

    String extension = form.getFirstValue("e");

    if (groupId == null || artifactId == null || version == null || repositoryId == null) {
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    // default the packaging
    if (StringUtils.isBlank(packaging)) {
      packaging = "jar";
    }

    ArtifactStoreRequest gavRequest =
        getResourceStoreRequest(
            request,
            false,
            repositoryId,
            groupId,
            artifactId,
            version,
            packaging,
            classifier,
            extension);

    try {
      MavenRepository mavenRepository = getMavenRepository(repositoryId);

      ArtifactStoreHelper helper = mavenRepository.getArtifactStoreHelper();

      StorageFileItem file = helper.retrieveArtifact(gavRequest);

      if (redirectTo) {
        Reference fileReference =
            createRepositoryReference(
                request,
                file.getRepositoryItemUid().getRepository().getId(),
                file.getRepositoryItemUid().getPath());

        response.setLocationRef(fileReference);

        response.setStatus(Status.REDIRECTION_PERMANENT);

        String redirectMessage =
            "If you are not automatically redirected use this url: " + fileReference.toString();
        return redirectMessage;
      } else {
        Representation result = new StorageFileItemRepresentation(file);

        result.setDownloadable(true);

        result.setDownloadName(file.getName());

        return result;
      }

    } catch (Exception e) {
      handleException(request, response, e);
    }

    return null;
  }
  /**
   * Search against all repositories using provided parameters. Note there are a few different types
   * of searches you can perform. If you provide the 'q' query parameter, a keyword search will be
   * performed. If you provide the 'g, a, v, p or c' query parameters, a maven coordinate search
   * will be performed. If you provide the 'cn' query parameter, a classname search will be
   * performed. If you provide the 'sha1' query parameter, a checksum search will be performed.
   *
   * @param q provide this param for a keyword search (g, a, v, p, c, cn, sha1 params will be
   *     ignored).
   * @param sha1 provide this param for a checksum search (g, a, v, p, c, cn params will be
   *     ignored).
   * @param cn provide this param for a classname search (g, a, v, p, c params will be ignored).
   * @param g group id to perform a maven search against (can be combined with a, v, p & c params as
   *     well).
   * @param a artifact id to perform a maven search against (can be combined with g, v, p & c params
   *     as well).
   * @param v version to perform a maven search against (can be combined with g, a, p & c params as
   *     well).
   * @param p packaging type to perform a maven search against (can be combined with g, a, v & c
   *     params as well).
   * @param c classifier to perform a maven search against (can be combined with g, a, v & p params
   *     as well).
   * @param from result index to start retrieving results from.
   * @param count number of results to have returned to you.
   * @param repositoryId The repositoryId to which repository search should be narrowed. Omit if
   *     search should be global.
   */
  @Override
  @GET
  @ResourceMethodSignature(
      queryParams = {
        @QueryParam("q"),
        @QueryParam("g"),
        @QueryParam("a"),
        @QueryParam("v"),
        @QueryParam("p"),
        @QueryParam("c"),
        @QueryParam("cn"),
        @QueryParam("sha1"),
        @QueryParam("from"),
        @QueryParam("count"),
        @QueryParam("repositoryId")
      },
      output = SearchResponse.class)
  public Object get(Context context, Request request, Response response, Variant variant)
      throws ResourceException {
    Form form = request.getResourceRef().getQueryAsForm();

    final Map<String, String> terms = new HashMap<String, String>();

    for (Parameter parameter : form) {
      terms.put(parameter.getName(), parameter.getValue());
    }

    Integer from = null;
    Boolean exact = null;
    String repositoryId = null;
    Boolean expandVersion = Boolean.FALSE;
    Boolean collapseResults = Boolean.FALSE;

    if (form.getFirstValue("from") != null) {
      try {
        from = Integer.valueOf(form.getFirstValue("from"));
      } catch (NumberFormatException e) {
        from = null;
      }
    }

    int count = LUCENE_HIT_LIMIT;
    if (form.getFirstValue("count") != null) {
      try {
        // capping the possible count
        count = Math.min(LUCENE_HIT_LIMIT, Integer.valueOf(form.getFirstValue("count")));
      } catch (NumberFormatException e) {
        count = LUCENE_HIT_LIMIT;
      }
    }

    if (form.getFirstValue("repositoryId") != null) {
      repositoryId = form.getFirstValue("repositoryId");
    }

    if (form.getFirstValue("exact") != null) {
      exact = Boolean.valueOf(form.getFirstValue("exact"));
    }

    if (form.getFirstValue("versionexpand") != null) {
      expandVersion = Boolean.valueOf(form.getFirstValue("versionexpand"));
    }
    if (form.getFirstValue("collapseresults") != null) {
      collapseResults = Boolean.valueOf(form.getFirstValue("collapseresults"));
    }

    // A little explanation about collapseResults, that might seems little bit awkward, since
    // currently we have only
    // one column "collapsable" (the version), but before and maybe in the future that's not the
    // case. So, here is
    // it:
    // the "collapseResults" is just a flag "do we allow collapse at all". It is just a shorthand to
    // turn on or off
    // collapse generally
    // Let's assume we have columns colA, colB and colC collapsable. So, instead saying
    // expandColA=true,expandColB=true,expandColC=true,
    // it is just easy to say collapseresults=false
    // BUT, if collapseresults=true is sent by client, even then an "override" will happen if there
    // is actually NO
    // ROW to collapse!
    // So: collapseresults=false EQUALS-TO expandColA=true & expandColB=true & expandColC=true
    if (collapseResults) {
      // here we would like to have ANDed all the collapsable column flags and negated the result
      // currently we
      collapseResults = !(true && expandVersion); // && expandColA && expandColB;
    }

    IteratorSearchResponse searchResult = null;

    SearchNGResponse result = new SearchNGResponse();

    int runCount = 0;

    while (runCount < RETRIES) {
      try {
        List<ArtifactInfoFilter> filters = new ArrayList<ArtifactInfoFilter>();

        // we need to save this reference to later
        SystemWideLatestVersionCollector systemWideCollector =
            new SystemWideLatestVersionCollector();
        filters.add(systemWideCollector);

        RepositoryWideLatestVersionCollector repositoryWideCollector = null;

        if (collapseResults) {
          repositoryWideCollector = new RepositoryWideLatestVersionCollector();
          filters.add(repositoryWideCollector);
        }

        try {
          searchResult =
              searchByTerms(
                  terms,
                  repositoryId,
                  from,
                  count,
                  exact,
                  expandVersion,
                  collapseResults,
                  filters,
                  searchers);

          if (searchResult == null) {
            collapseResults = false;

            continue;
          } else {
            repackIteratorSearchResponse(
                request,
                terms,
                result,
                collapseResults,
                from,
                count,
                searchResult,
                systemWideCollector,
                repositoryWideCollector);

            if (!result.isTooManyResults()) {
              // if we had collapseResults ON, and the totalHits are larger than actual (filtered)
              // results, and the actual result count is below COLLAPSE_OVERRIDE_TRESHOLD,
              // and full result set is smaller than HIT_LIMIT
              // then repeat without collapse
              if (collapseResults
                  && result.getData().size() < searchResult.getTotalHitsCount()
                  && result.getData().size() < COLLAPSE_OVERRIDE_TRESHOLD
                  && searchResult.getTotalHitsCount() < GA_HIT_LIMIT) {
                collapseResults = false;

                continue;
              }
            }
          }
        } catch (IOException e) {
          throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage(), e);
        }

        // we came here, so we break the while-loop, we got what we need
        break;
      } catch (NoSuchRepositoryException e) {
        throw new ResourceException(
            Status.CLIENT_ERROR_BAD_REQUEST, "Repository to be searched does not exists!", e);
      } catch (AlreadyClosedException e) {
        runCount++;

        getLogger()
            .info(
                "NexusIndexer issue (NEXUS-3702), we got AlreadyClosedException that happens when Reindexing or other \"indexer intensive\" task is running on instance while searching! Redoing search again.");

        if (getLogger().isDebugEnabled()) {
          // just keep it silent (DEBUG)
          getLogger().debug("Got AlreadyClosedException exception!", e);
        }

        result.setData(null);
      }
    }

    if (result.getData() == null) {
      try {
        repackIteratorSearchResponse(
            request,
            terms,
            result,
            collapseResults,
            from,
            count,
            IteratorSearchResponse.empty(null),
            null,
            null);
      } catch (NoSuchRepositoryException e) {
        // will not happen
      } catch (IOException e) {
        // will not happen
      }

      getLogger()
          .info(
              "Nexus issue (NEXUS-3702): Was unable to perform search "
                  + RETRIES
                  + " times, giving up, and lying about TooManyResults. Please retry to reproduce this with DEBUG logs and report this issue!");
    }

    return result;
  }
  @Override
  public Object get(Context context, Request request, Response response, Variant variant)
      throws ResourceException {
    // retrieve main parameters (r, g, a, v, p, c)
    Form form = request.getResourceRef().getQueryAsForm();
    String repositoryId = form.getFirstValue("r", null);
    Map<String, String> terms = new HashMap<String, String>(form.getValuesMap());

    // search
    IteratorSearchResponse searchResponse;
    try {
      searchResponse =
          searcher.flatIteratorSearch(
              terms, repositoryId, null, null, null, false, SearchType.EXACT, null);
    } catch (NoSuchRepositoryException e) {
      throw new ResourceException(
          Status.CLIENT_ERROR_BAD_REQUEST, "No repository at " + repositoryId, e);
    }

    // retrieve unique versions and sort them from newest to oldest
    List<Option> versions = new ArrayList<Option>();
    for (ArtifactInfo aInfo : searchResponse.getResults()) {
      if (!optionsContainsValue(versions, aInfo.version)) {
        versions.add(new Option(buildOptionName(aInfo), aInfo.version));
      }
    }
    Collections.sort(
        versions,
        new Comparator<Option>() {

          public int compare(Option o1, Option o2) {
            if (o1 == null || o1.getValue() == null || o2 == null || o2.getValue() == null) {
              throw new IllegalArgumentException();
            }

            VersionComparator vc = new VersionComparator();

            // we want to sort from newest to oldest
            return -(vc.compare(o1.getValue(), o2.getValue()));
          }
        });

    // optionally add "special" versions
    if (Boolean.parseBoolean(form.getFirstValue("includeLatest", null))) {
      versions.add(0, new Option("LATEST", "LATEST"));
    }
    if (Boolean.parseBoolean(form.getFirstValue("includeRelease", null))) {
      versions.add(0, new Option("RELEASE", "RELEASE"));
    }

    // optionally limit the number of versions returned
    Integer limit;
    try {
      limit = Integer.parseInt(form.getFirstValue("l", null));
    } catch (NumberFormatException e) {
      limit = null;
    }
    if (limit != null && limit > 0 && versions.size() > limit) {
      versions = new ArrayList<Option>(versions.subList(0, limit));
    }

    return versions;
  }