java.net.URI Java Examples

The following examples show how to use java.net.URI. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PersistentCookieStore.java    From NewsMe with Apache License 2.0 7 votes vote down vote up
@Override
public boolean remove(URI uri, HttpCookie cookie)
{
    String name = getCookieToken(uri, cookie);

    if (cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name))
    {
        cookies.get(uri.getHost()).remove(name);

        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name))
        {
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);
        }
        prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
        prefsWriter.commit();

        return true;
    } else
    {
        return false;
    }
}
 
Example #2
Source File: WebSessionIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void changeSessionId() throws Exception {

	// First request: no session yet, new session created
	RequestEntity<Void> request = RequestEntity.get(createUri()).build();
	ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	String oldId = extractSessionId(response.getHeaders());
	assertNotNull(oldId);
	assertEquals(1, this.handler.getSessionRequestCount());

	// Second request: session id changes
	URI uri = new URI("http://localhost:" + this.port + "/?changeId");
	request = RequestEntity.get(uri).header("Cookie", "SESSION=" + oldId).build();
	response = this.restTemplate.exchange(request, Void.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	String newId = extractSessionId(response.getHeaders());
	assertNotNull("Expected new session id", newId);
	assertNotEquals(oldId, newId);
	assertEquals(2, this.handler.getSessionRequestCount());
}
 
Example #3
Source File: DremioFileSystem.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(URI name, Configuration conf) throws IOException {
  originalURI = name;
  switch (name.getScheme()) {
    case AsyncReaderUtils.DREMIO_S3:
      conf.set(AsyncReaderUtils.FS_DREMIO_S3_IMPL, "com.dremio.plugins.s3.store.S3FileSystem");
      updateS3Properties(conf);
      break;
    case AsyncReaderUtils.DREMIO_HDFS:
      conf.set(AsyncReaderUtils.FS_DREMIO_HDFS_IMPL, "org.apache.hadoop.hdfs.DistributedFileSystem");
      break;
    case AsyncReaderUtils.DREMIO_AZURE:
      conf.set(AsyncReaderUtils.FS_DREMIO_AZURE_IMPL, "com.dremio.plugins.azure.AzureStorageFileSystem");
      updateAzureConfiguration(conf, name);
      break;
    default:
      throw new UnsupportedOperationException("Unsupported async read path for hive parquet: " + name.getScheme());
  }
  try (ContextClassLoaderSwapper swapper =
         ContextClassLoaderSwapper.newInstance(HadoopFileSystem.class.getClassLoader())) {
    underLyingFs = HadoopFileSystem.get(name, conf.iterator(), true);
  }
  workingDir = new Path(name).getParent();
  scheme = name.getScheme();
}
 
Example #4
Source File: TestJobEndNotifier.java    From big-c with Apache License 2.0 6 votes vote down vote up
private static HttpServer2 startHttpServer() throws Exception {
  new File(System.getProperty(
      "build.webapps", "build/webapps") + "/test").mkdirs();
  HttpServer2 server = new HttpServer2.Builder().setName("test")
      .addEndpoint(URI.create("http://localhost:0"))
      .setFindPort(true).build();
  server.addServlet("jobend", "/jobend", JobEndServlet.class);
  server.start();

  JobEndServlet.calledTimes = 0;
  JobEndServlet.requestUri = null;
  JobEndServlet.baseUrl = "http://localhost:"
      + server.getConnectorAddress(0).getPort() + "/";
  JobEndServlet.foundJobState = null;
  return server;
}
 
Example #5
Source File: T6852595.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #6
Source File: RegistrationManager.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public RegistrationReply execute(URI target, JsonObject request) {
    HttpPost registerProxyRq = RestClientUtils.post(resolveProxyUrl(target), GsonUtil.get(), request);
    try (CloseableHttpResponse response = client.execute(registerProxyRq)) {
        int status = response.getStatusLine().getStatusCode();
        if (status == 200) {
            // The user managed to register. We check if it had a session
            String sessionId = GsonUtil.findObj(request, "auth").flatMap(auth -> GsonUtil.findString(auth, "session")).orElse("");
            if (StringUtils.isEmpty(sessionId)) {
                // No session ID was provided. This is an edge case we do not support for now as investigation is needed
                // to ensure how and when this happens.

                HttpPost newSessReq = RestClientUtils.post(resolveProxyUrl(target), GsonUtil.get(), new JsonObject());
                try (CloseableHttpResponse newSessRes = client.execute(newSessReq)) {
                    RegistrationReply reply = new RegistrationReply();
                    reply.setStatus(newSessRes.getStatusLine().getStatusCode());
                    reply.setBody(GsonUtil.parseObj(EntityUtils.toString(newSessRes.getEntity())));
                    return reply;
                }
            }
        }

        throw new NotImplementedException("Registration");
    } catch (IOException e) {
        throw new RemoteHomeServerException(e.getMessage());
    }
}
 
Example #7
Source File: ObjGltfAssetCreatorV1.java    From JglTF with MIT License 6 votes vote down vote up
/**
 * Create a {@link GltfAssetV1} from the OBJ file with the given URI
 * 
 * @param objUri The OBJ URI
 * @return The {@link GltfAssetV1}
 * @throws IOException If an IO error occurs
 */
public GltfAssetV1 create(URI objUri) throws IOException
{
    logger.log(level, "Creating glTF with " + bufferStrategy + 
        " buffer strategy");
    
    // Obtain the relative path information and file names
    logger.log(level, "Resolving paths from " + objUri);
    URI baseUri = IO.getParent(objUri);
    String objFileName = IO.extractFileName(objUri);
    String baseName = stripFileNameExtension(objFileName);
    String mtlFileName = baseName + ".mtl";
    URI mtlUri = IO.makeAbsolute(baseUri, mtlFileName);
    
    // Read the input data
    Obj obj = readObj(objUri);
    Map<String, Mtl> mtls = Collections.emptyMap();
    if (IO.existsUnchecked(mtlUri))
    {
        mtls = readMtls(mtlUri);
    }
    return convert(obj, mtls, baseName, baseUri);
}
 
Example #8
Source File: ClientAuthenticatorTest.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Before public void setUp() throws Exception {
  clientSpiffe = new URI(clientSpiffeStr);

  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate clientCert = (X509Certificate) cf.generateCertificate(
      new ByteArrayInputStream(clientPem.getBytes(UTF_8)));
  certPrincipal = new CertificatePrincipal(clientCert.getSubjectDN().toString(),
      new X509Certificate[] {clientCert});

  authenticator = new ClientAuthenticator(clientDAO, clientDAO, clientAuthConfig);

  when(clientDAO.getClientByName(clientName)).thenReturn(Optional.of(client));
  when(clientDAO.getClientBySpiffeId(clientSpiffe)).thenReturn(Optional.of(client));

  when(clientAuthConfig.typeConfig()).thenReturn(clientAuthTypeConfig);

  when(clientAuthTypeConfig.useCommonName()).thenReturn(true);
  when(clientAuthTypeConfig.useSpiffeId()).thenReturn(true);
}
 
Example #9
Source File: HttpResponseCache.java    From crosswalk-cordova-android with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  SSLSocket sslSocket = getSslSocket(httpConnection);
  if (sslSocket != null) {
    cipherSuite = sslSocket.getSession().getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = sslSocket.getSession().getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example #10
Source File: UserAccessControlClient.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public boolean checkApiKeyHasPermission(String apiKey, String id, String permission)
        throws EmoApiKeyNotFoundException {
    checkNotNull(id, "id");
    checkNotNull(permission, "permission");
    try {
        URI uri = _uac.clone()
                .segment("api-key")
                .segment(id)
                .segment("permitted")
                .queryParam("permission", permission)
                .build();
        return _client.resource(uri)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey)
                .get(Boolean.class);
    } catch (EmoClientException e) {
        throw convertException(e);
    }
}
 
Example #11
Source File: SimpleHTTPPostPersistWriter.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 Override this to alter request URI.
 */
protected URI prepareURI(Map<String, String> params) {
  URI uri = null;
  for (Map.Entry<String,String> param : params.entrySet()) {
    uriBuilder = uriBuilder.setParameter(param.getKey(), param.getValue());
  }
  try {
    uri = uriBuilder.build();
  } catch (URISyntaxException ex) {
    LOGGER.error("URI error {}", uriBuilder.toString());
  }
  return uri;
}
 
Example #12
Source File: InfluxDBService.java    From influx-proxy with Apache License 2.0 5 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void deleteRetention(Long id) {
    //根据ID软删除本地信息
    ManagementInfoPo managementInfoPo = managementInfoService.deleteRetentionById(id);
    //再删除influxdb
    String deleteRetentionUrl = String.format(Constants.BASE_URL, managementInfoPo.getNodeUrl(), managementInfoPo.getDatabaseName());
    String deleteRetentionData = String.format(Constants.DELETE_RETENTION_URL, managementInfoPo.getRetentionName(), managementInfoPo.getDatabaseName());

    try {
        URI uri = getUri(deleteRetentionUrl, deleteRetentionData);
        restTemplate.postForObject(uri, null, String.class);
    } catch (RestClientException e) {
        throw new InfluxDBProxyException(e.getMessage());
    }
}
 
Example #13
Source File: OAuth2TokenKeyServiceWithCache.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
private void retrieveTokenKeysAndFillCache(URI jwksUri)
		throws OAuth2ServiceException, InvalidKeySpecException, NoSuchAlgorithmException {
	JsonWebKeySet keySet = JsonWebKeySetFactory.createFromJson(getTokenKeyService().retrieveTokenKeys(jwksUri));
	if (keySet == null) {
		return;
	}
	Set<JsonWebKey> jwks = keySet.getAll();
	for (JsonWebKey jwk : jwks) {
		getCache().put(getUniqueCacheKey(jwk.getKeyAlgorithm(), jwk.getId(), jwksUri), jwk.getPublicKey());
	}
}
 
Example #14
Source File: RecursiveFileFinder.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void _findFiles(File aDirectory, List<URI> campaignFiles)
{
	for (final File file : aDirectory.listFiles(pccFileFilter))
	{
		if (file.isDirectory())
		{
			_findFiles(file, campaignFiles);
			continue;
		}
		campaignFiles.add(file.toURI());
	}
}
 
Example #15
Source File: DockerOptions.java    From selenium with Apache License 2.0 5 votes vote down vote up
private URI getDockerUri() {
  try {
    Optional<String> possibleUri = config.get(DOCKER_SECTION, "url");
    if (possibleUri.isPresent()) {
      return new URI(possibleUri.get());
    }

    Optional<String> possibleHost = config.get(DOCKER_SECTION, "host");
    if (possibleHost.isPresent()) {
      String host = possibleHost.get();
      if (!(host.startsWith("tcp:") || host.startsWith("http:") || host.startsWith("https"))) {
        host = "http://" + host;
      }
      URI uri = new URI(host);
      return new URI(
        "http",
        uri.getUserInfo(),
        uri.getHost(),
        uri.getPort(),
        uri.getPath(),
        null,
        null);
    }

    // Default for the system we're running on.
    if (Platform.getCurrent().is(WINDOWS)) {
      return new URI("http://localhost:2376");
    }
    return new URI("unix:/var/run/docker.sock");
  } catch (URISyntaxException e) {
    throw new ConfigException("Unable to determine docker url", e);
  }
}
 
Example #16
Source File: JspBreakpointPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Creates new form JspBreakpointPanel */
public JspBreakpointPanel(JspLineBreakpoint b) {

    breakpoint = b;
    controller = new JspBreakpointController();
    initComponents ();
    putClientProperty("HelpID", "jsp_breakpoint");//NOI18N

    // a11y
    getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(JspBreakpointPanel.class, "ACSD_LineBreakpointPanel")); // NOI18N
 
    String url = b.getURL();
    try {
        URI uri = new URI(url);
        cboxJspSourcePath.setText(uri.getPath());
    } catch (Exception e) {
        cboxJspSourcePath.setText(url);
    }

    int lnum = b.getLineNumber();
    if (lnum < 1)  {
        tfLineNumber.setText("");  //NOI18N
    } else {
        tfLineNumber.setText(Integer.toString(lnum));
    }
    
    actionsPanel = new ActionsPanel(b);
    pActions.add(actionsPanel, "Center");
}
 
Example #17
Source File: TestWebUi.java    From presto with Apache License 2.0 5 votes vote down vote up
private void testFailedLogin(URI uri, boolean passwordAllowed)
        throws IOException
{
    testFailedLogin(uri, Optional.empty(), Optional.empty());
    testFailedLogin(uri, Optional.empty(), Optional.of(TEST_PASSWORD));
    testFailedLogin(uri, Optional.empty(), Optional.of("unknown"));

    if (passwordAllowed) {
        testFailedLogin(uri, Optional.of(TEST_USER), Optional.of("unknown"));
        testFailedLogin(uri, Optional.of("unknown"), Optional.of(TEST_PASSWORD));
        testFailedLogin(uri, Optional.of(TEST_USER), Optional.empty());
        testFailedLogin(uri, Optional.of("unknown"), Optional.empty());
    }
}
 
Example #18
Source File: RESTEndpoint.java    From container with Apache License 2.0 5 votes vote down vote up
public RESTEndpoint(final String host, final String path, final restMethod method, final String managingContainer,
                    final String triggeringContainer, final CsarId csarId,
                    final Long serviceInstanceID, final Map<String, String> metadata) throws URISyntaxException {
    // Check if the path starts with a "/", if not we prepend a "/".
    this(new URI(host + (path.charAt(0) == '/' ? path : '/' + path)), method, triggeringContainer,
        managingContainer, csarId, serviceInstanceID, metadata);
}
 
Example #19
Source File: Session.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Session(SessionId id, URI uri, Capabilities capabilities) {
  this.id = Require.nonNull("Session ID", id);
  this.uri = Require.nonNull("Where the session is running", uri);

  this.capabilities = ImmutableCapabilities.copyOf(
      Require.nonNull("Session capabilities", capabilities));
}
 
Example #20
Source File: DataTransformator.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public DataTransformator surrogateEndpoint(URI endpoint) {
	checkNotNull(endpoint,"Endpoint URI cannot be null");
	checkArgument(!endpoint.isAbsolute(),"Endpoint URI must be relative");
	DataTransformator result=new DataTransformator(this);
	result.setEndpoint(endpoint, false);
	return result;
}
 
Example #21
Source File: AuthenticationEndpointTenantActivityListener.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize listener
 */
private synchronized void init() {
    try {
        tenantDataReceiveURLs = ConfigurationFacade.getInstance().getTenantDataEndpointURLs();

        if (!tenantDataReceiveURLs.isEmpty()) {

            serverURL = IdentityUtil.getServerURL("", true, true);
            int index = 0;

            for (String tenantDataReceiveUrl : tenantDataReceiveURLs) {
                URI tenantDataReceiveURI = new URI(tenantDataReceiveUrl);

                if (log.isDebugEnabled()) {
                    log.debug("Tenant list receiving url added : " + tenantDataReceiveUrl);
                }

                if (!tenantDataReceiveURI.isAbsolute()) {
                    // Set the absolute URL for tenant list receiving endpoint
                    tenantDataReceiveURLs.set(index, serverURL + tenantDataReceiveUrl);
                }
                index++;
            }

            initialized = true;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("TenantDataListenerURLs are not set in configuration");
            }
        }
    } catch (URISyntaxException e) {
        log.error("Error while getting TenantDataListenerURLs", e);
    }
}
 
Example #22
Source File: Connection.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs a new object.
 * 
 * @param info
 *            the connection information
 */
public Connection(final ConnectionInformation info) {
    final String protocolName = info.getProtocolName();
    final String protocolVersion = info.getProtocolVersion();
    protocol = new ConnectionProtocol(protocolName, protocolVersion);
    final URI remoteUri = info.getCallingDevice();
    remote = new ConnectionRemote(remoteUri);
    final URI localUri = info.getCalledDevice();
    local = new ConnectionLocal(localUri);
}
 
Example #23
Source File: CreateAuthnRequestStepBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public CreateAuthnRequestStepBuilder(URI authServerSamlUrl, String issuer, String assertionConsumerURL, Binding requestBinding, SamlClientBuilder clientBuilder) {
    super(clientBuilder);
    this.issuer = issuer;
    this.authServerSamlUrl = authServerSamlUrl;
    this.requestBinding = requestBinding;
    this.assertionConsumerURL = assertionConsumerURL;

    this.forceLoginRequestDocument = null;
}
 
Example #24
Source File: IdentityProvidersApiServiceImpl.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
@Override
public Response addIDP(IdentityProviderPOSTRequest identityProviderPOSTRequest) {

    IdentityProviderResponse idPResponse = idpManagementService.addIDP(identityProviderPOSTRequest);
    URI location =
            ContextLoader.buildURIForHeader(V1_API_PATH_COMPONENT + IDP_PATH_COMPONENT + "/" + idPResponse.getId());
    return Response.created(location).entity(idPResponse).build();
}
 
Example #25
Source File: TestBookKeeperJournalManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * If a journal manager has an corrupt inprogress node, ensure that we throw
 * an error, as this should not be possible, and some third party has
 * corrupted the zookeeper state
 */
@Test
public void testCorruptInprogressNode() throws Exception {
  URI uri = BKJMUtil.createJournalURI("/hdfsjournal-corruptInprogress");
  NamespaceInfo nsi = newNSInfo();
  BookKeeperJournalManager bkjm = new BookKeeperJournalManager(conf, uri,
                                                               nsi);
  bkjm.format(nsi);

  EditLogOutputStream out = bkjm.startLogSegment(1,
      NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);;
  for (long i = 1; i <= 100; i++) {
    FSEditLogOp op = FSEditLogTestUtil.getNoOpInstance();
    op.setTransactionId(i);
    out.write(op);
  }
  out.close();
  bkjm.finalizeLogSegment(1, 100);

  out = bkjm.startLogSegment(101,
      NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION);
  out.close();
  bkjm.close();

  String inprogressZNode = bkjm.inprogressZNode(101);
  zkc.setData(inprogressZNode, "WholeLottaJunk".getBytes(), -1);

  bkjm = new BookKeeperJournalManager(conf, uri, nsi);
  try {
    bkjm.recoverUnfinalizedSegments();
    fail("Should have failed. There should be no way of creating"
        + " an empty inprogess znode");
  } catch (IOException e) {
    // correct behaviour
    assertTrue("Exception different than expected", e.getMessage().contains(
        "has no field named"));
  } finally {
    bkjm.close();
  }
}
 
Example #26
Source File: HttpUtility.java    From datasync with MIT License 5 votes vote down vote up
/**
 * Conducts a basic post of the given entity; auth information is passed in the header.
 * @param uri  the uri to which the entity will be posted
 * @param entity an entity to post
 * @return the unprocessed results of the post
 */
public CloseableHttpResponse post(URI uri, HttpEntity entity) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setHeader(HttpHeaders.USER_AGENT, userAgent);
    httpPost.setHeader(entity.getContentType());
    httpPost.addHeader(datasyncVersionHeader, VersionProvider.getThisVersion());
    httpPost.setEntity(entity);
    if (proxyConfig != null)
        httpPost.setConfig(proxyConfig);
    if (authRequired) {
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpPost.setHeader(appHeader, appToken);
    }
    return httpClient.execute(httpPost);
}
 
Example #27
Source File: SystemProxies.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void printProxies(String proto) {
    System.out.println("Protocol:" + proto);
    for (String uri : uriAuthority) {
        String uriStr =  proto + uri;
        try {
            List<Proxy> proxies = proxySel.select(new URI(uriStr));
            System.out.println("\tProxies returned for " + uriStr);
            for (Proxy proxy : proxies)
                System.out.println("\t\t" + proxy);
        } catch (URISyntaxException e) {
            System.err.println(e);
        }
    }
}
 
Example #28
Source File: WebSocketClient.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public static InetSocketAddress toSocketAddress(URI uri)
{
    String scheme = uri.getScheme();
    if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme)))
        throw new IllegalArgumentException("Bad WebSocket scheme: " + scheme);
    int port = uri.getPort();
    if (port == 0)
        throw new IllegalArgumentException("Bad WebSocket port: " + port);
    if (port < 0)
        port = "ws".equals(scheme) ? 80 : 443;

    return new InetSocketAddress(uri.getHost(), port);
}
 
Example #29
Source File: AsyncStreamingRequestMarshallerTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SdkHttpFullRequest generateBasicRequest() {
    return SdkHttpFullRequest.builder()
                             .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes()))
                             .method(SdkHttpMethod.POST)
                             .putHeader("Host", "demo.us-east-1.amazonaws.com")
                             .putHeader("x-amz-archive-description", "test  test")
                             .encodedPath("/")
                             .uri(URI.create("http://demo.us-east-1.amazonaws.com"))
                             .build();
}
 
Example #30
Source File: DataSetGetMetadataLegacy.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private void configureSampleDataset(String dataSetId) {
    URI uri;
    try {
        final URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl);
        uriBuilder.setPath(uriBuilder.getPath() + "/datasets/" + dataSetId + "/sample/metadata");
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }

    execute(() -> new HttpGet(uri));
    on(HttpStatus.OK).then(convertResponse(objectMapper, DataSetMetadata.class));
}