/**
  * 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;
 }
  /** 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);
  }
예제 #3
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);
  }
예제 #4
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();
  }
 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");
 }
예제 #6
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;
  }
  /** 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.");
  }
  @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
    }
  }
예제 #10
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;
  }
예제 #11
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;
  }
  @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));
  }
  @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;
  }
  @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;
  }
예제 #16
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());
    }
  }
  /**
   * 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;
  }
 protected void configureSslClientParameters(Context context) {
   Series<Parameter> parameters = context.getParameters();
   parameters.add("truststorePath", testKeystoreFile.getPath());
   parameters.add("truststorePassword", "testtest");
 }