/**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    String propertyFilePath = args.length > 0 ? args[0] : "jeevlet.properties";

    // Get configuration
    int listenPort =
        Integer.parseInt(ConfigUtils.getProps(propertyFilePath).getProperty(Config.LISTEN_PORT));
    String hostDomain = ConfigUtils.getProps(propertyFilePath).getProperty(Config.HOST_DOMAIN);

    // Prepare the request
    String url = "http://" + hostDomain + ":" + listenPort + "/";
    Request request = new Request(Method.GET, url);
    request.setEntity(Config.STOP_GEONETWORK, MediaType.TEXT_PLAIN);

    // Handle it using an HTTP client connector
    Client client = new Client(Protocol.HTTP);

    try {
      client.start();
      Response response = client.handle(request);
    } catch (Exception e) {
      System.err.println("ERROR: Not running!");
      e.printStackTrace();
    } finally {
      client.stop();
      System.out.println("GeoNetwork shutdown ...");
      System.exit(0);
    }
  }
  /**
   * Tests partial Get requests.
   *
   * @throws IOException
   * @throws NoSuchAlgorithmException
   */
  @Test
  public void testGet() throws IOException, NoSuchAlgorithmException {
    Client client = new Client(Protocol.HTTP);

    // Test partial Get.
    Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/");
    StringRepresentation rep = new StringRepresentation("0123456789");
    try {
      DigesterRepresentation digester = new DigesterRepresentation(rep);
      // Such representation computes the digest while
      // consuming the wrapped representation.
      digester.exhaust();
      // Set the digest with the computed one
      digester.setDigest(digester.computeDigest());
      request.setEntity(digester);

      Response response = client.handle(request);

      assertEquals(Status.SUCCESS_OK, response.getStatus());
      digester = new DigesterRepresentation(response.getEntity());
      digester.exhaust();
      assertTrue(digester.checkDigest());

      client.stop();
    } catch (Exception e) {
      fail(e.getMessage());
    }
  }
 /**
  * Creates an uniform call.
  *
  * @param jdbcURI The database's JDBC URI (ex: jdbc:mysql://[hostname]/[database]).
  * @param request The request to send (valid XML request).
  */
 public static Request create(String jdbcURI, Representation request) {
   Request result = new Request();
   result.getClientInfo().setAgent(Engine.VERSION_HEADER);
   result.setMethod(Method.POST);
   result.setResourceRef(jdbcURI);
   result.setEntity(request);
   return result;
 }
Beispiel #4
0
  /**
   * Allows filtering before its handling by the target Restlet. Does nothing by default.
   *
   * @param request The request to filter.
   * @param response The response to filter.
   * @return The continuation status.
   */
  @Override
  public int beforeHandle(Request request, Response response) {
    // Check if encoding of the request entity is needed
    if (isEncodingRequest() && canEncode(request.getEntity())) {
      request.setEntity(encode(request.getClientInfo(), request.getEntity()));
    }

    return CONTINUE;
  }
  private Request createRequest(Reference reference, Representation representation) {
    if (reference != null) {
      Request request = new Request();
      request.setResourceRef(reference);
      if (representation != null) {
        request.setEntity(representation);
      }

      return request;
    }

    throw new RepositoryException("Reference object is null!");
  }
 @Override
 public void init(Context context, Request request, Response response) {
   // System.out.println("init" + request + " " + response);
   // System.out.println("Content-Type: " +
   // request.getEntity().getMediaType());
   if (request.getMethod().compareTo(Method.GET) == 0) {
     Representation entity = request.getEntity();
     System.out.println(
         "Entity " + entity + " Content-Type: " + request.getEntity().getMediaType());
     request.setEntity(new StringRepresentation(""));
   }
   super.init(context, request, response);
 }
  public void testPost2() throws Exception {
    String aparam =
        "{'aradon':"
            + "[{'name':'employee','section':'system','path':'/lore/test/ion.dev.floor4/3477','param':{'empno':'3477','ename':'ddd','address':'ddd','sal':'20','dept':'ddd','memo':'222','aradon.result.method':'post', 'aradon.result.format':'json'}}, "
            + " {'name':'indexer','section':'system','path':'/index/ion.dev.floor4/3477','param':{'empno':'3477','ename':'ddd','address':'ddd','sal':'20','dept':'ddd','memo':'222','aradon.result.method':'post', 'aradon.result.format':'json'}}"
            + "]}";
    Request request = new Request(Method.POST, prefixURL);
    Form form = new Form();
    form.add("aradon.parameter", aparam);
    request.setEntity(form.getWebRepresentation());

    handle("resource/config/aradon-config.xml", request);
  }
  public void testLetsGet() throws Exception {
    String aparam =
        "{aradon:"
            + "[{name:'abcd',  section:'system', path:'/repository/bulletin.bleujin', param:{p1:'abc', p2:'${sequence.result.nodes[0].currval}', p3:['red','green','white'], modified:'${currdate.result.nodes[0].now}', 'aradon.result.format':'json', 'aradon.result.method':'get'}, page:{pageNo:1, listNum:10, screenCount:1}}, "
            + " {name:'sequence', section:'system', path:'/sequence/myseq', param:{'aradon.result.format':'json', 'aradon.result.method':'put'}}, "
            + " {name:'currdate', section:'system', path:'/utils/datetime', param:{'aradon.result.format':'json', 'aradon.result.method':'get'}}"
            + "]}";
    Request request = new Request(Method.POST, prefixURL);
    Form form = new Form();
    form.add("aradon.parameter", aparam);
    request.setEntity(form.getWebRepresentation());

    handle("resource/config/aradon-config.xml", request);
  }
  public void testLetsPost() throws Exception {
    String aparam =
        "{aradon:"
            + "[{name:'board',  	section:'system', path:'/repository/bulletin.bleujin', param:{subject:'HiHi This is Let', content:'11월엔 투피어', boardid:'board1', reguserid:'bleujin', no:'${sequence.result.nodes[0].currval}',  modified:'${currdate.result.nodes[0].now}', 'aradon.result.format':'json', 'aradon.result.method':'post', 'aradon.page.pageNo':1, 'aradon.page.listNum':10, 'aradon.page.screenCount':10}}, "
            + " {name:'sequence', section:'system', path:'/sequence/bulletin.bleujin', param:{'aradon.result.format':'json', 'aradon.result.method':'put'}}, "
            + " {name:'currdate', section:'system', path:'/utils/datetime', param:{'aradon.result.format':'json', 'aradon.result.method':'get'}}"
            + "]}";

    Request request = new Request(Method.POST, prefixURL);
    Form form = new Form();
    form.add("aradon.parameter", aparam);
    request.setEntity(form.getWebRepresentation());

    handle("resource/config/aradon-config.xml", request);
  }
  /** @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());
  }
  @Test
  public void testPutTriple() throws Exception {
    final Client client = new Client(Protocol.HTTP);
    final Reference reference = new Reference("http://localhost/clue/triples");
    reference.setHostPort(port);

    final Request request = new Request(Method.PUT, reference);
    request.setChallengeResponse(getChallengeResponse());

    final Weapon weapon = WeaponEnum.CANDLESTICK.getWeapon();
    final Suspect suspect = SuspectEnum.PEACOCK.getSuspect();
    final Room room = RoomEnum.BILLIARDROOM.getRoom();

    request.setEntity(new JacksonRepresentation<Triple>(new Triple(room, suspect, weapon)));
    System.out.println(request.getEntityAsText());
    client.handle(request);

    assertEquals(323, getRemainingCount());
  }
Beispiel #12
0
  /**
   * Handles the call by cloning the prototype request, setting the method and entity.
   *
   * @param method The request method to use.
   * @param entity The request entity to set.
   * @param clientInfo The client preferences.
   * @return The optional response entity.
   */
  private Representation handle(Method method, Representation entity, ClientInfo clientInfo) {
    Representation result = null;

    // Prepare the request by cloning the prototype request
    Request request = new Request(getRequest());
    request.setMethod(method);
    request.setEntity(entity);
    request.setClientInfo(clientInfo);

    // Actually handle the call
    Response response = handle(request);

    if (response.getStatus().isError()) {
      throw new ResourceException(response.getStatus());
    } else {
      result = (response == null) ? null : response.getEntity();
    }

    return result;
  }
 /**
  * Decodes form parameters that are sent double encoded by performing one decode step on their
  * values, if their restlet framework decoded value starts with an "%".
  *
  * @param request a restlet request
  * @throws IOException did not occur during tests but may.
  * @throws IllegalArgumentException if an Encode representation is received.
  */
 void decodeFormParamsIfDoubleEncoded(Request request) throws IOException {
   Representation r = request.getEntity();
   if (r instanceof EncodeRepresentation)
     throw new IllegalArgumentException(
         "Received an Encode representation."
             + " This filter must be after the Encoder filter. please check your filter chain order.");
   if (!(r instanceof EmptyRepresentation)) {
     ContentType c = new ContentType(r);
     if (MediaType.APPLICATION_WWW_FORM.equals(c.getMediaType(), true)) {
       Form form = new Form(r);
       Form newform = new Form(r);
       Map<String, String> valuesMap = form.getValuesMap();
       for (Map.Entry<String, String> e : valuesMap.entrySet()) {
         if (DBG) ThreadLocalStopwatch.now("" + e.getKey() + " - " + e.getValue());
         String shouldBeDecodedValue = e.getValue();
         if (shouldBeDecodedValue.startsWith("%")) {
           shouldBeDecodedValue = URLDecoder.decode(e.getValue(), DECODER_CHAR_SET);
           totalDecodings.incrementAndGet();
           if (DBG) {
             ThreadLocalStopwatch.now("DECODED " + request.getResourceRef());
             ThreadLocalStopwatch.now(
                 "DECODED "
                     + totalDecodings.get()
                     + " : "
                     + e.getKey()
                     + " - "
                     + shouldBeDecodedValue);
           }
         }
         newform.add(e.getKey(), shouldBeDecodedValue);
       }
       // we must always set the entity, because above getEntitiy call causes
       // NPEs later if repeated by the framework.
       request.setEntity(newform.encode(), c.getMediaType());
     }
   }
 }
  /**
   * Requests the target resource.
   *
   * @param resolver The data model that provides parameters value.
   * @throws ResourceException
   */
  protected void callTarget(Resolver<String> resolver) throws ResourceException {
    // A - Build the request for the target resource
    final Method method = getTargetMethod(resolver);

    final Reference targetRef = getTargetRef(resolver);

    final Request request = new Request(method, targetRef);
    final ChallengeResponse challengeResponse = getTargetChallengeResponse(resolver);
    if (challengeResponse != null) {
      request.setChallengeResponse(challengeResponse);
    }

    if (isTargetEntityEnabled()) {
      request.setEntity(getTargetEntity(resolver));
    }

    // B - Call the target resource
    final Response response = getContext().getClientDispatcher().handle(request);

    if (!response.getStatus().isSuccess()) {
      throw new ResourceException(
          Status.SERVER_ERROR_INTERNAL, "Call to the target resource didn't succeed");
    }
  }
 @Override
 public void applyParameters(Request request) {
   Representation rep = new MultipartRepresentation(getParameters(), FORM);
   request.setEntity(rep);
 }
Beispiel #16
0
  /**
   * Handle the call and follow redirection for safe methods.
   *
   * @param request The request to send.
   * @param response The response to update.
   * @param references The references that caused a redirection to prevent infinite loops.
   * @param retryAttempt The number of remaining attempts.
   * @param next The next handler handling the call.
   */
  private void handle(
      Request request,
      Response response,
      List<Reference> references,
      int retryAttempt,
      Uniform next) {
    if (next != null) {
      // Actually handle the call
      next.handle(request, response);

      // Check for redirections
      if (isFollowingRedirects()
          && response.getStatus().isRedirection()
          && (response.getLocationRef() != null)) {
        boolean doRedirection = false;

        if (request.getMethod().isSafe()) {
          doRedirection = true;
        } else {
          if (Status.REDIRECTION_SEE_OTHER.equals(response.getStatus())) {
            // The user agent is redirected using the GET method
            request.setMethod(Method.GET);
            request.setEntity(null);
            doRedirection = true;
          } else if (Status.REDIRECTION_USE_PROXY.equals(response.getStatus())) {
            doRedirection = true;
          }
        }

        if (doRedirection) {
          Reference newTargetRef = response.getLocationRef();

          if ((references != null) && references.contains(newTargetRef)) {
            getLogger().warning("Infinite redirection loop detected with URI: " + newTargetRef);
          } else if (request.getEntity() != null && !request.isEntityAvailable()) {
            getLogger()
                .warning(
                    "Unable to follow the redirection because the request entity isn't available anymore.");
          } else {
            if (references == null) {
              references = new ArrayList<Reference>();
            }

            // Add to the list of redirection reference
            // to prevent infinite loops
            references.add(request.getResourceRef());
            request.setResourceRef(newTargetRef);
            handle(request, response, references, 0, next);
          }
        }
      } else if (isRetryOnError()
          && response.getStatus().isRecoverableError()
          && request.getMethod().isIdempotent()
          && (retryAttempt < getRetryAttempts())
          && ((request.getEntity() == null) || request.getEntity().isAvailable())) {
        getLogger()
            .log(
                Level.INFO,
                "A recoverable error was detected ("
                    + response.getStatus().getCode()
                    + "), attempting again in "
                    + getRetryDelay()
                    + " ms.");

        // Wait before attempting again
        if (getRetryDelay() > 0) {
          try {
            Thread.sleep(getRetryDelay());
          } catch (InterruptedException e) {
            getLogger().log(Level.FINE, "Retry delay sleep was interrupted", e);
          }
        }

        // Retry the call
        handle(request, response, references, ++retryAttempt, next);
      }
    }
  }
 @Override
 public void setEntity(Representation entity) {
   super.setEntity(entity);
   this.entityAdded = true;
 }
  /**
   * Tests partial Put requests.
   *
   * @throws Exception
   */
  public void testPut() throws Exception {
    if (!SystemUtils.isWindows()) {
      Request request;
      Response response;

      BioUtils.delete(testDir, true);
      Client client = new Client(new Context(), Protocol.HTTP);
      client.getContext().getParameters().add("tracing", "true");

      // PUT on a file that does not exist
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("1234567890"));
      request.setRanges(Arrays.asList(new Range(0, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("1234567890", response.getEntity().getText());

      // Partial PUT on a file, the provided representation overflowed the
      // existing file
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      System.out.println(response.getStatus() + " / " + response.getStatus().getThrowable());
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10000000000", response.getEntity().getText());

      // Partial PUT on a file that does not exists, the provided range
      // does not start at the 0 index.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai2.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("0000000000", response.getEntity().getText());

      // Partial PUT on a file, simple range
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("22"));
      request.setRanges(Arrays.asList(new Range(2, 2)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000000", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // at the very end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000888", response.getEntity().getText());

      // Partial PUT on a file that does not exist, the range does not
      // specify the range size.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai3.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("888", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // just before the end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("99"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000998", response.getEntity().getText());

      request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("20000998", response.getEntity().getText());

      BioUtils.delete(testDir, true);
      client.stop();
    }
  }