Ejemplo n.º 1
0
  /**
   * Creates a {@link ClientInfo} instance with preferences matching exactly the current variant.
   *
   * @return The new {@link ClientInfo} instance.
   */
  public ClientInfo createClientInfo() {
    ClientInfo result = new ClientInfo();

    if (getCharacterSet() != null) {
      result.getAcceptedCharacterSets().add(new Preference<CharacterSet>(getCharacterSet()));
    }

    if (getEncodings() != null) {
      for (Encoding encoding : getEncodings()) {
        result.getAcceptedEncodings().add(new Preference<Encoding>(encoding));
      }
    }

    if (getLanguages() != null) {
      for (Language language : getLanguages()) {
        result.getAcceptedLanguages().add(new Preference<Language>(language));
      }
    }

    if (getMediaType() != null) {
      result.getAcceptedMediaTypes().add(new Preference<MediaType>(getMediaType()));
    }

    return result;
  }
Ejemplo n.º 2
0
  /**
   * Constructor.
   *
   * @param clientInfo
   * @param metadataService
   */
  public Conneg(ClientInfo clientInfo, MetadataService metadataService) {
    this.clientInfo = clientInfo;
    this.metadataService = metadataService;

    if (clientInfo != null) {
      // Get the enriched user preferences
      this.languagePrefs =
          getEnrichedPreferences(
              clientInfo.getAcceptedLanguages(),
              (metadataService == null) ? null : metadataService.getDefaultLanguage(),
              Language.ALL);
      this.mediaTypePrefs =
          getEnrichedPreferences(
              clientInfo.getAcceptedMediaTypes(),
              (metadataService == null) ? null : metadataService.getDefaultMediaType(),
              MediaType.ALL);
      this.characterSetPrefs =
          getEnrichedPreferences(
              clientInfo.getAcceptedCharacterSets(),
              (metadataService == null) ? null : metadataService.getDefaultCharacterSet(),
              CharacterSet.ALL);
      this.encodingPrefs =
          getEnrichedPreferences(
              clientInfo.getAcceptedEncodings(),
              (metadataService == null) ? null : metadataService.getDefaultEncoding(),
              Encoding.ALL);
    }
  }
 /** Tests client address getting/setting. */
 public void testClientAddress() throws Exception {
   final ClientInfo client = getRequest().getClientInfo();
   String address = "127.0.0.1";
   client.setAddress(address);
   assertEquals(address, client.getAddress());
   assertEquals(0, client.getForwardedAddresses().size());
 }
 /** Tests client agent getting/setting. */
 public void testClientAgent() throws Exception {
   final ClientInfo client = getRequest().getClientInfo();
   String name = "Restlet";
   client.setAgent(name);
   assertEquals(name, client.getAgent());
   name = "Restlet Client";
   client.setAgent(name);
   assertEquals(name, client.getAgent());
 }
 /** Tests client addresses getting/setting. */
 public void testClientForwardedAddresses() throws Exception {
   final ClientInfo client = getRequest().getClientInfo();
   String firstAddress = "127.0.0.1";
   final String secondAddress = "192.168.99.10";
   List<String> addresses = Arrays.asList(new String[] {firstAddress, secondAddress});
   client.getForwardedAddresses().addAll(addresses);
   assertEquals(addresses, client.getForwardedAddresses());
   client.getForwardedAddresses().clear();
   client.getForwardedAddresses().addAll(addresses);
   assertEquals(addresses, client.getForwardedAddresses());
 }
  /** @see HttpHeaderTestService#getLanguage(javax.ws.rs.core.HttpHeaders) */
  public void testLanguage() throws IOException {
    final List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>();
    acceptedLanguages.add(new Preference<Language>(Language.ENGLISH));
    final ClientInfo clientInfo = new ClientInfo();
    clientInfo.setAcceptedLanguages(acceptedLanguages);

    final Request request =
        new Request(Method.POST, createReference(HttpHeaderTestService.class, "language"));
    request.setClientInfo(clientInfo);
    request.setEntity(new StringRepresentation("entity", Language.ENGLISH));
    final Response response = accessServer(request);

    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("en", response.getEntity().getText());
  }
Ejemplo n.º 7
0
  /**
   * Returns the best supported encoding for a given client.
   *
   * @param client The client preferences to use.
   * @return The best supported encoding for the given call.
   */
  public Encoding getBestEncoding(ClientInfo client) {
    Encoding bestEncoding = null;
    Encoding currentEncoding = null;
    Preference<Encoding> currentPref = null;
    float bestScore = 0F;

    for (Iterator<Encoding> iter = getSupportedEncodings().iterator(); iter.hasNext(); ) {
      currentEncoding = iter.next();

      for (Iterator<Preference<Encoding>> iter2 = client.getAcceptedEncodings().iterator();
          iter2.hasNext(); ) {
        currentPref = iter2.next();

        if (currentPref.getMetadata().equals(Encoding.ALL)
            || currentPref.getMetadata().equals(currentEncoding)) {
          // A match was found, compute its score
          if (currentPref.getQuality() > bestScore) {
            bestScore = currentPref.getQuality();
            bestEncoding = currentEncoding;
          }
        }
      }
    }

    return bestEncoding;
  }
Ejemplo n.º 8
0
  protected Request createRequest(Method method, String path) {
    // TODO: in restlet 1.1.1 the Reference is broken, (it works great in 1.1.2, but that has other
    // problems)
    // so we need to a working solution
    String uri = repositoryRoot + (repositoryRoot.endsWith("/") ? "" : "/") + path;
    Reference reference = new Reference(uri);

    Request request = new Request(method, reference);

    ClientInfo ci = new ClientInfo();

    ci.setAgent("NexusRM/1.0.0");

    ci.setAcceptedMediaTypes(
        Collections.singletonList(new Preference<MediaType>(MediaType.APPLICATION_XML)));

    request.setClientInfo(ci);

    return request;
  }
  public void testAccMediaType() throws IOException {
    Response response = get("accMediaTypes", MediaType.TEXT_PLAIN);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals("[" + MediaType.TEXT_PLAIN.toString() + "]", response.getEntity().getText());

    ClientInfo clientInfo = new ClientInfo();
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_PLAIN, 0.5f));
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_HTML, 0.8f));
    clientInfo.getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML, 0.2f));
    response = get("accMediaTypes", clientInfo);
    assertEquals(Status.SUCCESS_OK, response.getStatus());
    assertEquals(
        "["
            + MediaType.TEXT_HTML.toString()
            + ", "
            + MediaType.TEXT_PLAIN.toString()
            + ", "
            + MediaType.TEXT_XML.toString()
            + "]",
        response.getEntity().getText());
  }
Ejemplo n.º 10
0
  /**
   * Handles an object entity. Automatically serializes the object using the {@link
   * org.restlet.service.ConverterService}.
   *
   * @param method The request method to use.
   * @param entity The object entity to post.
   * @param resultClass The class of the response entity.
   * @return The response object entity.
   * @throws ResourceException
   */
  private <T> T handle(Method method, Object entity, Class<T> resultClass)
      throws ResourceException {
    T result = null;
    org.restlet.service.ConverterService cs = getConverterService();

    ClientInfo clientInfo = getClientInfo();

    if (clientInfo.getAcceptedMediaTypes().isEmpty()) {
      cs.updatePreferences(clientInfo.getAcceptedMediaTypes(), resultClass);
    }

    Representation requestEntity = null;

    if (entity != null) {
      List<? extends Variant> variants = cs.getVariants(entity.getClass(), null);
      requestEntity =
          toRepresentation(entity, clientInfo.getPreferredVariant(variants, getMetadataService()));
    }

    result = toObject(handle(method, requestEntity, clientInfo), resultClass);
    return result;
  }
  /**
   * Returns the client-specific information.
   *
   * @return The client-specific information.
   */
  @Override
  public ClientInfo getClientInfo() {
    ClientInfo result = super.getClientInfo();

    if (!this.clientAdded) {
      if (getHeaders() != null) {
        // Extract the header values
        String acceptMediaType = getHeaders().getValues(HeaderConstants.HEADER_ACCEPT);
        String acceptCharset = getHeaders().getValues(HeaderConstants.HEADER_ACCEPT_CHARSET);
        String acceptEncoding = getHeaders().getValues(HeaderConstants.HEADER_ACCEPT_ENCODING);
        String acceptLanguage = getHeaders().getValues(HeaderConstants.HEADER_ACCEPT_LANGUAGE);
        String acceptPatch = getHeaders().getValues(HeaderConstants.HEADER_ACCEPT_PATCH);
        String expect = getHeaders().getValues(HeaderConstants.HEADER_EXPECT);

        // Parse the headers and update the call preferences

        // Parse the Accept* headers. If an error occurs during the
        // parsing
        // of each header, the error is traced and we keep on with the
        // other
        // headers.
        try {
          PreferenceReader.addCharacterSets(acceptCharset, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        try {
          PreferenceReader.addEncodings(acceptEncoding, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        try {
          PreferenceReader.addLanguages(acceptLanguage, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        try {
          PreferenceReader.addMediaTypes(acceptMediaType, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        try {
          PreferenceReader.addPatches(acceptPatch, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        try {
          ExpectationReader.addValues(expect, result);
        } catch (Exception e) {
          this.context.getLogger().log(Level.INFO, e.getMessage());
        }

        // Set other properties
        result.setAgent(getHeaders().getValues(HeaderConstants.HEADER_USER_AGENT));
        result.setFrom(getHeaders().getFirstValue(HeaderConstants.HEADER_FROM, true));
        result.setAddress(getConnection().getAddress());
        result.setPort(getConnection().getPort());

        if (userPrincipal != null) {
          result.getPrincipals().add(userPrincipal);
        }

        if (this.context != null) {
          // Special handling for the non standard but common
          // "X-Forwarded-For" header.
          final boolean useForwardedForHeader =
              Boolean.parseBoolean(
                  this.context.getParameters().getFirstValue("useForwardedForHeader", false));
          if (useForwardedForHeader) {
            // Lookup the "X-Forwarded-For" header supported by
            // popular
            // proxies and caches.
            final String header = getHeaders().getValues(HeaderConstants.HEADER_X_FORWARDED_FOR);
            if (header != null) {
              final String[] addresses = header.split(",");
              for (int i = 0; i < addresses.length; i++) {
                String address = addresses[i].trim();
                result.getForwardedAddresses().add(address);
              }
            }
          }
        }
      }

      this.clientAdded = true;
    }

    return result;
  }
 /**
  * Adds values to the given collection.
  *
  * @param header The header to read.
  * @param clientInfo The client info to update.
  */
 public static void addValues(String header, ClientInfo clientInfo) {
   if (header != null) {
     new ExpectationReader(header).addValues(clientInfo.getExpectations());
   }
 }