org.apache.http.client.methods.HttpTrace#java.net.URISyntaxException源码实例Demo

下面列出了org.apache.http.client.methods.HttpTrace#java.net.URISyntaxException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@SuppressWarnings( "squid:S2095" )
private Class<?> loadClassByName( final String className, final URL jarUrl, final ClassLoader parentClassLoader, boolean addConfigFiles )
  throws ClassNotFoundException, MalformedURLException, URISyntaxException {
  if ( className != null ) {
    // ignoring this warning; paths are to the local file system so no host name lookup should happen
    @SuppressWarnings( "squid:S2112" )
    Set<URL> urlSet = new HashSet<>();
    if ( addConfigFiles ) {
      List<URL> urlList = new ArrayList<>();
      ShimConfigsLoader.addConfigsAsResources( namedCluster.getName(), urlList::add );
      for ( URL url : urlList ) {
        // get the parent dir of each config file
        urlSet.add( Paths.get( url.toURI() ).getParent().toUri().toURL() );
      }
    }
    urlSet.add( jarUrl );
    URLClassLoader cl = new URLClassLoader( urlSet.toArray( new URL[0] ), parentClassLoader );
    return cl.loadClass( className.replace( "/", "." ) );
  } else {
    return null;
  }
}
 
源代码2 项目: olingo-odata2   文件: AtomEntryEntityProducer.java
private void appendAtomNavigationLink(final XMLStreamWriter writer, final String target,
    final String navigationPropertyName, final boolean isFeed, final EntityInfoAggregator eia,
    final Map<String, Object> data) throws EntityProviderException, EdmException, URISyntaxException {
  try {
    writer.writeStartElement(FormatXml.ATOM_LINK);
    writer.writeAttribute(FormatXml.ATOM_HREF, target);
    writer.writeAttribute(FormatXml.ATOM_REL, Edm.NAMESPACE_REL_2007_08 + navigationPropertyName);
    writer.writeAttribute(FormatXml.ATOM_TITLE, navigationPropertyName);
    if (isFeed) {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_FEED.toString());
      appendInlineFeed(writer, navigationPropertyName, eia, data, target);
    } else {
      writer.writeAttribute(FormatXml.ATOM_TYPE, ContentType.APPLICATION_ATOM_XML_ENTRY.toString());
      appendInlineEntry(writer, navigationPropertyName, eia, data);
    }
    writer.writeEndElement();
  } catch (XMLStreamException e) {
    throw new EntityProviderProducerException(EntityProviderException.COMMON, e);
  }
}
 
源代码3 项目: pb-java   文件: PandorabotsAPI.java
/**
 * composing URI for handling file.
 * <p>
 * URI form varies as follows depending on extension.<br>
 * <ul>
 * <li>/bot/{appId}/{botName}/{fileKind} for pdefaults, properties.
 * <li>/bot/{appId}/{botName}/{fileKind}/baseName for map, set,
 * substitution.
 * <li>/bot/{appId}/{botName}/file/baseName.extName for aiml.
 * </ul>
 * <p>
 * 
 * @param botName
 * @param pathName
 * @return URI for request
 * @throws URISyntaxException
 * @since 0.0.9
 */
private URI fileUri(String botName, String pathName)
		throws URISyntaxException {
	String baseName = FilenameUtils.getBaseName(pathName);
	String extName = FilenameUtils.getExtension(pathName);
	String fileKind = extName;
	String fileName = null;
	if (extName.equals("pdefaults") || extName.equals("properties")) {
		;
	} else if (extName.equals("map") || extName.equals("set")
			|| extName.equals("substitution")) {
		fileName = baseName;
	} else if (extName.equals("aiml")) {
		fileKind = "file";
		fileName = baseName + "." + extName;
	}
	return new URI(composeUri("bot", botName, fileKind, fileName)
			+ composeParams(null));
}
 
源代码4 项目: swagger2markup   文件: AsciidocConverterTest.java
@Test
public void testWithInlineSchemaAndFlatBody() throws URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_inlineSchema.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/inline_schema_flat_body");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config =  new Swagger2MarkupConfigBuilder()
            .withFlatBody()
            .build();
    Swagger2MarkupConverter.from(file)
            .withConfig(config)
            .build()
            .toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);
    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/inline_schema_flat_body").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testWithInlineSchemaAndFlatBody.html");
}
 
源代码5 项目: fxlauncher   文件: CreateManifest.java
public static FXManifest create(URI baseURI, String launchClass, Path appPath) throws IOException, URISyntaxException {
    FXManifest manifest = new FXManifest();
    manifest.ts = System.currentTimeMillis();
    manifest.uri = baseURI;
    manifest.launchClass = launchClass;

    if (!manifest.uri.getPath().endsWith("/")) {
        manifest.uri = new URI(String.format("%s/", baseURI.toString()));
    }
    Files.walkFileTree(appPath, new SimpleFileVisitor<Path>() {
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (!Files.isDirectory(file) && shouldIncludeInManifest(file) && !file.getFileName().toString().startsWith("fxlauncher"))
                manifest.files.add(new LibraryFile(appPath, file));
            return FileVisitResult.CONTINUE;
        }
    });

    return manifest;
}
 
源代码6 项目: cxf   文件: AbstractWrapperWSDLLocator.java
public InputSource getImportInputSource(String parentLocation, String importLocation) {
    // Do a check on the scheme to see if it's anything that could be a security risk
    try {
        URI url = new URI(importLocation);
        if (!(url.getScheme() == null || ALLOWED_SCHEMES.contains(url.getScheme()))) {
            throw new IllegalArgumentException("The " + url.getScheme() + " URI scheme is not allowed");
        }
    } catch (URISyntaxException e) {
        // Just continue here as we might still be able to load it from the filesystem
    }

    InputSource src = parent.getImportInputSource(parentLocation, importLocation);
    lastImport = null;
    if (src == null || (src.getByteStream() == null && src.getCharacterStream() == null)) {
        src = getInputSource(parentLocation, importLocation);
        if (src != null) {
            lastImport = src.getSystemId();
        }
    }
    return src;
}
 
源代码7 项目: p4ic4idea   文件: CharsetConverterTest.java
@Test(expected=FileDecoderException.class)
public void testCharsetConverterCharsetCharsetInvalid() throws IOException, UnsupportedCharsetException, ConnectionException, RequestException, AccessException, NoSuchObjectException, ConfigException, ResourceException, URISyntaxException, FileDecoderException, FileEncoderException {
	File testResourceFile = loadFileFromClassPath(CLASS_PATH_PREFIX + "/euc-jp.txt");
	
	CharsetConverter convert = new CharsetConverter(PerforceCharsets.getP4Charset("shiftjis"), CharsetDefs.UTF8);
	
	InputStream inStream = new FileInputStream(testResourceFile);

	byte[] bytes = new byte[2048];
	int read = inStream.read(bytes);
	inStream.close();
	
	byte[] trueIn = new byte[read];
	System.arraycopy(bytes, 0, trueIn, 0, read);
	
	ByteBuffer bufIn  = ByteBuffer.wrap(bytes, 0, read);
	convert.convert(bufIn);
}
 
源代码8 项目: components   文件: Oauth2JwtClientTest.java
@Test
public void testOK() throws UnsupportedEncodingException, IOException, InterruptedException, URISyntaxException {
    // start server
    JwtTestServer server = new JwtTestServer(UseCase.OK);
    Thread serverThread = new Thread(server);
    serverThread.start();

    Map<String, String> params = new HashMap<>();
    params.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");

    // Get Access Token
    JsonNode accessToken = Oauth2JwtClient.builder()//
            .withJwsHeaders(jwsHeaders())//
            .withJwtClaims(claims())//
            .signWithX509Key(x509Key(), org.talend.components.common.oauth.X509Key.Algorithm.SHA256withRSA)//
            .fromTokenEndpoint("http://" + endpoint + ":" + server.getLocalPort())//
            .withPlayloadParams(params)//
            .build()//
            .getAccessToken();

    serverThread.join(30000);

    assertNotNull(accessToken);
    assertNotNull(accessToken.get("access_token"));
}
 
源代码9 项目: tomee   文件: UriResolver.java
private void tryClasspath(String uriStr) throws IOException {
    if (uriStr.startsWith("classpath:")) {
        uriStr = uriStr.substring(10);
    }
    url = getResource(uriStr, calling);
    if (url == null) {
        tryRemote(uriStr);
    } else {
        try {
            uri = url.toURI();
        } catch (final URISyntaxException e) {
            // processing the jar:file:/ type value
            final String urlStr = url.toString();
            if (urlStr.startsWith("jar:")) {
                final int pos = urlStr.indexOf('!');
                if (pos != -1) {
                    uri = URLs.uri("classpath:" + urlStr.substring(pos + 1));
                }
            }

        }
        is = IO.read(url);
    }
}
 
private URI applyPHP(URI uri) throws ClientProtocolException  {
  if (bots!=null) {
    try {
      String orgUri = uri.toString();
      PHP php = parsePHP(bots.getHost());
      if (php!=null) {
        uri = updateURI(uri,php);
      }
      if (!uri.toString().equals(orgUri)) {
        LOG.debug(String.format("Uri updated from %s to %s", orgUri, uri));
      }
    } catch (URISyntaxException ex) {
      throw new ClientProtocolException("Unable to apply host robots.txt host directive.", ex);
    }
  }
  return uri;
}
 
源代码11 项目: magarena   文件: GameStateRunner.java
private JPanel getMainPanel() {

        try {
            testClasses = new JList<>(getListOfTestClasses());
        } catch (IOException | URISyntaxException ex) {
            System.err.println(ex);
        }

        testClasses.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        testClasses.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
                    loadTestClassAndRun(testClasses.getSelectedValue());
                }
            }
        });

        final JScrollPane listScroller = new JScrollPane(testClasses);
        listScroller.setPreferredSize(new Dimension(getWidth(), getHeight()));

        final JPanel panel = new JPanel(new MigLayout("insets 0, gap 0"));
        panel.add(listScroller, "w 100%, h 100%");
        return panel;
    }
 
源代码12 项目: apicurio-studio   文件: MockGitHubService.java
/**
 * @see io.apicurio.hub.api.github.IGitHubSourceConnector#validateResourceExists(java.lang.String)
 */
@Override
public ApiDesignResourceInfo validateResourceExists(String repositoryUrl) throws NotFoundException {
    getAudit().add("validateResourceExists::" + repositoryUrl);
    if (repositoryUrl.endsWith("new-api.json")) {
        throw new NotFoundException();
    }
    try {
        URI uri = new URI(repositoryUrl);
        String name = new File(uri.getPath()).getName();
        ApiDesignResourceInfo info = new ApiDesignResourceInfo();
        info.setName(name);
        info.setDescription(repositoryUrl);
        info.setTags(new HashSet<String>(Arrays.asList("tag1", "tag2")));
        info.setType(ApiDesignType.OpenAPI20);
        return info;
    } catch (URISyntaxException e) {
        throw new NotFoundException();
    }
}
 
源代码13 项目: java-cfenv   文件: SqlServerJdbcUrlCreator.java
@Override
public String buildJdbcUrlFromUriField(CfCredentials cfCredentials) {
	UriInfo uriInfo = cfCredentials.getUriInfo(SQLSERVER_SCHEME);
	Map<String, String> uriParameters = parseSqlServerUriParameters(uriInfo.getUriString());
	String databaseName = getDatabaseName(uriParameters);
	try {
		URI uri = new URI(uriInfo.getUriString().substring(0, uriInfo.getUriString().indexOf(";")));
		return String.format("jdbc:%s://%s:%d%s%s%s%s",
				SQLSERVER_SCHEME,
				uri.getHost(),
				uri.getPort(),
				uri.getPath() != null && !uri.getPath().isEmpty() ? "/" + uri.getPath() : "",
				databaseName != null ? ";database=" + UriInfo.urlEncode(databaseName) : "",
				uriParameters.containsKey("user") ? ";user=" +  UriInfo.urlEncode(uriParameters.get("user")) : "",
				uriParameters.containsKey("password") ? ";password=" +  UriInfo.urlEncode(uriParameters.get("password")) : ""
		);
	}
	catch (URISyntaxException e) {
		throw new RuntimeException(e);
	}
}
 
源代码14 项目: cosmic   文件: TemplateManagerImpl.java
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
public VirtualMachineTemplate registerTemplate(final RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
    final Account account = CallContext.current().getCallingAccount();
    if (cmd.getTemplateTag() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    if (cmd.isRoutingType() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }

    final TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
    final TemplateProfile profile = adapter.prepare(cmd);
    final VMTemplateVO template = adapter.create(profile);

    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
 
源代码15 项目: bazel   文件: ContainerCredentialsProvider.java
@Override
public URI getCredentialsEndpoint() throws URISyntaxException {
    String fullUri = System.getenv(CONTAINER_CREDENTIALS_FULL_URI);
    if (fullUri == null || fullUri.length() == 0) {
        throw new SdkClientException("The environment variable " + CONTAINER_CREDENTIALS_FULL_URI + " is empty");
    }

    URI uri = new URI(fullUri);

    if (!ALLOWED_FULL_URI_HOSTS.contains(uri.getHost())) {
        throw new SdkClientException("The full URI (" + uri + ") contained withing environment variable " +
            CONTAINER_CREDENTIALS_FULL_URI + " has an invalid host. Host can only be one of [" +
            CollectionUtils.join(ALLOWED_FULL_URI_HOSTS, ", ") + "]");
    }

    return uri;
}
 
源代码16 项目: phonegapbootcampsite   文件: HttpEngine.java
/**
 * @param requestHeaders the client's supplied request headers. This class
 *     creates a private copy that it can mutate.
 * @param connection the connection used for an intermediate response
 *     immediately prior to this request/response pair, such as a same-host
 *     redirect. This engine assumes ownership of the connection and must
 *     release it when it is unneeded.
 */
public HttpEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
    Connection connection, RetryableOutputStream requestBodyOut) throws IOException {
  this.client = client;
  this.policy = policy;
  this.method = method;
  this.connection = connection;
  this.requestBodyOut = requestBodyOut;

  try {
    uri = Platform.get().toUriLenient(policy.getURL());
  } catch (URISyntaxException e) {
    throw new IOException(e.getMessage());
  }

  this.requestHeaders = new RequestHeaders(uri, new RawHeaders(requestHeaders));
}
 
源代码17 项目: swagger2markup   文件: AsciidocConverterTest.java
@Test
public void testInterDocumentCrossReferences() throws URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/idxref");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config =  new Swagger2MarkupConfigBuilder()
            .withInterDocumentCrossReferences()
            .build();

    Swagger2MarkupConverter.from(file).withConfig(config).build()
            .toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);

    Path expectedFilesDirectory = Paths.get(AsciidocConverterTest.class.getResource("/expected/asciidoc/idxref").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory, "testInterDocumentCrossReferences.html");
}
 
源代码18 项目: flink   文件: AbstractYarnClusterDescriptor.java
/**
 * Uploads and registers a single resource and adds it to <tt>localResources</tt>.
 *
 * @param key
 * 		the key to add the resource under
 * @param fs
 * 		the remote file system to upload to
 * @param appId
 * 		application ID
 * @param localSrcPath
 * 		local path to the file
 * @param localResources
 * 		map of resources
 *
 * @return the remote path to the uploaded resource
 */
private static Path setupSingleLocalResource(
		String key,
		FileSystem fs,
		ApplicationId appId,
		Path localSrcPath,
		Map<String, LocalResource> localResources,
		Path targetHomeDir,
		String relativeTargetPath) throws IOException, URISyntaxException {

	Tuple2<Path, LocalResource> resource = Utils.setupLocalResource(
		fs,
		appId.toString(),
		localSrcPath,
		targetHomeDir,
		relativeTargetPath);

	localResources.put(key, resource.f1);

	return resource.f0;
}
 
@BeforeClass
public static void setUpTest_ConfigurationRepository() throws URISyntaxException {

    URL configFile1URL = Test_ConfigurationRepository.class.getResource(configFile1Name);
    configFile1 = new File(configFile1URL.toURI());

    URL configFile2URL = Test_ConfigurationRepository.class.getResource(configFile2Name);
    configFile2 = new File(configFile2URL.toURI());
}
 
源代码20 项目: halvade   文件: BWAMemInstance.java
static public BWAMemInstance getBWAInstance(Mapper.Context context, String bin) throws IOException, InterruptedException, URISyntaxException {
    if(instance == null) {
        instance = new BWAMemInstance(context, bin);
        instance.startAligner(context);
    }
    BWAMemInstance.context = context;
    return instance;
}
 
@Test
public void testZipSlipVulnerability_windows() throws URISyntaxException {
  Assume.assumeTrue(System.getProperty("os.name").startsWith("Windows"));

  Path extractionRoot = tmp.getRoot().toPath();
  Path testArchive = getResource("zipSlipSamples/zip-slip-win.zip");
  try {
    zipExtractorProvider.extract(testArchive, extractionRoot, mockProgressListener);
    Assert.fail("IOException expected");
  } catch (IOException expected) {
    MatcherAssert.assertThat(
        expected.getMessage(),
        CoreMatchers.startsWith("Blocked unzipping files outside destination: "));
  }
}
 
源代码22 项目: pushfish-android   文件: TestFile.java
private static URI toUri(URL url) {
    try {
        return url.toURI();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
 
源代码23 项目: hbc   文件: SitestreamControllerTest.java
@Test
public void testAddUsers() throws IOException, ControlStreamException, URISyntaxException {
  SitestreamController controlstreams = setupSimplControlStreamRequest(200, "{}");
  controlstreams.addUsers("mock_stream_id", Longs.asList(1111, 2222, 3333, 4444));
  Mockito.verify(client).execute(argThat(new ArgumentValidator<HttpPost>() {
    public void validate(HttpPost post) throws Exception {
      assertEquals("application/x-www-form-urlencoded", post.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
      assertEquals("https://host.com/1.1/site/c/mock_stream_id/add_user.json", post.getURI().toString());
      assertEquals("user_id=1111%2C2222%2C3333%2C4444", consumeUtf8String(post.getEntity().getContent()));
    }
  }));
}
 
源代码24 项目: Repeat   文件: MinimizedFrame.java
private void show() {
	if (!Desktop.isDesktopSupported()) {
		LOGGER.warning("Cannot open browser to UI since Desktop module is not supported.");
		return;
	}

	IIPCService server = IPCServiceManager.getIPCService(IPCServiceName.WEB_UI_SERVER);
	try {
		Desktop.getDesktop().browse(new URI("http://localhost:" + server.getPort()));
	} catch (IOException | URISyntaxException ex) {
		LOGGER.log(Level.WARNING, "Failed to show UI in browser.", ex);
	}
}
 
源代码25 项目: pentaho-kettle   文件: FileStream.java
private String getFilePath( String path ) {
  try {
    final FileObject fileObject = KettleVFS.getFileObject( environmentSubstitute( path ) );
    if ( !fileObject.exists() ) {
      throw new FileNotFoundException( path );
    }
    return Paths.get( fileObject.getURL().toURI() ).normalize().toString();
  } catch ( URISyntaxException | FileNotFoundException | FileSystemException | KettleFileException e ) {
    propagate( e );
  }
  return null;
}
 
源代码26 项目: juddi   文件: UDDIKeyConvention.java
public static String getBindingKey(Properties properties, QName serviceName, String portName, URL bindingUrl) {
	
	String bindingKey = null;
	try {
		URI bindingURI = bindingUrl.toURI();
		bindingKey =  getBindingKey(properties, serviceName, portName, bindingURI);
	} catch (URISyntaxException e) {
		
	}
	return bindingKey;
	
}
 
源代码27 项目: openjdk-8-source   文件: Test.java
static void eq0(URI u, URI v) throws URISyntaxException {
    testCount++;
    if (!u.equals(v))
        throw new RuntimeException("Not equal: " + u + " " + v);
    int uh = u.hashCode();
    int vh = v.hashCode();
    if (uh != vh)
        throw new RuntimeException("Hash codes not equal: "
                                   + u + " " + Integer.toHexString(uh) + " "
                                   + v + " " + Integer.toHexString(vh));
    out.println();
    out.println(u + " == " + v
                + "  [" + Integer.toHexString(uh) + "]");
}
 
源代码28 项目: azure-storage-android   文件: CloudFileTests.java
@Test
public void testCloudFileDownloadRangeToByteArrayNegativeTest() throws URISyntaxException, StorageException,
        IOException {
    CloudFile file = this.share.getRootDirectoryReference().getFileReference(
            FileTestHelper.generateRandomFileName());
    FileTestHelper.doDownloadRangeToByteArrayNegativeTests(file);
}
 
源代码29 项目: json-schema   文件: RegisteredURIResolutionTest.java
@Test
public void httpURL() throws URISyntaxException {
    SchemaClient mock = mock(SchemaClient.class);
    SchemaLoader loader = SchemaLoader.builder()
            .schemaClient(mock)
            .schemaJson(LOADER.readObj("ref-example-org.json"))
            .registerSchemaByURI(new URI("http://example.org"), LOADER.readObj("schema-by-urn.json"))
            .build();

    ReferenceSchema actual = (ReferenceSchema) loader.load().build();

    assertEquals("schema-by-urn", actual.getReferredSchema().getTitle());
    verifyNoMoreInteractions(mock);
}
 
源代码30 项目: geoportal-server-harvester   文件: UncFile.java
/**
 * Reads content.
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent() throws IOException, URISyntaxException {
  Date lastModifiedDate = readLastModifiedDate();
  MimeType contentType = readContentType();
  try (InputStream input = Files.newInputStream(file)) {
    SimpleDataReference ref = new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(), file.toAbsolutePath().toString(), lastModifiedDate, file.toUri(), broker.td.getSource().getRef(), broker.td.getRef());
    ref.addContext(contentType, IOUtils.toByteArray(input));
    return ref;
  }
}