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());
            }
          });
    }
  }
Esempio n. 2
0
 @Override
 public int getPort() {
   if (publicUri.getPort() == -1) {
     return publicUri.getScheme().equalsIgnoreCase("https") ? 443 : 80;
   }
   return publicUri.getPort();
 }
Esempio n. 3
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);
    }
  }
Esempio n. 4
0
  /**
   * Decodes a SmtpTransport URI.
   *
   * <p>Possible forms:
   *
   * <pre>
   * smtp://user:password@server:port CONNECTION_SECURITY_NONE
   * smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
   * smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
   * smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
   * smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
   * </pre>
   */
  public static ServerSettings decodeUri(String uri) {
    String host;
    int port;
    ConnectionSecurity connectionSecurity;
    String authenticationType = AUTH_AUTOMATIC;
    String username = null;
    String password = null;

    URI smtpUri;
    try {
      smtpUri = new URI(uri);
    } catch (URISyntaxException use) {
      throw new IllegalArgumentException("Invalid SmtpTransport URI", use);
    }

    String scheme = smtpUri.getScheme();
    if (scheme.equals("smtp")) {
      connectionSecurity = ConnectionSecurity.NONE;
      port = 25;
    } else if (scheme.equals("smtp+tls")) {
      connectionSecurity = ConnectionSecurity.STARTTLS_OPTIONAL;
      port = 25;
    } else if (scheme.equals("smtp+tls+")) {
      connectionSecurity = ConnectionSecurity.STARTTLS_REQUIRED;
      port = 25;
    } else if (scheme.equals("smtp+ssl+")) {
      connectionSecurity = ConnectionSecurity.SSL_TLS_REQUIRED;
      port = 465;
    } else if (scheme.equals("smtp+ssl")) {
      connectionSecurity = ConnectionSecurity.SSL_TLS_OPTIONAL;
      port = 465;
    } else {
      throw new IllegalArgumentException("Unsupported protocol (" + scheme + ")");
    }

    host = smtpUri.getHost();

    if (smtpUri.getPort() != -1) {
      port = smtpUri.getPort();
    }

    if (smtpUri.getUserInfo() != null) {
      try {
        String[] userInfoParts = smtpUri.getUserInfo().split(":");
        username = URLDecoder.decode(userInfoParts[0], "UTF-8");
        if (userInfoParts.length > 1) {
          password = URLDecoder.decode(userInfoParts[1], "UTF-8");
        }
        if (userInfoParts.length > 2) {
          authenticationType = userInfoParts[2];
        }
      } catch (UnsupportedEncodingException enc) {
        // This shouldn't happen since the encoding is hardcoded to UTF-8
        throw new IllegalArgumentException("Couldn't urldecode username or password.", enc);
      }
    }

    return new ServerSettings(
        TRANSPORT_TYPE, host, port, connectionSecurity, authenticationType, username, password);
  }
Esempio n. 5
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
    }
  }
Esempio n. 6
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;
 }
Esempio n. 7
0
  DnsNameResolver(
      @Nullable String nsAuthority,
      String name,
      Attributes params,
      Resource<ScheduledExecutorService> timerServiceResource,
      Resource<ExecutorService> executorResource) {
    // TODO: if a DNS server is provided as nsAuthority, use it.
    // https://www.captechconsulting.com/blogs/accessing-the-dusty-corners-of-dns-with-java

    this.timerServiceResource = timerServiceResource;
    this.executorResource = executorResource;
    // Must prepend a "//" to the name when constructing a URI, otherwise it will be treated as an
    // opaque URI, thus the authority and host of the resulted URI would be null.
    URI nameUri = URI.create("//" + name);
    authority =
        Preconditions.checkNotNull(
            nameUri.getAuthority(), "nameUri (%s) doesn't have an authority", nameUri);
    host = Preconditions.checkNotNull(nameUri.getHost(), "host");
    if (nameUri.getPort() == -1) {
      Integer defaultPort = params.get(NameResolver.Factory.PARAMS_DEFAULT_PORT);
      if (defaultPort != null) {
        port = defaultPort;
      } else {
        throw new IllegalArgumentException(
            "name '" + name + "' doesn't contain a port, and default port is not set in params");
      }
    } else {
      port = nameUri.getPort();
    }
  }
  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;
  }
  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;
      }
    }
  }
Esempio n. 10
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();
  }
  /**
   * 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;
  }
Esempio n. 12
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;
  }
Esempio n. 13
0
  public void parseURI(URI uri) throws URISyntaxException {
    String protocol = uri.getScheme();
    if (!protocol.equalsIgnoreCase("hdfs2")) {
      throw new IllegalArgumentException(
          "Unrecognized Cache protocol: " + protocol + " for uri: " + uri);
    }
    hostName = uri.getHost();
    if (hostName == null) {
      hostName = "localhost";
    }
    port = uri.getPort() == -1 ? HdfsConstants.DEFAULT_PORT : uri.getPort();
    path = uri.getPath();
    Map<String, Object> hdfsSettings = URISupport.parseParameters(uri);

    overwrite = getBoolean(hdfsSettings, "overwrite", overwrite);
    append = getBoolean(hdfsSettings, "append", append);
    wantAppend = append;
    bufferSize = getInteger(hdfsSettings, "bufferSize", bufferSize);
    replication = getShort(hdfsSettings, "replication", replication);
    blockSize = getLong(hdfsSettings, "blockSize", blockSize);
    compressionType = getCompressionType(hdfsSettings, "compressionType", compressionType);
    compressionCodec = getCompressionCodec(hdfsSettings, "compressionCodec", compressionCodec);
    fileType = getFileType(hdfsSettings, "fileType", fileType);
    fileSystemType = getFileSystemType(hdfsSettings, "fileSystemType", fileSystemType);
    keyType = getWritableType(hdfsSettings, "keyType", keyType);
    valueType = getWritableType(hdfsSettings, "valueType", valueType);
    openedSuffix = getString(hdfsSettings, "openedSuffix", openedSuffix);
    readSuffix = getString(hdfsSettings, "readSuffix", readSuffix);
    initialDelay = getLong(hdfsSettings, "initialDelay", initialDelay);
    delay = getLong(hdfsSettings, "delay", delay);
    pattern = getString(hdfsSettings, "pattern", pattern);
    chunkSize = getInteger(hdfsSettings, "chunkSize", chunkSize);
    splitStrategies = getSplitStrategies(hdfsSettings);
  }
Esempio n. 14
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");
    }
  }
Esempio n. 15
0
  public void run(URI uri) throws Exception {
    int port = uri.getPort() > 0 ? uri.getPort() : BaseTestConfig.HTTPS_PORT;
    String host = uri.getHost();

    // Configure SSL context if necessary.
    final SslContext sslCtx;
    sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    httpsInitializer = generateHttpsInitializer(sslCtx);
    try {
      Bootstrap b = new Bootstrap();
      b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
      b.group(group).channel(NioSocketChannel.class).handler(httpsInitializer);

      // Make the connection attempt.
      startTime = System.nanoTime();
      Channel ch = b.connect(host, port).sync().channel();
      localAddress = ch.localAddress();
      remoteAddress = ch.remoteAddress();

      sendRequests(uri.toURL(), ch);

      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      endTime = System.nanoTime();
      long duration = endTime - startTime;
      logger.info(String.format("connection duration: %,dns (%d)", duration, duration));
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
Esempio n. 16
0
  protected ServerSocket createSocket(URI uri)
      throws IOException, NoSuchAlgorithmException, KeyManagementException {
    SslConnector cnn = null;
    ServerSocketFactory ssf = null;
    cnn = (SslConnector) connector;
    // An SSLContext is an environment for implementing JSSE
    // It is used to create a ServerSocketFactory
    SSLContext sslc = SSLContext.getInstance(cnn.getProtocol().toLowerCase());

    // Initialize the SSLContext to work with our key managers
    sslc.init(cnn.getKeyManagerFactory().getKeyManagers(), null, null);

    ssf = sslc.getServerSocketFactory();

    String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
    int backlog = cnn.getBacklog();
    SSLServerSocket serverSocket = null;

    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost())
        || inetAddress.isLoopbackAddress()
        || host.trim().equals("localhost")) {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog);
    } else {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog, inetAddress);
    }
    // Authenticate the client?
    serverSocket.setNeedClientAuth(cnn.isRequireClientAuthentication());
    return serverSocket;
  }
  @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;
  }
Esempio n. 18
0
 public int getSchemePort(URI uri) {
   if (uri.getScheme() == null || !uri.getScheme().equals(scheme)) return -1;
   if (uri.getPort() == -1) {
     return port;
   } else {
     return uri.getPort();
   }
 }
Esempio n. 19
0
 private int getPort(URI uri) {
   if (uri.getScheme().equals("http") && uri.getPort() == 80
       || uri.getScheme().equals("https") && uri.getPort() == 443) {
     return -1;
   } else {
     return uri.getPort();
   }
 }
  private @Nullable Distribution toDistribution(
      @Nonnull ProviderContext ctx, @Nullable String container)
      throws CloudException, InternalException {
    if (container == null) {
      return null;
    }
    NovaMethod method = new NovaMethod(provider);
    Map<String, String> headers = method.headResource(SERVICE, RESOURCE, container);

    if (headers == null) {
      return null;
    }
    String enabled = null, uriString = null;
    for (String key : headers.keySet()) {
      if (key.equalsIgnoreCase("X-CDN-Enabled")) {
        enabled = headers.get(key);
      } else if (key.equalsIgnoreCase("X-CDN-URI")) {
        if (uriString == null) {
          uriString = headers.get(key);
        }
      } else if (key.equalsIgnoreCase("X-CDN-SSL-URI")) {
        uriString = headers.get(key);
      }
    }
    if (uriString == null) {
      return null;
    }
    String dns;

    try {
      URI uri = new URI(uriString);

      dns = uri.getHost();
      if (uri.getPort() > 0) {
        if (dns.startsWith("https:") && uri.getPort() != 443) {
          dns = dns + ":" + uri.getPort();
        }
        if (dns.startsWith("http:") && uri.getPort() != 80) {
          dns = dns + ":" + uri.getPort();
        }
      }
    } catch (URISyntaxException e) {
      throw new CloudException(e);
    }

    Distribution distribution = new Distribution();

    distribution.setName(container);
    distribution.setActive(enabled != null && enabled.equalsIgnoreCase("true"));
    distribution.setAliases(new String[0]);
    distribution.setDeployed(enabled != null && enabled.equalsIgnoreCase("true"));
    distribution.setDnsName(dns);
    distribution.setLocation(uriString);
    distribution.setLogDirectory(null);
    distribution.setProviderDistributionId(container);
    distribution.setProviderOwnerId(getTenantId());
    return distribution;
  }
 private static String localIp(String cloudControllerUri) {
   final URI uri = URI.create(cloudControllerUri);
   final int port = uri.getPort() == -1 ? 80 : uri.getPort();
   try (Socket socket = new Socket(uri.getHost(), port)) {
     return socket.getLocalAddress().getHostAddress();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 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();
  }
Esempio n. 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();
 }
Esempio n. 24
0
 private ServerAddress createServerAddress(String uriProperty)
     throws URISyntaxException, UnknownHostException {
   URI uri = new URI(uriProperty);
   int port = uri.getPort();
   ServerAddress serverAddress =
       port == -1
           ? new ServerAddress(uri.getHost())
           : new ServerAddress(uri.getHost(), uri.getPort());
   return serverAddress;
 }
Esempio n. 25
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);
  }
Esempio n. 26
0
 @SqlNullable
 @Description("extract port from url")
 @ScalarFunction
 @LiteralParameters("x")
 @SqlType(StandardTypes.BIGINT)
 public static Long urlExtractPort(@SqlType("varchar(x)") Slice url) {
   URI uri = parseUrl(url);
   if ((uri == null) || (uri.getPort() < 0)) {
     return null;
   }
   return (long) uri.getPort();
 }
Esempio n. 27
0
  public void setUri(URI uri, int defaultPort) {
    mHost = uri.getHost();

    mPort = defaultPort;
    if (uri.getPort() != -1) {
      mPort = uri.getPort();
    }

    if (uri.getUserInfo() != null) {
      mUserInfoParts = uri.getUserInfo().split(":", 2);
    }
  }
 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());
     }
   }
 }
Esempio n. 29
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri, String httpuser, String httppasswd) {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    postMethod.addHeader("charset", "UTF-8");
    // UPDATE THE VERSION NUMBER BEFORE RELEASE! <3 Dan
    postMethod.addHeader("User-Agent", "evodroid/" + Constants.versionNumber);

    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    // username & password not needed
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(httpuser, httppasswd);

    // this gets connections working over https
    if (uri.getScheme() != null) {
      if (uri.getScheme().equals("https")) {
        if (uri.getPort() == -1)
          try {
            client = new ConnectionClient(creds, 443);
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
        else
          try {
            client = new ConnectionClient(creds, uri.getPort());
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
      } else {
        client = new ConnectionClient(creds);
      }
    } else {
      client = new ConnectionClient(creds);
    }

    serializer = Xml.newSerializer();
  }
Esempio n. 30
0
  private void convertPort(Port port) throws IOException {
    String comment = "";
    String name = port.getName();
    String protocol = "soap";
    String location = "socket://localhost:80/";
    if (port.getDocumentationElement() != null) {
      comment = port.getDocumentationElement().getNodeValue();
    }
    List<ExtensibilityElement> extElements = port.getExtensibilityElements();
    for (ExtensibilityElement element : extElements) {
      if (element instanceof SOAPAddress) {
        location = ((SOAPAddress) element).getLocationURI().toString();
        StringBuilder builder = new StringBuilder();
        builder
            .append("soap {\n")
            .append("\t.wsdl = \"")
            .append(definition.getDocumentBaseURI())
            .append("\";\n")
            .append("\t.wsdl.port = \"")
            .append(port.getName())
            .append("\"\n}");
        protocol = builder.toString();

      } else if (element instanceof HTTPAddress) {
        location = ((HTTPAddress) element).getLocationURI().toString();
        protocol = "http";
      }
    }
    try {
      URI uri = new URI(location);
      uri =
          new URI(
              "socket",
              uri.getUserInfo(),
              uri.getHost(),
              (uri.getPort() < 1) ? 80 : uri.getPort(),
              uri.getPath(),
              uri.getQuery(),
              uri.getFragment());
      location = uri.toString();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    Binding binding = port.getBinding();
    PortType portType = binding.getPortType();
    convertPortType(portType, binding);
    outputPorts.put(
        name,
        new OutputPort(name, location, protocol, portType.getQName().getLocalPart(), comment));
  }