@Override
  public Representation represent(Variant variant) throws ResourceException {
    try {
      return super.represent(variant);
    } catch (ResourceException e) {
      // NEXUS-4238, NEXUS-4290
      // if it's server error based on HTTP Code, but NOT when Nexus throws a known 503
      // (see
      // org.sonatype.nexus.rest.AbstractResourceStoreContentPlexusResource.handleException(Request,
      // Response, Exception))
      final Status status = e.getStatus();
      if (status == null) {
        handleError(e);
      } else {
        final int code = status.getCode();
        if (Status.isServerError(code)
            && Status.SERVER_ERROR_SERVICE_UNAVAILABLE.getCode() != code) {
          handleError(e);
        }
      }

      throw e;
    } catch (RuntimeException e) {
      handleError(e);

      throw e;
    }
  }
  protected void createSnapshotTask(String name) throws Exception {
    ScheduledServicePropertyResource repositoryProp = new ScheduledServicePropertyResource();
    repositoryProp.setKey("repositoryId");
    repositoryProp.setValue("nexus-test-harness-snapshot-repo");

    ScheduledServicePropertyResource keepSnapshotsProp = new ScheduledServicePropertyResource();
    keepSnapshotsProp.setKey("minSnapshotsToKeep");
    keepSnapshotsProp.setValue(String.valueOf(0));

    ScheduledServicePropertyResource ageProp = new ScheduledServicePropertyResource();
    ageProp.setKey("removeOlderThanDays");
    ageProp.setValue(String.valueOf(0));

    ScheduledServicePropertyResource removeReleasedProp = new ScheduledServicePropertyResource();
    removeReleasedProp.setKey("removeIfReleaseExists");
    removeReleasedProp.setValue(String.valueOf(true));

    ScheduledServiceBaseResource scheduledTask = new ScheduledServiceBaseResource();
    scheduledTask.setEnabled(true);
    scheduledTask.setId(null);
    scheduledTask.setName(name);
    scheduledTask.setTypeId(SnapshotRemovalTaskDescriptor.ID);
    scheduledTask.setSchedule("manual");
    scheduledTask.addProperty(repositoryProp);
    scheduledTask.addProperty(keepSnapshotsProp);
    scheduledTask.addProperty(ageProp);
    scheduledTask.addProperty(removeReleasedProp);

    Status status = TaskScheduleUtil.create(scheduledTask);

    Assert.assertTrue(status.isSuccess());
  }
  @Test
  public void withoutPermission() throws Exception {
    overwriteUserRole(
        TEST_USER_NAME,
        "anonymous-with-login-but-setpw",
        "1",
        "2" /* login */,
        "6",
        "14",
        "17",
        "19",
        "44",
        "54",
        "55",
        "57",
        "58",
        "59", /* "72" set pw, */
        "T1",
        "T2");

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

    // NOT Should be able to forgot my own username
    Status status = ChangePasswordUtils.changePassword("test-user", "123admin");
    Assert.assertEquals(403, status.getCode());

    // NOT Should be able to forgot anyone username
    status = ChangePasswordUtils.changePassword("admin", "123admin");
    Assert.assertEquals(403, status.getCode());
  }
 @Override
 public Representation getRepresentation(Status status, Request request, Response response) {
   StringWriter st = new StringWriter();
   PrintWriter pw = new PrintWriter(st);
   if (status.getCode() == 404) {
     pw.append("<h1>Page not found</h1>\n");
     pw.append(
         "The page you are looking for does not exist.  "
             + "You may be able to recover by going "
             + "<a href='javascript:history.back();void(0);'>back</a>.\n");
   } else {
     pw.append("<h1>An error occured</h1>\n");
     pw.append(
         "You may be able to recover and try something "
             + "else by going "
             + "<a href='javascript:history.back();void(0);'>back</a>.\n");
     if (status.getThrowable() != null) {
       pw.append("<h2>Cause: " + status.getThrowable().toString() + "</h2>\n");
       pw.append("<pre>");
       status.getThrowable().printStackTrace(pw);
       pw.append("</pre>");
     }
   }
   pw.flush();
   return new StringRepresentation(st.toString(), MediaType.TEXT_HTML);
 }
Beispiel #5
0
  /** Tests for status classes. */
  public void testStatusClasses() {
    final Status s1 = new Status(287);
    assertTrue(s1.isSuccess());

    final Status s2 = Status.CLIENT_ERROR_BAD_REQUEST;
    assertTrue(s2.isClientError());
    assertTrue(s2.isError());
  }
 public static void removeAllTarget() throws IOException {
   List<RepositoryTargetListResource> targets = getList();
   for (RepositoryTargetListResource target : targets) {
     Status status =
         RequestFacade.sendMessage("service/local/repo_targets/" + target.getId(), Method.DELETE)
             .getStatus();
     Assert.assertTrue(status.isSuccess(), "Failt to delete: " + status.getDescription());
   }
 }
  @Test
  public void changePassword() throws Exception {

    Status status = ChangePasswordUtils.changePassword("test-user", "newPassword");
    Assert.assertEquals("Status", 204, status.getCode());

    // we need to change the password around for this
    status = ChangePasswordUtils.changePassword("test-user", TEST_USER_PASSWORD);
    Assert.assertEquals("Status", 204, status.getCode());
  }
  @Test
  public void wrongAnonymousAccount() throws Exception {
    TestContainer.getInstance().getTestContext().useAdminForRequests();

    GlobalConfigurationResource globalConfig = SettingsMessageUtil.getCurrentSettings();
    globalConfig.setSecurityAnonymousUsername("zigfrid");

    Status status = SettingsMessageUtil.save(globalConfig);
    Assert.assertEquals(status.getCode(), 400, "Can't set an invalid user as anonymous");
  }
  private int download() throws Exception {
    URL url =
        new URL(
            "http://localhost:"
                + nexusApplicationPort
                + "/artifactory/main-local/nxcm281/released/1.0/released-1.0.jar");

    Status status = RequestFacade.sendMessage(url, Method.GET, null).getStatus();
    return status.getCode();
  }
 public static void removeAllRoutes() throws IOException {
   List<RepositoryRouteListResource> routes = getList();
   for (RepositoryRouteListResource route : routes) {
     Status status = delete(route.getResourceURI()).getStatus();
     Assert.assertTrue(
         "Unable to delete route: '"
             + route.getResourceURI()
             + "', due to: "
             + status.getDescription(),
         status.isSuccess());
   }
 }
  public void testDownload() throws Exception {

    final Long processId = issueProcessAndWaitForTermination();

    // zip extension is not required but should be handled
    final String request = RESTLET_PATH + "/" + processId.longValue() + ".zip";

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));
    assertEquals(
        "attachment; filename=\"test map.zip\"", response.getHeader("Content-Disposition"));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    final ZipInputStream zipIn = new ZipInputStream(responseStream);

    Set<String> expectedFiles = new HashSet<String>();
    expectedFiles.add("README.txt");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shp");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".cst");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".prj");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".dbf");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shx");
    // TODO: change this expectation once we normalize the raster file name
    expectedFiles.add(RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff");

    Set<String> archivedFiles = new HashSet<String>();

    ZipEntry nextEntry;
    while ((nextEntry = zipIn.getNextEntry()) != null) {
      archivedFiles.add(nextEntry.getName());
    }

    assertEquals(expectedFiles, archivedFiles);
  }
Beispiel #12
0
  @Override
  public void sendResponse(Response response) throws IOException {
    // Add call headers
    Header header;

    for (Iterator<Header> iter = getResponseHeaders().iterator(); iter.hasNext(); ) {
      header = iter.next();
      getConnection().getResponse().addHeader(header.getName(), header.getValue());
    }

    // Set the status code in the response. We do this after adding the
    // headers because when we have to rely on the 'sendError' method,
    // the Servlet containers are expected to commit their response.
    if (Status.isError(getStatusCode()) && (response.getEntity() == null)) {
      try {
        getConnection().getResponse().sendError(getStatusCode(), getReasonPhrase());
      } catch (IOException ioe) {
        getLogger().log(Level.WARNING, "Unable to set the response error status", ioe);
      }
    } else {
      // Send the response entity
      getConnection().getResponse().setStatus(getStatusCode());
      super.sendResponse(response);
    }
  }
  public void testCoverageContents() throws Exception {
    final Long processId = issueProcessAndWaitForTermination();

    final String request = RESTLET_PATH + "/" + processId.longValue();

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    File dataDirectoryRoot = super.getTestData().getDataDirectoryRoot();
    File file = new File(dataDirectoryRoot, "testCoverageContents.zip");
    super.getTestData().copyTo(responseStream, file.getName());

    ZipFile zipFile = new ZipFile(file);
    try {
      // TODO: change this expectation once we normalize the raster file name
      String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff";
      ZipEntry nextEntry = zipFile.getEntry(rasterName);
      assertNotNull(nextEntry);
      InputStream coverageInputStream = zipFile.getInputStream(nextEntry);
      // Use a file, geotiffreader might not work well reading out of a plain input stream
      File covFile = new File(file.getParentFile(), "coverage.tiff");
      IOUtils.copy(coverageInputStream, covFile);
      GeoTiffReader geoTiffReader = new GeoTiffReader(covFile);
      GridCoverage2D coverage = geoTiffReader.read(null);
      CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem();
      assertEquals(CRS.decode("EPSG:4326", true), crs);
    } finally {
      zipFile.close();
    }
  }
  @SuppressWarnings("deprecation")
  public File downloadSnapshotArtifact(String repository, Gav gav, File parentDir)
      throws IOException {
    // @see http://issues.sonatype.org/browse/NEXUS-599
    // r=<repoId> -- mandatory
    // g=<groupId> -- mandatory
    // a=<artifactId> -- mandatory
    // v=<version> -- mandatory
    // c=<classifier> -- optional
    // p=<packaging> -- optional, jar is taken as default
    // http://localhost:8087/nexus/service/local/artifact/maven/redirect?r=tasks-snapshot-repo&g=nexus&a=artifact&
    // v=1.0-SNAPSHOT
    String serviceURI =
        "service/local/artifact/maven/redirect?r="
            + repository
            + "&g="
            + gav.getGroupId()
            + "&a="
            + gav.getArtifactId()
            + "&v="
            + gav.getVersion();
    Response response = RequestFacade.doGetRequest(serviceURI);
    Status status = response.getStatus();
    if (status.isError()) {
      throw new FileNotFoundException(status + ": (" + status.getCode() + ")");
    }
    Assert.assertEquals(
        "Snapshot download should redirect to a new file\n "
            + response.getRequest().getResourceRef().toString()
            + " \n Error: "
            + status.getDescription(),
        301,
        status.getCode());

    Reference redirectRef = response.getRedirectRef();
    Assert.assertNotNull(
        "Snapshot download should redirect to a new file "
            + response.getRequest().getResourceRef().toString(),
        redirectRef);

    serviceURI = redirectRef.toString();

    File file = FileUtils.createTempFile(gav.getArtifactId(), '.' + gav.getExtension(), parentDir);
    RequestFacade.downloadFile(new URL(serviceURI), file.getAbsolutePath());

    return file;
  }
  @Test
  @Category(SECURITY.class)
  public void withPermission() throws Exception {
    overwriteUserRole(
        TEST_USER_NAME,
        "anonymous-with-login-changepw",
        "1",
        "2" /* login */,
        "6",
        "14",
        "17",
        "19",
        "44",
        "54",
        "55",
        "57",
        "58",
        "59",
        "64" /* change pw */,
        "T1",
        "T2");

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

    // Should be able to change my own password
    Status status = ChangePasswordUtils.changePassword("test-user", "admin123", "123admin");
    Assert.assertTrue(status.isSuccess());

    // password changed ! should fail
    status = ChangePasswordUtils.changePassword("test-user", "admin123", "123admin");
    Assert.assertEquals(401, status.getCode());
    status = ChangePasswordUtils.changePassword("test-user", "123admin", "admin123");
    Assert.assertEquals(401, status.getCode());

    TestContainer.getInstance().getTestContext().setUsername(TEST_USER_NAME);
    TestContainer.getInstance().getTestContext().setPassword("123admin");

    // should pass
    status = ChangePasswordUtils.changePassword("test-user", "123admin", "admin123");
    Assert.assertTrue(status.isSuccess());

    // should NOT be able to change another users password
  }
Beispiel #16
0
  /** Unequality tests. */
  public void testUnEquals() throws Exception {
    final Status s1 = new Status(200);
    final Status s2 = Status.SUCCESS_CREATED;

    assertFalse(s1.equals(s2));
    assertFalse(s1.getCode() == s2.getCode());
    assertFalse(s1.equals(null));
    assertFalse(s2.equals(null));
  }
  /**
   * Writes the current object as an XML element using the given SAX writer.
   *
   * @param writer The SAX writer.
   * @throws SAXException
   */
  public void writeElement(XmlWriter writer) throws SAXException {
    AttributesImpl attributes = new AttributesImpl();

    if ((getStatuses() != null) && !getStatuses().isEmpty()) {
      StringBuilder builder = new StringBuilder();

      for (Iterator<Status> iterator = getStatuses().iterator(); iterator.hasNext(); ) {
        Status status = iterator.next();
        builder.append(status.getCode());
        if (iterator.hasNext()) {
          builder.append(" ");
        }
      }

      attributes.addAttribute("", "status", null, "xs:string", builder.toString());
    }

    if (getDocumentations().isEmpty()
        && getParameters().isEmpty()
        && getRepresentations().isEmpty()) {
      writer.emptyElement(APP_NAMESPACE, "response", null, attributes);
    } else {
      writer.startElement(APP_NAMESPACE, "response", null, attributes);

      for (DocumentationInfo documentationInfo : getDocumentations()) {
        documentationInfo.writeElement(writer);
      }

      for (ParameterInfo parameterInfo : getParameters()) {
        parameterInfo.writeElement(writer);
      }

      for (RepresentationInfo representationInfo : getRepresentations()) {
        representationInfo.writeElement(writer);
      }

      writer.endElement(APP_NAMESPACE, "response");
    }
  }
  private void postAssessment(Request request, Response response, String username) {
    try {
      String entity = request.getEntity().getText();

      NativeDocument doc = NativeDocumentFactory.newNativeDocument();
      doc.parse(entity);
      AssessmentParser parser = new AssessmentParser(doc);
      AssessmentData assessment = parser.getAssessment();

      VFSPath assessmentUrl = new VFSPath(ServerPaths.getPathForAssessment(assessment, username));

      if (vfs.exists(assessmentUrl)) {
        Status status =
            FileLocker.impl.persistentLockAssessment(
                assessment.getAssessmentID(),
                BaseAssessment.DRAFT_ASSESSMENT_STATUS,
                LockType.SAVE_LOCK,
                username);

        if (status.isSuccess()) {
          AssessmentIOWriteResult result = saveAssessment(assessment, username);
          if (result.status.isSuccess()) {
            response.setEntity(result.newLastModified + "", MediaType.TEXT_PLAIN);
            response.setStatus(status);
          } else {
            response.setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED);
          }
        } else {
          response.setStatus(status);
        }
      }
    } catch (RegionConflictException e) {
      response.setStatus(Status.CLIENT_ERROR_CONFLICT);
    } catch (Exception e) {
      e.printStackTrace();
      response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
  }
  @Test
  public void withPermission() throws Exception {
    overwriteUserRole(
        TEST_USER_NAME,
        "anonymous-with-login-setpw",
        "1",
        "2" /* login */,
        "6",
        "14",
        "17",
        "19",
        "44",
        "54",
        "55",
        "57",
        "58",
        "59",
        "72" /* set pw */,
        "T1",
        "T2");

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

    // Should be able to change my own password
    Status status = ChangePasswordUtils.changePassword("test-user", "newPassword");
    Assert.assertEquals("Status", 204, status.getCode());

    // we need to change the password around for this
    TestContainer.getInstance().getTestContext().setPassword("newPassword");
    status = ChangePasswordUtils.changePassword("test-user", "newPassword");
    Assert.assertEquals("Status", 204, status.getCode());

    status = ChangePasswordUtils.changePassword("test-user", TEST_USER_PASSWORD);
    Assert.assertEquals("Status", 204, status.getCode());
    TestContainer.getInstance().getTestContext().setPassword(TEST_USER_PASSWORD);
  }
Beispiel #20
0
  @Override
  public void removeRepresentations() throws ResourceException {
    try {
      super.removeRepresentations();
    } catch (ResourceException e) {
      if (Status.isServerError(e.getStatus().getCode())) {
        handleError(e);
      }
      throw e;
    } catch (RuntimeException e) {
      handleError(e);

      throw e;
    }
  }
Beispiel #21
0
  /** Equality tests. */
  public void testEquals() throws Exception {
    final Status s1 = new Status(201);
    final Status s2 = Status.SUCCESS_CREATED;

    assertTrue(s1.equals(s2));
    assertTrue(s1.getCode() == s2.getCode());
    assertEquals(s1, s2);

    assertTrue(s1.equals(s1));
    assertEquals(s1, s1);
  }
  private static void completeOperationThrows(
      CollectInfo collectInfo,
      Operation operation,
      MethodAnnotationInfo mai,
      List<? extends IntrospectionHelper> introspectionHelper) {
    Class<?>[] thrownClasses = mai.getJavaMethod().getExceptionTypes();
    if (thrownClasses != null) {
      for (Class<?> thrownClass : thrownClasses) {
        ThrowableAnnotationInfo throwableAnnotationInfo =
            AnnotationUtils.getInstance().getThrowableAnnotationInfo(thrownClass);
        if (throwableAnnotationInfo != null) {
          int statusCode = throwableAnnotationInfo.getStatus().getCode();
          Response response = new Response();
          response.setCode(statusCode);
          response.setName(Status.valueOf(statusCode).getReasonPhrase());
          response.setMessage("Status " + statusCode);

          Class<?> outputPayloadType =
              throwableAnnotationInfo.isSerializable() ? thrownClass : StatusInfo.class;
          TypeInfo outputTypeInfo = null;
          try {
            outputTypeInfo = Types.getTypeInfo(outputPayloadType, null);
          } catch (UnsupportedTypeException e) {
            LOGGER.warning(
                "Could not add output payload for exception "
                    + thrownClass
                    + " throws by method "
                    + mai.getJavaMethod()
                    + ". "
                    + e.getMessage());
            continue;
          }

          RepresentationCollector.addRepresentation(
              collectInfo, outputTypeInfo, introspectionHelper);

          PayLoad outputPayLoad = new PayLoad();
          outputPayLoad.setType(outputTypeInfo.getRepresentationName());
          response.setOutputPayLoad(outputPayLoad);
          operation.getResponses().add(response);
        }
      }
    }
  }
 public void testInvalidProcessId() throws Exception {
   String request = RESTLET_PATH + "/notAProcessId";
   MockHttpServletResponse r = getAsServletResponse(request);
   assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, Status.valueOf(r.getStatus()));
 }
  @Test
  public void downloadWithPermission() throws Exception {
    TestContainer.getInstance().getTestContext().useAdminForRequests();

    assertThat("Unable to download artifact", Status.isSuccess(download()));
  }
 public void testHTTPMethod() throws Exception {
   MockHttpServletResponse r = postAsServletResponse(RESTLET_PATH, "");
   assertEquals(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, Status.valueOf(r.getStatus()));
 }
 public void testNonExistentProcess() throws Exception {
   String request = RESTLET_PATH + "/10000";
   MockHttpServletResponse r = getAsServletResponse(request);
   assertEquals(Status.CLIENT_ERROR_NOT_FOUND, Status.valueOf(r.getStatus()));
 }
Beispiel #27
0
 public void testCustomDescription() {
   final String customDescription = "My custom description";
   final Status s = new Status(Status.CLIENT_ERROR_NOT_FOUND, customDescription);
   assertEquals(customDescription, s.getDescription());
 }