/**
   * Creates a UniversalResourceAddressBean based on a URA.
   *
   * @param address A URA to parse and turn into a UniversalResourceAddressBean
   * @return A UniversalResourceAddressBean or null
   * @throws URISyntaxException DOCUMENT ME!
   * @see https://socraticgrid.org/display/docs/Universal+Resource+Addresses
   */
  public UniversalResourceAddressBean createUniversalResourceBean(String address)
      throws URISyntaxException {

    UniversalResourceAddressBean out = null;

    if ((address == null) || (address.isEmpty())) {
      throw new URISyntaxException("", "Null or Empty Address sent");
    }

    URI u = new URI(address);

    String entity = u.getScheme();
    String scheme = getScheme(u.getHost());
    String path = u.getPath();

    if (!path.isEmpty()) {
      path = path.substring(1);
    }

    EntityType et = EntityTypeHelper.getType(entity);

    if (scheme == null) {
      out = new GenericResourceAddressBean(et, entity, "unknown", u.getHost(), "");
    } else if (scheme.compareToIgnoreCase("id") == 0) {
      out = new IdAddressBean(et, path, getSubScheme(u.getHost()));
    } else {
      out = new GenericResourceAddressBean(et, entity, scheme, getSubScheme(u.getHost()), path);
    }

    return out;
  }
예제 #2
0
  /** @tests java.net.URI(java.lang.String) */
  public void test_ConstructorLjava_lang_String() throws URISyntaxException {
    // Regression test for HARMONY-23
    try {
      new URI("%3");
      fail("Assert 0: URI constructor failed to throw exception on invalid input.");
    } catch (URISyntaxException e) {
      // Expected
      assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex());
    }

    // Regression test for HARMONY-25
    // if port value is negative, the authority should be considered registry-based.
    URI uri = new URI("http://host:-8096/path/index.html");
    assertEquals("Assert 2: returned wrong port value,", -1, uri.getPort());
    assertNull("Assert 3: returned wrong host value,", uri.getHost());
    try {
      uri.parseServerAuthority();
      fail("Assert 4: Expected URISyntaxException");
    } catch (URISyntaxException e) {
      // Expected
    }

    uri = new URI("http", "//myhost:-8096", null);
    assertEquals("Assert 5: returned wrong port value,", -1, uri.getPort());
    assertNull("Assert 6: returned wrong host value,", uri.getHost());
    try {
      uri.parseServerAuthority();
      fail("Assert 7: Expected URISyntaxException");
    } catch (URISyntaxException e) {
      // Expected
    }
  }
  private void checkMasterNodesChange(Collection<ClusterPartition> newPartitions) {
    for (ClusterPartition newPart : newPartitions) {
      for (ClusterPartition currentPart : lastPartitions.values()) {
        if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
          continue;
        }
        // current master marked as failed
        if (newPart.isMasterFail()) {
          for (ClusterSlotRange currentSlotRange : currentPart.getSlotRanges()) {
            ClusterPartition newMasterPart = find(newPartitions, currentSlotRange);
            // does partition has a new master?
            if (!newMasterPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
              log.info(
                  "changing master from {} to {} for {}",
                  currentPart.getMasterAddress(),
                  newMasterPart.getMasterAddress(),
                  currentSlotRange);
              URI newUri = newMasterPart.getMasterAddress();
              URI oldUri = currentPart.getMasterAddress();

              changeMaster(currentSlotRange, newUri.getHost(), newUri.getPort());
              slaveDown(currentSlotRange, oldUri.getHost(), oldUri.getPort(), FreezeReason.MANAGER);

              currentPart.setMasterAddress(newMasterPart.getMasterAddress());
            }
          }
        }
        break;
      }
    }
  }
  private void addRemoveSlaves(
      final MasterSlaveEntry entry,
      final ClusterPartition currentPart,
      final ClusterPartition newPart) {
    Set<URI> removedSlaves = new HashSet<URI>(currentPart.getSlaveAddresses());
    removedSlaves.removeAll(newPart.getSlaveAddresses());

    for (URI uri : removedSlaves) {
      currentPart.removeSlaveAddress(uri);

      slaveDown(entry, uri.getHost(), uri.getPort(), FreezeReason.MANAGER);
      log.info("slave {} removed for slot ranges: {}", uri, currentPart.getSlotRanges());
    }

    Set<URI> addedSlaves = new HashSet<URI>(newPart.getSlaveAddresses());
    addedSlaves.removeAll(currentPart.getSlaveAddresses());
    for (final URI uri : addedSlaves) {
      Future<Void> future = entry.addSlave(uri.getHost(), uri.getPort());
      future.addListener(
          new FutureListener<Void>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
              if (!future.isSuccess()) {
                log.error("Can't add slave: " + uri, future.cause());
                return;
              }

              currentPart.addSlaveAddress(uri);
              entry.slaveUp(uri.getHost(), uri.getPort(), FreezeReason.MANAGER);
              log.info("slave {} added for slot ranges: {}", uri, currentPart.getSlotRanges());
            }
          });
    }
  }
  /**
   * Creates a IdAddressBean based on a URA.
   *
   * @param address A URA which must use the ID scheme
   * @return A IdAddressBean or null
   * @throws URISyntaxException If the URA is ill formed
   */
  public IdAddressBean createIdAddressBean(String address) throws URISyntaxException {

    IdAddressBean out = null;

    if ((address == null) || (address.isEmpty())) {
      throw new URISyntaxException("", "Null or Empty Address sent");
    }

    URI u = new URI(address);
    String entity = u.getScheme();
    String scheme = getScheme(u.getHost());

    String path = u.getPath();

    if (!path.isEmpty()) {
      path = path.substring(1);
    }

    EntityType et = EntityTypeHelper.getType(entity);

    if (scheme != null) {

      if (scheme.compareToIgnoreCase("id") == 0) {
        out = new IdAddressBean(et, path, getSubScheme(u.getHost()));
      }
    }

    return out;
  }
예제 #6
0
  public void setUp() {
    if (uri == null) return;

    if (config != null) {
      if (config.getServletConfig().getInitParameter(REDIS_AUTH) != null) {
        authToken = config.getServletConfig().getInitParameter(REDIS_AUTH);
      }

      if (config.getServletConfig().getInitParameter(REDIS_SERVER) != null) {
        uri = URI.create(config.getServletConfig().getInitParameter(REDIS_SERVER));
      }
    }

    jedisSubscriber = new Jedis(uri.getHost(), uri.getPort());
    try {
      jedisSubscriber.connect();
    } catch (IOException e) {
      logger.error("failed to connect subscriber", e);
    }

    jedisSubscriber.auth(authToken);
    jedisSubscriber.flushAll();

    jedisPublisher = new Jedis(uri.getHost(), uri.getPort());
    try {
      jedisPublisher.connect();
    } catch (IOException e) {
      logger.error("failed to connect publisher", e);
    }
    jedisPublisher.auth(authToken);
    jedisPublisher.flushAll();
  }
예제 #7
0
  /** @return the IFile corresponding to the given input, or null if none */
  public static IFile getFile(IEditorInput editorInput) {
    IFile file = null;

    if (editorInput instanceof IFileEditorInput) {
      IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
      file = fileEditorInput.getFile();
    } else if (editorInput instanceof IPathEditorInput) {
      IPathEditorInput pathInput = (IPathEditorInput) editorInput;
      IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
      if (wsRoot.getLocation().isPrefixOf(pathInput.getPath())) {
        file = ResourcesPlugin.getWorkspace().getRoot().getFile(pathInput.getPath());
      } else {
        // Can't get an IFile for an arbitrary file on the file system; return null
      }
    } else if (editorInput instanceof IStorageEditorInput) {
      file = null; // Can't get an IFile for an arbitrary IStorageEditorInput
    } else if (editorInput instanceof IURIEditorInput) {
      IURIEditorInput uriEditorInput = (IURIEditorInput) editorInput;
      IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
      URI uri = uriEditorInput.getURI();
      String path = uri.getPath();
      // Bug 526: uri.getHost() can be null for a local file URL
      if (uri.getScheme().equals("file")
          && (uri.getHost() == null || uri.getHost().equals("localhost"))
          && !path.startsWith(wsRoot.getLocation().toOSString())) {
        file = wsRoot.getFile(new Path(path));
      }
    }
    return file;
  }
예제 #8
0
  /**
   * Valide le format de l'adresse du serveur et sépare le nom d'hôte ainsi que le port pour
   * utilisation future. Utilise la classe URI de Java pour séparer les deux sections plus
   * facilement.
   *
   * <p>Largement inspiré de cet exemple:
   * http://stackoverflow.com/questions/2345063/java-common-way-to-validate-
   * and-convert-hostport-to-inetsocketaddress
   *
   * @param adresse Adresse du serveur fournit par l'utilisateur.
   * @return Si l'adresse est au format exigé ou non.
   */
  public static boolean estValide(String adresse) {

    boolean valide = true;

    try {

      // En cas d'adresse vide
      if (adresse.equals("")) {
        throw new URISyntaxException("", "L'adresse ne peut pas être vide.");
      }

      URI uri = new URI("my://" + adresse);
      host = uri.getHost();
      port = uri.getPort();

      // Si le nom d'hôte est invalide
      if (uri.getHost() == null || uri.getHost() == "")
        throw new URISyntaxException(
            uri.toString(), "L'adresse doit contenir un hôte au format valide.");
      // Si le port est invalide
      else if (uri.getPort() == -1)
        throw new URISyntaxException(uri.toString(), "L'adresse doit contenir un port valide.");

    } catch (URISyntaxException ex) {

      valide = false;
      JOptionPane.showMessageDialog(null, ex.getReason(), "Serveur", JOptionPane.WARNING_MESSAGE);
    }

    return valide;
  }
  public NetServerSpecFactoryBean configure(URI uri) {
    setHost(null != uri.getHost() ? uri.getHost() : "0.0.0.0");
    setPort(uri.getPort() > 0 ? uri.getPort() : 3000);
    setFraming(null != uri.getPath() ? uri.getPath().substring(1) : "linefeed");
    this.delegateCodec = StandardCodecs.STRING_CODEC;

    if (null != uri.getQuery()) {
      String[] params = StringUtils.split(uri.getQuery(), "&");
      if (null == params) {
        params = new String[] {uri.getQuery()};
      }
      for (String pair : params) {
        String[] parts = StringUtils.split(pair, "=");
        if (parts.length > 1) {
          if ("codec".equals(parts[0])) {
            setCodec(parts[1]);
          } else if ("dispatcher".equals(parts[0])) {
            setDispatcher(parts[1]);
          } else if ("lengthFieldLength".equals(parts[0])) {
            setLengthFieldLength(Integer.parseInt(parts[1]));
          }
        }
      }
    }
    return this;
  }
  /**
   * Helper method to check whether requests from the specified origin must be allowed.
   *
   * @param requestOrigin origin as reported by the client, {@code null} if unknown.
   * @return {@code true} if the origin is allowed, else {@code false}.
   */
  public boolean isAllowedOrigin(final String requestOrigin) {
    if (allowAnyOrigin) {
      return true;
    }

    if (requestOrigin == null) {
      return false;
    }

    URI requestOriginURI;
    try {
      requestOriginURI = new URI(requestOrigin);
    } catch (URISyntaxException e) {
      return false;
    }

    String requestScheme = requestOriginURI.getScheme();
    String requestHost = requestOriginURI.getHost();
    int requestPort = requestOriginURI.getPort();

    if (requestScheme == null || requestHost == null) {
      return false;
    }

    for (URI allowedOrigin : allowedOrigins) {
      if ((requestHost.equalsIgnoreCase(allowedOrigin.getHost())
              || requestHost.toLowerCase().endsWith("." + allowedOrigin.getHost().toLowerCase()))
          && requestPort == allowedOrigin.getPort()
          && requestScheme.equalsIgnoreCase(allowedOrigin.getScheme())) {
        return true;
      }
    }

    return false;
  }
예제 #11
0
 /*
  * see if two file systems are the same or not.
  */
 private boolean compareFs(FileSystem srcFs, FileSystem destFs) {
   URI srcUri = srcFs.getUri();
   URI dstUri = destFs.getUri();
   if (srcUri.getScheme() == null) {
     return false;
   }
   if (!srcUri.getScheme().equals(dstUri.getScheme())) {
     return false;
   }
   String srcHost = srcUri.getHost();
   String dstHost = dstUri.getHost();
   if ((srcHost != null) && (dstHost != null)) {
     try {
       srcHost = InetAddress.getByName(srcHost).getCanonicalHostName();
       dstHost = InetAddress.getByName(dstHost).getCanonicalHostName();
     } catch (UnknownHostException ue) {
       return false;
     }
     if (!srcHost.equals(dstHost)) {
       return false;
     }
   } else if (srcHost == null && dstHost != null) {
     return false;
   } else if (srcHost != null && dstHost == null) {
     return false;
   }
   // check for ports
   if (srcUri.getPort() != dstUri.getPort()) {
     return false;
   }
   return true;
 }
  @Test
  public void testLowerCaseOfResolvedServices() throws Exception {
    configFile =
        createTempFileFromResource(
            "org/kaazing/gateway/server/context/parse/data/gateway-config-mixedcase.xml");
    GatewayConfigDocument doc = parser.parse(configFile);
    GatewayContext ctx = resolver.resolve(doc);

    Collection<? extends ServiceContext> services = ctx.getServices();
    for (ServiceContext service : services) {
      // validate that the accepts have lower-case host names
      Collection<String> acceptURIs = service.getAccepts();
      for (String acceptURI : acceptURIs) {
        Assert.assertTrue(
            URIUtils.getHost(acceptURI).equals(URIUtils.getHost(acceptURI).toLowerCase()));
      }

      // validate that the cross-site-constraints have lower-case host names
      Map<String, ? extends Map<String, ? extends CrossSiteConstraintContext>>
          crossSiteConstraints = service.getCrossSiteConstraints();
      for (String key : crossSiteConstraints.keySet()) {
        Map<String, ? extends CrossSiteConstraintContext> crossSiteConstraintsByURI =
            crossSiteConstraints.get(key);
        for (CrossSiteConstraintContext crossSiteConstraint : crossSiteConstraintsByURI.values()) {
          String allowOrigin = crossSiteConstraint.getAllowOrigin();
          if (!"*".equals(allowOrigin)) {
            URI originURI = URI.create(allowOrigin);
            Assert.assertTrue(originURI.getHost().equals(originURI.getHost().toLowerCase()));
          }
        }
      }
    }
  }
예제 #13
0
  /**
   * Creates a new FTPFile instance by converting the given file: URI into an abstract pathname.
   *
   * <p>FTP URI protocol:<br>
   * ftp:// [ userName [ : password ] @ ] host [ : port ][ / path ]
   *
   * <p>example:<br>
   * ftp://[email protected]:21/pub/testfile.txt
   *
   * @param uri An absolute, hierarchical URI using a supported scheme.
   * @throws NullPointerException if <code>uri</code> is <code>null</code>.
   * @throws IllegalArgumentException If the preconditions on the parameter do not hold.
   */
  public FTPFile(URI uri) throws IOException, URISyntaxException {
    super(uri);

    if (uri.getScheme().equals("ftp")) {
      String userinfo = uri.getUserInfo();
      if (userinfo != null) {
        int index = userinfo.indexOf(":");
        if (index >= 0) {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(
                      uri.getHost(),
                      uri.getPort(),
                      userinfo.substring(0, index - 1),
                      userinfo.substring(index + 1),
                      uri.getPath())));
        } else {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(uri.getHost(), uri.getPort(), userinfo, "", uri.getPath())));
        }
      } else {
        fileSystem =
            new FTPFileSystem(
                new FTPAccount(uri.getHost(), uri.getPort(), null, "", uri.getPath()));
      }

      setFileName(uri.getPath());
      ftpClient = ((FTPFileSystem) fileSystem).getFTPClient();
    } else {
      throw new URISyntaxException(uri.toString(), "Wrong URI scheme");
    }
  }
예제 #14
0
  protected void bind() throws IOException {
    URI bind = getBindLocation();

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {
      if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog);
      } else {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
      }
      this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
      throw IOExceptionSupport.create(
          "Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
      setConnectURI(
          new URI(
              bind.getScheme(),
              bind.getUserInfo(),
              resolveHostName(bind.getHost()),
              serverSocket.getLocalPort(),
              bind.getPath(),
              bind.getQuery(),
              bind.getFragment()));
    } catch (URISyntaxException e) {
      throw IOExceptionSupport.create(e);
    }
  }
  private List<HttpCookie> getValidCookies(URI uri) {
    List<HttpCookie> targetCookies = new ArrayList<HttpCookie>();
    // If the stored URI does not have a path then it must match any URI in
    // the same domain
    for (URI storedUri : allCookies.keySet()) {
      // Check ith the domains match according to RFC 6265
      if (checkDomainsMatch(storedUri.getHost(), uri.getHost())) {
        // Check if the paths match according to RFC 6265
        if (checkPathsMatch(storedUri.getPath(), uri.getPath())) {
          targetCookies.addAll(allCookies.get(storedUri));
        }
      }
    }

    // Check it there are expired cookies and remove them
    if (!targetCookies.isEmpty()) {
      List<HttpCookie> cookiesToRemoveFromPersistence = new ArrayList<HttpCookie>();
      for (Iterator<HttpCookie> it = targetCookies.iterator(); it.hasNext(); ) {
        HttpCookie currentCookie = it.next();
        if (currentCookie.hasExpired()) {
          cookiesToRemoveFromPersistence.add(currentCookie);
          it.remove();
        }
      }

      if (!cookiesToRemoveFromPersistence.isEmpty()) {
        removeFromPersistence(uri, cookiesToRemoveFromPersistence);
      }
    }
    return targetCookies;
  }
    @Override
    protected List<Map<String, Object>> doInBackground(Void... notUsed) {
      String xmlrpcUrl = null;
      if (mSelfHostedUrl != null && mSelfHostedUrl.length() != 0) {
        xmlrpcUrl = getSelfHostedXmlrpcUrl(mSelfHostedUrl);
      }

      if (xmlrpcUrl == null) {
        if (!mHttpAuthRequired && mErrorMsgId == 0) {
          mErrorMsgId = org.wordpress.android.R.string.no_site_error;
        }
        return null;
      }

      // Validate the URL found before calling the client. Prevent a crash that can occur
      // during the setup of self-hosted sites.
      URI xmlrpcUri;
      xmlrpcUri = URI.create(xmlrpcUrl);
      XMLRPCClientInterface client =
          XMLRPCFactory.instantiate(xmlrpcUri, mHttpUsername, mHttpPassword);
      Object[] params = {mUsername, mPassword};
      try {
        Object[] userBlogs = (Object[]) client.call("wp.getUsersBlogs", params);
        if (userBlogs == null) {
          // Could happen if the returned server response is truncated
          mErrorMsgId = org.wordpress.android.R.string.xmlrpc_error;
          mClientResponse = client.getResponse();
          return null;
        }
        Arrays.sort(userBlogs, BlogUtils.BlogNameComparator);
        List<Map<String, Object>> userBlogList = new ArrayList<Map<String, Object>>();
        for (Object blog : userBlogs) {
          try {
            userBlogList.add((Map<String, Object>) blog);
          } catch (ClassCastException e) {
            AppLog.e(T.NUX, "invalid data received from XMLRPC call wp.getUsersBlogs");
          }
        }
        return userBlogList;
      } catch (XmlPullParserException parserException) {
        mErrorMsgId = org.wordpress.android.R.string.xmlrpc_error;
        AppLog.e(T.NUX, "invalid data received from XMLRPC call wp.getUsersBlogs", parserException);
      } catch (XMLRPCFault xmlRpcFault) {
        handleXmlRpcFault(xmlRpcFault);
      } catch (XMLRPCException xmlRpcException) {
        AppLog.e(
            T.NUX, "XMLRPCException received from XMLRPC call wp.getUsersBlogs", xmlRpcException);
        mErrorMsgId = org.wordpress.android.R.string.no_site_error;
      } catch (SSLHandshakeException e) {
        if (xmlrpcUri.getHost() != null && xmlrpcUri.getHost().endsWith("wordpress.com")) {
          mErroneousSslCertificate = true;
        }
        AppLog.w(T.NUX, "SSLHandshakeException failed. Erroneous SSL certificate detected.");
      } catch (IOException e) {
        AppLog.e(T.NUX, "Exception received from XMLRPC call wp.getUsersBlogs", e);
        mErrorMsgId = org.wordpress.android.R.string.no_site_error;
      }
      mClientResponse = client.getResponse();
      return null;
    }
 public String getNormalizedServerUri() throws URISyntaxException {
   URI uri = new URI(originalServerUri);
   if (uri.getAuthority() == null) uri = new URI("ws://" + originalServerUri);
   if (uri.getPort() == -1)
     if ("ws".equals(uri.getScheme().toLowerCase(Locale.ENGLISH)))
       uri =
           new URI(
               "ws",
               uri.getUserInfo(),
               uri.getHost(),
               PluginConfig.DEFAULT_TCP_PORT,
               uri.getPath(),
               uri.getQuery(),
               uri.getFragment());
     else if ("wss".equals(uri.getScheme().toLowerCase(Locale.ENGLISH)))
       uri =
           new URI(
               "wss",
               uri.getUserInfo(),
               uri.getHost(),
               PluginConfig.DEFAULT_SSL_PORT,
               uri.getPath(),
               uri.getQuery(),
               uri.getFragment());
   return uri.toString();
 }
  @Override
  public UriBuilder uri(URI uri) {
    if (uri == null) {
      throw new IllegalArgumentException("URI parameter is null");
    }

    if (uri.getRawFragment() != null) {
      fragment = uri.getRawFragment();
    }

    if (uri.isOpaque()) {
      scheme = uri.getScheme();
      ssp = uri.getRawSchemeSpecificPart();
      return this;
    }

    if (uri.getScheme() == null) {
      if (ssp != null) {
        if (uri.getRawSchemeSpecificPart() != null) {
          ssp = uri.getRawSchemeSpecificPart();
          return this;
        }
      }
    } else {
      scheme = uri.getScheme();
    }

    ssp = null;
    if (uri.getRawAuthority() != null) {
      if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) {
        authority = uri.getRawAuthority();
        userInfo = null;
        host = null;
        port = -1;
      } else {
        authority = null;
        if (uri.getRawUserInfo() != null) {
          userInfo = uri.getRawUserInfo();
        }
        if (uri.getHost() != null) {
          host = uri.getHost();
        }
        if (uri.getPort() != -1) {
          port = uri.getPort();
        }
      }
    }

    if (uri.getRawPath() != null && uri.getRawPath().length() > 0) {
      path.setLength(0);
      path.append(uri.getRawPath());
    }
    if (uri.getRawQuery() != null && uri.getRawQuery().length() > 0) {
      query.setLength(0);
      query.append(uri.getRawQuery());
    }

    return this;
  }
예제 #19
0
  public void run() {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if (scheme.equalsIgnoreCase("http")) {
        port = 80;
      } else if (scheme.equalsIgnoreCase("https")) {
        port = 443;
      }
    }

    if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
      logger.error("Only HTTP(S) is supported.");
      return;
    }

    boolean ssl = scheme.equalsIgnoreCase("https");

    // Configure the client.
    ClientBootstrap bootstrap =
        new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(ssl));

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
      bootstrap.releaseExternalResources();
      return;
    }

    // Prepare the HTTP request.
    HttpRequest request =
        new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    // Set some example cookies.
    CookieEncoder httpCookieEncoder = new CookieEncoder(false);
    httpCookieEncoder.addCookie("my-cookie", "foo");
    httpCookieEncoder.addCookie("another-cookie", "bar");
    request.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());

    // Send the HTTP request.
    channel.write(request);

    // Wait for the server to close the connection.
    channel.getCloseFuture().awaitUninterruptibly();

    // Shut down executor threads to exit.
    bootstrap.releaseExternalResources();
  }
예제 #20
0
 /**
  * Gets the server domain name of the document
  *
  * @return Domain name
  */
 public String getDocumentDomain() {
   try {
     URI uri = documentBasePath.toURI();
     return (uri.getHost() != null) ? uri.getHost() : "";
   } catch (URISyntaxException e) {
     return null;
   }
 }
예제 #21
0
  public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new HttpDownloadertInitializer(sslCtx, handler));
      // Make the connection attempt.
      Channel ch = b.connect(host, port).sync().channel();
      // Prepare the HTTP request.
      HttpRequest request =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
      HttpHeaders headers = request.headers();
      headers.set(HttpHeaders.Names.HOST, host);
      headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
      // Set some example cookies.
      headers.set(
          HttpHeaders.Names.COOKIE,
          ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
      ch.writeAndFlush(request);
      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      Thread.sleep(1000);
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
예제 #22
0
  protected void connect() throws Exception {

    if (socket == null && socketFactory == null) {
      throw new IllegalStateException(
          "Cannot connect if the socket or socketFactory have not been set");
    }

    InetSocketAddress localAddress = null;
    InetSocketAddress remoteAddress = null;

    if (localLocation != null) {
      localAddress =
          new InetSocketAddress(
              InetAddress.getByName(localLocation.getHost()), localLocation.getPort());
    }

    if (remoteLocation != null) {
      String host = resolveHostName(remoteLocation.getHost());
      remoteAddress = new InetSocketAddress(host, remoteLocation.getPort());
    }
    // Set the traffic class before the socket is connected when possible so
    // that the connection packets are given the correct traffic class.
    this.trafficClassSet = setTrafficClass(socket);

    if (socket != null) {

      if (localAddress != null) {
        socket.bind(localAddress);
      }

      // If it's a server accepted socket.. we don't need to connect it
      // to a remote address.
      if (remoteAddress != null) {
        if (connectionTimeout >= 0) {
          socket.connect(remoteAddress, connectionTimeout);
        } else {
          socket.connect(remoteAddress);
        }
      }

    } else {
      // For SSL sockets.. you can't create an unconnected socket :(
      // This means the timout option are not supported either.
      if (localAddress != null) {
        socket =
            socketFactory.createSocket(
                remoteAddress.getAddress(), remoteAddress.getPort(),
                localAddress.getAddress(), localAddress.getPort());
      } else {
        socket = socketFactory.createSocket(remoteAddress.getAddress(), remoteAddress.getPort());
      }
    }

    initialiseSocket(socket);
    initializeStreams();
  }
예제 #23
0
 /**
  * Return the complete host of the uri
  *
  * @param uri the uri to extract host from
  * @return the complete host of the uri
  */
 public static String getCompleteHost(URI uri) {
   if (uri.getPort() > 0) {
     return uri.getScheme()
         + HtmlConstants.SCHEME_AND_AUTHORITY_SEPARATOR
         + uri.getHost()
         + ":"
         + uri.getPort();
   }
   return uri.getScheme() + HtmlConstants.SCHEME_AND_AUTHORITY_SEPARATOR + uri.getHost();
 }
예제 #24
0
  public Text evaluate(final Text fromUrl, final Text toUrl, final IntWritable type) {

    if (fromUrl == null || toUrl == null) {
      return null;
    }
    boolean isFrom = true; // type == 0
    if (type.compareTo(new IntWritable(1)) == 0) { // type == 1
      isFrom = false;
    }
    String fqdn = "";
    try {
      if (isFrom) {
        URI uri = new URI(fromUrl.toString());
        fqdn = uri.getHost();
      } else {
        List<String> result = new ArrayList<String>();
        Pattern pattern =
            Pattern.compile(
                "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)"
                    + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov"
                    + "|mil|biz|info|mobi|name|aero|jobs|museum"
                    + "|travel|[a-z]{2}))(:[\\d]{1,5})?"
                    + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?"
                    + "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?"
                    + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)"
                    + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?"
                    + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*"
                    + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");

        Matcher matcher = pattern.matcher(toUrl.toString());
        while (matcher.find()) {
          result.add(matcher.group());
        }

        if (result.size() == 0) {
          URI uri = new URI(fromUrl.toString());
          fqdn = uri.getHost();
        } else {
          String firstRes = result.get(0);
          if (firstRes.startsWith("//")) {
            firstRes = "http:" + firstRes;
          }
          URI uri = new URI(firstRes);
          fqdn = uri.getHost();
        }
      }
    } catch (URISyntaxException e) {
      fqdn = "ERROR" + e.toString();
    }
    if (fqdn == null) {
      return new Text("unknown://");
    }
    return new Text(fqdn);
  }
예제 #25
0
 /**
  * Normalize the given URL into an URL that only contains protocol://host:port/
  *
  * @param url the url to transform
  * @return an URL that only contains protocol://host:port/
  */
 public static String getHostURL(String url) {
   URI uri = URI.create(url);
   String scheme = (uri.getScheme() == null) ? "rmi" : uri.getScheme();
   String host = (uri.getHost() == null) ? "localhost" : uri.getHost();
   int port = uri.getPort();
   if (port == -1) {
     return scheme + "://" + host + "/";
   } else {
     return scheme + "://" + host + ":" + port + "/";
   }
 }
  public static InetAddress getMyIP(URI master) {

    try {
      return getMyIP(master.getHost(), master.getPort());
    } catch (UnknownHostException e) {
      throw new RuntimeException("Unknown hostname for ROS master: " + master.getHost());
    } catch (IOException e) {
      throw new RuntimeException(
          "Cannot connect to ROS host " + master.getHost() + "\n" + e.getMessage());
    }
  }
예제 #27
0
  public ClusterInstance instance(String to) throws URISyntaxException {
    URI uri = new URI(to);
    for (ClusterInstance clusterInstance : instances) {
      URI instanceUri = clusterInstance.uri();
      if (instanceUri.getHost().equals(uri.getHost()) && instanceUri.getPort() == uri.getPort()) {
        return clusterInstance;
      }
    }

    throw new IllegalArgumentException("No instance in cluster at address: " + to);
  }
 private static URI getDuplicate(URI uri, String type, String title, String locality) {
   URI duplicate_uri = null;
   if (uri.getHost().contains("eventful.com")) {
     duplicate_uri = getDuplicateInDomain(valid_triples_eventful, uri, type, title, locality);
   } else if (uri.getHost().contains("eventbrite.com")) {
     duplicate_uri = getDuplicateInDomain(valid_triples_eventbrite, uri, type, title, locality);
   } else if (uri.getHost().contains("yahoo.com")) {
     duplicate_uri = getDuplicateInDomain(valid_triples_upcoming, uri, type, title, locality);
   }
   return duplicate_uri;
 }
 private static void addHostHeader(
     final Request request, final URI uri, final HttpRequestPacket requestPacket) {
   String host = request.getVirtualHost();
   if (host != null) {
     requestPacket.addHeader(Header.Host, host);
   } else {
     if (uri.getPort() == -1) {
       requestPacket.addHeader(Header.Host, uri.getHost());
     } else {
       requestPacket.addHeader(Header.Host, uri.getHost() + ':' + uri.getPort());
     }
   }
 }
예제 #30
0
 /** @since 3.0 */
 protected URI createURI(
     org.osgi.service.remoteserviceadmin.EndpointDescription endpointDescription,
     IDiscoveryAdvertiser advertiser,
     IServiceTypeID serviceTypeID,
     String serviceName)
     throws URISyntaxException {
   String path = "/" + serviceName; // $NON-NLS-1$
   String str = endpointDescription.getId();
   URI uri = null;
   while (true) {
     try {
       uri = new URI(str);
       if (uri.getHost() != null) {
         break;
       } else {
         final String rawSchemeSpecificPart = uri.getRawSchemeSpecificPart();
         // make sure we break eventually
         if (str.equals(rawSchemeSpecificPart)) {
           uri = null;
           break;
         } else {
           str = rawSchemeSpecificPart;
         }
       }
     } catch (URISyntaxException e) {
       uri = null;
       break;
     }
   }
   String scheme = RemoteConstants.DISCOVERY_SERVICE_TYPE;
   int port = 32565;
   if (uri != null) {
     port = uri.getPort();
     if (port == -1) port = 32565;
   }
   String host = null;
   if (uri != null) {
     host = uri.getHost();
   } else {
     try {
       host = InetAddress.getLocalHost().getHostAddress();
     } catch (Exception e) {
       logWarning(
           "createURI", //$NON-NLS-1$
           "failed to get local host adress, falling back to \'localhost\'.",
           e); //$NON-NLS-1$
       host = "localhost"; // $NON-NLS-1$
     }
   }
   return new URI(scheme, null, host, port, path, null, null);
 }