示例#1
0
 /** @see ProviderTestService#mMapPost(javax.ws.rs.core.MultivaluedMap) */
 public void testMultivaluedMapPost() throws Exception {
   final Response response = post("MultivaluedMap", createForm().getWebRepresentation());
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final MediaType respMediaType = response.getEntity().getMediaType();
   assertEqualMediaType(MediaType.TEXT_PLAIN, respMediaType);
   final String respEntity = response.getEntity().getText();
   assertEquals("[lastname: Merkel, firstname: Angela]", respEntity);
 }
示例#2
0
  public void testWithDefault() throws Exception {
    Request request = createGetRequest("headerWithDefault");
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME, "abc");
    Response response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("headerWithDefault");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("default", response.getEntity().getText());
  }
示例#3
0
  @SuppressWarnings("unchecked")
  public Object sendMessage(Method method, String url, Representation representation)
      throws NexusConnectionException {

    // get the response
    Response response = this.sendRequest(method, url, representation);

    // always expect a success
    if (!response.getStatus().isSuccess()) {
      String errorMessage = "Error in response from server: " + response.getStatus() + ".";
      List<ErrorMessage> errors = new ArrayList<ErrorMessage>();
      try {
        if (response.getEntity() != null) {

          String responseText = response.getEntity().getText();

          // this is kinda hackish, but this class is already tied to xstream
          if (responseText.contains("<error")) // quick check before we parse the string
          {
            // try to parse the response
            ErrorResponse errorResponse =
                (ErrorResponse) this.xstream.fromXML(responseText, new ErrorResponse());
            // if we made it this far we can stick the ErrorMessages in the Exception
            errors = errorResponse.getErrors();
          } else {
            // the response text might be helpful in debugging, so we will add it
            errorMessage +=
                "\nResponse: "
                    + (!StringUtils.isEmpty(responseText) ? "\n" + responseText : "<empty>");
          }
        } else {
          errorMessage = response.getStatus().getName();
        }
      } catch (Exception e) // we really don't want our fancy exception to cause another problem.
      {
        logger.warn("Error getting the response text: " + e.getMessage(), e);
      }

      // now finally throw it...
      throw new NexusConnectionException(errorMessage, errors);
    }

    Object result = null;
    try {
      String responseText = response.getEntity().getText();
      if (StringUtils.isNotEmpty(responseText)) {
        result = this.xstream.fromXML(responseText);
      }
    } catch (IOException e) {
      throw new NexusConnectionException("Error getting response text: " + e.getMessage(), e);
    }
    return result;
  }
示例#4
0
 public void testByteArrayPost() throws Exception {
   final Representation entity =
       new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM);
   final Response response = post("byteArray", entity);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("big test", response.getEntity().getText());
 }
示例#5
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));
   }
 }
示例#6
0
 public void testXmlTransformPost() throws Exception {
   final Response response =
       post("source", new StringRepresentation("abcdefg", MediaType.TEXT_XML));
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("abcdefg", response.getEntity().getText());
 }
  @Test
  public void noPatternsTest() throws IOException {

    RepositoryTargetResource resource = new RepositoryTargetResource();

    // resource.setId( "createTest" );
    resource.setContentClass("maven1");
    resource.setName("noPatternsTest");

    // List<String> patterns = new ArrayList<String>();
    // patterns.add( ".*foo.*" );
    // patterns.add( ".*bar.*" );
    // resource.setPatterns( patterns );

    Response response = this.messageUtil.sendMessage(Method.POST, resource);
    String responseText = response.getEntity().getText();

    if (response.getStatus().isSuccess()) {
      Assert.fail(
          "Target should not have been created: " + response.getStatus() + "\n" + responseText);
    }
    Assert.assertTrue(
        "Response text did not contain an error message. \nResponse Text:\n " + responseText,
        responseText.startsWith("{\"errors\":"));
  }
示例#8
0
 public void testCookies() throws IOException {
   final Request request = createGetRequest("cookies/cookieName");
   request.getCookies().add(new Cookie("cookieName", "cookie-value"));
   final Response response = accessServer(request);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   assertEquals("cookieName=cookie-value", response.getEntity().getText());
 }
示例#9
0
  @SuppressWarnings("unchecked")
  @Test
  public void updateTest() throws IOException {
    // FIXME: this test is known to fail, but is commented out so the CI builds are useful
    if (this.printKnownErrorButDoNotFail(this.getClass(), "updateTest")) {
      return;
    }

    // create
    RepositoryRouteResource resource = this.runCreateTest("exclusive");
    resource.setPattern(".*update.*");

    Response response = this.messageUtil.sendMessage(Method.PUT, resource);

    if (!response.getStatus().isSuccess()) {
      String responseText = response.getEntity().getText();
      Assert.fail(
          "Could not create privilege: " + response.getStatus() + "\nresponse:\n" + responseText);
    }

    // get the Resource object
    RepositoryRouteResource resourceResponse = this.messageUtil.getResourceFromResponse(response);

    Assert.assertNotNull(resourceResponse.getId());

    Assert.assertEquals(resource.getGroupId(), resourceResponse.getGroupId());
    Assert.assertEquals(resource.getPattern(), resourceResponse.getPattern());
    Assert.assertEquals(resource.getRuleType(), resourceResponse.getRuleType());
    this.messageUtil.validateSame(resource.getRepositories(), resourceResponse.getRepositories());

    // now check the nexus config
    this.messageUtil.validateRoutesConfig(resourceResponse);
  }
示例#10
0
  @SuppressWarnings("unchecked")
  @Test
  public void readTest() throws IOException {
    // create
    RepositoryRouteResource resource = this.runCreateTest("exclusive");

    Response response = this.messageUtil.sendMessage(Method.GET, resource);

    if (!response.getStatus().isSuccess()) {
      String responseText = response.getEntity().getText();
      Assert.fail(
          "Could not create privilege: " + response.getStatus() + "\nresponse:\n" + responseText);
    }

    // get the Resource object
    RepositoryRouteResource resourceResponse = this.messageUtil.getResourceFromResponse(response);

    Assert.assertNotNull(resourceResponse.getId());

    Assert.assertEquals(resource.getGroupId(), resourceResponse.getGroupId());
    Assert.assertEquals(resource.getPattern(), resourceResponse.getPattern());
    Assert.assertEquals(resource.getRuleType(), resourceResponse.getRuleType());
    this.messageUtil.validateSame(resource.getRepositories(), resourceResponse.getRepositories());

    // now check the nexus config
    this.messageUtil.validateRoutesConfig(resourceResponse);
  }
示例#11
0
 public void testCharSequenceGet() throws Exception {
   final Response response = get("CharSequence");
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final Representation entity = response.getEntity();
   assertEquals(ProviderTestService.createCS(), entity.getText());
 }
  protected Metadata downloadMetadataFromRepository(Gav gav, String repoId)
      throws IOException, XmlPullParserException {
    // File f =
    // new File( nexusWorkDir, "storage/" + repoId + "/" + gav.getGroupId() + "/" +
    // gav.getArtifactId()
    // + "/maven-metadata.xml" );
    //
    // if ( !f.exists() )
    // {
    // throw new FileNotFoundException( "Metadata do not exist! " + f.getAbsolutePath() );
    // }

    String url =
        this.getBaseNexusUrl()
            + REPOSITORY_RELATIVE_URL
            + repoId
            + "/"
            + gav.getGroupId()
            + "/"
            + gav.getArtifactId()
            + "/maven-metadata.xml";

    Response response = RequestFacade.sendMessage(new URL(url), Method.GET, null);
    if (response.getStatus().isError()) {
      return null;
    }

    InputStream stream = response.getEntity().getStream();
    try {
      MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
      return metadataReader.read(stream);
    } finally {
      IOUtil.close(stream);
    }
  }
示例#13
0
 public void testXmlTransformGet() throws Exception {
   final Response response = get("source");
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final String entity = response.getEntity().getText();
   assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><abc/>", entity);
 }
  public RepositoryTargetResource saveTarget(RepositoryTargetResource target, boolean update)
      throws IOException {
    Response response = this.sendMessage(update ? Method.PUT : Method.POST, target);
    String responseText = response.getEntity().getText();

    Assert.assertTrue(
        response.getStatus().isSuccess(),
        "Could not save Repository Target: "
            + response.getStatus()
            + "\nResponse Text:\n"
            + responseText
            + "\n"
            + xstream.toXML(target));

    // get the Resource object
    RepositoryTargetResource responseResource = this.getResourceFromResponse(responseText);

    // validate
    // make sure the id != null
    Assert.assertTrue(StringUtils.isNotEmpty(responseResource.getId()));
    if (update) {
      Assert.assertEquals(target.getId(), responseResource.getId());
    }

    Assert.assertEquals(target.getContentClass(), responseResource.getContentClass());
    Assert.assertEquals(target.getName(), responseResource.getName());
    Assert.assertEquals(target.getPatterns(), responseResource.getPatterns());

    this.verifyTargetsConfig(responseResource);

    return responseResource;
  }
示例#15
0
  public void serialize(
      ResultSummary summary,
      List<DashBoardItem> workItems,
      String columnsDefinition,
      List<String> labels,
      String lang,
      Response response,
      HttpServletRequest req)
      throws ClientException {
    // TODO labels, lang

    SyndFeed atomFeed = new SyndFeedImpl();
    atomFeed.setFeedType(ATOM_TYPE);

    // XXX TODO : To be translated
    atomFeed.setTitle(summary.getTitle());

    atomFeed.setLink(summary.getLink());

    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    for (DashBoardItem item : workItems) {
      entries.add(adaptDashBoardItem(item, req));
    }

    atomFeed.setEntries(entries);

    SyndFeedOutput output = new SyndFeedOutput();

    // Try to return feed
    try {
      response.setEntity(output.outputString(atomFeed), MediaType.TEXT_XML);
      response.getEntity().setCharacterSet(CharacterSet.UTF_8);
    } catch (FeedException fe) {
    }
  }
示例#16
0
 /**
  * @param subPath
  * @throws IOException
  */
 private Response getAndExpectAlphabet(String subPath) throws IOException {
   final Response response = get(subPath);
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final Representation entity = response.getEntity();
   assertEquals(ProviderTestService.ALPHABET, entity.getText());
   return response;
 }
示例#17
0
 public void testBufferedReaderPost() throws Exception {
   Representation entity =
       new StringRepresentation("big test", MediaType.APPLICATION_OCTET_STREAM);
   final Response response = post("BufferedReader", entity);
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   entity = response.getEntity();
   assertEquals("big test", entity.getText());
 }
示例#18
0
  public void testStringGet() throws Exception {
    getAndExpectAlphabet("String");

    final Response response = get("String2");
    sysOutEntityIfError(response);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    final Representation entity = response.getEntity();
    assertEquals(ProviderTestService.STRING2, entity.getText());
  }
示例#19
0
  public void testHttpHeaders() throws IOException {
    Request request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME, "abc");
    Response response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME.toLowerCase(), "abc");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());

    request = createGetRequest("header/" + HttpHeaderTestService.TEST_HEADER_NAME);
    Util.getHttpHeaders(request).add(HttpHeaderTestService.TEST_HEADER_NAME.toUpperCase(), "abc");
    response = accessServer(request);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("abc", response.getEntity().getText());
  }
示例#20
0
  /** Use {@link #getResourceFromText(String)} instead. */
  @Deprecated
  public RepositoryRouteResource getResourceFromResponse(Response response) throws IOException {
    String responseString = response.getEntity().getText();
    LOG.debug("responseText: " + responseString);

    Assert.assertTrue(
        response.getStatus() + "\n" + responseString, response.getStatus().isSuccess());

    return getResourceFromText(responseString);
  }
示例#21
0
 /**
  * @param subPath
  * @throws IOException
  */
 private void postAndCheckXml(String subPath) throws Exception {
   final Representation send =
       new DomRepresentation(
           new StringRepresentation(
               "<person><firstname>Helmut</firstname><lastname>Kohl</lastname></person>",
               MediaType.TEXT_XML));
   final Response response = post(subPath, send);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final Representation respEntity = response.getEntity();
   assertEquals("Helmut Kohl", respEntity.getText());
 }
  public LdapConnectionInfoDTO getResourceFromResponse(Response response) throws IOException {
    String responseString = response.getEntity().getText();
    LOG.debug(" getResourceFromResponse: " + responseString);

    XStreamRepresentation representation =
        new XStreamRepresentation(xstream, responseString, mediaType);
    LdapConnectionInfoResponse resourceResponse =
        (LdapConnectionInfoResponse) representation.getPayload(new LdapConnectionInfoResponse());

    return resourceResponse.getData();
  }
示例#23
0
  public RepositoryRouteResource getRoute(String routeId) throws IOException {
    Response response = null;
    try {
      response = getRouteResponse(routeId);

      assertThat(response, isSuccessful());

      return this.getResourceFromText(response.getEntity().getText());
    } finally {
      RequestFacade.releaseResponse(response);
    }
  }
示例#24
0
  public void testAccMediaType() throws IOException {
    Response response = get("accMediaTypes", MediaType.TEXT_PLAIN);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("[" + MediaType.TEXT_PLAIN.toString() + "]", response.getEntity().getText());

    ClientInfo clientInfo = new ClientInfo();
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_PLAIN, 0.5f));
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_HTML, 0.8f));
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML, 0.2f));
    response = get("accMediaTypes", clientInfo);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals(
        "["
            + MediaType.TEXT_HTML.toString()
            + ", "
            + MediaType.TEXT_PLAIN.toString()
            + ", "
            + MediaType.TEXT_XML.toString()
            + "]",
        response.getEntity().getText());
  }
示例#25
0
  private UserAccount readAccount(Response response) throws IOException {
    if (response.getStatus().isSuccess()) {
      String responseText = response.getEntity().getText();

      LOGGER.debug("Response Text: \n" + responseText);

      XStreamRepresentation representation =
          new XStreamRepresentation(xmlXstream, responseText, MediaType.APPLICATION_XML);

      UserAccountRequestResponseWrapper responseDTO =
          (UserAccountRequestResponseWrapper)
              representation.getPayload(new UserAccountRequestResponseWrapper());

      return responseDTO.getData();
    } else {
      LOGGER.warn("HTTP Error: '" + response.getStatus().getCode() + "'");

      LOGGER.warn(response.getEntity().getText());

      return null;
    }
  }
示例#26
0
 /**
  * @param subPath
  * @param postEntity
  * @param postMediaType
  * @param responseMediaType if null, it will not be testet
  * @throws IOException
  */
 private void postAndExceptGiven(
     String subPath, String postEntity, MediaType postMediaType, MediaType responseMediaType)
     throws IOException {
   Representation entity = new StringRepresentation(postEntity, postMediaType);
   final Response response = post(subPath, entity);
   sysOutEntityIfError(response);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   entity = response.getEntity();
   assertEquals(postEntity, entity.getText());
   if (responseMediaType != null) {
     assertEqualMediaType(responseMediaType, entity);
   }
 }
示例#27
0
 /**
  * @param subPath
  * @throws IOException
  * @see ProviderTestService#jaxbPostNamespace(javax.xml.bind.JAXBElement)
  */
 public void testJaxbElementPostRootElement() throws Exception {
   if (true) // LATER conversion to JAXBElement doesn't work
   return;
   final Representation send =
       new DomRepresentation(
           new StringRepresentation(
               "<person><firstname>Helmut</firstname><lastname>Kohl</lastname></person>\n",
               MediaType.TEXT_XML));
   final Response response = post("jaxbElement/rootElement", send);
   assertEquals(Status.SUCCESS_OK, response.getStatus());
   final Representation respEntity = response.getEntity();
   assertEquals("person", respEntity.getText());
 }
  @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);
  }
  public LdapConnectionInfoDTO updateConnectionInfo(LdapConnectionInfoDTO connInfo)
      throws Exception {
    Response response = this.sendMessage(Method.PUT, connInfo);

    if (!response.getStatus().isSuccess()) {
      String responseText = response.getEntity().getText();
      Assert.fail("Could not create Repository: " + response.getStatus() + ":\n" + responseText);
    }
    LdapConnectionInfoDTO responseResource = this.getResourceFromResponse(response);

    this.validateResourceResponse(connInfo, responseResource);

    return responseResource;
  }
  public LdapUserAndGroupConfigurationDTO updateUserGroupConfig(
      LdapUserAndGroupConfigurationDTO userGroupConfig) throws Exception {
    Response response = this.sendMessage(Method.PUT, userGroupConfig);

    if (!response.getStatus().isSuccess()) {
      String responseText = response.getEntity().getText();
      Assert.fail("Could not create Repository: " + response.getStatus() + ":\n" + responseText);
    }
    LdapUserAndGroupConfigurationDTO responseResource = this.getResourceFromResponse(response);

    this.validateResourceResponse(userGroupConfig, responseResource);

    return responseResource;
  }