Example usage for java.net URI URI

List of usage examples for java.net URI URI

Introduction

In this page you can find the example usage for java.net URI URI.

Prototype

public URI(String str) throws URISyntaxException 

Source Link

Document

Constructs a URI by parsing the given string.

Usage

From source file:com.github.wnameless.spring.papertrail.test.jpa.BeforePaperTrailCallbackTest.java

@Test
public void testBefore() throws Exception {
    RequestEntity<Void> req = RequestEntity.post(new URI(host + "/before")).header("Authorization", encodedAuth)
            .build();// w w w . j a v a2s  .c  o  m
    template.exchange(req, String.class);

    JpaPaperTrail trail = repo.findByRequestUri("/before");
    assertEquals("BEFORE", trail.getUserId());
    assertEquals("127.0.0.1", trail.getRemoteAddr());
    assertEquals("POST", trail.getHttpMethod().toString());
    assertEquals("/before", trail.getRequestUri());
    assertEquals(201, trail.getHttpStatus());
    assertNotNull(trail.getCreatedAt());
}

From source file:com.jpeterson.littles3.bo.GroupBaseTest.java

/**
 * Test the constructor.//  w ww . ja  v a2s .  co m
 */
public void test_constructor() {
    GroupBase group;
    URI uri;
    String uriString = "http://www.foo.com";

    try {
        uri = new URI(uriString);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail("Unexpected exception");
        return;
    }

    group = new MyGroupBase(uri);

    assertEquals("Unexpected value", uri, group.getUri());
}

From source file:io.github.jhipster.security.uaa.LoadBalancedResourceDetails.java

@Override
public String getAccessTokenUri() {
    if (loadBalancerClient != null && tokenServiceId != null && !tokenServiceId.isEmpty()) {
        try {//from  w  w  w.j a  v  a 2 s  .co  m
            return loadBalancerClient.reconstructURI(loadBalancerClient.choose(tokenServiceId),
                    new URI(super.getAccessTokenUri())).toString();
        } catch (URISyntaxException e) {
            log.error("{}: {}", e.getClass().toString(), e.getMessage());

            return super.getAccessTokenUri();
        }
    } else {
        return super.getAccessTokenUri();
    }
}

From source file:kindleclippings.quizlet.GetAccessToken.java

static JSONObject oauthDance() throws IOException, URISyntaxException, InterruptedException, JSONException {

    // start HTTP server, so when can get the authorization code
    InetSocketAddress addr = new InetSocketAddress(7777);
    HttpServer server = HttpServer.create(addr, 0);
    AuthCodeHandler handler = new AuthCodeHandler();
    server.createContext("/", handler);
    ExecutorService ex = Executors.newCachedThreadPool();
    server.setExecutor(ex);/*ww w . jav a 2 s  . c o  m*/
    server.start();
    String authCode;
    try {
        Desktop.getDesktop()
                .browse(new URI(new StringBuilder("https://quizlet.com/authorize/")
                        .append("?scope=read%20write_set").append("&client_id=" + clientId)
                        .append("&response_type=code").append("&state=" + handler.state).toString()));

        authCode = handler.result.take();
    } finally {
        server.stop(0);
        ex.shutdownNow();
    }

    if (authCode == null || authCode.length() == 0)
        return null;

    HttpPost post = new HttpPost("https://api.quizlet.com/oauth/token");
    post.setHeader("Authorization", authHeader);

    post.setEntity(
            new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("grant_type", "authorization_code"),
                    new BasicNameValuePair("code", authCode))));
    HttpResponse response = new DefaultHttpClient().execute(post);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000);
    response.getEntity().writeTo(buffer);
    return new JSONObject(new String(buffer.toByteArray(), "UTF-8"));
}

From source file:com.brightcove.com.uploader.helper.MediaAPIWaiterTest.java

@Test
public void testMediaAPIWaiterOnePoll()
        throws URISyntaxException, IOException, BadEnvironmentException, MediaAPIError {
    mediaHelper = context.mock(MediaAPIHelper.class);
    final URI targetURL = new URI("http://test.com");
    final JsonNode node = mapper.readTree("{\"method\": \"getuploadstatus\", \"params\": null}");
    final JsonNode complete = mapper.readTree("{\"result\": \"COMPLETE\", \"error\": null, \"id\": null}");
    context.checking(new Expectations() {
        {//from   ww  w  . j a va 2s.  c o  m
            one(mediaHelper);
            will(returnValue(node));
            one(mediaHelper).executeWrite(node, targetURL);
            will(returnValue(complete));
        }
    });

    MediaAPIWaiter maw = new MediaAPIWaiter("token", targetURL, 123l, 1, 1, mediaHelper);
    maw.sit();
    assertTrue(maw.isComplete());
}

From source file:cool.pandora.modeller.util.ResourceIntegerValue.java

/**
 * ResourceIntegerValue.// w  ww .  j  a  v a 2  s . c o m
 *
 * @param resourceURI      String
 * @param resourceProperty String
 */
ResourceIntegerValue(final String resourceURI, final String resourceProperty) {

    try {
        final String resource = ModellerClient.doGetContainerResources(new URI(resourceURI));
        final Model model = ModelFactory.createDefaultModel();
        model.read(new ByteArrayInputStream(resource != null ? resource.getBytes() : new byte[0]), null, "TTL");
        this.resourceValue = getValue(model, resourceProperty);
    } catch (ModellerClientFailedException e) {
        System.out.println(getMessage(e));
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository//  ww w.  ja v  a2  s .  c o  m
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}

From source file:com.josue.tiled2.client.network.WSNetworkClient.java

public WSNetworkClient(String host, int port, String map) {
    this.container = ContainerProvider.getWebSocketContainer();
    String url = "ws://" + host + ":" + port + "/game/" + map;
    try {/*from w ww. j a va  2s.  c o  m*/
        endpointURI = new URI(url);
    } catch (URISyntaxException ex) {
        System.err.println(":: NETWORK ERROR, MALFORMED URI SYNTAX: " + url + " ::");
    }

    mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);

}

From source file:de.betterform.connector.xmlrpc.XMLRPCURIResolver.java

/**
 * Decodes the <code>xmlrpc</code> URI, runs the indicated function
 * and returns the result as a DOM document.
 *
 * @return a DOM node parsed from the <code>xmlrpc</code> URI.
 * @throws XFormsException if any error occurred.
 *///w w w  . j a  v a 2s.c o m
public Object resolve() throws XFormsException {
    try {

        URI uri = new URI(getURI());
        log.info("Getting URI: '" + uri + "'");

        Vector v = parseURI(uri);
        String rpcURL = (String) v.get(0);
        String function = (String) v.get(1);
        Hashtable params = (Hashtable) v.get(2);

        de.betterform.connector.xmlrpc.RPCClient rpc = new de.betterform.connector.xmlrpc.RPCClient(rpcURL);

        Document document = rpc.getDocument(function, params);

        if (uri.getFragment() != null) {
            return document.getElementById(uri.getFragment());
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.jtalks.tests.jcommune.mail.mailtrap.MailtrapClient.java

/**
 * Get message by identifier/*from   w w  w.  j a  va2 s  .  c o  m*/
 *
 * @param id the UUID type identifier
 * @return the message
 * @throws CouldNotGetMessageException
 */
public static String getMessage(String id) {
    RestTemplate client = new RestTemplate();
    try {
        String data = client.getForObject(
                new URI(API_INBOXES_URL + JTALKS_AUTOTESTS_MESSAGES + id + API_TOKEN_PARAM), String.class);
        return data;
    } catch (Exception e) {
        throw new CouldNotGetMessageException(e);
    }
}