javax.servlet.http.HttpServletRequestWrapper#java.net.URI源码实例Demo

下面列出了javax.servlet.http.HttpServletRequestWrapper#java.net.URI 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: NewsMe   文件: PersistentCookieStore.java
@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;
    }
}
 
源代码2 项目: mxisd   文件: RegistrationManager.java
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());
    }
}
 
源代码3 项目: dremio-oss   文件: DremioFileSystem.java
@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();
}
 
@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());
}
 
源代码5 项目: big-c   文件: TestJobEndNotifier.java
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;
}
 
源代码6 项目: JglTF   文件: ObjGltfAssetCreatorV1.java
/**
 * 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);
}
 
源代码7 项目: emodb   文件: UserAccessControlClient.java
@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);
    }
}
 
源代码8 项目: keywhiz   文件: ClientAuthenticatorTest.java
@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);
}
 
源代码9 项目: TencentKona-8   文件: T6852595.java
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);
}
 
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;
  }
}
 
源代码11 项目: cyberduck   文件: DefaultUrlProvider.java
@Override
public DescriptiveUrlBag toUrl(final Path file) {
    final DescriptiveUrlBag list = new DescriptiveUrlBag();
    if(file.attributes().getLink() != DescriptiveUrl.EMPTY) {
        list.add(file.attributes().getLink());
    }
    list.add(new DescriptiveUrl(URI.create(String.format("%s%s",
        new HostUrlProvider().withUsername(false).get(host), URIEncoder.encode(file.getAbsolute()))),
        DescriptiveUrl.Type.provider,
        MessageFormat.format(LocaleFactory.localizedString("{0} URL"), host.getProtocol().getScheme().toString().toUpperCase(Locale.ROOT))));
    list.addAll(new WebUrlProvider(host).toUrl(file));
    return list;
}
 
源代码12 项目: cosmic   文件: NiciraNvpGuestNetworkGuru.java
private void checkThatLogicalSwitchExists(final Network userSpecified, final NiciraNvpDeviceVO niciraNvpDeviceVO) {
    final URI broadcastUri = userSpecified == null ? null : userSpecified.getBroadcastUri();
    if (broadcastUri != null) {
        final String lswitchUuid = broadcastUri.getRawSchemeSpecificPart();
        if (!lswitchExists(lswitchUuid, niciraNvpDeviceVO)) {
            throw new CloudRuntimeException("Refusing to design this network because the specified lswitch (" + lswitchUuid + ") does not exist.");
        }
    }
}
 
源代码13 项目: gcs   文件: OutputPreferences.java
@Override
public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == mPNGResolutionCombo) {
        Preferences.getInstance().setPNGResolution(DPI[mPNGResolutionCombo.getSelectedIndex()]);
    } else if (source == mGurpsCalculatorLink && Desktop.isDesktopSupported()) {
        try {
            Desktop.getDesktop().browse(new URI(GURPS_CALCULATOR_URL));
        } catch (Exception exception) {
            WindowUtils.showError(this, MessageFormat.format(I18n.Text("Unable to open {0}"), GURPS_CALCULATOR_URL));
        }
    }
    adjustResetButton();
}
 
源代码14 项目: capsule   文件: PathURLStreamHandler.java
@Override
protected URLConnection openConnection(URL url) throws IOException {
    try {
        URI uri = url.toURI();
        Path path = Paths.get(uri);
        return new PathURLConnection(url, path);
    } catch (URISyntaxException e) {
        throw new IOException("invalid URL", e);
    }
}
 
源代码15 项目: lucene-solr   文件: TestRandomChains.java
private static void collectClassesForPackage(String pckgname, List<Class<?>> classes) throws Exception {
  final ClassLoader cld = TestRandomChains.class.getClassLoader();
  final String path = pckgname.replace('.', '/');
  final Enumeration<URL> resources = cld.getResources(path);
  while (resources.hasMoreElements()) {
    final URI uri = resources.nextElement().toURI();
    if (!"file".equalsIgnoreCase(uri.getScheme()))
      continue;
    final Path directory = Paths.get(uri);
    if (Files.exists(directory)) {
      try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
        for (Path file : stream) {
          if (Files.isDirectory(file)) {
            // recurse
            String subPackage = pckgname + "." + file.getFileName().toString();
            collectClassesForPackage(subPackage, classes);
          }
          String fname = file.getFileName().toString();
          if (fname.endsWith(".class")) {
            String clazzName = fname.substring(0, fname.length() - 6);
            // exclude Test classes that happen to be in these packages.
            // class.ForName'ing some of them can cause trouble.
            if (!clazzName.endsWith("Test") && !clazzName.startsWith("Test")) {
              // Don't run static initializers, as we won't use most of them.
              // Java will do that automatically once accessed/instantiated.
              classes.add(Class.forName(pckgname + '.' + clazzName, false, cld));
            }
          }
        }
      }
    }
  }
}
 
源代码16 项目: activemq-artemis   文件: MQTTTest.java
@Test(timeout = 60 * 1000)
public void testLinkRouteAmqpReceiveMQTT() throws Exception {

   MQTT mqtt = createMQTTConnection();
   mqtt.setClientId("TestClient");
   BlockingConnection blockingConnection = mqtt.blockingConnection();
   blockingConnection.connect();
   Topic t = new Topic("test", QoS.AT_LEAST_ONCE);
   blockingConnection.subscribe(new Topic[]{t});

   AmqpClient client = new AmqpClient(new URI(AMQP_URI), null, null);
   AmqpConnection connection = client.connect();

   try {
      AmqpSession session = connection.createSession();
      AmqpSender sender = session.createSender("test", true);
      AmqpMessage message = new AmqpMessage();
      message.setText("Test-Message");
      sender.send(message);
      sender.close();
   } finally {
      connection.close();
   }

   try {
      blockingConnection.subscribe(new Topic[]{t});
      assertNotNull(blockingConnection.receive(5, TimeUnit.SECONDS));
   } finally {
      blockingConnection.kill();
   }
}
 
源代码17 项目: influx-proxy   文件: InfluxDBService.java
@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());
    }
}
 
源代码18 项目: lams   文件: Netty4ClientHttpRequestFactory.java
private Bootstrap getBootstrap(URI uri) {
	boolean isSecure = (uri.getPort() == 443 || "https".equalsIgnoreCase(uri.getScheme()));
	if (isSecure) {
		return buildBootstrap(uri, true);
	}
	else {
		if (this.bootstrap == null) {
			this.bootstrap = buildBootstrap(uri, false);
		}
		return this.bootstrap;
	}
}
 
源代码19 项目: cdi   文件: CustomerEndpoint.java
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createCustomer(Customer customer) {
  String customerId = UUID.randomUUID().toString();
  commandGateway.sendAndWait(new CreateCustomerCommand(customerId, customer.getFullName(), customer.getAge()));
  return Response.created(URI.create("http://localhost:8080/customer/" + customerId)).build();
}
 
源代码20 项目: Pushjet-Android   文件: WrapperExecutor.java
private URI readDistroUrl() throws URISyntaxException {
    if (properties.getProperty(DISTRIBUTION_URL_PROPERTY) != null) {
        return new URI(getProperty(DISTRIBUTION_URL_PROPERTY));
    }
    //try the deprecated way:
    return readDistroUrlDeprecatedWay();
}
 
源代码21 项目: netbeans   文件: AntArtifact.java
/**
 * Convenience method to find the actual artifacts, if they currently exist.
 * Uses {@link #getScriptFile} or {@link #getScriptLocation} and resolves {@link #getArtifactLocations} from it.
 * Note that a project which has been cleaned more recently than it has been built
 * will generally not have the build artifacts on disk and so this call may easily
 * return empty array. If you do not rely on the actual presence of the file but just need to
 * refer to it abstractly, use {@link #getArtifactLocations} instead.
 * @return the artifact files which exist on disk, or empty array if none could be found
 * @since 1.5
 */
public final FileObject[] getArtifactFiles() {
    List<FileObject> l = new ArrayList<FileObject>();
    for (URI artifactLocation : getArtifactLocations()) {
        FileObject fo = getArtifactFile(artifactLocation);
        if (fo != null) {
            l.add(fo);
        }
    }
    return l.toArray(new FileObject[l.size()]);
}
 
源代码22 项目: nexus-public   文件: UriStringValidator.java
@Override
public boolean isValid(final String uri, final ConstraintValidatorContext constraintValidatorContext) {
  if (isBlank(uri)) {
    return true;
  }

  try {
    new URI(uri);
    return true;
  }
  catch (URISyntaxException ignore) { // NOSONAR
    return false;
  }
}
 
源代码23 项目: Moss   文件: HipchatNotifierTest.java
@Before
public void setUp() {
    repository = mock(InstanceRepository.class);
    when(repository.find(instance.getId())).thenReturn(Mono.just(instance));

    restTemplate = mock(RestTemplate.class);
    notifier = new HipchatNotifier(repository);
    notifier.setNotify(true);
    notifier.setAuthToken("--token-");
    notifier.setRoomId("-room-");
    notifier.setUrl(URI.create("http://localhost/v2"));
    notifier.setRestTemplate(restTemplate);
}
 
@Test // gh-22107
public void readAsynchronousFileChannelCancelWithoutDemand() throws Exception {
	URI uri = this.resource.getURI();
	Flux<DataBuffer> flux = DataBufferUtils.readAsynchronousFileChannel(
			() -> AsynchronousFileChannel.open(Paths.get(uri), StandardOpenOption.READ),
			this.bufferFactory, 3);

	BaseSubscriber<DataBuffer> subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber);
	subscriber.cancel();
}
 
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());
	}
}
 
源代码26 项目: selenium   文件: DockerOptions.java
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);
  }
}
 
源代码27 项目: netbeans   文件: JspBreakpointPanel.java
/** 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");
}
 
/**
 * 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);
    }
}
 
源代码29 项目: streams   文件: SimpleHTTPPostPersistWriter.java
/**
 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;
}
 
源代码30 项目: keycloak   文件: CreateAuthnRequestStepBuilder.java
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;
}