org.sonatype.nexus.common.app.BaseUrlHolder Java Examples

The following examples show how to use org.sonatype.nexus.common.app.BaseUrlHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NpmPackageRootMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() {
  // reset for every request
  BaseUrlHolder.unset();
    
  when(packageRootAsset.name()).thenReturn("@foo/bar");
  when(packageRootAsset.requireBlobRef()).thenReturn(packageRootBlobRef);
  when(packageRootAsset.formatAttributes()).thenReturn(new NestedAttributesMap("metadata", new HashMap<>()));
  when(packageRootAsset.getEntityMetadata())
      .thenReturn(new DetachedEntityMetadata(new DetachedEntityId("foo"), new DetachedEntityVersion("a")));

  when(storageTx.requireBlob(packageRootBlobRef)).thenReturn(packageRootBlob);
  when(storageTx.findAssetWithProperty(eq(P_NAME), eq("@foo/bar"), any(Bucket.class))).thenReturn(packageRootAsset);
  when(packageRootBlob.getInputStream())
      .thenReturn(new ByteArrayInputStream(("{\"" + DIST_TAGS + "\": {\"latest\":\"1.5.3\"}}").getBytes()));

  UnitOfWork.beginBatch(storageTx);
}
 
Example #2
Source File: CleanupTaskConanProxyIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());
  testData.addDirectory(NexusPaxExamSupport.resolveBaseFile("target/it-resources/conan"));
  testData.addDirectory(NexusPaxExamSupport.resolveBaseFile("target/test-classes/conan"));

  server = Server.withPort(0)
      .serve("/" + JSON_FOR_MODERN_CPP_URL)
      .withBehaviours(Behaviours.file(testData.resolveFile(DOWNLOAD_URLS_FILE_NAME)))
      .serve("/" + LIB_URL)
      .withBehaviours(Behaviours.file(testData.resolveFile(LIB_DOWNLOAD_URLS_FILE_NAME)))
      .start();

  proxyRepo = repos.createConanProxy(testName.getMethodName(), server.getUrl().toExternalForm());
  URL repositoryUrl = repositoryBaseUrl(proxyRepo);
  proxyClient = new ConanClient(
      clientBuilder(repositoryUrl).build(),
      clientContext(),
      repositoryUrl.toURI()
  );
  proxyClient.get(JSON_FOR_MODERN_CPP_URL);
}
 
Example #3
Source File: MavenTestHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private String url(final Repository repo, final String path) {
  boolean reset = false;
  if (!BaseUrlHolder.isSet()) {
    reset = true;
    BaseUrlHolder.set(nexusUrl.toString());
  }
  String repoPath = path.startsWith("/") ? path : '/' + path;
  try {
    return String.format("%s%s", repo.getUrl(), repoPath);
  }
  finally {
    if (reset) {
      BaseUrlHolder.unset();
    }
  }
}
 
Example #4
Source File: NpmMetadataUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Rewrites dist/tarball entry URLs to point back to this Nexus instance and given repository.
 */
public static void rewriteTarballUrl(final String repositoryName, final NestedAttributesMap packageRoot) {
  if (BaseUrlHolder.isSet()) {
    NestedAttributesMap versions = packageRoot.child(VERSIONS);
    for (String v : versions.keys()) {
      if (versions.get(v) instanceof Map) { // only if not incomplete
        NestedAttributesMap version = versions.child(v);
        NestedAttributesMap dist = version.child(DIST);
        String tarballName = extractTarballName(dist.get(TARBALL, String.class));
        dist.set(
            TARBALL,
            String.format(
                "%s/repository/%s/%s/-/%s", BaseUrlHolder.get(), repositoryName, version.get(NAME), tarballName
            )
        );
      }
    }
  }
}
 
Example #5
Source File: RProxyIT.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());
  server = Server.withPort(0)
      .serve("/*")
      .withBehaviours(error(NOT_FOUND))
      .serve("/" + AGRICOLAE_131_TGZ.fullPath)
      .withBehaviours(file(testData.resolveFile(AGRICOLAE_131_TGZ.filename)))
      .serve("/" + AGRICOLAE_131_TARGZ.fullPath)
      .withBehaviours(file(testData.resolveFile(AGRICOLAE_131_TARGZ.filename)))
      .serve("/" + AGRICOLAE_131_XXX.fullPath)
      .withBehaviours(file(testData.resolveFile(AGRICOLAE_131_XXX.filename)))
      .serve("/" + PACKAGES_SRC_GZ.fullPath)
      .withBehaviours(file(testData.resolveFile(PACKAGES_SRC_GZ.filename)))
      .serve("/" + PACKAGES_RDS.fullPath)
      .withBehaviours(file(testData.resolveFile(PACKAGES_RDS.filename)))
      .serve("/" + ARCHIVE_RDS.fullPath)
      .withBehaviours(file(testData.resolveFile(ARCHIVE_RDS.filename)))
      .start();
  repository = repos.createRProxy("r-proxy-test", server.getUrl().toExternalForm());
  client = rClient(repository);
}
 
Example #6
Source File: RRestoreBlobIT.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());
  hostedRepository = repos.createRHosted(HOSTED_REPO_NAME);
  hostedClient = createRClient(hostedRepository);

  proxyServer = Server.withPort(0)
      .serve("/" + AGRICOLAE_131_TARGZ.fullPath)
      .withBehaviours(file(testData.resolveFile(AGRICOLAE_131_TARGZ.filename)))
      .start();

  proxyRepository = repos.createRProxy(PROXY_REPO_NAME, "http://localhost:" + proxyServer.getPort() + "/");
  proxyClient = createRClient(proxyRepository);

  assertThat(hostedClient.put(AGRICOLAE_131_TARGZ.fullPath,
      fileToHttpEntity(AGRICOLAE_131_TARGZ.filename)).getStatusLine().getStatusCode(), is(HttpStatus.OK));
  assertThat(proxyClient.fetch(AGRICOLAE_131_TARGZ.fullPath).getStatusLine().getStatusCode(), is(HttpStatus.OK));
}
 
Example #7
Source File: NpmMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void rewriteTarballUrlTest() {
  try {
    assertThat(BaseUrlHolder.isSet(), is(false));
    BaseUrlHolder.set("http://localhost:8080/");

    NestedAttributesMap packageRoot = new NestedAttributesMap("package", Maps.newHashMap());
    packageRoot.set("_id", "id");
    packageRoot.set("name", "package");
    packageRoot.child("versions").child("1.0").set("name", "package");
    packageRoot.child("versions").child("1.0").set("version", "1.0");
    packageRoot.child("versions").child("1.0").child("dist")
        .set("tarball", "http://example.com/path/package-1.0.tgz");
    packageRoot.child("versions").set("2.0", "incomplete");

    NpmMetadataUtils.rewriteTarballUrl("testRepo", packageRoot);

    String rewritten = packageRoot.child("versions").child("1.0").child("dist").get("tarball", String.class);
    assertThat(rewritten, equalTo("http://localhost:8080/repository/testRepo/package/-/package-1.0.tgz"));
  }
  finally {
    BaseUrlHolder.unset();
  }
}
 
Example #8
Source File: ViewServletTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  defaultResponseSender = spy(new DefaultHttpResponseSender());

  when(descriptionRenderer.renderHtml(any(Description.class))).thenReturn("HTML");
  when(descriptionRenderer.renderJson(any(Description.class))).thenReturn("JSON");

  underTest = spy(new ViewServlet(mock(RepositoryManager.class),
      new HttpResponseSenderSelector(Collections.<String, HttpResponseSender>emptyMap(), defaultResponseSender),
      mock(DescriptionHelper.class),
      descriptionRenderer, true
  ));

  when(request.getPath()).thenReturn("/test");

  parameters = new Parameters();
  when(request.getParameters()).thenReturn(parameters);

  BaseUrlHolder.set("http://placebo");
}
 
Example #9
Source File: RaptureWebResourceBundle.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The bootstrap.js resource.
 */
private WebResource bootstrap_js() {
  return new TemplateWebResource()
  {
    @Override
    public String getPath() {
      return "/static/rapture/bootstrap.js";
    }

    @Override
    public String getContentType() {
      return JAVASCRIPT;
    }

    @Override
    protected byte[] generate() throws IOException {
      return render("bootstrap.vm", new TemplateParameters()
              .set("baseUrl", BaseUrlHolder.get())
              .set("debug", isDebug())
              .set("urlSuffix", generateUrlSuffix())
              .set("namespaces", getExtJsNamespaces())
      );
    }
  };
}
 
Example #10
Source File: RaptureWebResourceBundle.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The app.js resource.
 */
private WebResource app_js() {
  return new TemplateWebResource()
  {
    @Override
    public String getPath() {
      return "/static/rapture/app.js";
    }

    @Override
    public String getContentType() {
      return JAVASCRIPT;
    }

    @Override
    protected byte[] generate() throws IOException {
      return render("app.vm", new TemplateParameters()
              .set("baseUrl", BaseUrlHolder.get())
              .set("debug", isDebug())
              .set("state", gson.toJson(getState()))
              .set("pluginConfigs", getExtJsPluginConfigs())
      );
    }
  };
}
 
Example #11
Source File: HelmRestoreBlobIT.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());
  hostedRepository = repos.createHelmHosted(HOSTED_REPO_NAME);
  hostedClient = createHelmClient(hostedRepository);

  proxyServer = Server.withPort(0)
      .serve("/" + MONGO_PATH_FULL_728_TARGZ)
      .withBehaviours(file(testData.resolveFile(MONGO_PKG_FILE_NAME_728_TGZ)))
      .start();

  proxyRepository = repos.createHelmProxy(PROXY_REPO_NAME, "http://localhost:" + proxyServer.getPort() + "/");
  proxyClient = createHelmClient(proxyRepository);

  assertThat(hostedClient.put(MONGO_PATH_FULL_728_TARGZ,
      fileToHttpEntity(MONGO_PKG_FILE_NAME_728_TGZ)).getStatusLine().getStatusCode(), is(HttpStatus.OK));
  assertThat(proxyClient.fetch(MONGO_PATH_FULL_728_TARGZ, CONTENT_TYPE_TGZ).getStatusLine().getStatusCode(), is(HttpStatus.OK));
}
 
Example #12
Source File: NpmPackageRootMetadataUtilsTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void createFullPackageMetadataImpl(final BiFunction<String, String, String> function, String packageJsonFilename) throws URISyntaxException, IOException {
  try {
    assertThat(BaseUrlHolder.isSet(), is(false));
    BaseUrlHolder.set("http://localhost:8080/");

    File packageJsonFile = new File(NpmPackageRootMetadataUtilsTest.class.getResource(packageJsonFilename).toURI());
    File archive = tempFolderRule.newFile();
    Map<String, Object> packageJson = new NpmPackageParser()
        .parsePackageJson(() -> ArchiveUtils.pack(archive, packageJsonFile, "package/package.json"));

    NestedAttributesMap packageMetadata = NpmPackageRootMetadataUtils
        .createFullPackageMetadata(new NestedAttributesMap("metadata", packageJson),
            "npm-hosted",
            "abcd",
            repository,
            function);

    assertPackageMetadata(packageMetadata);
  }
  finally {
    BaseUrlHolder.unset();
  }
}
 
Example #13
Source File: MavenApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertRepository(
    final AbstractApiRepository repository,
    final String type,
    final Boolean online)
{
  assertThat(repository.getFormat(), is("maven2"));
  assertThat(repository.getName(), is("my-repo"));
  assertThat(repository.getOnline(), is(online));
  assertThat(repository.getType(), is(type));
  assertThat(repository.getUrl(), is(BaseUrlHolder.get() + "/repository/my-repo"));
}
 
Example #14
Source File: AptApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertRepository(
    final AbstractApiRepository repository,
    final String type,
    final Boolean online)
{
  assertThat(repository.getFormat(), is("apt"));
  assertThat(repository.getName(), is("my-repo"));
  assertThat(repository.getOnline(), is(online));
  assertThat(repository.getType(), is(type));
  assertThat(repository.getUrl(), is(BaseUrlHolder.get() + "/repository/my-repo"));
}
 
Example #15
Source File: ViewServlet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@VisibleForTesting
Response describe(final Request request, final Response response, final Exception exception, final String flags) {
  final Description description = new Description(ImmutableMap.<String, Object>of(
      "path", request.getPath(),
      "nexusUrl", BaseUrlHolder.get()
  ));
  if (exception != null) {
    descriptionHelper.describeException(description, exception);
  }
  descriptionHelper.describeRequest(description, request);
  if (response != null) {
    descriptionHelper.describeResponse(description, response);
  }

  DescribeType type = DescribeType.parse(flags);
  log.trace("Describe type: {}", type);
  switch (type) {
    case HTML: {
      String html = descriptionRenderer.renderHtml(description);
      return HttpResponses.ok(new StringPayload(html, ContentTypes.TEXT_HTML));
    }
    case JSON: {
      String json = descriptionRenderer.renderJson(description);
      return HttpResponses.ok(new StringPayload(json, ContentTypes.APPLICATION_JSON));
    }
    default:
      throw new RuntimeException("Invalid describe-type: " + type);
  }
}
 
Example #16
Source File: BaseUrlManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Detect and set (if non-null) the base-url.
 */
@Override
public void detectAndHoldUrl() {
  String url = detectUrl();
  if (url != null) {
    BaseUrlHolder.set(url);
  }
}
 
Example #17
Source File: ExtDirectJsonRequestProcessorThread.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public ExtDirectJsonRequestProcessorThread() {
  Subject subject = SecurityUtils.getSubject();
  checkState(subject != null, "Subject is not set");
  // create the thread state by this moment as this is created in the master (web container) thread
  threadState = new SubjectThreadState(subject);

  final String baseUrl = BaseUrlHolder.get();

  processRequest = ServletScopes.transferRequest(new Callable<String>()
  {
    @Override
    public String call() {
      threadState.bind();
      UserIdMdcHelper.set();
      try {
        // apply base-url from the original thread
        BaseUrlHolder.set(baseUrl);

        return ExtDirectJsonRequestProcessorThread.super.processRequest();
      }
      finally {
        UserIdMdcHelper.unset();
        threadState.restore();
      }

    }
  });
}
 
Example #18
Source File: RepositoryAuditor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Map<String, Object> createFullAttributes(final Repository repository) {
  boolean baseUrlAbsent = !BaseUrlHolder.isSet();
  try {
    if (baseUrlAbsent) {
      BaseUrlHolder.set(""); // use empty base URL placeholder during conversion to avoid log-spam
    }

    AbstractApiRepository apiObject = convert(repository);

    ObjectWriter writer = mapper.writerFor(apiObject.getClass());

    String json = writer.writeValueAsString(apiObject);

    return mapper.readerFor(new TypeReference<Map<String, Object>>()
    {
    }).readValue(json);
  }
  catch (Exception e) {
    log.error("Failed to convert repo object falling back to simple", e);
    return createSimple(repository);
  }
  finally {
    if (baseUrlAbsent) {
      BaseUrlHolder.unset();
    }
  }
}
 
Example #19
Source File: SimpleApiRepositoryAdapterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertRepository(
    final AbstractApiRepository repository,
    final String type,
    final Boolean online)
{
  assertThat(repository.getFormat(), is("test-format"));
  assertThat(repository.getName(), is("my-repo"));
  assertThat(repository.getOnline(), is(online));
  assertThat(repository.getType(), is(type));
  assertThat(repository.getUrl(), is(BaseUrlHolder.get() + "/repository/my-repo"));
}
 
Example #20
Source File: NpmStreamingObjectMapperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void verify_TarballUrl_Manipulation_Of_Json_While_Streaming_Out() throws IOException {
  String nxrmUrl = "http://localhost:8080/";
  String remoteUrl = "https://registry.npmjs.org";
  String distTarballPath = "\"dist\":{\"tarball\":\"";
  String packageId = "array-first";
  String packagePath = "/" + packageId + "/-/" + packageId;

  // these are not the complete tarball urls but are unique enough to identify that it was changed
  String normDistTarball = distTarballPath + nxrmUrl + "repository/" + REPO_NAME + packagePath;
  String remoteDistTarball = distTarballPath + remoteUrl + packagePath;

  assertThat(BaseUrlHolder.isSet(), is(false));

  BaseUrlHolder.set(nxrmUrl);

  try (InputStream packageRoot = getResource("streaming-payload-manipulate-while-streaming-out.json");
       InputStream packageRoot2 = getResource("streaming-payload-manipulate-while-streaming-out.json")) {

    String original = IOUtils.toString(packageRoot);

    assertThat(original, containsString(remoteDistTarball));
    assertThat(original, not(containsString(normDistTarball)));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    new NpmStreamingObjectMapper(singletonList(rewriteTarballUrlMatcher(REPO_NAME, packageId)))
        .readAndWrite(packageRoot2, outputStream);

    String streamed = outputStream.toString();
    assertThat(streamed, not(containsString(remoteDistTarball)));
    assertThat(streamed, containsString(normDistTarball));
  }
}
 
Example #21
Source File: WebResourceServlet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
    throws ServletException, IOException
{
  String path = request.getPathInfo();

  // default-page handling
  if ("".equals(path) || "/".equals(path)) {
    path = INDEX_PATH;
  }
  else if (path.endsWith("/")) {
    path += "index.html";
  }
  else if (INDEX_PATH.equals(path)) {
    response.sendRedirect(BaseUrlHolder.get()); // prevent browser from sending XHRs to incorrect URL - NEXUS-14593
    return;
  }

  WebResource resource = webResources.getResource(path);
  if (resource == null) {
    // if there is an index.html for the requested path, redirect to it
    if (webResources.getResource(path + INDEX_PATH) != null) {
      String location = String.format("%s%s/", BaseUrlHolder.get(), path);
      log.debug("Redirecting: {} -> {}", path, location);
      response.sendRedirect(location);
    }
    else {
      response.sendError(SC_NOT_FOUND);
    }
    return;
  }

  serveResource(resource, request, response);
}
 
Example #22
Source File: TemplateHelperImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public TemplateParameters parameters() {
  TemplateParameters params = new TemplateParameters();
  params.set("nexusVersion", applicationVersion.getVersion());
  params.set("nexusEdition", applicationVersion.getEdition());
  params.set("nexusBrandedEditionAndVersion", applicationVersion.getBrandedEditionAndVersion());
  params.set("nexusUrl", BaseUrlHolder.get());
  params.set("urlSuffix", applicationVersion.getVersion()); // for cache busting
  params.set("esc", new EscapeHelper());
  return params;
}
 
Example #23
Source File: ErrorPageServletTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  TemplateHelper templateHelper = new TemplateHelperImpl(new ApplicationVersionSupport()
  {
    @Override
    public String getEdition() {
      return "Test";
    }
  }, new VelocityEngine());

  XFrameOptions xFrameOptions = new XFrameOptions(true);

  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new ErrorPageServlet(templateHelper, xFrameOptions)), "/error.html");
  context.addServlet(new ServletHolder(new BadServlet()), "/bad/*");

  ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
  errorHandler.addErrorPage(GLOBAL_ERROR_PAGE, "/error.html");
  context.setErrorHandler(errorHandler);

  BaseUrlHolder.set("http://127.0.0.1");

  server = new Server(0);
  server.setHandler(context);
  server.start();

  port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
}
 
Example #24
Source File: RaptureWebResourceBundle.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The index.html resource.
 */
private WebResource index_html() {
  return new TemplateWebResource()
  {
    @Override
    public String getPath() {
      return "/index.html";
    }

    @Override
    public String getContentType() {
      return HTML;
    }

    @Override
    protected byte[] generate() throws IOException {
      return render("index.vm", new TemplateParameters()
              .set("baseUrl", BaseUrlHolder.get())
              .set("debug", isDebug())
              .set("urlSuffix", generateUrlSuffix())
              .set("styles", getStyles())
              .set("scripts", getScripts())
              .set("util", new TemplateUtil())
      );
    }
  };
}
 
Example #25
Source File: RaptureWebResourceBundle.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Generate a URI for the given path.
 */
private URI uri(final String path) {
  try {
    return new URI(String.format("%s/static/rapture/%s", BaseUrlHolder.get(), path));
  }
  catch (URISyntaxException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: RaptureWebResourceBundle.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param path
 * @return BaseUrlHolder.get() + /static/ + path
 */
private URI relativeToAbsoluteUri(final String path) {
  try {
    return new URI(String.format("%s%s", BaseUrlHolder.get(), path));
  }
  catch (URISyntaxException e) {
    throw new RuntimeException(e);
  }
}
 
Example #27
Source File: RaptureWebResourceBundleTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() {
  BaseUrlHolder.set("http://baseurl/");

  when(httpServletRequest.getParameter("debug")).thenReturn("false");

  underTest =
      new RaptureWebResourceBundle(applicationVersion, Providers.of(httpServletRequest), Providers.of(stateComponent),
          templateHelper, asList(new UiPluginDescriptorImpl()),
          asList(new ExtJsUiPluginDescriptorImpl("test-1"), new ExtJsUiPluginDescriptorImpl("test-2")));
}
 
Example #28
Source File: CleanupTaskP2ProxyIT.java    From nexus-repository-p2 with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());
  testData.addDirectory(NexusPaxExamSupport.resolveBaseFile("target/test-classes/p2"));
  server = Server.withPort(0)
      .serve("/" + VALID_PACKAGE_URL)
      .withBehaviours(Behaviours.file(testData.resolveFile(PACKAGE_NAME)))
      .serve("/" + VALID_HELP_PACKAGE_URL)
      .withBehaviours(Behaviours.file(testData.resolveFile(HELP_PACKAGE_NAME)))
      .start();

  proxyRepo = repos.createP2Proxy(testName.getMethodName(), server.getUrl().toExternalForm());
  proxyClient = p2Client(proxyRepo);
  deployArtifacts(VALID_HELP_PACKAGE_URL);
}
 
Example #29
Source File: P2RestoreBlobIT.java    From nexus-repository-p2 with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  BaseUrlHolder.set(this.nexusUrl.toString());

  proxyServer = Server.withPort(0)
      .serve("/" + VALID_PACKAGE_URL)
      .withBehaviours(Behaviours.file(testData.resolveFile(PACKAGE_NAME)))
      .start();

  proxyRepository = repos.createP2Proxy(P2ProxyRecipe.NAME, "http://localhost:" + proxyServer.getPort() + "/");
  proxyClient = p2Client(proxyRepository);

  assertThat(proxyClient.get(VALID_PACKAGE_URL).getStatusLine().getStatusCode(), is(HttpStatus.OK));
}
 
Example #30
Source File: NpmStreamingObjectMapperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void verify_Large_Json_StreamsOut_Within_Reasonable_Performance() throws IOException {
  assertThat(BaseUrlHolder.isSet(), is(false));
  BaseUrlHolder.set("http://localhost:8080/");

  double maxTimesSlowerAllowed = 2.5;
  double streamTotalDuration = 0;
  double memoryTotalDuration = 0;
  long counter = 100;
  int tenMb = 10485760; // 8361219 bytes in the json file use 10485760 bytes = 10240kb = 10mb

  for (int i = 0; i < counter; i++) {
    try (InputStream packageRoot = getResource("streaming-payload-large.json");
         InputStream packageRoot2 = getResource("streaming-payload-large.json")) {

      long start = currentTimeMillis();

      NpmJsonUtils.parse(() -> packageRoot);

      long memoryDuration = currentTimeMillis() - start;

      start = currentTimeMillis();

      new NpmStreamingObjectMapper().readAndWrite(packageRoot2, new BufferedOutputStream(new ByteArrayOutputStream(), tenMb));

      long streamDuration = currentTimeMillis() - start;

      memoryTotalDuration += memoryDuration;
      streamTotalDuration += streamDuration;
    }
  }

  double averageTimeSlower = (streamTotalDuration / memoryTotalDuration);

  if (averageTimeSlower > maxTimesSlowerAllowed) {
    fail(format("Streaming %s slower then using in memory parsing, while only %s times slower is allowed",
        averageTimeSlower, maxTimesSlowerAllowed));
  }
}