Example usage for java.net URI toString

List of usage examples for java.net URI toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the content of this URI as a string.

Usage

From source file:com.aaasec.sigserv.cscommon.xmldsig.OfflineResolver.java

/**
 * We resolve http URIs <I>without</I> fragment...
 *
 * @param uri/* w  w w  . ja  v a2 s. co m*/
 * @param BaseURI
 *
 */
public boolean engineCanResolve(Attr uri, String BaseURI) {

    String uriNodeValue = uri.getNodeValue();
    if (uriNodeValue.equals("") || uriNodeValue.startsWith("#")) {
        return false;
    }

    try {
        URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
        if (uriNew.getScheme().equals("http")) {
            log.debug("I state that I can resolve " + uriNew.toString());
            return true;
        }

        log.debug("I state that I can't resolve " + uriNew.toString());
    } catch (URISyntaxException ex) {
        //
    }

    return false;
}

From source file:info.rmapproject.auth.service.AuthServiceImplTest.java

@Test
public void testGetAgentUriByKeySecret() {
    String accessKey = "rmaptest";
    String secret = "rmaptest";
    URI agentUri = null;
    try {/*from   w  ww .  java 2  s. c  om*/
        agentUri = rmapAuthService.getAgentUriByKeySecret(accessKey, secret);
    } catch (RMapAuthException e) {
        e.printStackTrace();
    }
    assertEquals(agentUri.toString(), "rmap:rmaptestagent");
}

From source file:net.lizhaoweb.aws.api.service.impl.SNSNotificationHandlerForCloudSearch.java

private String getAccessUrl(S3Object s3Object) {
    if (s3Object == null) {
        return null;
    }//from ww w. jav a2 s  .c om
    S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();
    if (s3ObjectInputStream == null) {
        return null;
    }
    HttpRequestBase httpRequestBase = s3ObjectInputStream.getHttpRequest();
    if (httpRequestBase == null) {
        return null;
    }
    URI uri = httpRequestBase.getURI();
    if (uri == null) {
        return null;
    }
    String accessUrl = uri.toString();
    return accessUrl;
}

From source file:org.wso2.carbon.ml.core.impl.BAMInputAdapter.java

/**
 * Set the size of the sample to be retrieved from BAM, and return the new URI.
 * /*from   w w w.  j a  va 2 s.  c  o  m*/
 * @param uri           URI of the BAM Data Source
 * @param sampleSize    Size of the sample needed.
 * @return              New URI having the sample size set.
 * @throws              URISyntaxException
 * @throws              MLInputAdapterException
 */
private URI getUriWithSampleSize(URI uri, int sampleSize) throws URISyntaxException, MLInputAdapterException {
    if (uriResourceParameters.length == 1) {
        uri = new URI(uri.toString() + "/-1/-1/0/" + sampleSize);
    } else if (uriResourceParameters.length == 2) {
        uri = new URI(uri.toString() + "/-1/0/" + sampleSize);
    } else if (uriResourceParameters.length == 3) {
        uri = new URI(uri.toString() + "/0/" + sampleSize);
    } else if (uriResourceParameters.length == 4) {
        uri = new URI(uri.toString() + "/" + sampleSize);
    } else if (uriResourceParameters.length == 5) {
        uri = new URI(uri.getScheme() + "://" + uri.getAuthority() + "/analytics/tables/"
                + uriResourceParameters[0] + "/" + uriResourceParameters[1] + "/" + uriResourceParameters[2]
                + "/" + uriResourceParameters[3] + "/" + sampleSize);
    } else {
        throw new MLInputAdapterException("Invalid data source URI: " + uri);
    }
    return uri.normalize();
}

From source file:com.meltmedia.cadmium.servlets.AbstractSecureRedirectStrategy.java

/**
 * Returns the secure version of the original URL for the request.
 * /*from  w w w.ja va2 s  . c o  m*/
 * @param request the insecure request that was made.
 * @param response the response for the request.
 * @return the secure version of the original URL for the request.
 * @throws IOException if the url could not be created.
 */
public String secureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String protocol = getProtocol(request);
    if (protocol.equalsIgnoreCase(HTTP_PROTOCOL)) {
        int port = mapPort(TO_SECURE_PORT_MAP, getPort(request));
        try {
            URI newUri = changeProtocolAndPort(HTTPS_PROTOCOL, port == DEFAULT_HTTPS_PORT ? -1 : port, request);
            return newUri.toString();
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Failed to create URI.", e);
        }
    } else {
        throw new UnsupportedProtocolException("Cannot build secure url for " + protocol);
    }
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//from w  ww  .  j a v  a  2 s . c  o m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000"));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getInitParameter(WebHdfsHaHttpClientDispatch.RESOURCE_ROLE_ATTRIBUTE))
            .andReturn(serviceName).anyTimes();
    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }
            };
        }
    }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    WebHdfsHaHttpClientDispatch dispatch = new WebHdfsHaHttpClientDispatch();
    dispatch.init(filterConfig);
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:bg.vitkinov.edu.services.JokeService.java

@RequestMapping(value = "/jokeImage/{id}", method = RequestMethod.GET, produces = { MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getJokeImage(@PathVariable Long id,
        @RequestHeader(value = "Accept") String acceptType,
        @RequestParam(required = false, defaultValue = "Arial-14") String font,
        @RequestParam(required = false, defaultValue = "black") String foreColor,
        @RequestParam(required = false) String backColor) {
    Joke joke = jokeRepository.findOne(id);
    ServiceInstance instance = loadBalancerClient.choose("image-service");
    if (instance == null)
        return null;
    /*//from   w w  w .j  a v a2s.  c o  m
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.set("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
      params.set("Accept", acceptType);
      params.set("base64", "true");
      params.set("font", font);
      params.set("foreColor", foreColor);
      params.set("foreColor", foreColor);
      params.set("backColor", backColor);
      */
    HttpHeaders params = new HttpHeaders();
    MediaType requestAcceptType = acceptType == null || "".equals(acceptType) ? MediaType.IMAGE_PNG
            : MediaType.parseMediaType(acceptType);
    params.setAccept(Arrays.asList(requestAcceptType));
    params.add("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
    params.add("base64", "true");
    params.add("font", font);
    params.add("foreColor", foreColor);
    params.add("backColor", backColor);

    //        URI url = URI.create(String.format("%s/img", instance.getUri().toString()))
    URI url = instance.getUri().resolve("/img");
    HttpEntity<byte[]> entity = new HttpEntity<byte[]>(null, params);
    return restTemplate.exchange(url.toString(), HttpMethod.POST, entity, byte[].class);
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testDigestAuthWithBasicPreemptive() throws Exception {
    Sardine sardine = SardineFactory.begin(properties.getProperty("username"),
            properties.getProperty("password"));
    URI url = URI.create("http://sudo.ch/dav/digest/");
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {/*ww w.  j a v a  2  s  .c o m*/
        sardine.list(url.toString());
        fail("Expected authentication to fail");
    } catch (SardineException e) {
        // Preemptive basic authentication is expected to fail when no basic
        // method is returned in Authentication response header
    }
}

From source file:org.wso2.carbon.dynamic.client.web.proxy.OAuthEndpointProxy.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response issueAccessToken(MultivaluedMap<String, String> paramMap) {
    DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient();
    String host = DCRProxyUtils.getKeyManagerHost();
    Response response;//w  w w  .  j  av a 2s  .  c o  m
    try {
        URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host).setPath(Constants.RemoteServiceProperties.OAUTH2_TOKEN_ENDPOINT).build();
        HttpHost httpHost = new HttpHost(uri.toString());
        CloseableHttpResponse serverResponse = httpClient.execute(httpHost, null);
        HttpEntity responseData = serverResponse.getEntity();
        int status = serverResponse.getStatusLine().getStatusCode();
        String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8);
        response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build();
    } catch (URISyntaxException | IOException e) {
        String msg = "Service invoke error occurred while registering client";
        log.error(msg, e);
        response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    } finally {
        httpClient.close();
    }
    return response;
}

From source file:org.opencredo.couchdb.core.CouchDbDocumentTemplate.java

public void writeDocument(URI uri, Object document, MessageHeaders headers) throws CouchDbOperationException {
    HttpEntity<?> httpEntity = createHttpEntity(document);
    try {//from  w  ww .  j  av a2  s  .  c om
        restOperations.put(uri.toString(), httpEntity, headers);
    } catch (RestClientException e) {
        throw new CouchDbOperationException("Unable to communicate with CouchDB", e);
    }
}