/**
   * @see
   *     org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper#parseRequest(org.apache.wicket.request.Request)
   */
  @Override
  protected UrlInfo parseRequest(Request request) {
    Url url = request.getUrl();
    if (url.getSegments().size() >= 1) {
      // try to extract page and component information from URL
      PageComponentInfo info = getPageComponentInfo(url);

      // load the page class
      String className = url.getSegments().get(0);

      if (isValidClassName(className) == false) {
        return null;
      }

      className = transformFromUrl(className);
      String fullyQualifiedClassName = packageName.getName() + '.' + className;
      Class<? extends IRequestablePage> pageClass = getPageClass(fullyQualifiedClassName);

      if (pageClass != null
          && Modifier.isAbstract(pageClass.getModifiers()) == false
          && IRequestablePage.class.isAssignableFrom(pageClass)) {
        // extract the PageParameters from URL if there are any
        PageParameters pageParameters = extractPageParameters(request, 1, pageParametersEncoder);

        return new UrlInfo(info, pageClass, pageParameters);
      }
    }
    return null;
  }
  /** WICKET-4935 prevent another double slash */
  @Test
  public void test15() {
    UrlRenderer r1 = new UrlRenderer(new MockWebRequest(Url.parse("private/AdminPage")));

    assertEquals(
        "../signIn;jsessionid=16k3wqa9c4sgq1cnp7fisa20u",
        r1.renderRelativeUrl(Url.parse("/signIn;jsessionid=16k3wqa9c4sgq1cnp7fisa20u")));
  }
 /**
  * Verify that absolute urls are rendered as is, ignoring the current client url and base url
  * completely.
  *
  * <p>https://issues.apache.org/jira/browse/WICKET-4466
  */
 @Test
 public void renderAbsoluteUrl() {
   String absoluteUrl = "http://www.example.com/some/path.ext";
   Url url = Url.parse(absoluteUrl);
   UrlRenderer renderer = new UrlRenderer(new MockWebRequest(Url.parse("foo/bar")));
   String renderedUrl = renderer.renderUrl(url);
   assertEquals(absoluteUrl, renderedUrl);
 }
 @Test
 public void test1() {
   UrlRenderer r1 = new UrlRenderer(new MockWebRequest(Url.parse("foo/bar/baz?a=b")));
   assertEquals("./xyz?x=y", r1.renderUrl(Url.parse("foo/bar/xyz?x=y")));
   assertEquals("./baz/xyz?x=y", r1.renderUrl(Url.parse("foo/bar/baz/xyz?x=y")));
   assertEquals("../aaa/xyz?x=y", r1.renderUrl(Url.parse("foo/aaa/xyz?x=y")));
   assertEquals("../../bbb/aaa/xyz?x=y", r1.renderUrl(Url.parse("bbb/aaa/xyz?x=y")));
 }
 @Test
 public void test7() {
   UrlRenderer r1 =
       new UrlRenderer(
           new MockWebRequest(
               Url.parse("MyTestPage/indexed1/indexed2/indexed3?10-27.ILinkListener-l2&p1=v1")));
   assertEquals("../../../MyTestPage?10", r1.renderUrl(Url.parse("MyTestPage?10")));
 }
 @Test
 public void test8() {
   UrlRenderer r1 =
       new UrlRenderer(new MockWebRequest(Url.parse("en/first-test-page?16-1.ILinkListener-l1")));
   assertEquals(
       "./first-test-page/indexed1/indexed2/indexed3?p1=v1",
       r1.renderUrl(Url.parse("en/first-test-page/indexed1/indexed2/indexed3?p1=v1")));
 }
  private Url parseUrl(String urlString) {
    Url url = Url.parse(urlString);

    // to avoid UrlRenderer touching the url (shouldRenderAsFull)
    url.setProtocol(null);
    url.setHost(null);
    url.setPort(null);

    return url;
  }
 private boolean isInternalWicket(Request request) {
   Url url = request.getUrl();
   if (url.getSegments().size() > 0) {
     if (url.getSegments().get(0).equals((Application.get().getMapperContext().getNamespace()))) {
       // starts with wicket namespace - is an internal wicket url
       return true;
     }
   }
   return false;
 }
  @Test
  public void renderFullUrlAsRelativeToBaseUrlWithoutSchemeHostnameAndPort() {
    Url baseUrl = Url.parse("/contextPath/filterPath/a/b/c/d");
    Url encodedFullUrl = Url.parse("http://host:8080/contextPath/filterPath/a/b;jsessionid=123456");

    UrlRenderer renderer = new UrlRenderer(new MockWebRequest(baseUrl));
    String encodedRelativeUrl = renderer.renderRelativeUrl(encodedFullUrl);

    assertEquals("../../b;jsessionid=123456", encodedRelativeUrl);
  }
 /**
  * Get the absolute bookmarkable path of a page
  *
  * @param pageClass Page
  * @param pageParameters Optional page parameters
  * @return Bookmarkable path
  */
 public static String absoluteMountPathForPage(
     Class<? extends Page> pageClass, PageParameters pageParameters) {
   HttpServletRequest req = getHttpServletRequest();
   RequestCycle requestCycle = RequestCycle.get();
   Url url = requestCycle.mapUrlFor(pageClass, pageParameters);
   String renderedUrl = url.toString();
   renderedUrl = Strings.isEmpty(renderedUrl) ? "." : renderedUrl;
   return RequestUtils.toAbsolutePath(
       HttpUtils.getWebappContextUrl(req),
       requestCycle.getOriginalResponse().encodeURL(renderedUrl));
 }
  @Test
  public void renderFullUrlAsRelativeToBaseUrlWithoutComposedFilterPath() {
    Url baseUrl = Url.parse("a/b/c/d"); // base url without context path and filter path
    Url encodedFullUrl = Url.parse("http://host:8080/context/path/a/b;jsessionid=123456");

    MockWebRequest request = new MockWebRequest(baseUrl);
    request.setContextPath("context/path");
    UrlRenderer renderer = new UrlRenderer(request);
    String encodedRelativeUrl = renderer.renderRelativeUrl(encodedFullUrl);

    assertEquals("../../b;jsessionid=123456", encodedRelativeUrl);
  }
  /**
   * @see
   *     org.apache.wicket.request.mapper.parameter.IPageParametersEncoder#encodePageParameters(org.apache.wicket.request.mapper.parameter.PageParameters)
   */
  public Url encodePageParameters(final PageParameters pageParameters) {
    Url url = new Url();

    for (int i = 0; i < pageParameters.getIndexedCount(); ++i) {
      url.getSegments().add(pageParameters.get(i).toString());
    }

    for (PageParameters.NamedPair pair : pageParameters.getAllNamed()) {
      QueryParameter param = new QueryParameter(pair.getKey(), pair.getValue());
      url.getQueryParameters().add(param);
    }

    return url;
  }
Beispiel #13
0
  /**
   * Creates a url for the handler. Modifies it with the correct {@link Scheme} if necessary.
   *
   * @param handler
   * @param request
   * @return url
   */
  final Url mapHandler(IRequestHandler handler, Request request) {
    Url url = delegate.mapHandler(handler);

    Scheme desired = getDesiredSchemeFor(handler);
    Scheme current = getSchemeOf(request);
    if (!desired.isCompatibleWith(current)) {
      // the generated url does not have the correct scheme, set it (which in turn will cause
      // the url to be rendered in its full representation)
      url.setProtocol(desired.urlName());
      if (url.getPort() != null || !desired.usesStandardPort(config)) {
        url.setPort(desired.getPort(config));
      }
    }
    return url;
  }
  @Override
  public CharSequence getCallbackUrl() {
    final Url url = Url.parse(super.getCallbackUrl().toString());
    final PageParameters params = getPageParameters();

    return StatelessEncoder.mergeParameters(url, params).toString();
  }
  private Url encodeRenderUrl(Url url, boolean forceRenderUrl) {
    if ((!forceRenderUrl) && (ThreadPortletContext.isResourceRequest())) {
      return encodeResourceUrl(url);
    }

    if (url != null) {
      String qualifiedPath = getQualifiedPath(url.toString());

      PortletResponse portletResponse = ThreadPortletContext.getPortletResponse();
      if ((portletResponse != null) && (portletResponse instanceof MimeResponse)) {
        try {
          PortletURL portletUrl = ((MimeResponse) portletResponse).createRenderURL();
          portletUrl.setParameter(
              WicketPortlet.WICKET_URL_PORTLET_PARAMETER
                  + ThreadPortletContext.getPortletMode().toString(),
              qualifiedPath);
          qualifiedPath = portletUrl.toString();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }

      url = parseUrl(qualifiedPath);
    }

    return url;
  }
  @Test
  public void renderFullUrlAsRelativeToBaseUrlWithFirstSegmentsEqualToTheFilterPath() {
    // base url without context path and filter path
    // 'filterPath' here is a normal segment with the same value
    Url baseUrl = Url.parse("filterPath/a/b/c/d");

    // here 'filterPath' is the actual filter path and should be ignored
    Url encodedFullUrl = Url.parse("http://host:8080/filterPath/a/b;jsessionid=123456");

    MockWebRequest request = new MockWebRequest(baseUrl);
    request.setFilterPath("filterPath");
    UrlRenderer renderer = new UrlRenderer(request);
    String encodedRelativeUrl = renderer.renderRelativeUrl(encodedFullUrl);

    assertEquals("../../../../a/b;jsessionid=123456", encodedRelativeUrl);
  }
 /**
  * Specify that charts.js depends on Google JS APIs and Wicket WebSocket JavaScript
  *
  * @return a list of dependencies
  */
 @Override
 public List<HeaderItem> getDependencies() {
   final List<HeaderItem> dependencies = new ArrayList<HeaderItem>();
   dependencies.add(
       JavaScriptHeaderItem.forReference(
           new UrlResourceReference(Url.parse("https://www.google.com/jsapi"))));
   return dependencies;
 }
  private Url encodeSharedResourceUrl(Url url) {
    if (url != null) {
      Request request = RequestCycle.get().getRequest();

      StringBuilder urlBuilder = new StringBuilder();
      urlBuilder.append(request.getContextPath());
      urlBuilder.append(request.getFilterPath());
      urlBuilder.append(PortletFilter.SHARED_RESOURCE_URL_PORTLET_WINDOW_ID_PREFIX);
      urlBuilder.append(
          Base64.encodeBase64URLSafeString(ThreadPortletContext.getWindowID().getBytes()));
      urlBuilder.append('/');
      urlBuilder.append(url.toString());

      url = Url.parse(urlBuilder.toString());
    }

    return url;
  }
 protected void encodePageComponentInfo(Url url, PageComponentInfo info) {
   Args.notNull(url, "url");
   if (info != null && Session.exists() && !Session.get().isSessionInvalidated()) {
     String s = info.toString();
     if (!Strings.isEmpty(s)) {
       QueryParameter parameter = new QueryParameter(s, "");
       url.getQueryParameters().add(parameter);
     }
   }
 }
  /** WICKET-4920 prevent double slash */
  @Test
  public void test14() {
    UrlRenderer r1 = new UrlRenderer(new MockWebRequest(new Url()));

    assertEquals(
        "./;jsessionid=1p87c5424zjuvd57kljcu2bwa?0-1.IBehaviorListener.1-component",
        r1.renderRelativeUrl(
            Url.parse(
                "http://localhost:8080/;jsessionid=1p87c5424zjuvd57kljcu2bwa?0-1.IBehaviorListener.1-component")));
  }
  private RequestCycle newRequestCycle(final RuntimeException exception) {
    final Response originalResponse = newResponse();
    Request request = new MockWebRequest(Url.parse("http://wicket.apache.org"));
    handler =
        new IRequestHandler() {
          @Override
          public void respond(IRequestCycle requestCycle) {
            if (exception != null) {
              throw exception;
            }
            responses++;
          }

          @Override
          public void detach(IRequestCycle requestCycle) {
            detaches++;
          }
        };
    IRequestMapper requestMapper =
        new IRequestMapper() {
          @Override
          public IRequestHandler mapRequest(Request request) {
            return handler;
          }

          @Override
          public Url mapHandler(IRequestHandler requestHandler) {
            throw new UnsupportedOperationException();
          }

          @Override
          public int getCompatibilityScore(Request request) {
            throw new UnsupportedOperationException();
          }
        };
    IExceptionMapper exceptionMapper =
        new IExceptionMapper() {
          @Override
          public IRequestHandler map(Exception e) {
            exceptionsMapped++;
            return null;
          }
        };
    RequestCycleContext context =
        new RequestCycleContext(request, originalResponse, requestMapper, exceptionMapper);

    RequestCycle cycle = new RequestCycle(context);

    if (Application.exists()) {
      cycle.getListeners().add(Application.get().getRequestCycleListeners());
    }

    return cycle;
  }
  /** @see org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper#buildUrl(UrlInfo) */
  @Override
  protected Url buildUrl(UrlInfo info) {
    Class<? extends IRequestablePage> pageClass = info.getPageClass();
    PackageName pageClassPackageName = PackageName.forClass(pageClass);
    if (pageClassPackageName.equals(packageName)) {
      Url url = new Url();

      String fullyQualifiedClassName = pageClass.getName();
      String packageRelativeClassName = fullyQualifiedClassName;
      int packageNameLength = packageName.getName().length();
      if (packageNameLength > 0) {
        packageRelativeClassName = fullyQualifiedClassName.substring(packageNameLength + 1);
      }
      packageRelativeClassName = transformForUrl(packageRelativeClassName);
      url.getSegments().add(packageRelativeClassName);
      encodePageComponentInfo(url, info.getPageComponentInfo());
      return encodePageParameters(url, info.getPageParameters(), pageParametersEncoder);
    }

    return null;
  }
  private Url encode(String nodeURL, PageParameters parameters, PageInfo info) {
    StringBuilder builder = new StringBuilder();

    if (nodeURL.startsWith("/")) {
      nodeURL = nodeURL.substring(1);
    }

    builder.append(urlEncodePath(new Path(nodeURL, false)));

    boolean skipFirstSlash = builder.charAt(builder.length() - 1) == '/';

    for (int i = 0; i < parameters.getIndexedCount(); ++i) {
      if (!skipFirstSlash) {
        builder.append('/');
      } else {
        skipFirstSlash = false;
      }

      final StringValue value = parameters.get(i);
      final String s = value.toString();

      if (s != null) {
        builder.append(urlEncode(s));
      }
    }

    Set<String> keys = parameters.getNamedKeys();
    if (info != null || !keys.isEmpty()) {
      builder.append("?");
    }

    if (info != null) {
      builder.append(info.toString());
    }

    boolean first = (info == null);

    for (String key : keys) {
      List<StringValue> values = parameters.getValues(key);
      for (StringValue value : values) {
        if (first) {
          first = false;
        } else {
          builder.append("&");
        }
        builder.append(urlEncode(key));
        builder.append("=");
        builder.append(urlEncode(value.toString()));
      }
    }

    return Url.parse(builder.toString());
  }
  private BrixPageParameters createBrixPageParams(Url url, Path path) {
    BrixPageParameters parameters = new BrixPageParameters();
    Path nodePath = path;
    Path requestPath = new Path("/" + url.getPath());

    if (nodePath.isAncestorOf(requestPath)) {
      Path remaining = new Path(requestPath.toString(), false).toRelative(nodePath);
      int i = 0;
      for (String s : remaining) {
        parameters.set(i, BrixNodePageUrlMapper.urlDecode(s));
        ++i;
      }
    }
    for (QueryParameter parameter : url.getQueryParameters()) {
      String parameterName = parameter.getName();
      if (PageComponentInfo.parse(parameterName) == null) {
        parameters.add(parameterName, parameter.getValue());
      }
    }
    return parameters;
  }
 @Override
 public IInstagramService create(CharSequence url) {
   String callbackUrl =
       RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(url.toString()));
   InstagramService service =
       new InstagramAuthService()
           .apiKey(clientId)
           .apiSecret(clientSecret)
           .callback(callbackUrl)
           .build();
   return new InstagramServiceAdapter(service);
 }
 private Url encryptUrl(final Url url) {
   if (url.getSegments().isEmpty() && url.getQueryParameters().isEmpty()) {
     return url;
   }
   final String encryptedUrlString = this.getCrypt().encryptUrlSafe(url.toString());
   final Url encryptedUrl = new Url(url.getCharset());
   encryptedUrl.getSegments().add(encryptedUrlString);
   final int numberOfSegments = url.getSegments().size();
   final HashedSegmentGenerator generator = new HashedSegmentGenerator(encryptedUrlString);
   for (int segNo = 0; segNo < numberOfSegments; ++segNo) {
     encryptedUrl.getSegments().add(generator.next());
   }
   return encryptedUrl;
 }
  @Override
  public void onUrlMapped(RequestCycle cycle, IRequestHandler handler, Url url) {
    Conversation conversation = container.getCurrentConversation(cycle);

    if (conversation == null || conversation.isTransient()) {
      return;
    }

    if (propagation == ConversationPropagation.ALL) {
      // propagate cid to bookmarkable pages via urls
      url.setQueryParameter(CID, conversation.getId());
    }
  }
  @Override
  public Url mapHandler(IRequestHandler requestHandler) {
    if (!(requestHandler instanceof ResourceReferenceRequestHandler)) {
      return null;
    }

    ResourceReferenceRequestHandler handler = (ResourceReferenceRequestHandler) requestHandler;

    // see if request handler addresses the resource reference we serve
    if (!handlesRequest(handler)) {
      return null;
    }

    Url url = new Url();

    // add mount path segments
    for (String segment : mountSegments) {
      url.getSegments().add(segment);
    }

    // replace placeholder parameters
    PageParameters parameters = new PageParameters(handler.getPageParameters());

    for (int index = 0; index < mountSegments.length; ++index) {
      String placeholder = getPlaceholder(mountSegments[index]);

      if (placeholder != null) {
        url.getSegments().set(index, parameters.get(placeholder).toString(""));
        parameters.remove(placeholder);
      }
    }

    // add caching information
    addCachingDecoration(url, parameters);

    // create url
    return encodePageParameters(url, parameters, parametersEncoder);
  }
 /**
  * Extracts the {@link PageComponentInfo} from the URL. The {@link PageComponentInfo} is encoded
  * as the very first query parameter and the parameter consists of name only (no value).
  *
  * @param url
  * @return PageComponentInfo instance if one was encoded in URL, <code>null</code> otherwise.
  */
 protected PageComponentInfo getPageComponentInfo(final Url url) {
   if (url == null) {
     throw new IllegalStateException("Argument 'url' may not be null.");
   } else {
     for (QueryParameter queryParameter : url.getQueryParameters()) {
       if (Strings.isEmpty(queryParameter.getValue())) {
         PageComponentInfo pageComponentInfo = PageComponentInfo.parse(queryParameter.getName());
         if (pageComponentInfo != null) {
           return pageComponentInfo;
         }
       }
     }
   }
   return null;
 }
  private Url encodeResourceUrl(Url url) {
    if (url != null) {
      String qualifiedPath = getQualifiedPath(url.toString());

      PortletResponse portletResponse = ThreadPortletContext.getPortletResponse();
      if ((portletResponse != null) && (portletResponse instanceof MimeResponse)) {
        try {
          ResourceURL resourceUrl = ((MimeResponse) portletResponse).createResourceURL();
          resourceUrl.setResourceID(qualifiedPath);
          qualifiedPath = resourceUrl.toString();

          // resource URLs preserve all request render parameters (at
          // least for Liferay even all POST parameters), so we have
          // to remove all Wicket parameters (that have the portlet
          // namespace), otherwise we would have all submited values
          // in the URL
          int queryStringSeparator = qualifiedPath.indexOf('?');
          if (queryStringSeparator > 0) {
            Map<String, String[]> parameterMap =
                Utils.parseQueryString(qualifiedPath.substring(queryStringSeparator + 1));

            boolean changed = false;
            Iterator<Map.Entry<String, String[]>> it = parameterMap.entrySet().iterator();
            String namespace = ThreadPortletContext.getNamespace();
            while (it.hasNext()) {
              if (it.next().getKey().startsWith(namespace)) {
                changed = true;
                it.remove();
              }
            }
            if (changed) {
              qualifiedPath =
                  qualifiedPath.substring(0, queryStringSeparator)
                      + '?'
                      + Utils.buildQueryString(parameterMap);
            }
          }
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }

      url = parseUrl(qualifiedPath);
    }

    return url;
  }