public void fixResolvedClasses() {
    for (Concept con : model.getConcepts()) {
      if (con.getResolvedAs() != Concept.Resolution.NONE) {
        if (con.getChosenProperties().size() > 0) {
          // This is very likely an extension/restriction of the original concept, so we need to
          // redefine it
          String extPack = model.getDefaultPackage() + "." + con.getPackage();
          model.removeConcept(con);
          Concept original = con.clone();
          original.getSubConcepts().clear();
          original.getSubConcepts().add(con);
          con.getSuperConcepts().clear();
          con.addSuperConcept(original);
          con.setChosenSuperConcept(original);
          con.setPackage(extPack);

          URI xuri = NameUtils.packageToNamespaceURI(extPack);
          con.setNamespace(xuri.toASCIIString());
          con.setIri(IRI.create(NameUtils.separatingName(xuri.toASCIIString()) + con.getName()));

          model.addConcept(con);
          model.addConcept(original);
        }
      }
    }
  }
  public String getString(String relativePath) throws IOException {
    URI uri = this.baseUri.resolve(relativePath);
    System.out.println("GET (String): " + uri.toASCIIString());

    InputStream in = null;
    InputStreamReader reader = null;
    HttpURLConnection connection = null;

    try {
      connection = (HttpURLConnection) uri.toURL().openConnection();
      connection.connect();
      if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
        String body = getPotentialBody(connection);
        String err =
            String.format(
                "GET request failed (%d %s) %s%n%s",
                connection.getResponseCode(),
                connection.getResponseMessage(),
                uri.toASCIIString(),
                body);
        throw new IOException(err);
      }
      in = connection.getInputStream();
      reader = new InputStreamReader(in);
      StringWriter writer = new StringWriter();
      IO.copy(reader, writer);
      return writer.toString();
    } finally {
      IO.close(reader);
      IO.close(in);
    }
  }
 @Override
 public void run() {
   byte[] buffer = new byte[4096];
   while (!this.stats.isComplete()) {
     HttpMethod httpmethod;
     if (this.content == null) {
       GetMethod httpget = new GetMethod(target.toASCIIString());
       httpmethod = httpget;
     } else {
       PostMethod httppost = new PostMethod(target.toASCIIString());
       httppost.setRequestEntity(new ByteArrayRequestEntity(content));
       httpmethod = httppost;
     }
     long contentLen = 0;
     try {
       httpclient.executeMethod(httpmethod);
       InputStream instream = httpmethod.getResponseBodyAsStream();
       if (instream != null) {
         int l = 0;
         while ((l = instream.read(buffer)) != -1) {
           contentLen += l;
         }
       }
       this.stats.success(contentLen);
     } catch (IOException ex) {
       this.stats.failure(contentLen);
     } finally {
       httpmethod.releaseConnection();
     }
   }
 }
  public Properties getProperties(String relativePath) throws IOException {
    URI uri = this.baseUri.resolve(relativePath);
    System.out.println("GET (Properties): " + uri.toASCIIString());

    InputStream in = null;
    HttpURLConnection connection = null;

    try {
      connection = (HttpURLConnection) uri.toURL().openConnection();
      connection.connect();
      if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
        String body = getPotentialBody(connection);
        String err =
            String.format(
                "GET request failed (%d %s) %s%n%s",
                connection.getResponseCode(),
                connection.getResponseMessage(),
                uri.toASCIIString(),
                body);
        throw new IOException(err);
      }
      in = connection.getInputStream();
      Properties props = new Properties();
      props.load(in);
      return props;
    } finally {
      IO.close(in);
    }
  }
 private String getURLForRegistration(String eventName) {
   try {
     URI uri = new URI("https", "festnimbus.herokuapp.com", "/api/user/" + eventName, null);
     Log.d("url", uri.toASCIIString());
     return uri.toASCIIString();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return "";
 }
 private void sendMail(
     HttpServletRequest request, BlogAuthor blogAuthor, Entity blog, Settings settings)
     throws IOException {
   if (settings.dontSendEmail()) {
     return;
   }
   try {
     String digest = DS.getBlogDigest(blog);
     MailService mailService = MailServiceFactory.getMailService();
     Message reply = new Message();
     reply.setSender(blogAuthor.toString());
     Email sender = (Email) blog.getProperty(SenderProperty);
     reply.setTo(sender.getEmail());
     String subject = (String) blog.getProperty(SubjectProperty);
     reply.setSubject("Blog: " + subject + " received");
     StringBuilder sb = new StringBuilder();
     URI reqUri = new URI(request.getScheme(), NamespaceManager.get(), "", "");
     if (!settings.isPublishImmediately()) {
       sb.append("<div>");
       sb.append(
           "<p>Blog is not yet published because it was sent from untrusted email address "
               + sender.getEmail()
               + ". </p>");
       URI publishUri =
           reqUri.resolve(
               "/blog?action=publish&blog="
                   + KeyFactory.keyToString(blog.getKey())
                   + "&auth="
                   + digest);
       sb.append("<a href=\"" + publishUri.toASCIIString() + "\">Publish Blog</a>");
       sb.append("</div>");
     }
     sb.append("<div>");
     sb.append("<p>If blog is not ok, you can delete and then resend it.</p>");
     URI deleteUri =
         reqUri.resolve(
             "/blog?action=remove&blog="
                 + KeyFactory.keyToString(blog.getKey())
                 + "&auth="
                 + digest);
     sb.append("<a href=\"" + deleteUri.toASCIIString() + "\">Delete Blog</a>");
     sb.append("</div>");
     reply.setHtmlBody(sb.toString());
     mailService.send(reply);
   } catch (URISyntaxException ex) {
     throw new IOException(ex);
   }
 }
Esempio n. 7
0
 public CachedHDFSBlob(URI uri, CachedHDFSBlobStoreConnection conn) {
   super(uri, conn);
   this.conn = conn;
   this.uri = uri;
   this.path = new Path(this.uri.toASCIIString());
   log.debug("opening blob " + uri.toASCIIString() + " at " + this.path.toString());
 }
  @Override
  public InputStream doGetSound4Word(String ch) {
    Log.i(TAG, "get sound for word:" + ch + " from googel translate.");
    try {
      final URI uri = new URI("http://translate.google.cn/translate_tts?tl=zh-CN&q=" + ch);
      final URL u = new URL(uri.toASCIIString());

      // this is the name of the local file you will create

      final HttpURLConnection connection = (HttpURLConnection) u.openConnection();
      connection.addRequestProperty("User-Agent", "Mozilla/5.0");
      connection.setRequestMethod("GET");
      connection.setDoOutput(true);
      connection.connect();
      final InputStream in = connection.getInputStream();
      return in;
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (ProtocolException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 9
0
  public static String encodeDocumentUrl(String urlString) {
    try {

      URL url = new URL(urlString);
      URI uri =
          new URI(
              url.getProtocol(),
              url.getUserInfo(),
              url.getHost(),
              url.getPort(),
              url.getPath(),
              url.getQuery(),
              url.getRef());

      return uri.toASCIIString();

    } catch (MalformedURLException e) {
      if (Log.LOGD)
        Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
      return null;
    } catch (URISyntaxException e) {
      if (Log.LOGD)
        Log.d(ExoUtils.class.getSimpleName(), e.getMessage(), Log.getStackTraceString(e));
      return null;
    }
  }
Esempio n. 10
0
  private String getDataStatus(String mTitle) {
    String title = mTitle;
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    System.out.println(
        Constant.WEBSERVICE_URL + Constant.WEBSERVICE_Category + "categorytitle=" + title);

    String url = "categorytitle=" + title;
    String text = null;

    try {

      URI uri = new URI("https", "www.sellyourtime.in", "/api/categories_count.php", url, null);
      String ll = uri.toASCIIString();
      HttpGet httpGet = new HttpGet(ll);

      try {
        HttpResponse response = httpClient.execute(httpGet, localContext);

        HttpEntity entity = response.getEntity();

        text = getASCIIContentFromEntity(entity);

      } catch (Exception e) {
        return e.getLocalizedMessage();
      }
    } catch (Exception e) {

    }

    return text;
  }
Esempio n. 11
0
  public void sendRequest(MetaInfo meta) {
    System.out.println(Thread.currentThread().getId() + " start sendRequest");
    URI uri = null;
    try {
      System.out.println(meta.getParams());
      uri = new URI(meta.getUrl());
    } catch (URISyntaxException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    String host = uri.getHost();
    int port = 80;

    HttpRequest request =
        new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString());
    meta.buildHttpRequestHeader(request);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    Channel channel = future.getChannel();
    channel.getPipeline().addLast("handler", new DownloaderHandler());
    GlobalVar.metaInfoVar.set(channel, meta);

    future.addListener(new ConnectOk(request));
    channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose());
    System.out.println(Thread.currentThread().getId() + " end sendRequest");
  }
Esempio n. 12
0
  private String getBookmarkJson(String deviceID) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();

    String url = "";
    String text = null;

    try {

      URI uri = new URI("http", "www.newsd.in", "/demo1/ws/special", url, null);
      String ll = uri.toASCIIString();

      System.out.println("BookMark URL" + ll);
      HttpGet httpGet = new HttpGet(ll);

      HttpResponse response = httpClient.execute(httpGet, localContext);
      HttpEntity entity = response.getEntity();
      text = getASCIIContentFromEntity(entity);
    } catch (Exception e) {
      System.out.println("in last catch block");
      e.printStackTrace();
      return e.getLocalizedMessage();
    }
    return text;
  }
  public Boolean updateBugzillaUserAsAdmin(BugzillaUser bugzillaUser) {
    setProperties();
    try {
      url =
          new URI(
              REST_UPDATE_USER_URL
                  + bugzillaUser.getEmail()
                  + "?Bugzilla_api_key="
                  + BUGZILLA_API_KEY);
      System.out.println("in update group " + url.toASCIIString());
      String userdate =
          "{\"name\" : \""
              + bugzillaUser.getEmail()
              + "\", \"groups\" : { \"set\" : [\"admin\"] }}";
      HttpEntity<?> requestEntity = new HttpEntity<Object>(userdate, createHeaders());
      System.out.println(userdate);
      ResponseEntity<String> responseEntity =
          getRestTemplate().exchange(url, HttpMethod.PUT, requestEntity, String.class);
      if (responseEntity.getBody() != null) {
        return true;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
Esempio n. 14
0
 public void start() throws InterruptedException, URISyntaxException {
   EventLoopGroup group = new NioEventLoopGroup();
   try {
     Bootstrap b = new Bootstrap();
     b.group(group).channel(NioSocketChannel.class);
     b.handler(
         new ChannelInitializer<Channel>() {
           @Override
           protected void initChannel(Channel ch) throws Exception {
             ChannelPipeline pipeline = ch.pipeline();
             pipeline.addLast("decoder", new RtspResponseDecoder());
             pipeline.addLast("encoder", new RtspRequestEncoder());
             pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 64));
             pipeline.addLast("handler", new ResponseHandler());
           }
         });
     b.option(ChannelOption.SO_KEEPALIVE, true);
     ChannelFuture channelFutrue = b.connect(host, port).sync();
     if (channelFutrue.isSuccess()) {
       channel = channelFutrue.channel();
       URI uri = new URI("rtsp://127.0.0.1:554/hello-world");
       HttpRequest request = this.buildOptionsRequest(uri.toASCIIString());
       this.send(request);
       channel.closeFuture().sync();
     }
   } finally {
     // 优雅退出,释放NIO线程组
     group.shutdownGracefully();
   }
 }
Esempio n. 15
0
 public static String quoteURIPathComponent(String s, boolean quoteSlash, boolean quoteAt) {
   if ("".equals(s)) {
     return s;
   }
   URI uri;
   try {
     // fake scheme so that a colon is not mistaken as a scheme
     uri = new URI("x", s, null);
   } catch (URISyntaxException e) {
     throw new IllegalArgumentException("Illegal characters in: " + s, e);
   }
   String r = uri.toASCIIString().substring(2);
   // replace reserved characters ;:$&+=?/[]@
   // FIXME: find a better way to do this...
   r = r.replace(";", "%3B");
   r = r.replace(":", "%3A");
   r = r.replace("$", "%24");
   r = r.replace("&", "%26");
   r = r.replace("+", "%2B");
   r = r.replace("=", "%3D");
   r = r.replace("?", "%3F");
   r = r.replace("[", "%5B");
   r = r.replace("]", "%5D");
   if (quoteAt) {
     r = r.replace("@", "%40");
   }
   if (quoteSlash) {
     r = r.replace("/", "%2F");
   }
   return r;
 }
  @Override
  public ODataEntitySet getODataEntitySet(final Feed resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
      final StringWriter writer = new StringWriter();
      client.getSerializer().feed(resource, writer);
      writer.flush();
      LOG.debug("Feed -> ODataEntitySet:\n{}", writer.toString());
    }

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final URI next = resource.getNext();

    final ODataEntitySet entitySet =
        next == null
            ? client.getObjectFactory().newEntitySet()
            : client.getObjectFactory().newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getCount() != null) {
      entitySet.setCount(resource.getCount());
    }

    for (Entry entryResource : resource.getEntries()) {
      entitySet.addEntity(getODataEntity(entryResource));
    }

    return entitySet;
  }
Esempio n. 17
0
  /**
   * Takes the extracted base URI and parameters from the {@link RequestConfig} consolidated
   * parameter type and creates a {@link HttpRequestBase} of the designated method type.
   *
   * @param uri the {@link URI} whose parameters should be populated
   * @param annotatedParams the list of {@link Param}s and the parameter objects which were
   *     annotated with them
   * @param staticParams the list of {@link Request.Param}s and the parameter objects which were
   *     annotated with them <br>
   *     <br>
   * @return the created {@link HttpRequestBase} which is an instance of {@link HttpGet} <br>
   *     <br>
   * @throws Exception when the {@link HttpRequestBase} could not be created due to an exception
   *     <br>
   *     <br>
   * @since 1.1.2
   */
  private static HttpRequestBase populateGetParameters(
      URI uri, Map<Object, Param> annotatedParams, List<Request.Param> staticParams)
      throws Exception {

    Uri.Builder uriBuilder = Uri.parse(uri.toASCIIString()).buildUpon();

    for (Request.Param param : staticParams)
      uriBuilder.appendQueryParameter(param.name(), param.value());

    Set<Entry<Object, Param>> methodParams = annotatedParams.entrySet();

    for (Entry<Object, Param> entry : methodParams) {

      if (!(entry.getKey() instanceof String)) {

        StringBuilder message = new StringBuilder();

        message.append("Parameters for GET requests can only be of type ");
        message.append(String.class.getName());
        message.append(
            "\nIf it is a complex type, consider overriding toString() "
                + "and providing a meaningful String representation");

        throw new IllegalArgumentException(message.toString());
      }

      uriBuilder.appendQueryParameter(entry.getValue().value(), (String) entry.getKey());
    }

    return new HttpGet(uriBuilder.build().toString());
  }
Esempio n. 18
0
 private String getPath(URI uri) {
   String path = uri.toASCIIString();
   path = path.substring(path.indexOf('!') + 1);
   while (path.startsWith("/")) {
     path = path.substring(1);
   }
   return path;
 }
Esempio n. 19
0
 static void sendRedirect(
     final ChannelHandlerContext ctx,
     final ChannelEvent e,
     final Class<? extends ComponentId> compClass,
     final MappingHttpRequest request) {
   e.getFuture().cancel();
   String redirectUri = null;
   if (Topology.isEnabled(compClass)) { // have an enabled service, lets use that
     final URI serviceUri = ServiceUris.remote(Topology.lookup(compClass));
     redirectUri =
         serviceUri.toASCIIString() + request.getServicePath().replace(serviceUri.getPath(), "");
   } else if (Topology.isEnabled(
       Eucalyptus.class)) { // can't find service info, redirect via clc master
     final URI serviceUri = ServiceUris.remote(Topology.lookup(Eucalyptus.class));
     redirectUri =
         serviceUri.toASCIIString().replace(Eucalyptus.INSTANCE.getServicePath(), "")
             + request.getServicePath().replace(serviceUri.getPath(), "");
   }
   HttpResponse response = null;
   if (redirectUri == null || isRedirectLoop(request, redirectUri)) {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE);
     if (Logs.isDebug()) {
       String errorMessage =
           "Failed to lookup service for "
               + Components.lookup(compClass).getName()
               + " for path "
               + request.getServicePath()
               + ".\nCurrent state: \n\t"
               + Joiner.on("\n\t").join(Topology.enabledServices());
       byte[] errorBytes = Exceptions.string(new ServiceStateException(errorMessage)).getBytes();
       response.setContent(ChannelBuffers.wrappedBuffer(errorBytes));
     }
   } else {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
     if (request.getQuery() != null) {
       redirectUri += "?" + request.getQuery();
     }
     response.setHeader(HttpHeaders.Names.LOCATION, redirectUri);
   }
   response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
   if (ctx.getChannel().isConnected()) {
     ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
   }
 }
Esempio n. 20
0
    private Bundle startBundle(URI bundleURI) {
      NavigableMap<URI, Bundle> expect, update;
      Bundle bundle = null;
      do {
        expect = get();
        if (expect.containsKey(bundleURI)) break;

        BundleContext ctx = m_framework.getBundleContext();
        bundle = ctx.getBundle(bundleURI.toASCIIString());
        if (bundle != null) {
          try {
            bundle.update();
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to update bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to update bundle %s", bundleURI);
          }
        } else {
          try {
            bundle = ctx.installBundle(bundleURI.toASCIIString());
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to install bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to instal bundle %s", bundleURI);
          }
        }
        try {
          bundle.start();
        } catch (BundleException e) {
          String msg = e.getMessage();
          throw loggedModularException(e, "Unable to start bundle %s. %s", bundleURI, msg);
        } catch (Throwable t) {
          throw loggedModularException(t, "Unable to start bundle %s", bundleURI);
        }

        update =
            ImmutableSortedMap.<URI, Bundle>naturalOrder()
                .putAll(expect)
                .put(bundleURI, bundle)
                .build();
      } while (!compareAndSet(expect, update));

      return get().get(bundleURI);
    }
Esempio n. 21
0
 private RowResource getResource(Row row) {
   String appId = dm.getAppId();
   String tableId = dm.getTableId();
   String rowId = row.getRowId();
   UriBuilder ub = info.getBaseUriBuilder();
   ub.path(TableService.class);
   URI self =
       ub.clone()
           .path(TableService.class, "getData")
           .path(DataService.class, "getRow")
           .build(appId, tableId, rowId);
   URI table = ub.clone().path(TableService.class, "getTable").build(appId, tableId);
   RowResource resource = new RowResource(row);
   resource.setSelfUri(self.toASCIIString());
   resource.setTableUri(table.toASCIIString());
   return resource;
 }
 @RequestMapping(value = "/", method = RequestMethod.POST)
 @ResponseStatus(HttpStatus.CREATED)
 public void simpan(
     @RequestBody Peserta peserta, HttpServletRequest request, HttpServletResponse response) {
   service.simpan(peserta);
   String requestUrl = request.getRequestURL().toString();
   URI uri = new UriTemplate("{requestUrl}/{id}").expand(requestUrl, peserta.getId());
   response.setHeader("Location", uri.toASCIIString());
 }
Esempio n. 23
0
 @RequestMapping(value = "/master/topik", method = RequestMethod.POST)
 @ResponseStatus(HttpStatus.CREATED)
 public void save(
     @RequestBody @Valid Topik topik, HttpServletRequest request, HttpServletResponse response) {
   belajarRestfulService.save(topik);
   String requestUrl = request.getRequestURL().toString();
   URI uri = new UriTemplate("{requestUrl}/{id}").expand(requestUrl, topik.getId());
   response.setHeader("Location", uri.toASCIIString());
 }
 public String deleteResource(final File file, final URI uri)
     throws IOException, ForbiddenException {
   m_log.debug(
       "Deleting resource '" + file.getPath() + "' with server: " + ShootConstants.SERVER_URL);
   final Map<String, String> paramMap = createDeleteParams();
   paramMap.put("uri", uri.toASCIIString());
   final String baseUrl = createBaseUrl("/api/deleteFile");
   return post(baseUrl, paramMap);
 }
 /**
  * Add a link to this resource
  *
  * @param uri The target URI for the link, possibly relative to the href of this resource.
  * @param rel
  * @return
  */
 public MutableResource withLink(
     URI uri,
     String rel,
     Optional<Predicate<ReadableResource>> predicate,
     Optional<String> name,
     Optional<String> title,
     Optional<String> hreflang) {
   return withLink(uri.toASCIIString(), rel, predicate, name, title, hreflang);
 }
Esempio n. 26
0
 @Override
 public List<Proxy> select(URI uri) {
   if (HTTP.equalsIgnoreCase(uri.getScheme()) || SOCKS.equalsIgnoreCase(uri.getScheme())) {
     if (isInExcludedSet(uri.toASCIIString())) {
       if (isLogEnabled()) {
         Log.d(TAG, "Found in excludedSet. Returning default proxy for url : " + uri);
       }
       if (sDefaultProxy == null) {
         return mDefaultProxySelector.select(uri);
       }
       return Arrays.asList(
           new Proxy(
               Proxy.Type.HTTP,
               new InetSocketAddress(sDefaultProxy.getHost(), sDefaultProxy.getPort())));
     }
     ProxyInfo proxyForUrl = getProxyForUrl(uri.toASCIIString());
     if (proxyForUrl != null) {
       if (isLogEnabled()) {
         Log.d(
             TAG,
             "Found in includeSet. Returning proxy ("
                 + proxyForUrl.getHost()
                 + ", "
                 + proxyForUrl.getPort()
                 + ") for url : "
                 + uri);
       }
       return Arrays.asList(
           new Proxy(
               Proxy.Type.HTTP,
               new InetSocketAddress(proxyForUrl.getHost(), proxyForUrl.getPort())));
     }
   }
   if (isLogEnabled()) {
     Log.d(TAG, "Not found anywhere. Returning default proxy (which is none generally).");
   }
   if (sDefaultProxy == null) {
     return mDefaultProxySelector.select(uri);
   }
   return Arrays.asList(
       new Proxy(
           Proxy.Type.HTTP,
           new InetSocketAddress(sDefaultProxy.getHost(), sDefaultProxy.getPort())));
 }
Esempio n. 27
0
 /*
  * (non-Javadoc)
  * @see org.apollo.update.resource.ResourceProvider#accept(java.lang.String)
  */
 @Override
 public boolean accept(String path) throws IOException {
   File f = new File(base, path);
   final URI target = f.toURI().normalize();
   if (target.toASCIIString().startsWith(base.toURI().normalize().toASCIIString())) {
     if (f.isDirectory()) f = new File(f, "index.html");
     return f.exists();
   }
   return false;
 }
Esempio n. 28
0
  public static HttpRequest create(HttpMethod method, String action) throws URISyntaxException {
    URI uri = new URI(action);
    HttpRequest request =
        new DefaultHttpRequest(new HttpVersion("STREST", 0, 1, true), method, uri.toASCIIString());

    //        request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.setHeader("Strest-Txn-Id", generateTxnId());
    request.setProtocolVersion(new HttpVersion("STREST", 0, 1, true));
    return request;
  }
Esempio n. 29
0
 // NOTE this does not currently check anything
 public static void checkHref(URI href) {
   String uri = href.toASCIIString();
   String auth = href.getAuthority();
   String host = href.getHost();
   String path = href.getPath();
   // TODO inject the endpoint of the provider here for rudimentary checks as below
   // assertEquals(auth + "://" + host + path, endpoint, "The Href must contain the provider
   // endpoint");
   // assertTrue(uri.startsWith(endpoint), "The Href must contain the provider endpoint");
 }
Esempio n. 30
0
  /**
   * Creates the HttpMethod to use to call the remote server, either its GET or POST.
   *
   * @param exchange the exchange
   * @return the created method as either GET or POST
   * @throws CamelExchangeException is thrown if error creating RequestEntity
   */
  @SuppressWarnings("deprecation")
  protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
      // update url and query string from the rewritten url
      url = rewriteUrl;
      uri = new URI(url);
      // use raw query to have uri decimal encoded which http client requires
      queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
      url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse =
        HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
      // need to encode query string
      queryString = UnsafeUriCharactersEncoder.encode(queryString);
      method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
      ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
      if (requestEntity != null && requestEntity.getContentType() == null) {
        LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
      }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
      throw new IllegalArgumentException(
          "Invalid uri: "
              + url
              + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
              + getEndpoint());
    }

    return method;
  }