Java Code Examples for java.net.URI

The following are top voted examples for showing how to use java.net.URI. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Reer   File: ClasspathUtil.java   View source code 7 votes vote down vote up
public static File getClasspathForClass(Class<?> targetClass) {
    URI location;
    try {
        CodeSource codeSource = targetClass.getProtectionDomain().getCodeSource();
        if (codeSource != null && codeSource.getLocation() != null) {
            location = codeSource.getLocation().toURI();
            if (location.getScheme().equals("file")) {
                return new File(location);
            }
        }
        if (targetClass.getClassLoader() != null) {
            String resourceName = targetClass.getName().replace('.', '/') + ".class";
            URL resource = targetClass.getClassLoader().getResource(resourceName);
            if (resource != null) {
                return getClasspathForResource(resource, resourceName);
            }
        }
        throw new GradleException(String.format("Cannot determine classpath for class %s.", targetClass.getName()));
    } catch (URISyntaxException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 2
Project: cf-mta-deploy-service   File: ProcessGitSourceStepTest.java   View source code 6 votes vote down vote up
@Test
public void testZipRepoContent() throws Exception {
    Path repoDir = Paths.get(getClass().getResource(repository).toURI());
    Path mtarZip = null;
    try {
        mtarZip = step.zipRepoContent(repoDir.toAbsolutePath());
        URI jarMtarUri = URI.create("jar:" + mtarZip.toAbsolutePath().toUri().toString());
        try (FileSystem mtarFS = FileSystems.newFileSystem(jarMtarUri, new HashMap<>())) {
            Path mtarRoot = mtarFS.getRootDirectories().iterator().next();
            assertFalse(Files.exists(mtarRoot.resolve(".git")));
            assertFalse(Files.exists(mtarRoot.resolve(".gitignore")));
            assertTrue(Files.exists(mtarRoot.resolve("a/cool-script.script")));
            assertTrue(Files.exists(mtarRoot.resolve("META-INF/mtad.yaml")));
            assertTrue(Files.exists(mtarRoot.resolve("META-INF/MANIFEST.MF")));
        }
    } finally {
        if (mtarZip != null) {
            Files.deleteIfExists(mtarZip);
        }
    }
}
 
Example 3
Project: JRediClients   File: ClusterConnectionManager.java   View source code 6 votes vote down vote up
private void checkSlaveNodesChange(Collection<ClusterPartition> newPartitions) {
    for (ClusterPartition newPart : newPartitions) {
        for (ClusterPartition currentPart : getLastPartitions()) {
            if (!newPart.getMasterAddress().equals(currentPart.getMasterAddress())) {
                continue;
            }

            MasterSlaveEntry entry = getEntry(currentPart.getMasterAddr());
            // should be invoked first in order to remove stale failedSlaveAddresses
            Set<URI> addedSlaves = addRemoveSlaves(entry, currentPart, newPart);
            // Do some slaves have changed state from failed to alive?
            upDownSlaves(entry, currentPart, newPart, addedSlaves);

            break;
        }
    }
}
 
Example 4
Project: hadoop   File: TestDFSUtil.java   View source code 6 votes vote down vote up
@Test
public void testGetInfoServer() throws IOException, URISyntaxException {
  HdfsConfiguration conf = new HdfsConfiguration();
  
  URI httpsport = DFSUtil.getInfoServer(null, conf, "https");
  assertEquals(new URI("https", null, "0.0.0.0",
      DFS_NAMENODE_HTTPS_PORT_DEFAULT, null, null, null), httpsport);
  
  URI httpport = DFSUtil.getInfoServer(null, conf, "http");
  assertEquals(new URI("http", null, "0.0.0.0",
      DFS_NAMENODE_HTTP_PORT_DEFAULT, null, null, null), httpport);

  URI httpAddress = DFSUtil.getInfoServer(new InetSocketAddress(
      "localhost", 8020), conf, "http");
  assertEquals(
      URI.create("http://localhost:" + DFS_NAMENODE_HTTP_PORT_DEFAULT),
      httpAddress);
}
 
Example 5
Project: omero-ms-queue   File: QueuedOmeroKeepAliveTest.java   View source code 6 votes vote down vote up
@Test
public void enforceValueEquality() {
    URI omero = URI.create("h:1");
    String sessionKey = "sk";
    FutureTimepoint now = now();
    QueuedOmeroKeepAlive value =
            new QueuedOmeroKeepAlive(omero, sessionKey, now);
    QueuedOmeroKeepAlive valueCopy =
            new QueuedOmeroKeepAlive(omero, sessionKey, now);

    assertThat(value.getOmero(), is(omero));
    assertThat(value.getSessionKey(), is(sessionKey));
    assertThat(value.getUntilWhen(), is(now));

    assertThat(value, is(valueCopy));
    assertThat(value.hashCode(), is(valueCopy.hashCode()));
}
 
Example 6
Project: neoscada   File: VisualInterfaceViewer.java   View source code 6 votes vote down vote up
private void applyImage ( final Symbol symbol, final SymbolLoader symbolLoader )
{
    if ( symbol.getBackgroundImage () == null || symbol.getBackgroundImage ().isEmpty () )
    {
        return;
    }

    logInfo ( "Trying to load background image: " + symbol.getBackgroundImage () );
    final String uriString = symbolLoader.resolveUri ( symbol.getBackgroundImage () );

    final org.eclipse.emf.common.util.URI uri = org.eclipse.emf.common.util.URI.createURI ( uriString );
    this.loadedResources.add ( uri );
    try
    {
        final Image img = this.manager.createImageWithDefault ( ImageDescriptor.createFromURL ( new URL ( uriString ) ) );
        this.canvas.setBackgroundImage ( img );
    }
    catch ( final MalformedURLException e )
    {
        logError ( "Loading background image: " + uriString, e ); //$NON-NLS-1$
    }
}
 
Example 7
Project: OpenJSharp   File: OCSP.java   View source code 6 votes vote down vote up
public static RevocationStatus check(X509Certificate cert,
                                     X509Certificate issuerCert,
                                     URI responderURI,
                                     X509Certificate responderCert,
                                     Date date, List<Extension> extensions)
    throws IOException, CertPathValidatorException
{
    CertId certId = null;
    try {
        X509CertImpl certImpl = X509CertImpl.toImpl(cert);
        certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
    } catch (CertificateException | IOException e) {
        throw new CertPathValidatorException
            ("Exception while encoding OCSPRequest", e);
    }
    OCSPResponse ocspResponse = check(Collections.singletonList(certId),
        responderURI, issuerCert, responderCert, date, extensions);
    return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
 
Example 8
Project: incubator-netbeans   File: LibrariesNode.java   View source code 6 votes vote down vote up
private Key (
        @NonNull final AntArtifact a,
        @NonNull final URI uri,
        @NonNull final String classPathId,
        @NonNull final String entryId,
        @NullAllowed final Consumer<Pair<String,String>> preRemoveAction,
        @NullAllowed final Consumer<Pair<String,String>> postRemoveAction, 
        boolean shared) {
    this.type = TYPE_PROJECT;
    this.antArtifact = a;
    this.uri = uri;
    this.classPathId = classPathId;
    this.entryId = entryId;
    this.preRemoveAction = preRemoveAction;
    this.postRemoveAction = postRemoveAction;
    this.shared = shared;
}
 
Example 9
Project: mid-tier   File: CustomerEventServiceExposureTest.java   View source code 6 votes vote down vote up
@Test
public void testListEventsByCategory() throws URISyntaxException {
    UriInfo ui = mock(UriInfo.class);
    when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock")));

    Request request = mock(Request.class);

    when(archivist.getEventsForCategory(Event.getCategory("some", "category"), Optional.empty()))
            .thenReturn(Collections.singletonList(new Event(new URI("customer-events/some-category/eventSID"),
                    "some-category", CurrentTime.now())));

    Response response = service.getCustomerEventsByCategory(ui, request, "application/hal+json", "some-category", "");
    EventsRepresentation events = (EventsRepresentation) response.getEntity();

    assertEquals(1, events.getEvents().size());
    assertEquals("http://mock/customer-events", events.getSelf().getHref());

    response = service.getCustomerEventsByCategory(ui, request, "application/hal+json;no-real-type", "some-category", "");
    assertEquals(415,response.getStatus());
}
 
Example 10
Project: openjdk-jdk10   File: XDesktopPeer.java   View source code 6 votes vote down vote up
private void launch(URI uri) throws IOException {
    byte[] uriByteArray = ( uri.toString() + '\0' ).getBytes();
    boolean result = false;
    XToolkit.awtLock();
    try {
        if (!nativeLibraryLoaded) {
            throw new IOException("Failed to load native libraries.");
        }
        result = gnome_url_show(uriByteArray);
    } finally {
        XToolkit.awtUnlock();
    }
    if (!result) {
        throw new IOException("Failed to show URI:" + uri);
    }
}
 
Example 11
Project: elasticsearch_my   File: RestClient.java   View source code 6 votes vote down vote up
private static URI buildUri(String pathPrefix, String path, Map<String, String> params) {
    Objects.requireNonNull(path, "path must not be null");
    try {
        String fullPath;
        if (pathPrefix != null) {
            if (path.startsWith("/")) {
                fullPath = pathPrefix + path;
            } else {
                fullPath = pathPrefix + "/" + path;
            }
        } else {
            fullPath = path;
        }

        URIBuilder uriBuilder = new URIBuilder(fullPath);
        for (Map.Entry<String, String> param : params.entrySet()) {
            uriBuilder.addParameter(param.getKey(), param.getValue());
        }
        return uriBuilder.build();
    } catch(URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
 
Example 12
Project: redirector   File: RedirectorOfflineUI.java   View source code 6 votes vote down vote up
@GET
@Produces(MediaType.TEXT_HTML)
public Response defaultPage(@Context UriInfo ui) throws URISyntaxException {
    /*
    * This redirect is required due to change of "Jersey" version from "1.17" to "2.13".
    * The "1.*" version of jersey has property "FEATURE_REDIRECT".
    * For example, when making request "localhost:8888/context/dev", Jersey checks whether "FEATURE_REDIRECT" is set to "true" in ServletContainer and request does not end with '/'.
    * If so, trailing slash is added and redirect is occurred to "localhost:8888/context/dev/"
    *
    * Jersey "2.*" does not contain property "FEATURE_REDIRECT".
    * The code that made redirect in "1.*" jersey is commented out in ServletContainer.java:504
    * Jersey "2.*" resolves request even if '/' was not present in the end.
    * But all links in our *.jsp and *.html to *.js and *.css are relative. So without adding '/' in the end, files can not be opened.
    * To solve it, we introduced this redirect
    */
    if (!ui.getAbsolutePath().toString().endsWith("/")) {
        return Response.temporaryRedirect(new URI(ui.getAbsolutePath().toString() + "/")).build();
    } else {
        return Response.ok(new Viewable("/index.jsp", new HashMap<String, Object>())).build();
    }
}
 
Example 13
Project: verify-hub   File: MatchingServiceHealthChecker.java   View source code 5 votes vote down vote up
private MatchingServiceHealthCheckDetails generateHealthCheckFailureDescription(
        final MatchingServiceHealthCheckResponseDto response,
        final URI matchingServiceUri,
        final boolean isOnboarding) {

    if (!response.getResponse().isPresent()) {
        return generateHealthCheckDescription("no response", matchingServiceUri, response.getVersionNumber(), isOnboarding);
    }

    return generateHealthCheckDescription("responded with non-healthy status", matchingServiceUri,
            response.getVersionNumber(), isOnboarding);
}
 
Example 14
Project: rs-aggregator   File: SyncJob.java   View source code 5 votes vote down vote up
public void readListAndSynchronize() throws Exception {
  List<URI> uriList = new ArrayList<>();
  Scanner scanner = new Scanner(new File(getUriListLocation()));
  while (scanner.hasNextLine()) {
    String uriString = scanner.nextLine();
    Optional<URI> maybeUri = NormURI.normalize(uriString);
    if (maybeUri.isPresent()) {
      uriList.add(maybeUri.get());
    } else {
      logger.warn("Unable to convert {} to a URI", uriString);
    }
  }
  synchronize(uriList);
}
 
Example 15
Project: lams   File: FileBackedHttpResource.java   View source code 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param resource HTTP(S) URL of the resource
 * @param backingFile file: URI location to store the resource
 * 
 * @since 1.2
 */
public FileBackedHttpResource(String resource, URI backingFile) {
    super(resource);

    if (backingFile == null) {
        throw new IllegalArgumentException("Backing file path may not be null or empty");
    }

    resourceFile = new File(backingFile);
}
 
Example 16
Project: hadoop   File: TestMRCredentials.java   View source code 5 votes vote down vote up
/**
 * run a distributed job and verify that TokenCache is available
 * @throws IOException
 */
@Test
public void test () throws IOException {

  // make sure JT starts
  Configuration jobConf =  new JobConf(mrCluster.getConfig());

  // provide namenodes names for the job to get the delegation tokens for
  //String nnUri = dfsCluster.getNameNode().getUri(namenode).toString();
  NameNode nn = dfsCluster.getNameNode();
  URI nnUri = NameNode.getUri(nn.getNameNodeAddress());
  jobConf.set(JobContext.JOB_NAMENODES, nnUri + "," + nnUri.toString());


  jobConf.set("mapreduce.job.credentials.json" , "keys.json");

  // using argument to pass the file name
  String[] args = {
      "-m", "1", "-r", "1", "-mt", "1", "-rt", "1"
  };

  int res = -1;
  try {
    res = ToolRunner.run(jobConf, new CredentialsTestJob(), args);
  } catch (Exception e) {
    System.out.println("Job failed with" + e.getLocalizedMessage());
    e.printStackTrace(System.out);
    fail("Job failed");
  }
  assertEquals("dist job res is not 0", res, 0);

}
 
Example 17
Project: BUbiNG   File: FilterAdaptersTest.java   View source code 5 votes vote down vote up
@Test
public void testAdaptationSimple() throws ParseException {
	FilterParser<URI> filterParser = new FilterParser<>(URI.class);
	Filter<URI> filter = filterParser.parse("HostEquals(www.dsi.unimi.it) or " +
			"it.unimi.di.law.warc.filters.FiltersTest$StartsWithStringFilter(http://xx)");
	System.out.println("TESTING: " + filter);
	assertTrue(filter.apply(BURL.parse("http://www.dsi.unimi.it/mb")));
	assertTrue(filter.apply(BURL.parse("http://xxx.foo.bar")));
	assertFalse(filter.apply(BURL.parse("http://yyy.foo.bar")));
}
 
Example 18
Project: GitHub   File: ResponseCacheTest.java   View source code 5 votes vote down vote up
/**
 * Fail if a badly-behaved cache returns a null status line header.
 * https://code.google.com/p/android/issues/detail?id=160522
 */
@Test public void responseCacheReturnsNullStatusLine() throws Exception {
  String cachedContentString = "Hello";
  final byte[] cachedContent = cachedContentString.getBytes(StandardCharsets.US_ASCII);

  setInternalCache(new CacheAdapter(new AbstractResponseCache() {
    @Override
    public CacheResponse get(URI uri, String requestMethod,
        Map<String, List<String>> requestHeaders)
        throws IOException {
      return new CacheResponse() {
        @Override public Map<String, List<String>> getHeaders() throws IOException {
          String contentType = "text/plain";
          Map<String, List<String>> headers = new LinkedHashMap<>();
          headers.put("Content-Length", Arrays.asList(Integer.toString(cachedContent.length)));
          headers.put("Content-Type", Arrays.asList(contentType));
          headers.put("Expires", Arrays.asList(formatDate(-1, TimeUnit.HOURS)));
          headers.put("Cache-Control", Arrays.asList("max-age=60"));
          // Crucially, the header with a null key is missing, which renders the cache response
          // unusable because OkHttp only caches responses with cacheable response codes.
          return headers;
        }

        @Override public InputStream getBody() throws IOException {
          return new ByteArrayInputStream(cachedContent);
        }
      };
    }
  }));
  HttpURLConnection connection = openConnection(server.url("/").url());
  // If there was no status line from the cache an exception will be thrown. No network request
  // should be made.
  try {
    connection.getResponseCode();
    fail();
  } catch (ProtocolException expected) {
  }
}
 
Example 19
Project: incubator-netbeans   File: StandardProjectSettings.java   View source code 5 votes vote down vote up
@Override
public Preferences getProjectSettings(String mimeType) {
    if (hasLocation()) {
        URI settingsLocation = project.getProjectDirectory().toURI().resolve(encodeSettingsFileLocation(getSettingsFileLocation()));
        return ToolPreferences.from(settingsLocation).getPreferences(HINTS_TOOL_ID, mimeType);
    } else {
        return ProjectUtils.getPreferences(project, ProjectSettings.class, true).node(mimeType);
    }
}
 
Example 20
Project: athena   File: GrpcRemoteServiceProvider.java   View source code 5 votes vote down vote up
private ManagedChannel createChannel(URI uri) {
    log.debug("Creating channel for {}", uri);
    int port = GrpcRemoteServiceServer.DEFAULT_LISTEN_PORT;
    if (uri.getPort() != -1) {
        port = uri.getPort();
    }
    return NettyChannelBuilder.forAddress(uri.getHost(), port)
            .negotiationType(NegotiationType.PLAINTEXT)
            .build();
}
 
Example 21
Project: verify-hub   File: MatchingServiceRequestGeneratorResourceTest.java   View source code 5 votes vote down vote up
private Response getAttributeQuery(AttributeQueryRequestDto dto) {
    final URI uri = samlEngineAppRule.getUri(Urls.SamlEngineUrls.GENERATE_ATTRIBUTE_QUERY_RESOURCE);
    return client.target(uri)
            .request()
            .post(Entity.json(dto), Response.class);

}
 
Example 22
Project: incubator-netbeans   File: LibrariesSupport.java   View source code 5 votes vote down vote up
/**
 * Returns a URI representing the root of an archive.
 * @param uri of a ZIP- (or JAR-) format archive file; can be relative
 * @return the <code>jar</code>-protocol URI of the root of the archive
 * @since org.netbeans.modules.project.libraries/1 1.18
 */
public static URI getArchiveRoot(URI uri) {
    assert !uri.toString().contains("!/") : uri;
    try {
        return new URI((uri.isAbsolute() ? "jar:" : "") + uri.toString() + "!/"); // NOI18N
    } catch (URISyntaxException ex) {
            throw new AssertionError(ex);
    }
}
 
Example 23
Project: joal   File: TrackerClientProvider.java   View source code 5 votes vote down vote up
public TrackerClientProvider(final TorrentWithStats torrent, final ConnectionHandler connectionHandler, final BitTorrentClient bitTorrentClient) {
    this.torrent = torrent;
    this.connectionHandler = connectionHandler;
    this.bitTorrentClient = bitTorrentClient;
    final Set<URI> addresses = torrent.getTorrent().getAnnounceList().stream()
            .unordered()
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());

    this.addressIterator = Iterators.cycle(addresses);
    this.addressesCount = addresses.size();
}
 
Example 24
Project: keti   File: MonitoringHttpMethodsFilterTest.java   View source code 5 votes vote down vote up
@Test(dataProvider = "urisAndTheirAllowedHttpMethods")
public void testUriPatternsAndTheirAllowedHttpMethods(final String uri, final Set<HttpMethod> allowedHttpMethods)
        throws Exception {
    Set<HttpMethod> disallowedHttpMethods = new HashSet<>(ALL_HTTP_METHODS);
    disallowedHttpMethods.removeAll(allowedHttpMethods);
    for (HttpMethod disallowedHttpMethod : disallowedHttpMethods) {
        this.mockMvc.perform(MockMvcRequestBuilders.request(disallowedHttpMethod, URI.create(uri)))
                .andExpect(MockMvcResultMatchers.status().isMethodNotAllowed());
    }
}
 
Example 25
Project: verify-hub   File: SamlMessageSenderApiResourceTest.java   View source code 5 votes vote down vote up
@Test
public void sendSignedJsonAuthnResponseFromHub_shouldRespondWithNextLocation() throws Exception {
    SessionId sessionId = SessionId.createNewSessionId();
    URI nextLocationUri = URI.create("http://blah");
    String requestId = UUID.randomUUID().toString();


    ResponseAssertionSigner responseAssertionSigner = new ResponseAssertionSigner(
            new SignatureFactory(new IdaKeyStoreCredentialRetriever(getKeyStore()), SIGNATURE_ALGORITHM, DIGEST_ALGORITHM)
    );
    Function<OutboundResponseFromHub, String> outboundResponseFromHubToStringTransformer = new HubTransformersFactory()
            .getOutboundResponseFromHubToStringTransformer(
                    new HardCodedKeyStore(HUB_ENTITY_ID),
                    getKeyStore(),
                    new IdpHardCodedEntityToEncryptForLocator(),
                    responseAssertionSigner,
                    SIGNATURE_ALGORITHM,
                    DIGEST_ALGORITHM
            );
    OutboundResponseFromHub authnResponseFromHub = anAuthnResponse()
            .withInResponseTo(requestId)
            .withIssuerId(HUB_ENTITY_ID)
            .withTransactionIdaStatus(TransactionIdaStatus.Success)
            .buildOutboundResponseFromHub();
    String samlString = outboundResponseFromHubToStringTransformer.apply(authnResponseFromHub);

    AuthnResponseFromHubContainerDto authnResponseFromHubContainerDto = new AuthnResponseFromHubContainerDto(
            samlString,
            nextLocationUri,
            com.google.common.base.Optional.absent(),
            authnResponseFromHub.getId());

    policyStubRule.anAuthnResponseFromHubToRp(sessionId, authnResponseFromHubContainerDto);

    javax.ws.rs.core.Response response = getResponseFromSamlProxy(Urls.SamlProxyUrls.SEND_RESPONSE_FROM_HUB_API_RESOURCE, sessionId);
    assertThat(response.readEntity(SamlMessageSenderHandler.SamlMessage.class).getPostEndpoint()).isEqualTo(nextLocationUri.toASCIIString());
}
 
Example 26
Project: monarch   File: TierStoreORCWriter.java   View source code 5 votes vote down vote up
@Override
public void _openChunkWriter(final Properties props, URI baseURI, String[] tablePathParts,
    Configuration conf) throws IOException {
  CompressionKind compression = getCompressionKind(props);
  int bufferSize = getBufferSize(props);
  int stripeSize = getStripeSize(props);
  int newIndexStride = getNewIndexStride(props);
  this.chunkWriter = createWriter(Paths.get(baseURI.getPath(), tablePathParts), conf, compression,
      bufferSize, stripeSize, newIndexStride, WriteAheadLog.WAL_FILE_RECORD_LIMIT);
}
 
Example 27
Project: OCast-Java   File: LinkProfile.java   View source code 5 votes vote down vote up
/**
 * Returns the hostname
 * @return
 */
public String getHostname() {
    if(hostname == null && app2AppUrl != null) {
        return URI.create(app2AppUrl).getHost();
    } else {
        return hostname;
    }
}
 
Example 28
Project: shibboleth-idp-oidc-extension   File: SectorIdentifierLookupFunctionTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@BeforeMethod
protected void setUp() throws Exception {
    sector = new URI("https://example.org/uri");
    lookup = new SectorIdentifierLookupFunction();
    final RequestContext requestCtx = new RequestContextBuilder().buildRequestContext();
    prc = new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
    msgCtx = new MessageContext<AuthenticationRequest>();
    prc.setInboundMessageContext(msgCtx);
    ctx = new OIDCMetadataContext();
    OIDCClientMetadata metadata= new OIDCClientMetadata();
    OIDCClientInformation information = new OIDCClientInformation(new ClientID(), new Date(), metadata, new Secret() );
    ctx.setClientInformation(information);
    msgCtx.addSubcontext(ctx);
}
 
Example 29
Project: vrap   File: WebJarHandler.java   View source code 5 votes vote down vote up
private FileSystem initJarFileSystem(final URI uri) {
    try {
        return FileSystems.newFileSystem(uri, Collections.emptyMap());
    } catch (IOException e) {
        throw uncheck(e);
    }
}
 
Example 30
Project: educational-plugin   File: EduStepicConnector.java   View source code 5 votes vote down vote up
public static StepicWrappers.CoursesContainer getCoursesFromStepik(@Nullable StepicUser user, URI url) throws IOException {
  final StepicWrappers.CoursesContainer coursesContainer;
  if (user != null) {
    coursesContainer = EduStepicAuthorizedClient.getFromStepic(url.toString(), StepicWrappers.CoursesContainer.class, user);
  }
  else {
    coursesContainer = EduStepicClient.getFromStepic(url.toString(), StepicWrappers.CoursesContainer.class);
  }
  return coursesContainer;
}
 
Example 31
Project: incubator-netbeans   File: WSDLSemanticValidatorTest.java   View source code 5 votes vote down vote up
public void testValidateSolicitResponseOperationFaultInvalidMessage() throws Exception {
    String fileName = "/org/netbeans/modules/xml/wsdl/validator/resources/ptTests/opTests/solrep/faultBogusMsg_error.wsdl";
    URL url = getClass().getResource(fileName);
    URI uri = url.toURI();
    
    HashSet<String> expectedErrors = new HashSet<String>();
    expectedErrors.add(format(mMessages.getString("VAL_MESSAGE_NOT_FOUND_IN_OPERATION_FAULT")));
    validate(uri, expectedErrors);
}
 
Example 32
Project: lams   File: SpdyClientProvider.java   View source code 5 votes vote down vote up
private ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final URI uri, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
    return new ChannelListener<StreamConnection>() {
        @Override
        public void handleEvent(StreamConnection connection) {
            handleConnected(connection, listener, uri, ssl, bufferPool, options);
        }
    };
}
 
Example 33
Project: scott-eu   File: ActionType.java   View source code 5 votes vote down vote up
public ActionType(final URI about)
       throws URISyntaxException
{
    super(about);

    // Start of user code constructor2
    // End of user code
}
 
Example 34
Project: AthenaX   File: AthenaXServer.java   View source code 5 votes vote down vote up
private void start(AthenaXConfiguration conf) throws Exception {
  ServerContext.INSTANCE.initialize(conf);
  ServerContext.INSTANCE.start();
  try (WebServer server = new WebServer(URI.create(conf.masterUri()))) {
    server.start();
    Thread.currentThread().join();
  }
}
 
Example 35
Project: asura   File: TokenSmsSender.java   View source code 5 votes vote down vote up
/**
 * post 参数
 *
 * @param smsMessage
 */
@Override
protected HttpPost buildPostParam(SmsMessage smsMessage) throws UnsupportedEncodingException, URISyntaxException {
    URI uri = super.buildURIByConfig();
    HttpPost httpPost = new HttpPost(uri);
    TokenSmsSenderConfig config = (TokenSmsSenderConfig) getConfig();
    HashMap<String, String> map = new HashMap<>();
    map.put("token", config.getToken());
    map.put("to", smsMessage.getToPhone());
    map.put("content", smsMessage.getContent());
    StringEntity entity = new StringEntity(JsonEntityTransform.Object2Json(map), config.getCharset());
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 36
Project: lams   File: SpdyClientProvider.java   View source code 5 votes vote down vote up
@Override
public void connect(final ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
    if(uri.getScheme().equals("spdy-plain")) {

        if(bindAddress == null) {
            ioThread.openStreamConnection(new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null);
        } else {
            ioThread.openStreamConnection(bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), null, options).addNotifier(createNotifier(listener), null);
        }
        return;
    }

    if(ALPN_PUT_METHOD == null) {
        listener.failed(UndertowMessages.MESSAGES.jettyNPNNotAvailable());
        return;
    }
    if (ssl == null) {
        listener.failed(UndertowMessages.MESSAGES.sslWasNull());
        return;
    }
    if(bindAddress == null) {
        ssl.openSslConnection(ioThread, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null);
    } else {
        ssl.openSslConnection(ioThread, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null);
    }

}
 
Example 37
Project: spring-webflux-client   File: DefaultReactiveInvocationHandlerFactory.java   View source code 5 votes vote down vote up
@Override
public InvocationHandler build(ExtendedClientCodecConfigurer codecConfigurer, List<RequestProcessor> requestProcessors, List<ResponseProcessor> responseProcessors, Logger logger, LogLevel logLevel, Class<?> target, URI uri) {
    ExchangeFilterFunction exchangeFilterFunction = exchangeFilterFunctionFactory.build(requestProcessors, responseProcessors, logger, logLevel);
    RequestExecutor requestExecutor = requestExecutorFactory.build(codecConfigurer, exchangeFilterFunction);
    ResponseBodyProcessor responseBodyProcessor = new DefaultResponseBodyProcessor(codecConfigurer.getErrorReaders());

    Map<Method, ClientMethodHandler> invocationDispatcher = methodMetadataFactory.build(target, uri)
            .stream()
            .collect(toMap(MethodMetadata::getTargetMethod, methodMetadata -> new DefaultClientMethodHandler(methodMetadata, requestExecutor, responseBodyProcessor)));

    return new DefaultReactiveInvocationHandler(invocationDispatcher);
}
 
Example 38
Project: scanning   File: ConsumerView.java   View source code 5 votes vote down vote up
@Override
public void createPartControl(Composite content) {

	content.setLayout(new GridLayout(1, false));
	Util.removeMargins(content);

	this.viewer   = new TableViewer(content, SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
	viewer.setUseHashlookup(true);
	viewer.getTable().setHeaderVisible(true);
	viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

	createColumns();
	viewer.setContentProvider(createContentProvider());

	consumers = new ConcurrentHashMap<>();
	viewer.setInput(consumers);

       createActions();
       try {
		createTopicListener(new URI(Activator.getJmsUri()));
	} catch (Exception e) {
		logger.error("Cannot listen to topic of command server!", e);
	}

       final String partName = getSecondaryIdAttribute("partName");
       if (partName!=null) setPartName(partName);
}
 
Example 39
Project: minijax   File: HttpHeadersTest.java   View source code 5 votes vote down vote up
@Test
public void testLanguageMissing() {
    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    final MockHttpServletRequest request = new MockHttpServletRequest("GET", URI.create("/"), headers, null, null);
    final MinijaxHttpHeaders httpHeaders = new MinijaxHttpHeaders(request);
    assertNull(httpHeaders.getLanguage());
}
 
Example 40
Project: verify-hub   File: MatchingServiceConfigProxy.java   View source code 5 votes vote down vote up
@Inject
public MatchingServiceConfigProxy(
        JsonClient jsonClient,
        @Config URI configUri) {

    this.jsonClient = jsonClient;
    this.configUri = configUri;
}