Example #1
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) {
    }
  }
Example #2
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());
 }
  /** Reset a user's password. */
  @Override
  @POST
  @ResourceMethodSignature(input = UserForgotPasswordRequest.class)
  public Object post(Context context, Request request, Response response, Object payload)
      throws ResourceException {
    UserForgotPasswordRequest forgotPasswordRequest = (UserForgotPasswordRequest) payload;

    if (forgotPasswordRequest != null) {
      UserForgotPasswordResource resource = forgotPasswordRequest.getData();

      try {
        if (!isAnonymousUser(resource.getUserId(), request)) {
          getSecuritySystem().forgotPassword(resource.getUserId(), resource.getEmail());

          response.setStatus(Status.SUCCESS_ACCEPTED);
        } else {
          response.setStatus(
              Status.CLIENT_ERROR_BAD_REQUEST, "Anonymous user cannot forget password");

          getLogger().debug("Anonymous user forgot password is blocked");
        }
      } catch (UserNotFoundException e) {
        getLogger().debug("Invalid Username", e);

        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid Username");
      } catch (InvalidConfigurationException e) {
        // this should never happen
        getLogger().warn("Failed to set password!", e);

        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Failed to set password!.");
      }
    }
    // return null because the status is 202
    return null;
  }
  @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\":"));
  }
  @Test
  public void createTestWithId() throws IOException {

    RepositoryTargetResource resource = new RepositoryTargetResource();

    // FIXME: This should be allowed
    // resource.setId( "createTestWithId" );
    resource.setContentClass("maven1");
    resource.setName("createTestWithId");

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

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

    if (!response.getStatus().isSuccess()) {
      Assert.fail("Could not create Repository Target: " + response.getStatus());
    }

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

    // make sure the id != null
    Assert.assertTrue(StringUtils.isNotEmpty(responseResource.getId()));

    // FIXME: This should be allowed
    // Assert.assertEquals( resource.getId(), responseResource.getId() );
    Assert.assertEquals(responseResource.getContentClass(), resource.getContentClass());
    Assert.assertEquals(responseResource.getName(), resource.getName());
    Assert.assertEquals(resource.getPatterns(), responseResource.getPatterns());

    this.messageUtil.verifyTargetsConfig(responseResource);
  }
  @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);
  }
  // @Test
  // eclipseContentClass is disabled for beta5!
  public void eclipseContentClassTest() throws IOException {
    // m2namespace
    RepositoryTargetResource resource = new RepositoryTargetResource();

    // resource.setId( "createTest" );
    resource.setContentClass("eclipse-update-site");
    resource.setName("eclipseContentClassTest");

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

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

    if (!response.getStatus().isSuccess()) {
      Assert.fail("Could not create Repository Target: " + response.getStatus());
    }

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

    // make sure the id != null
    Assert.assertTrue(StringUtils.isNotEmpty(responseResource.getId()));

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

    this.messageUtil.verifyTargetsConfig(responseResource);
  }
Example #8
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);
 }
  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);
    }
  }
Example #10
0
    @Override
    protected void afterHandle(Request request, Response response) {
      Form headers = (Form) response.getAttributes().get("org.restlet.http.headers");
      if (headers == null) {
        response.getAttributes().put("org.restlet.http.headers", headers = new Form());
      }
      Long start = (Long) request.getAttributes().get("start.request.time");
      long processTime = System.currentTimeMillis() - start;
      headers.add("CacheMiss", start + " " + processTime);

      headers = (Form) request.getAttributes().get("org.restlet.http.headers");

      /*
      headers.add("Cache-Control", "max-age=3600");
      long time = new Date().getTime() + 3600000;
      if (response.getEntity() != null) {
      if (response.getEntity().getModificationDate() == null) {
      response.getEntity().setModificationDate(new Date(time - 7200000));
      }
      if (response.getEntity().getExpirationDate() == null) {
      response.getEntity().setExpirationDate(new Date(time));
      }
      }
       */
    }
  @Test
  public void testContentClassComponentListPlexusResource() throws Exception {
    String role = "repo_content_classes";
    // do admin
    List<PlexusComponentListResource> result1 =
        this.getResult(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertThat(getHints(result1), IsCollectionContaining.hasItems("maven1", "maven2"));

    // 403 test
    this.overwriteUserRole(TEST_USER_NAME, "login-only" + role, "2");
    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);
    Response response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertTrue(
        "Expected Error: Status was: " + response.getStatus().getCode(),
        response.getStatus().isClientError());
    Assert.assertEquals(403, response.getStatus().getCode());

    // only content class priv
    this.overwriteUserRole(TEST_USER_NAME, "content-classes" + role, "70");
    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);
    response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertTrue(response.getStatus().isSuccess());
  }
  @Test
  public void testScheduledTaskTypeComonentListPlexusResource() throws Exception {
    String role = "schedule_types";
    // do admin
    List<PlexusComponentListResource> result1 =
        this.getResult(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertTrue("Expected list larger then 1.", result1.size() > 1);

    // 403 test
    this.overwriteUserRole(TEST_USER_NAME, "login-only" + role, "2");
    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);
    Response response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertTrue(
        "Expected Error: Status was: " + response.getStatus().getCode(),
        response.getStatus().isClientError());
    Assert.assertEquals(403, response.getStatus().getCode());

    // only content class priv
    this.overwriteUserRole(TEST_USER_NAME, "schedule_types" + role, "71");
    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);
    response = sendMessage(role, this.getXMLXStream(), MediaType.APPLICATION_XML);
    Assert.assertTrue(response.getStatus().isSuccess());
  }
Example #13
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));
   }
 }
 @Test
 public void testInvalidRole() throws Exception {
   Response response1 =
       sendMessage("JUNK-foo-Bar-JUNK", this.getXMLXStream(), MediaType.APPLICATION_XML);
   Assert.assertTrue(response1.getStatus().isClientError());
   Assert.assertEquals(404, response1.getStatus().getCode());
 }
Example #15
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());
 }
Example #16
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());
 }
Example #17
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);
  }
  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;
  }
  protected boolean deleteFromRepository(String repository, String groupOrArtifactPath)
      throws IOException {
    String serviceURI =
        "service/local/repositories/" + repository + "/content/" + groupOrArtifactPath;

    Response response = RequestFacade.doGetRequest(serviceURI);
    if (response.getStatus().equals(Status.CLIENT_ERROR_NOT_FOUND)) {
      log.debug("It was not deleted because it didn't exist " + serviceURI);
      return true;
    }

    log.debug("deleting: " + serviceURI);
    response = RequestFacade.sendMessage(serviceURI, Method.DELETE);

    boolean deleted = response.getStatus().isSuccess();

    if (!deleted) {
      log.debug("Failed to delete: " + serviceURI + "  - Status: " + response.getStatus());
    }

    // fake it because the artifact doesn't exist
    // TODO: clean this up.
    if (response.getStatus().getCode() == 404) {
      deleted = true;
    }

    return deleted;
  }
Example #20
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());
 }
  @Test
  public void withoutPermission() throws Exception {
    overwriteUserRole(
        TEST_USER_NAME,
        "anonymous-with-login-but-forgot",
        "1",
        "2" /* login */,
        "6",
        "14",
        "17",
        "19",
        "44",
        "54",
        "55", /* "57" forgot, */
        "58",
        "59",
        "T1",
        "T2");

    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);

    // NOT Should be able to forgot anyone password
    Response response =
        ForgotPasswordUtils.get(this).recoverUserPassword("anonymous", "*****@*****.**");
    Assert.assertEquals("Status", response.getStatus().getCode(), 403);

    // NOT Should be able to forgot my own password
    response =
        ForgotPasswordUtils.get(this)
            .recoverUserPassword(TEST_USER_NAME, "*****@*****.**");
    Assert.assertEquals("Status", response.getStatus().getCode(), 403);
  }
  @Test
  public void cyclic() throws Exception {
    RepositoryGroupResource groupA = new RepositoryGroupResource();

    groupA.setId("groupA");
    groupA.setName("groupA");
    groupA.setFormat("maven2");
    groupA.setProvider("maven2");

    createMembers(groupA);

    this.messageUtil.createGroup(groupA);

    RepositoryGroupResource groupB = new RepositoryGroupResource();

    groupB.setId("groupB");
    groupB.setName("groupB");
    groupB.setFormat("maven2");
    groupB.setProvider("maven2");

    RepositoryGroupMemberRepository member = new RepositoryGroupMemberRepository();
    member.setId(groupA.getId());
    groupB.addRepository(member);

    this.messageUtil.createGroup(groupB);

    // introduces cyclic referece between repos
    member = new RepositoryGroupMemberRepository();
    member.setId(groupB.getId());
    groupA.addRepository(member);
    Response resp = this.messageUtil.sendMessage(Method.PUT, groupA);
    Assert.assertFalse(resp.getStatus().isSuccess());
  }
Example #23
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);
 }
Example #24
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;
 }
Example #25
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());
 }
Example #26
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());
  }
Example #27
0
  public void delete(String service, String id) throws NexusClientException {
    String url = this.buildUrl(service, id);
    Response response = this.sendRequest(Method.DELETE, url, (Representation) null);

    if (!response.getStatus().isSuccess()) {
      throw new NexusClientException("Error in response from the server: " + response.getStatus());
    }
    // thats it
  }
Example #28
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);
  }
  @Test
  public void testGroupIndexTree() throws Exception {
    String repoId = "public";

    // get the index tree
    Response response =
        RequestFacade.doGetRequest(
            RequestFacade.SERVICE_LOCAL + "repo_groups/" + repoId + "/index_content/");
    Assert.assertEquals(200, response.getStatus().getCode());
  }
Example #30
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());
 }