Java Code Examples for java.net.URI.getPort()

The following are Jave code examples for showing how to use getPort() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: whackpad   File: HttpServletRequestFactory.java   View Source Code Vote up 6 votes
public InnerHttpServletRequest(URI uri, Map<String, String> headers, String method,
			       String body) 
  throws java.net.URISyntaxException {
    this.method = method;
    this.host = uri.getHost();
    this.scheme = uri.getScheme();
    this.port = uri.getPort();
    this.path = uri.getRawPath();
    this.queryString = uri.getRawQuery();
    extractParameters();
    extractHeaders(headers);
    this.headers.put("host", host);
    if (body != null)
	this.headers.put("content-length", Integer.toString(body.length()));
    this.body = body;
}
 
Example 2
Project: lams   File: HTTPMetadataProvider.java   View Source Code Vote up 6 votes
/**
 * Constructor.
 * 
 * @param metadataURL the URL to fetch the metadata
 * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond
 * 
 * @throws MetadataProviderException thrown if the URL is not a valid URL or the metadata can not be retrieved from
 *             the URL
 */
@Deprecated
public HTTPMetadataProvider(String metadataURL, int requestTimeout) throws MetadataProviderException {
    super();
    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(requestTimeout);
    httpClient = new HttpClient(clientParams);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(requestTimeout);
    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());

}
 
Example 3
Project: lams   File: OAuthSignatureMethod.java   View Source Code Vote up 6 votes
protected static String normalizeUrl(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String scheme = uri.getScheme().toLowerCase();
    String authority = uri.getAuthority().toLowerCase();
    boolean dropPort = (scheme.equals("http") && uri.getPort() == 80)
                       || (scheme.equals("https") && uri.getPort() == 443);
    if (dropPort) {
        // find the last : in the authority
        int index = authority.lastIndexOf(":");
        if (index >= 0) {
            authority = authority.substring(0, index);
        }
    }
    String path = uri.getRawPath();
    if (path == null || path.length() <= 0) {
        path = "/"; // conforms to RFC 2616 section 3.2.2
    }
    // we know that there is no query and no fragment here.
    return scheme + "://" + authority + path;
}
 
Example 4
Project: x7   File: BinaryJedis.java   View Source Code Vote up 6 votes
private void initializeClientFromURI(URI uri) {
  if (!JedisURIHelper.isValid(uri)) {
    throw new InvalidURIException(String.format(
      "Cannot open Redis connection due invalid URI. %s", uri.toString()));
  }

  client = new Client(uri.getHost(), uri.getPort());

  String password = JedisURIHelper.getPassword(uri);
  if (password != null) {
    client.auth(password);
    client.getStatusCodeReply();
  }

  int dbIndex = JedisURIHelper.getDBIndex(uri);
  if (dbIndex > 0) {
    client.select(dbIndex);
    client.getStatusCodeReply();
    client.setDb(dbIndex);
  }
}
 
Example 5
Project: jSpace   File: TcpGateBuilder.java   View Source Code Vote up 6 votes
@Override
public ServerGate createServerGate(URI uri) {
	String host = uri.getHost();
	int port = uri.getPort();
	if (port < 0) {
		port = DEFAULT_PORT;
	}
	HashMap<String,String> query = GateFactory.parseQuery(uri.getQuery());
	jSpaceMarshaller marshaller = getMarshaller(query.get(GateFactory.LANGUAGE_QUERY_ELEMENT));
	String mode = query.getOrDefault(GateFactory.MODE_QUERY_ELEMENT,DEFAULT_MODE).toUpperCase();
	if (query.containsKey(KEEP_MODE)) {
		return new KeepServerGate(marshaller,new InetSocketAddress(host, port),DEFAULT_BACKLOG);
	}
	if (query.containsKey(CONN_MODE)) {
		return new ConnServerGate(marshaller, new InetSocketAddress(host, port),DEFAULT_BACKLOG);
	}
	//TODO: Add here other modes!
	return new KeepServerGate(marshaller,new InetSocketAddress(host, port),DEFAULT_BACKLOG);
}
 
Example 6
Project: RNLearn_Project1   File: WebSocketModule.java   View Source Code Vote up 5 votes
/**
 * Get the default HTTP(S) origin for a specific WebSocket URI
 *
 * @param String uri
 * @return A string of the endpoint converted to HTTP protocol (http[s]://host[:port])
 */

private static String getDefaultOrigin(String uri) {
  try {
    String defaultOrigin;
    String scheme = "";

    URI requestURI = new URI(uri);
    if (requestURI.getScheme().equals("wss")) {
      scheme += "https";
    } else if (requestURI.getScheme().equals("ws")) {
      scheme += "http";
    } else if (requestURI.getScheme().equals("http") || requestURI.getScheme().equals("https")) {
      scheme += requestURI.getScheme();
    }

    if (requestURI.getPort() != -1) {
      defaultOrigin = String.format(
        "%s://%s:%s",
        scheme,
        requestURI.getHost(),
        requestURI.getPort());
    } else {
      defaultOrigin = String.format("%s://%s/", scheme, requestURI.getHost());
    }

    return defaultOrigin;
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException("Unable to set " + uri + " as default origin header");
  }
}
 
Example 7
Project: indeed-grpc-java   File: ConsulNameResolverProvider.java   View Source Code Vote up 5 votes
@Nullable
@Override
public ConsulNameResolver newNameResolver(final URI targetUri, final Attributes params) {
    if (!SCHEME.equals(targetUri.getScheme())) {
        return null;
    }

    final String targetPath = checkNotNull(targetUri.getPath(), "targetPath");
    checkArgument(targetPath.startsWith("/"));

    final String serviceName = targetPath.substring(1);
    checkArgument(serviceName.length() > 0, "serviceName");

    String consulHost = targetUri.getHost();
    if (Strings.isNullOrEmpty(consulHost)) {
        consulHost = DEFAULT_HOST;
    }

    int consulPort = targetUri.getPort();
    if (consulPort == -1) {
        consulPort = DEFAULT_PORT;
    }

    final String tag = Strings.emptyToNull(targetUri.getFragment());

    final ConsulClient consulClient = ConsulClientManager.getInstance(consulHost, consulPort);

    return new ConsulNameResolver(
            consulClient /* CatalogClient */,
            consulClient /* KeyValueClient */,
            serviceName,
            Optional.ofNullable(tag),
            GrpcUtil.TIMER_SERVICE,
            GrpcUtil.SHARED_CHANNEL_EXECUTOR
    );
}
 
Example 8
Project: syndesis   File: BaseCredentialProvider.java   View Source Code Vote up 5 votes
protected static String callbackUrlFor(final URI baseUrl, final MultiValueMap<String, String> additionalParams) {
    final String path = baseUrl.getPath();

    final String callbackPath = path + "credentials/callback";

    try {
        final URI base = new URI(baseUrl.getScheme(), null, baseUrl.getHost(), baseUrl.getPort(), callbackPath,
            null, null);

        return UriComponentsBuilder.fromUri(base).queryParams(additionalParams).build().toUriString();
    } catch (final URISyntaxException e) {
        throw new IllegalStateException("Unable to generate callback URI", e);
    }
}
 
Example 9
Project: lams   File: AutoRetryHttpClient.java   View Source Code Vote up 5 votes
public HttpResponse execute(HttpUriRequest request, HttpContext context)
        throws IOException {
    URI uri = request.getURI();
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(),
            uri.getScheme());
    return execute(httpHost, request, context);
}
 
Example 10
Project: hadoop   File: NetUtils.java   View Source Code Vote up 5 votes
/**
 * Create an InetSocketAddress from the given target string and
 * default port. If the string cannot be parsed correctly, the
 * <code>configName</code> parameter is used as part of the
 * exception message, allowing the user to better diagnose
 * the misconfiguration.
 *
 * @param target a string of either "host" or "host:port"
 * @param defaultPort the default port if <code>target</code> does not
 *                    include a port number
 * @param configName the name of the configuration from which
 *                   <code>target</code> was loaded. This is used in the
 *                   exception message in the case that parsing fails. 
 */
public static InetSocketAddress createSocketAddr(String target,
                                                 int defaultPort,
                                                 String configName) {
  String helpText = "";
  if (configName != null) {
    helpText = " (configuration property '" + configName + "')";
  }
  if (target == null) {
    throw new IllegalArgumentException("Target address cannot be null." +
        helpText);
  }
  target = target.trim();
  boolean hasScheme = target.contains("://");    
  URI uri = null;
  try {
    uri = hasScheme ? URI.create(target) : URI.create("dummyscheme://"+target);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(
        "Does not contain a valid host:port authority: " + target + helpText
    );
  }

  String host = uri.getHost();
  int port = uri.getPort();
  if (port == -1) {
    port = defaultPort;
  }
  String path = uri.getPath();
  
  if ((host == null) || (port < 0) ||
      (!hasScheme && path != null && !path.isEmpty()))
  {
    throw new IllegalArgumentException(
        "Does not contain a valid host:port authority: " + target + helpText
    );
  }
  return createSocketAddrForHost(host, port);
}
 
Example 11
Project: ysoserial-modified   File: JBoss.java   View Source Code Vote up 5 votes
private static void doRun ( URI u, final Object payloadObject, String username, String password ) {
    ConnectionProvider instance = null;
    ConnectionProviderContextImpl context = null;
    ConnectionHandler ch = null;
    Channel c = null;
    VersionedConnection vc = null;
    try {
        Logger logger = LogManager.getLogManager().getLogger("");
        logger.addHandler(new ConsoleLogHandler());
        logger.setLevel(Level.INFO);
        OptionMap options = OptionMap.builder().set(Options.SSL_ENABLED, u.getScheme().equals("https")).getMap();
        context = new ConnectionProviderContextImpl(options, "endpoint");
        instance = new HttpUpgradeConnectionProviderFactory().createInstance(context, options);
        String host = u.getHost();
        int port = u.getPort() > 0 ? u.getPort() : 9990;
        SocketAddress destination = new InetSocketAddress(host, port);
        ConnectionHandlerFactory chf = getConnection(destination, username, password, context, instance, options);
        ch = chf.createInstance(new ConnectionHandlerContextImpl(context));
        c = getChannel(context, ch, options);
        System.err.println("Connected");
        vc = makeVersionedConnection(c);
        MBeanServerConnection mbc = vc.getMBeanServerConnection(null);
        doExploit(payloadObject, mbc);
        System.err.println("DONE");
    }
    catch ( Throwable e ) {
        e.printStackTrace(System.err);
    }
    finally {
        cleanup(instance, context, ch, c, vc);
    }
}
 
Example 12
Project: JRediClients   File: RedisNodes.java   View Source Code Vote up 5 votes
@Override
public N getNode(String address) {
    Collection<N> clients = (Collection<N>) connectionManager.getClients();
    URI uri = URIBuilder.create(address);
    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
    for (N node : clients) {
        if (node.getAddr().equals(addr)) {
            return node;
        }
    }
    return null;
}
 
Example 13
Project: dremio-oss   File: RemoteNodeFileSystem.java   View Source Code Vote up 5 votes
@Override
public void initialize(URI name, Configuration conf) throws IOException {
  super.initialize(name, conf);
  if (name.getHost() == null || name.getPort() == -1) {
    throw new IllegalArgumentException("FileSystem name needs a complete authority element.");
  }
  uri = name;  }
 
Example 14
Project: angel   File: HdfsUtil.java   View Source Code Vote up 5 votes
public static Path generateTmpDirectory(Configuration conf, String appId, Path outputPath) {
  URI uri = outputPath.toUri();
  String path = (uri.getScheme() != null ? uri.getScheme() : "hdfs") + "://"
           + (uri.getHost() != null ? uri.getHost() : "")
           + (uri.getPort() > 0 ? (":" + uri.getPort()) : "");
  String user = conf.get(AngelConf.USER_NAME, "");
  String tmpDir = conf.get(AngelConf.ANGEL_JOB_TMP_OUTPUT_PATH_PREFIX, "/tmp/" + user);
  String finalTmpDirForApp = path + tmpDir + "/" + appId + "_" + UUID.randomUUID().toString();
  LOG.info("tmp output dir is " + finalTmpDirForApp);
  return new Path(finalTmpDirForApp);
}
 
Example 15
Project: talchain   File: Node.java   View Source Code Vote up 5 votes
public Node(String enodeURL) {
    try {
        URI uri = new URI(enodeURL);
        if (!uri.getScheme().equals("enode")) {
            throw new RuntimeException("expecting URL in the format enode://[email protected]:PORT");
        }
        this.id = Hex.decode(uri.getUserInfo());
        this.host = uri.getHost();
        this.port = uri.getPort();
    } catch (URISyntaxException e) {
        throw new RuntimeException("expecting URL in the format enode://[email protected]:PORT", e);
    }
}
 
Example 16
Project: APacheSynapseSimplePOC   File: JBoss.java   View Source Code Vote up 5 votes
private static void doRun ( URI u, final Object payloadObject, String username, String password ) {
    ConnectionProvider instance = null;
    ConnectionProviderContextImpl context = null;
    ConnectionHandler ch = null;
    Channel c = null;
    VersionedConnection vc = null;
    try {
        Logger logger = LogManager.getLogManager().getLogger("");
        logger.addHandler(new ConsoleLogHandler());
        logger.setLevel(Level.INFO);
        OptionMap options = OptionMap.builder().set(Options.SSL_ENABLED, u.getScheme().equals("https")).getMap();
        context = new ConnectionProviderContextImpl(options, "endpoint");
        instance = new HttpUpgradeConnectionProviderFactory().createInstance(context, options);
        String host = u.getHost();
        int port = u.getPort() > 0 ? u.getPort() : 9990;
        SocketAddress destination = new InetSocketAddress(host, port);
        ConnectionHandlerFactory chf = getConnection(destination, username, password, context, instance, options);
        ch = chf.createInstance(new ConnectionHandlerContextImpl(context));
        c = getChannel(context, ch, options);
        System.err.println("Connected");
        vc = makeVersionedConnection(c);
        MBeanServerConnection mbc = vc.getMBeanServerConnection(null);
        doExploit(payloadObject, mbc);
        System.err.println("DONE");
    }
    catch ( Throwable e ) {
        e.printStackTrace(System.err);
    }
    finally {
        cleanup(instance, context, ch, c, vc);
    }
}
 
Example 17
Project: kafka-streams-on-heroku   File: PostgresSink.java   View Source Code Vote up 5 votes
private static Connection getConnection() throws URISyntaxException, SQLException {
  URI dbUri = new URI(System.getenv("HEROKU_POSTGRESQL_URL"));

  String[] userInfo = Optional.ofNullable(dbUri.getUserInfo()).orElse(":").split(":");
  String username = userInfo.length == 0 ? null : userInfo[0];
  String password = userInfo.length == 0 ? null : userInfo[1];
  String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

  return DriverManager.getConnection(dbUrl, username, password);
}
 
Example 18
Project: cyberduck   File: CloudFrontDistributionConfiguration.java   View Source Code Vote up 4 votes
protected com.amazonaws.services.cloudfront.model.Distribution createCustomDistribution(final Path container, final Distribution distribution)
    throws BackgroundException {
    final AmazonCloudFront client = client(container);
    int httpPort = 80;
    int httpsPort = 443;
    final URI origin = this.getOrigin(container, distribution.getMethod());
    if(origin.getPort() != -1) {
        if(origin.getScheme().equals(Scheme.http.name())) {
            httpPort = origin.getPort();
        }
        if(origin.getScheme().equals(Scheme.https.name())) {
            httpsPort = origin.getPort();
        }
    }
    final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
    final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(), distribution.isEnabled())
        .withComment(originId)
        .withOrigins(new Origins()
            .withQuantity(1)
            .withItems(new Origin()
                .withId(originId)
                .withDomainName(origin.getHost())
                .withCustomOriginConfig(new CustomOriginConfig()
                    .withHTTPPort(httpPort)
                    .withHTTPSPort(httpsPort)
                    .withOriginSslProtocols(new OriginSslProtocols().withQuantity(2).withItems("TLSv1.1", "TLSv1.2"))
                    .withOriginProtocolPolicy(this.getPolicy(distribution.getMethod()))
                )
            )
        )
        .withPriceClass(PriceClass.PriceClass_All)
        .withDefaultCacheBehavior(new DefaultCacheBehavior()
            .withTargetOriginId(originId)
            .withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(new CookiePreference().withForward(ItemSelection.All)))
            .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
            .withMinTTL(0L)
            .withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
        .withDefaultRootObject(distribution.getIndexDocument())
        .withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
    if(distribution.isLogging()) {
        // Make bucket name fully qualified
        final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
            false, new S3Protocol().getDefaultHostname());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
        }
        config.setLogging(new LoggingConfig()
            .withEnabled(distribution.isLogging())
            .withIncludeCookies(true)
            .withBucket(loggingTarget)
            .withPrefix(preferences.getProperty("cloudfront.logging.prefix"))
        );
    }
    return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}
 
Example 19
Project: Pogamut3   File: SocketConnectionAddress.java   View Source Code Vote up 4 votes
public SocketConnectionAddress(URI uri) {
	this(uri.getHost(), uri.getPort());
}
 
Example 20
Project: hadoop   File: NameNodeProxies.java   View Source Code Vote up 4 votes
/** Creates the Failover proxy provider instance*/
@VisibleForTesting
public static <T> AbstractNNFailoverProxyProvider<T> createFailoverProxyProvider(
    Configuration conf, URI nameNodeUri, Class<T> xface, boolean checkPort,
    AtomicBoolean fallbackToSimpleAuth) throws IOException {
  Class<FailoverProxyProvider<T>> failoverProxyProviderClass = null;
  AbstractNNFailoverProxyProvider<T> providerNN;
  Preconditions.checkArgument(
      xface.isAssignableFrom(NamenodeProtocols.class),
      "Interface %s is not a NameNode protocol", xface);
  try {
    // Obtain the class of the proxy provider
    failoverProxyProviderClass = getFailoverProxyProviderClass(conf,
        nameNodeUri);
    if (failoverProxyProviderClass == null) {
      return null;
    }
    // Create a proxy provider instance.
    Constructor<FailoverProxyProvider<T>> ctor = failoverProxyProviderClass
        .getConstructor(Configuration.class, URI.class, Class.class);
    FailoverProxyProvider<T> provider = ctor.newInstance(conf, nameNodeUri,
        xface);

    // If the proxy provider is of an old implementation, wrap it.
    if (!(provider instanceof AbstractNNFailoverProxyProvider)) {
      providerNN = new WrappedFailoverProxyProvider<T>(provider);
    } else {
      providerNN = (AbstractNNFailoverProxyProvider<T>)provider;
    }
  } catch (Exception e) {
    String message = "Couldn't create proxy provider " + failoverProxyProviderClass;
    if (LOG.isDebugEnabled()) {
      LOG.debug(message, e);
    }
    if (e.getCause() instanceof IOException) {
      throw (IOException) e.getCause();
    } else {
      throw new IOException(message, e);
    }
  }

  // Check the port in the URI, if it is logical.
  if (checkPort && providerNN.useLogicalURI()) {
    int port = nameNodeUri.getPort();
    if (port > 0 && port != NameNode.DEFAULT_PORT) {
      // Throwing here without any cleanup is fine since we have not
      // actually created the underlying proxies yet.
      throw new IOException("Port " + port + " specified in URI "
          + nameNodeUri + " but host '" + nameNodeUri.getHost()
          + "' is a logical (HA) namenode"
          + " and does not use port information.");
    }
  }
  providerNN.setFallbackToSimpleAuth(fallbackToSimpleAuth);
  return providerNN;
}