/**
  * Creates the media type of a multipart form which must include the used boundary.
  *
  * @param boundary The multipart boundary.
  * @return The multipart media type.
  */
 private static MediaType createMultipartMediaType(String boundary) {
   Series<Parameter> params = new Series<Parameter>(Parameter.class);
   params.add("boundary", boundary);
   MediaType result = new MediaType(MediaType.MULTIPART_FORM_DATA.getName(), params);
   return result;
 }
示例#2
0
  /**
   * Returns the list of request headers.
   *
   * @return The list of request headers.
   */
  @Override
  public Series<Header> getRequestHeaders() {
    final Series<Header> result = super.getRequestHeaders();

    if (!this.requestHeadersAdded) {
      // Copy the headers from the request object
      String headerName;
      String headerValue;

      for (Enumeration<String> names = getConnection().getRequestFields().getFieldNames();
          names.hasMoreElements(); ) {
        headerName = names.nextElement();

        for (Enumeration<String> values = getConnection().getRequestFields().getValues(headerName);
            values.hasMoreElements(); ) {
          headerValue = values.nextElement();
          result.add(headerName, headerValue);
        }
      }

      this.requestHeadersAdded = true;
    }

    return result;
  }
示例#3
0
  public static void main(String[] args) throws Exception {
    // Create and configure HTTPS client
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", "certs/client-truststore.jks");
    parameters.add("truststorePassword", "password");
    parameters.add("truststoreType", "JKS");

    // Create and configure client resource
    ClientResource clientResource =
        new ClientResource("https://localhost:8183/accounts/chunkylover53/mails/123");
    clientResource.setNext(client);

    // Preemptively configure the authentication credentials
    ChallengeResponse authentication =
        new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "chunkylover53", "pwd");
    clientResource.setChallengeResponse(authentication);

    // Communicate with remote resource
    MailResource mailClient = clientResource.wrap(MailResource.class);
    Mail m = mailClient.retrieve();
    System.out.println("Subject: " + m.getSubject());
    System.out.println("Content: " + m.getContent());

    // Store HTTPS client
    client.stop();
  }
示例#4
0
  @Override
  protected int beforeHandle(Request request, Response response) {
    if (Method.OPTIONS.equals(request.getMethod())) {
      Series<Header> requestHeaders =
          (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
      String origin = requestHeaders.getFirstValue("Origin", false, "*");
      String rh = requestHeaders.getFirstValue("Access-Control-Request-Headers", false, "*");
      Series<Header> responseHeaders =
          (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
      if (responseHeaders == null) {
        responseHeaders = new Series<Header>(Header.class);
      }
      responseHeaders.add("Access-Control-Allow-Origin", origin);
      responseHeaders.set("Access-Control-Expose-Headers", "Authorization, Link");
      responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
      responseHeaders.add("Access-Control-Allow-Headers", rh);
      responseHeaders.add("Access-Control-Allow-Credentials", "true");
      responseHeaders.add("Access-Control-Max-Age", "60");
      response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
      response.setEntity(new EmptyRepresentation());
      return SKIP;
    }

    return super.beforeHandle(request, response);
  }
示例#5
0
  @Override
  public synchronized void start() throws Exception {
    // restlet servlet engine will pass parameters from web.xml via the context parameters
    Series<Parameter> parameters = getContext().getParameters();
    dataSource = PSCPDataSource.createDataSource(parameters);
    daoFactory = PGDaoFactory.createPGDaoFactory(dataSource);
    lookupCache = new LookupCache(daoFactory);
    secretResolver = new SecretResolver();
    adminPage = parameters.getFirstValue("pscp.web.admin");
    urls = new URLS(adminPage);
    // links out to website
    urls.putStatic(
        new Template(getSlashedURL(parameters, "pscp.web.products")), URLS.Name.PRODUCT_LOCATION);
    urls.putStatic(
        new Template(getSlashedURL(parameters, "pscp.web.root")), URLS.Name.STATIC_MEDIA);

    // @todo how to deal with this?
    baseURIs = new ArrayList<String>(Arrays.asList("localhost:8080"));

    Map<String, Object> contextAttributes = getContext().getAttributes();
    contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_DAO_FACTORY, daoFactory);
    contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_URL_MAPPER, urls);
    contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_LOOKUP_CACHE, lookupCache);
    contextAttributes.put(
        BaseResource.CONTEXT_ATTRIBUTE_PRODUCT_ROOT,
        getRootDir(BaseResource.CONTEXT_ATTRIBUTE_PRODUCT_ROOT, "pscp-products"));
    contextAttributes.put(
        BaseResource.CONTEXT_ATTRIBUTE_UPLOAD_ROOT,
        getRootDir(BaseResource.CONTEXT_ATTRIBUTE_UPLOAD_ROOT, "pscp-uploads"));

    super.start();
  }
  @SuppressWarnings("unchecked")
  public void testUnmodifiable() {
    Form form = new Form();
    form.add("name1", "value1");

    try {
      Series<Parameter> unmodifiableForm = (Series<Parameter>) Series.unmodifiableSeries(form);
      unmodifiableForm.add("name2", "value2");
      fail("The series should be unmodifiable now");
    } catch (UnsupportedOperationException uoe) {
      // As expected
    }
  }
示例#7
0
  /**
   * Returns the modifiable list of response headers.
   *
   * @return The modifiable list of response headers.
   */
  @Override
  public Series<Parameter> getResponseHeaders() {
    final Series<Parameter> result = super.getResponseHeaders();

    if (!this.responseHeadersAdded) {
      for (final Header header : getHttpMethod().getResponseHeaders()) {
        result.add(header.getName(), header.getValue());
      }

      this.responseHeadersAdded = true;
    }

    return result;
  }
  // TODO The secret should be a char[].
  private Representation doNoneFlow(
      String clientId, String clientSecret, Series<Parameter> params) {
    Client client = validate(clientId, clientSecret);

    // null check on failed
    if (client == null) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_client, "Client id verification failed.", null);
    }

    if (!client.containsUser(AUTONOMOUS_USER)) {
      client.createUser(AUTONOMOUS_USER);
    }

    AuthenticatedUser user = client.findUser(AUTONOMOUS_USER);

    // Adding all scopes since super-user
    // String[] scopes = parseScope(params.getFirstValue(SCOPE));
    List<Role> roles = Scopes.toRoles(params.getFirstValue(SCOPE));
    for (Role r : roles) {
      getLogger().fine("Requested scopes none flow = " + roles);
      user.addRole(r, "");
      getLogger().fine("Adding scope = " + r.getName() + " to auto user");
    }

    Token token = this.generator.generateToken(user, this.tokenTimeSec);
    JSONObject body = createJsonToken(token, null); // Scopes N/A

    // Sets the no-store Cache-Control header
    getResponse().setCacheDirectives(noStore);
    return new JsonStringRepresentation(body);
  }
示例#9
0
 private String getSlashedURL(Series<Parameter> params, String key) {
   String url = params.getFirstValue(key);
   if (url.indexOf('?') < 0 && !url.endsWith("/")) {
     url = url + "/";
   }
   return url;
 }
  // TODO The secret should be a char[].
  private Representation doAuthCodeFlow(
      String clientId, String clientSecret, Series<Parameter> params)
      throws IllegalArgumentException {
    String redirUri = params.getFirstValue(REDIR_URI);

    if ((redirUri == null) || (redirUri.length() == 0)) {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return sendError(
          OAuthError.invalid_request, "Mandatory parameter redirect_uri is missing", null);
    }

    String code = params.getFirstValue(CODE);
    if ((code == null) || (code.length() == 0)) {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return sendError(OAuthError.invalid_request, "Mandatory parameter code is missing", null);
    }

    Client client = validate(clientId, clientSecret);
    // null check on failed
    if (client == null) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_request, "Client id verification failed.", null);
    }

    // check the client secret
    if (!clientSecret.equals(client.getClientSecret())) {
      setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
      return sendError(OAuthError.invalid_request, "Client secret did not match", null);
    }

    // TODO could add a cookie match on the owner but could fail if code is
    // sent to other entity
    // unauthorized_client, right now this is only performed if
    // ScopedResource getOwner returns the user

    // 5 min timeout on tokens, 0 for unlimited
    Token token = generator.exchangeForToken(code, tokenTimeSec);

    // TODO send back scopes if limited

    JSONObject body = createJsonToken(token, null);

    // Sets the no-store Cache-Control header
    getResponse().setCacheDirectives(noStore);
    return new JsonStringRepresentation(body);
  }
  /**
   * Creates a content type.
   *
   * @param mediaType The media type name.
   * @param parameters The parameters parsed.
   * @return The content type.
   */
  private ContentType createContentType(StringBuilder mediaType, Series<Parameter> parameters) {
    // Attempt to extract the character set
    CharacterSet characterSet = null;

    if (parameters != null) {
      String charSet = parameters.getFirstValue("charset");

      if (charSet != null) {
        parameters.removeAll("charset");
        characterSet = new CharacterSet(charSet);
      }

      return new ContentType(new MediaType(mediaType.toString(), parameters), characterSet);
    }

    return new ContentType(new MediaType(mediaType.toString()), null);
  }
  @Override
  public void formatResponse(
      ChallengeWriter cw,
      ChallengeResponse challenge,
      Request request,
      Series<Header> httpHeaders) {

    // Setup the Date header
    String date = "";

    if (httpHeaders.getFirstValue("x-ms-date", true) == null) {
      // X-ms-Date header didn't override the standard Date header
      date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true);

      if (date == null) {
        // Add a fresh Date header
        date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123.get(0));
        httpHeaders.add(HeaderConstants.HEADER_DATE, date);
      }
    } else {
      date = httpHeaders.getFirstValue("x-ms-date", true);
    }

    // Setup the canonicalized path
    String canonicalizedResource = getCanonicalizedResourceName(request.getResourceRef());

    // Setup the message part
    StringBuilder rest = new StringBuilder();
    rest.append(date)
        .append('\n')
        .append('/')
        .append(challenge.getIdentifier())
        .append(canonicalizedResource);

    // Append the SharedKey credentials
    cw.append(challenge.getIdentifier())
        .append(':')
        .append(
            Base64.encode(
                DigestUtils.toHMacSha256(rest.toString(), Base64.decode(challenge.getSecret())),
                true));
  }
  /** Test references that are unequal. */
  public void testUnEquals() throws Exception {
    MediaType mt1 = new MediaType("application/xml");
    MediaType mt2 = new MediaType("application/xml2");
    assertFalse(mt1.equals(mt2));

    final Series<Parameter> mediaParams1 = new Form();
    mediaParams1.add(new Parameter("charset", "ISO-8859-1"));
    final MediaType mt1Bis = new MediaType("application/xml", mediaParams1);

    final Series<Parameter> mediaParams3 = new Form();
    mediaParams3.add(new Parameter("charset", "ISO-8859-15"));
    final MediaType mt3 = new MediaType("application/xml", mediaParams3);

    assertFalse(mt1Bis.equals(mt1));
    assertFalse(mt1Bis.equals(mt3));

    mt1 = new MediaType("application/1");
    mt2 = MediaType.APPLICATION_ALL;
    assertFalse(mt1.equals(mt2));
  }
  private void sendXRDSLocation() {
    ConcurrentMap<String, Object> attribs = getContext().getAttributes();
    String id = getQuery().getFirstValue("id");
    String xrds = attribs.get("xrds").toString();
    String location = (id != null) ? xrds + "?id=" + id : xrds;
    getLogger().info("XRDS endpoint = " + xrds);

    @SuppressWarnings("unchecked")
    Series<Header> headers =
        (Series<Header>) getResponse().getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);

    if (headers == null) {
      headers = new Series<Header>(Header.class);
      headers.add("X-XRDS-Location", location);
      getResponse().getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headers);
    } else {
      headers.add("X-XRDS-Location", location);
    }

    getLogger().info("Sending empty representation.");
  }
  /** Equality tests. */
  public void testEquals() throws Exception {
    MediaType mt1 = new MediaType("application/xml");
    MediaType mt2 = MediaType.APPLICATION_XML;
    assertTrue(mt1.equals(mt2));
    assertEquals(mt1, mt2);

    final Series<Parameter> mediaParams1 = new Form();
    mediaParams1.add(new Parameter("charset", "ISO-8859-1"));
    final MediaType mt1Bis = new MediaType("application/xml", mediaParams1);

    final Series<Parameter> mediaParams2 = new Form();
    mediaParams2.add(new Parameter("charset", "ISO-8859-1"));
    final MediaType mt2Bis = new MediaType("application/xml", mediaParams2);

    final Series<Parameter> mediaParams3 = new Form();
    mediaParams3.add(new Parameter("charset", "ISO-8859-15"));
    final MediaType mt3 = new MediaType("application/xml", mediaParams3);

    assertTrue(mt1Bis.equals(mt2Bis));
    assertEquals(mt1, mt2);
    assertTrue(mt1Bis.equals(mt1, true));
    assertTrue(mt1Bis.equals(mt2, true));
    assertTrue(mt1Bis.equals(mt3, true));

    mt1 = new MediaType("application/*");
    mt2 = MediaType.APPLICATION_ALL;
    assertTrue(mt1.equals(mt2));
    assertEquals(mt1, mt2);
  }
  @Override
  public void parseRequest(
      ChallengeRequest challenge, Response response, Series<Header> httpHeaders) {
    String raw = challenge.getRawValue();

    if (raw != null && raw.length() > 0) {
      StringTokenizer st = new StringTokenizer(raw, ",");
      String realm = st.nextToken();

      if (realm != null && realm.length() > 0) {
        int eq = realm.indexOf('=');

        if (eq > 0) {
          String value = realm.substring(eq + 1).trim();
          // Remove the quotes, first and last after trim...
          challenge.setRealm(value.substring(1, value.length() - 1));
        }
      }

      Series<Parameter> params = new Form();

      while (st.hasMoreTokens()) {
        String param = st.nextToken();

        if (param != null && param.length() > 0) {
          int eq = param.indexOf('=');

          if (eq > 0) {
            String name = param.substring(0, eq).trim();
            String value = param.substring(eq + 1).trim();
            // Remove the quotes, first and last after trim...
            params.add(name, value.substring(1, value.length() - 1));
          }
        }
      }

      challenge.setParameters(params);
    }
  }
  /**
   * Extract the media parameters. Only leave as the quality parameter if found. Modifies the
   * parameters list.
   *
   * @param parameters All the preference parameters.
   * @return The media parameters.
   */
  protected Series<Parameter> extractMediaParams(Series<Parameter> parameters) {
    Series<Parameter> result = null;
    boolean qualityFound = false;
    Parameter param = null;

    if (parameters != null) {
      result = new Form();

      for (final Iterator<Parameter> iter = parameters.iterator();
          !qualityFound && iter.hasNext(); ) {
        param = iter.next();

        if (param.getName().equals("q")) {
          qualityFound = true;
        } else {
          iter.remove();
          result.add(param);
        }
      }
    }

    return result;
  }
 protected void configureSslServerParameters(Context context) {
   Series<Parameter> parameters = context.getParameters();
   parameters.add("keystorePath", testKeystoreFile.getPath());
   parameters.add("keystorePassword", "testtest");
   parameters.add("keyPassword", "testtest");
   parameters.add("truststorePath", testKeystoreFile.getPath());
   parameters.add("truststorePassword", "testtest");
   // parameters.add("tracing", "true");
 }
  // TODO The secret should be a char[].
  private Representation doPasswordFlow(
      String clientId, String clientSecret, Series<Parameter> params) {
    Client client = validate(clientId, clientSecret);

    // null check on failed
    if (client == null) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_client, "Client id verification failed.", null);
    }

    String username = params.getFirstValue(USERNAME);
    AuthenticatedUser user = null;

    if ((username == null) || ((user = client.findUser(username)) == null)) {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return sendError(OAuthError.invalid_request, "Mandatory parameter username missing.", null);
    }

    String password = params.getFirstValue(PASSWORD);

    if (password == null) {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return sendError(OAuthError.invalid_request, "Mandatory parameter password missing.", null);
    }

    if (!password.equals(user.getPassword())) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_grant, "Password not correct.", null);
    }

    Token token = this.generator.generateToken(user, this.tokenTimeSec);
    JSONObject body = createJsonToken(token, null); // Scopes N/A

    // Sets the no-store Cache-Control header
    getResponse().setCacheDirectives(noStore);
    return new JsonStringRepresentation(body);
  }
  @Post
  public Representation acceptItem(Representation entity) {
    logger.info("Attempting to delete a device");

    Series<Cookie> cookies = this.getRequest().getCookies();
    String parent_username = cookies.getFirstValue(COOKIE_USER);
    String auth_Token = cookies.getFirstValue(COOKIE_AUTH);

    if ((parent_username == null) || (auth_Token == null)) return null;

    User thisUser = new User(parent_username);

    // Is this a valid cookie?
    if (!thisUser.validateCookie(auth_Token)) return null;

    // Cookie is valid
    Form form = new Form(entity);
    String device_id = form.getFirstValue("deviceID");

    Device thisDevice = new Device(device_id);
    thisDevice.deleteDevice();

    return null;
  }
  // TODO The secret should be a char[].
  private Representation doRefreshFlow(
      String clientId, String clientSecret, Series<Parameter> params) {
    String rToken = params.getFirstValue(REFRESH_TOKEN);

    if ((rToken == null) || (rToken.length() == 0)) {
      setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return sendError(
          OAuthError.invalid_request, "Mandatory parameter refresh_token is missing", null);
    }

    Client client = validate(clientId, clientSecret);

    // null check on failed
    if (client == null) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_client, "Client id verification failed.", null);
    }

    Token token = generator.findToken(rToken);

    if ((token != null) && (token instanceof ExpireToken)) {
      AuthenticatedUser user = token.getUser();

      // Make sure that the user owning the token is owned by this client
      if (client.containsUser(user.getId())) {
        // refresh the token
        generator.refreshToken((ExpireToken) token);

        JSONObject body = createJsonToken(token, null); // Scopes N/A

        // Sets the no-store Cache-Control header
        getResponse().setCacheDirectives(noStore);
        return new JsonStringRepresentation(body);
      } else { // error not owner
        setStatus(Status.CLIENT_ERROR_FORBIDDEN);
        return sendError(OAuthError.unauthorized_client, "User does not match.", null);
      }
    } else { // error no such token.
      setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
      return sendError(OAuthError.invalid_grant, "Refresh token.", null);
    }
  }
  /**
   * Extract the quality value. If the value is not found, 1 is returned.
   *
   * @param parameters The preference parameters.
   * @return The quality value.
   */
  protected float extractQuality(Series<Parameter> parameters) {
    float result = 1F;
    boolean found = false;

    if (parameters != null) {
      Parameter param = null;
      for (final Iterator<Parameter> iter = parameters.iterator(); !found && iter.hasNext(); ) {
        param = iter.next();
        if (param.getName().equals("q")) {
          result = PreferenceUtils.parseQuality(param.getValue());
          found = true;

          // Remove the quality parameter as we will directly store it
          // in the Preference object
          iter.remove();
        }
      }
    }

    return result;
  }
示例#23
0
  @Override
  protected int doHandle(final Request request, final Response response) {
    int result = super.doHandle(request, response);

    Map<String, Object> requestAttributes = request.getAttributes();
    Map<String, Object> responseAttributes = response.getAttributes();
    Series<Header> requestHeaders =
        (Series<Header>)
            requestAttributes.computeIfAbsent(
                "org.restlet.http.headers", key -> new Series<Header>(Header.class));
    Series<Header> responseHeaders =
        (Series<Header>)
            responseAttributes.computeIfAbsent(
                "org.restlet.http.headers", key -> new Series<Header>(Header.class));
    // TODO fix me
    responseHeaders.add("Access-Control-Allow-Origin", requestHeaders.getFirstValue("Origin"));
    responseHeaders.add("Access-Control-Allow-Credentials", "true");
    responseHeaders.add(
        "Access-Control-Allow-Methods", "HEAD, GET, PUT, POST, DELETE, OPTIONS, TRACE");
    responseHeaders.add("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
    return result;
  }
  /**
   * Read the next preference.
   *
   * @return The next preference.
   */
  public Preference<T> readPreference() throws Exception {
    Preference<T> result = null;

    boolean readingMetadata = true;
    boolean readingParamName = false;
    boolean readingParamValue = false;

    final StringBuilder metadataBuffer = new StringBuilder();
    StringBuilder paramNameBuffer = null;
    StringBuilder paramValueBuffer = null;

    Series<Parameter> parameters = null;

    final String nextValue = readValue();
    int nextIndex = 0;

    if (nextValue != null) {
      int nextChar = nextValue.charAt(nextIndex++);

      while (result == null) {
        if (readingMetadata) {
          if (nextChar == -1) {
            if (metadataBuffer.length() > 0) {
              // End of metadata section
              // No parameters detected
              result = createPreference(metadataBuffer, null);
              paramNameBuffer = new StringBuilder();
            } else {
              // Ignore empty metadata name
            }
          } else if (nextChar == ';') {
            if (metadataBuffer.length() > 0) {
              // End of metadata section
              // Parameters detected
              readingMetadata = false;
              readingParamName = true;
              paramNameBuffer = new StringBuilder();
              parameters = new Form();
            } else {
              throw new Exception("Empty metadata name detected.");
            }
          } else if (HttpUtils.isSpace(nextChar)) {
            // Ignore spaces
          } else if (HttpUtils.isText(nextChar)) {
            metadataBuffer.append((char) nextChar);
          } else {
            throw new Exception("Control characters are not allowed within a metadata name.");
          }
        } else if (readingParamName) {
          if (nextChar == '=') {
            if (paramNameBuffer.length() > 0) {
              // End of parameter name section
              readingParamName = false;
              readingParamValue = true;
              paramValueBuffer = new StringBuilder();
            } else {
              throw new Exception("Empty parameter name detected.");
            }
          } else if (nextChar == -1) {
            if (paramNameBuffer.length() > 0) {
              // End of parameters section
              parameters.add(HttpUtils.createParameter(paramNameBuffer, null));
              result = createPreference(metadataBuffer, parameters);
            } else {
              throw new Exception("Empty parameter name detected.");
            }
          } else if (nextChar == ';') {
            // End of parameter
            parameters.add(HttpUtils.createParameter(paramNameBuffer, null));
            paramNameBuffer = new StringBuilder();
            readingParamName = true;
            readingParamValue = false;
          } else if (HttpUtils.isSpace(nextChar) && (paramNameBuffer.length() == 0)) {
            // Ignore white spaces
          } else if (HttpUtils.isTokenChar(nextChar)) {
            paramNameBuffer.append((char) nextChar);
          } else {
            throw new Exception("Separator and control characters are not allowed within a token.");
          }
        } else if (readingParamValue) {
          if (nextChar == -1) {
            if (paramValueBuffer.length() > 0) {
              // End of parameters section
              parameters.add(HttpUtils.createParameter(paramNameBuffer, paramValueBuffer));
              result = createPreference(metadataBuffer, parameters);
            } else {
              throw new Exception("Empty parameter value detected");
            }
          } else if (nextChar == ';') {
            // End of parameter
            parameters.add(HttpUtils.createParameter(paramNameBuffer, paramValueBuffer));
            paramNameBuffer = new StringBuilder();
            readingParamName = true;
            readingParamValue = false;
          } else if ((nextChar == '"') && (paramValueBuffer.length() == 0)) {
            // Parse the quoted string
            boolean done = false;
            boolean quotedPair = false;

            while ((!done) && (nextChar != -1)) {
              nextChar = (nextIndex < nextValue.length()) ? nextValue.charAt(nextIndex++) : -1;

              if (quotedPair) {
                // End of quoted pair (escape sequence)
                if (HttpUtils.isText(nextChar)) {
                  paramValueBuffer.append((char) nextChar);
                  quotedPair = false;
                } else {
                  throw new Exception(
                      "Invalid character detected in quoted string. Please check your value");
                }
              } else if (HttpUtils.isDoubleQuote(nextChar)) {
                // End of quoted string
                done = true;
              } else if (nextChar == '\\') {
                // Begin of quoted pair (escape sequence)
                quotedPair = true;
              } else if (HttpUtils.isText(nextChar)) {
                paramValueBuffer.append((char) nextChar);
              } else {
                throw new Exception(
                    "Invalid character detected in quoted string. Please check your value");
              }
            }
          } else if (HttpUtils.isTokenChar(nextChar)) {
            paramValueBuffer.append((char) nextChar);
          } else {
            throw new Exception("Separator and control characters are not allowed within a token");
          }
        }

        nextChar = (nextIndex < nextValue.length()) ? nextValue.charAt(nextIndex++) : -1;
      }
    }

    return result;
  }
  @Override
  public ContentType readValue() throws IOException {
    ContentType result = null;

    boolean readingMediaType = true;
    boolean readingParamName = false;
    boolean readingParamValue = false;

    StringBuilder mediaTypeBuffer = new StringBuilder();
    StringBuilder paramNameBuffer = null;
    StringBuilder paramValueBuffer = null;

    Series<Parameter> parameters = null;
    String nextValue = readRawValue();
    int nextIndex = 0;

    if (nextValue != null) {
      int nextChar = nextValue.charAt(nextIndex++);

      while (result == null) {
        if (readingMediaType) {
          if (nextChar == -1) {
            if (mediaTypeBuffer.length() > 0) {
              // End of metadata section
              // No parameters detected
              result = createContentType(mediaTypeBuffer, null);
              paramNameBuffer = new StringBuilder();
            } else {
              // Ignore empty metadata name
            }
          } else if (nextChar == ';') {
            if (mediaTypeBuffer.length() > 0) {
              // End of mediaType section
              // Parameters detected
              readingMediaType = false;
              readingParamName = true;
              paramNameBuffer = new StringBuilder();
              // [ifndef gwt] instruction
              parameters = new Series<Parameter>(Parameter.class);
              // [ifdef gwt] instruction uncomment
              // parameters = new
              // org.restlet.engine.util.ParameterSeries();
            } else {
              throw new IOException("Empty mediaType name detected.");
            }
          } else if (HeaderUtils.isSpace(nextChar)) {
            // Ignore spaces
          } else if (HeaderUtils.isText(nextChar)) {
            mediaTypeBuffer.append((char) nextChar);
          } else {
            throw new IOException(
                "The " + (char) nextChar + " character isn't allowed in a media type name.");
          }
        } else if (readingParamName) {
          if (nextChar == '=') {
            if (paramNameBuffer.length() > 0) {
              // End of parameter name section
              readingParamName = false;
              readingParamValue = true;
              paramValueBuffer = new StringBuilder();
            } else {
              throw new IOException("Empty parameter name detected.");
            }
          } else if (nextChar == -1) {
            if (paramNameBuffer.length() > 0) {
              // End of parameters section
              parameters.add(Parameter.create(paramNameBuffer, null));
              result = createContentType(mediaTypeBuffer, parameters);
            } else if (paramNameBuffer.length() == 0) {
              result = createContentType(mediaTypeBuffer, parameters);
            } else {
              throw new IOException("Empty parameter name detected.");
            }
          } else if (nextChar == ';') {
            // End of parameter
            parameters.add(Parameter.create(paramNameBuffer, null));
            paramNameBuffer = new StringBuilder();
            readingParamName = true;
            readingParamValue = false;
          } else if (HeaderUtils.isSpace(nextChar) && (paramNameBuffer.length() == 0)) {
            // Ignore white spaces
          } else if (HeaderUtils.isTokenChar(nextChar)) {
            paramNameBuffer.append((char) nextChar);
          } else {
            throw new IOException(
                "The \""
                    + (char) nextChar
                    + "\" character isn't allowed in a media type parameter name.");
          }
        } else if (readingParamValue) {
          if (nextChar == -1) {
            if (paramValueBuffer.length() > 0) {
              // End of parameters section
              parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer));
              result = createContentType(mediaTypeBuffer, parameters);
            } else {
              throw new IOException("Empty parameter value detected");
            }
          } else if (nextChar == ';') {
            // End of parameter
            parameters.add(Parameter.create(paramNameBuffer, paramValueBuffer));
            paramNameBuffer = new StringBuilder();
            readingParamName = true;
            readingParamValue = false;
          } else if ((nextChar == '"') && (paramValueBuffer.length() == 0)) {
            // Parse the quoted string
            boolean done = false;
            boolean quotedPair = false;

            while ((!done) && (nextChar != -1)) {
              nextChar = (nextIndex < nextValue.length()) ? nextValue.charAt(nextIndex++) : -1;

              if (quotedPair) {
                // End of quoted pair (escape sequence)
                if (HeaderUtils.isText(nextChar)) {
                  paramValueBuffer.append((char) nextChar);
                  quotedPair = false;
                } else {
                  throw new IOException(
                      "Invalid character \""
                          + (char) nextChar
                          + "\" detected in quoted string. Please check your value");
                }
              } else if (HeaderUtils.isDoubleQuote(nextChar)) {
                // End of quoted string
                done = true;
              } else if (nextChar == '\\') {
                // Begin of quoted pair (escape sequence)
                quotedPair = true;
              } else if (HeaderUtils.isText(nextChar)) {
                paramValueBuffer.append((char) nextChar);
              } else {
                throw new IOException(
                    "Invalid character \""
                        + (char) nextChar
                        + "\" detected in quoted string. Please check your value");
              }
            }
          } else if (HeaderUtils.isTokenChar(nextChar)) {
            paramValueBuffer.append((char) nextChar);
          } else {
            throw new IOException(
                "The \""
                    + (char) nextChar
                    + "\" character isn't allowed in a media type parameter value.");
          }
        }

        nextChar = (nextIndex < nextValue.length()) ? nextValue.charAt(nextIndex++) : -1;
      }
    }

    return result;
  }
 protected void configureSslClientParameters(Context context) {
   Series<Parameter> parameters = context.getParameters();
   parameters.add("truststorePath", testKeystoreFile.getPath());
   parameters.add("truststorePassword", "testtest");
 }
示例#27
0
  @Get
  @Override
  public Representation get() {
    try {
      // Info
      JSONObject info = new JSONObject();
      info.put("title", "Pinot Controller");
      info.put("version", "0.1");

      // Paths
      JSONObject paths = new JSONObject();
      Router router = ControllerRestApplication.router;
      RouteList routeList = router.getRoutes();

      for (Route route : routeList) {
        if (route instanceof TemplateRoute) {
          TemplateRoute templateRoute = (TemplateRoute) route;
          JSONObject pathObject = new JSONObject();
          String routePath = templateRoute.getTemplate().getPattern();

          // Check which methods are present
          Restlet routeTarget = templateRoute.getNext();
          if (routeTarget instanceof Finder) {
            Finder finder = (Finder) routeTarget;
            generateSwaggerForFinder(pathObject, routePath, finder);
          } else if (routeTarget instanceof Filter) {
            do {
              Filter filter = (Filter) routeTarget;
              routeTarget = filter.getNext();
            } while (routeTarget instanceof Filter);
            if (routeTarget instanceof Finder) {
              Finder finder = (Finder) routeTarget;
              generateSwaggerForFinder(pathObject, routePath, finder);
            }
          }

          if (pathObject.keys().hasNext()) {
            paths.put(routePath, pathObject);
          }
        }
      }

      // Tags
      JSONArray tags = new JSONArray();
      addTag(tags, "tenant", "Tenant-related operations");
      addTag(tags, "instance", "Instance-related operations");
      addTag(tags, "table", "Table-related operations");
      addTag(tags, "segment", "Segment-related operations");
      addTag(tags, "schema", "Schema-related operations");

      // Swagger
      JSONObject swagger = new JSONObject();
      swagger.put("swagger", "2.0");
      swagger.put("info", info);
      swagger.put("paths", paths);
      swagger.put("tags", tags);

      StringRepresentation representation = new StringRepresentation(swagger.toString());

      // Set up CORS
      Series<Header> responseHeaders =
          (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
      if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
      }
      responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
      return representation;
    } catch (JSONException e) {
      return new StringRepresentation(e.toString());
    }
  }
示例#28
0
  /**
   * Handles a PUT call by invoking the {@link #storeRepresentation(Representation)} method. It also
   * handles conditional PUTs and forbids partial PUTs as they are not supported yet. Finally, it
   * prevents PUT with no entity by setting the response status to {@link
   * Status#CLIENT_ERROR_BAD_REQUEST} following the HTTP specifications.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void handlePut() {
    boolean canPut = true;

    if (getRequest().getConditions().hasSome()) {
      Variant preferredVariant = null;

      if (isNegotiateContent()) {
        preferredVariant = getPreferredVariant();
      } else {
        final List<Variant> variants = getVariants();

        if (variants.size() == 1) {
          preferredVariant = variants.get(0);
        } else {
          getResponse().setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED);
          canPut = false;
        }
      }

      // The conditions have to be checked
      // even if there is no preferred variant.
      if (canPut) {
        final Status status =
            getRequest()
                .getConditions()
                .getStatus(getRequest().getMethod(), getRepresentation(preferredVariant));
        if (status != null) {
          getResponse().setStatus(status);
          canPut = false;
        }
      }
    }

    if (canPut) {
      // Check the Content-Range HTTP Header
      // in order to prevent usage of partial PUTs
      final Object oHeaders = getRequest().getAttributes().get("org.restlet.http.headers");
      if (oHeaders != null) {
        final Series<Parameter> headers = (Series<Parameter>) oHeaders;
        if (headers.getFirst("Content-Range", true) != null) {
          getResponse()
              .setStatus(
                  new Status(
                      Status.SERVER_ERROR_NOT_IMPLEMENTED,
                      "The Content-Range header is not understood"));
          canPut = false;
        }
      }
    }

    if (canPut) {
      if (getRequest().isEntityAvailable()) {
        put(getRequest().getEntity());

        // HTTP spec says that PUT may return
        // the list of allowed methods
        updateAllowedMethods();
      } else {
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Missing request entity");
      }
    }
  }