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.rusticisoftware.tincan.Verb.java

public Verb(JsonNode jsonNode) throws URISyntaxException {
    this();//from   ww w .  j  ava2s .  c  om

    JsonNode idNode = jsonNode.path("id");
    if (!idNode.isMissingNode()) {
        this.setId(new URI(idNode.textValue()));
    }

    JsonNode displayNode = jsonNode.path("display");
    if (!displayNode.isMissingNode()) {
        this.setDisplay(new LanguageMap(displayNode));
    }
}

From source file:org.opencredo.couchdb.transformer.CouchDbUrlToDocumentTransformerTest.java

@Test
public void transformUriMessage() throws Exception {
    URI uri = new URI("http://test");
    DummyDocument document = new DummyDocument("test");
    when(documentOperations.readDocument(eq(uri), eq(DummyDocument.class))).thenReturn(document);

    Message<URI> message = MessageBuilder.withPayload(uri).build();
    Message<DummyDocument> transformedMessage = (Message<DummyDocument>) transformer.transform(message);

    assertThat(transformedMessage.getPayload(), equalTo(document));
}

From source file:edu.harvard.iq.dvn.api.datadeposit.UrlManager.java

void processUrl(String url) throws SwordError {
    logger.fine("URL was: " + url);
    this.originalUrl = url;
    URI javaNetUri;/*from ww  w.j  av a 2  s  .c  om*/
    try {
        javaNetUri = new URI(url);
    } catch (URISyntaxException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Invalid URL syntax: " + url);
    }
    if (!"https".equals(javaNetUri.getScheme())) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                "https is required but protocol was " + javaNetUri.getScheme());
    }
    this.port = javaNetUri.getPort();
    String[] urlPartsArray = javaNetUri.getPath().split("/");
    List<String> urlParts = Arrays.asList(urlPartsArray);
    String dataDepositApiBasePath;
    try {
        List<String> dataDepositApiBasePathParts;
        //             1 2   3   4            5  6       7          8         9
        // for example: /dvn/api/data-deposit/v1/swordv2/collection/dataverse/sword
        dataDepositApiBasePathParts = urlParts.subList(0, 6);
        dataDepositApiBasePath = StringUtils.join(dataDepositApiBasePathParts, "/");
    } catch (IndexOutOfBoundsException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Error processing URL: " + url);
    }
    if (!dataDepositApiBasePath.equals(swordConfiguration.getBaseUrlPath())) {
        throw new SwordError(
                dataDepositApiBasePath + " found but " + swordConfiguration.getBaseUrlPath() + " expected");
    }
    try {
        this.servlet = urlParts.get(6);
    } catch (ArrayIndexOutOfBoundsException ex) {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                "Unable to determine servlet path from URL: " + url);
    }
    if (!servlet.equals("service-document")) {
        List<String> targetTypeAndIdentifier;
        try {
            //               6          7         8
            // for example: /collection/dataverse/sword
            targetTypeAndIdentifier = urlParts.subList(7, urlParts.size());
        } catch (IndexOutOfBoundsException ex) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                    "No target components specified in URL: " + url);
        }
        this.targetType = targetTypeAndIdentifier.get(0);
        if (targetType != null) {
            if (targetType.equals("dataverse")) {
                String dvAlias;
                try {
                    dvAlias = targetTypeAndIdentifier.get(1);
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                            "No dataverse alias provided in URL: " + url);
                }
                this.targetIdentifier = dvAlias;
            } else if (targetType.equals("study")) {
                String globalId;
                try {
                    List<String> globalIdParts = targetTypeAndIdentifier.subList(1,
                            targetTypeAndIdentifier.size());
                    globalId = StringUtils.join(globalIdParts, "/");
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                            "Invalid study global id provided in URL: " + url);
                }
                this.targetIdentifier = globalId;
            } else if (targetType.equals("file")) {
                String fileIdString;
                try {
                    // a user might reasonably pass in a filename as well [.get(2)] since
                    // we expose it in the statement of a study but we ignore it here
                    fileIdString = targetTypeAndIdentifier.get(1);
                } catch (IndexOutOfBoundsException ex) {
                    throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "No file id provided in URL: " + url);
                }
                this.targetIdentifier = fileIdString;
            } else {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "unsupported target type: " + targetType);
            }
        } else {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
                    "Unable to determine target type from URL: " + url);
        }
        logger.fine("target type: " + targetType);
        logger.fine("target identifier: " + targetIdentifier);
    }
}

From source file:fx.browser.Window.java

public void setLocation(String location) throws URISyntaxException {
    System.out.println("# " + this.toString() + "-Classloader: " + getClass().getClassLoader().toString()
            + " setLocation()");
    this.location = location;
    HttpGet httpGet = new HttpGet(new URI(location));

    try (CloseableHttpResponse response = Browser.getHttpClient().execute(httpGet)) {
        switch (response.getStatusLine().getStatusCode()) {

        case HttpStatus.SC_OK:
            FXMLLoader loader = new FXMLLoader();
            Header header = response.getFirstHeader("class-loader-url");

            if (header != null) {
                URL url = new URL(location);

                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), header.getValue());
                if (logger.isLoggable(Level.INFO)) {
                    logger.log(Level.INFO, "Set up remote classloader: {0}", url);
                }/*from ww w  .  j av a  2 s. c  om*/

                loader.setClassLoader(HttpClassLoader.getInstance(url, getClass().getClassLoader()));
            }

            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                response.getEntity().writeTo(buffer);
                response.close();
                setContent(loader.load(new ByteArrayInputStream(buffer.toByteArray())));
            } catch (Exception e) {
                response.close();
                logger.log(Level.INFO, e.toString(), e);
                Node node = loader.load(getClass().getResourceAsStream("/fxml/webview.fxml"));
                WebViewController controller = (WebViewController) loader.getController();

                controller.view(location);
                setContent(node);
            }

            break;

        case HttpStatus.SC_UNAUTHORIZED:
            response.close();
            Optional<Pair<String, String>> result = new LoginDialog().showAndWait();

            if (result.isPresent()) {
                URL url = new URL(location);

                Browser.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                        new UsernamePasswordCredentials(result.get().getKey(), result.get().getValue()));
                setLocation(location);
            }

            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.macrossx.wechat.impl.WechatHelper.java

/**
 * {@code _token_time}<tokentoken(7200-60)
 *///  ww w. j  a v a 2  s .  co  m
public Optional<WechatAccessToken> getAccessToken() {
    try {
        if (System.currentTimeMillis() < _token_time) {
            return Optional.of(_access_token);
        }
        long current = System.currentTimeMillis();
        HttpGet httpGet = new HttpGet();
        httpGet.setURI(new URI(MessageFormat.format(WechatConstants.ACCESS_TOKEN_URL, appid, appsecret)));
        return new WechatHttpClient().send(httpGet, WechatAccessToken.class).map((e) -> {
            _access_token = e;
            _token_time = current + _access_token.getExpires_in() - 60;
            return _access_token;
        });
    } catch (URISyntaxException e) {
        log.info(e.getMessage());
        return Optional.empty();
    }

}

From source file:HelloWorld.HelloWorldTest.java

@Test
public void postPeopleTest() throws URISyntaxException, IOException {
    URI uri = new URI(baseURI + "api/person");
    HttpPost post = new HttpPost(uri);
    Person person = new Person();
    person.firstName = "Sally";
    person.lastName = "Smith";
    person.age = 25;//from  w w  w  . java2s . c  om
    person.married = false;
    person.birthDate = new Date();

    Gson gson = new GsonBuilder().setDateFormat("MM/dd/yyyy").create();
    String json = gson.toJson(person);
    post.setEntity(new StringEntity(json));

    CloseableHttpResponse response = client.execute(post);
    assertEquals(201, response.getStatusLine().getStatusCode());
    assertEquals("Person creation success!", EntityUtils.toString(response.getEntity(), "UTF-8"));
}

From source file:com.whatsthatlight.teamcity.hipchat.HipChatApiProcessor.java

public HipChatEmoticons getEmoticons(int startIndex) {
    try {/*from   ww  w  .  j a  v a 2 s . c o m*/
        URI uri = new URI(
                String.format("%s%s?start-index=%s", this.configuration.getApiUrl(), "emoticon", startIndex));
        String authorisationHeader = String.format("Bearer %s", this.configuration.getApiToken());

        // Make request
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet(uri.toString());
        getRequest.addHeader(HttpHeaders.AUTHORIZATION, authorisationHeader);
        getRequest.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
        HttpResponse getResponse = client.execute(getRequest);
        StatusLine status = getResponse.getStatusLine();
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            logger.error(String.format("Could not retrieve emoticons: %s %s", status.getStatusCode(),
                    status.getReasonPhrase()));
            return new HipChatEmoticons(new ArrayList<HipChatEmoticon>(), 0, 0, null);
        }

        Reader reader = new InputStreamReader(getResponse.getEntity().getContent());
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(reader, HipChatEmoticons.class);
    } catch (Exception e) {
        logger.error("Could not get emoticons", e);
    }

    return new HipChatEmoticons(new ArrayList<HipChatEmoticon>(), 0, 0, null);
}

From source file:org.fosstrak.ale.server.type.FileSubscriberOutputChannel.java

public FileSubscriberOutputChannel(String notificationURI) throws InvalidURIException {
    super(notificationURI);
    try {//from   w ww.j av  a 2 s.co m
        uri = new URI(notificationURI.replaceAll("\\\\", "/"));
        path = StringUtils.startsWithIgnoreCase(uri.getPath(), "/") ? uri.getPath().substring(1)
                : uri.getPath();
        if ("".equalsIgnoreCase(path) || StringUtils.endsWithIgnoreCase(path, "/")) {
            throw new InvalidURIException("missing filename");
        }
        host = (uri.getHost() == null) ? LOCALHOST.toLowerCase() : uri.getHost();
        if (!(LOCALHOST.equalsIgnoreCase(getHost()))) {
            throw new InvalidURIException("This implementation can not write reports to a remote file.");
        }
        if (!("FILE".equalsIgnoreCase(uri.getScheme()))) {
            LOG.error("invalid scheme: " + uri.getScheme());
            throw new InvalidURIException("invalid scheme: " + uri.getScheme());
        }
    } catch (Exception e) {
        LOG.error("malformed URI");
        throw new InvalidURIException("malformed URI: ", e);
    }
}

From source file:org.fcrepo.kernel.impl.services.ExternalContentServiceImplTest.java

@Before
public void setUp() throws URISyntaxException, IOException {
    initMocks(this);
    sourceUri = new URI("http://localhost:8080/xyz");
    testObj = spy(new ExternalContentServiceImpl());
    testObj.setConnManager(mockClientPool);

    when(testObj.getCloseableHttpClient()).thenReturn(mockClient);
    when(mockClient.execute(any(HttpGet.class))).thenReturn(mockResponse);
    when(mockResponse.getEntity()).thenReturn(mockEntity);
    when(mockEntity.getContent()).thenReturn(mockInputStream);
}

From source file:com.sun.jersey.server.impl.uri.rules.UriRuleContextDbl.java

public static UriRuleContext make() throws Exception {
    WebApplicationImpl app = new WebApplicationImpl();
    ContainerRequest request = new ContainerRequest(app, // web application requested
            "GET", // HTTP method
            new URI("/"), // base URI
            new URI("/test"), // request URI
            new InBoundHeaders(), // headers
            IOUtils.toInputStream("") // incoming entity
    );/* w  w  w. j  a  v a  2s.  co m*/
    ContainerResponse response = new ContainerResponse(app, // web application requested
            request, // container request
            new ResponseWriterDbl());
    UriRuleContext context = new WebApplicationContext(app, request, response);
    return context;
}