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.seajas.search.contender.scripting.FeedScriptsTestBase.java

/**
 * Evaluates the script.//from w ww.  j  a v a 2 s  .c o m
 */
protected SyndFeed run(final String feedUri, final String scriptFile) throws Exception {
    final ScriptEngine engine = engineManager.getEngineByMimeType("text/javascript");

    injectionService = new MockInjectionService();
    subject = new FeedScriptEvaluation(new WebResolverSettings());
    subject.setScriptResolver(new ScriptCacheResolver<FeedScript>() {
        @Override
        public FeedScript resolve(final Bindings bindings) throws ScriptException {
            try {
                for (Map.Entry<String, Object> entry : bindings.entrySet())
                    engine.put(entry.getKey(), entry.getValue());

                engine.eval(readFileToString(new File("src/main/scripts/feed/" + scriptFile), "UTF-8"));

                return ((Invocable) engine).getInterface(FeedScript.class);
            } catch (IOException e) {
                throw new IllegalArgumentException("Invalid script", e);
            }
        }
    });

    if (scriptFile.endsWith(".js"))
        subject.setEngine(engine);
    else
        throw new IllegalArgumentException("Unknown script file extension.");

    subject.setFeedContent(samples.values().iterator().next());

    subject.setWebPages(new WebPages());
    subject.setWebResolver(new WebResolver() {
        @Override
        public String retrieveText(URI resource) {
            return samples.get(resource.toString());
        }
    });
    subject.setFeedURI(new URI(feedUri));
    subject.setCacheResolver(new FeedScriptCacheResolver() {
        @Override
        public boolean isCached(String resource) {
            return false;
        }
    });

    subject.setInjectionService(injectionService);

    subject.init();
    subject.run();

    SyndFeed feed = subject.getFeed();
    assertNotNull("feed", feed);

    // The validated feed must be serializable:
    SyndFeed result = (SyndFeed) feed.clone();
    WebFeeds.validate(result, new URI(feedUri));
    new SyndFeedOutput().outputString(result, true);

    return feed;
}

From source file:com.nec.harvest.controller.SonekisController.java

/** {@inheritDoc} */
@Override/*from w w w .j a  va  2 s  .c o m*/
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering sonekis page view without parameters...");
    }

    // Automatically build a redirect link
    UriComponents uriComponents = UriComponentsBuilder
            .fromUriString(Constants.SONEKIS_PATH + "/{orgCode}/{month}").build();
    String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
    URI uri = uriComponents.expand(proGNo, userOrgCode, businessMonth).encode().toUri();
    return "redirect:" + uri.toString();
}

From source file:eu.openanalytics.shinyproxy.ShinyProxyTestStrategy.java

@Override
public boolean testProxy(Proxy proxy) {

    int totalWaitMs = Integer.parseInt(environment.getProperty("proxy.container-wait-time", "20000"));
    int waitMs = Math.min(2000, totalWaitMs);
    int maxTries = totalWaitMs / waitMs;
    int timeoutMs = Integer.parseInt(environment.getProperty("proxy.container-wait-timeout", "5000"));

    if (proxy.getTargets().isEmpty())
        return false;
    URI targetURI = proxy.getTargets().values().iterator().next();

    return retry(i -> {
        try {/*from  w  w  w.ja va 2s  . c  o  m*/
            URL testURL = new URL(targetURI.toString());
            HttpURLConnection connection = ((HttpURLConnection) testURL.openConnection());
            connection.setConnectTimeout(timeoutMs);
            int responseCode = connection.getResponseCode();
            if (responseCode == 200)
                return true;
        } catch (Exception e) {
            if (i > 1 && log != null)
                log.warn(String.format("Container unresponsive, trying again (%d/%d): %s", i, maxTries,
                        targetURI));
        }
        return false;
    }, maxTries, waitMs, false);
}

From source file:org.openlmis.fulfillment.service.referencedata.RightReferenceDataServiceTest.java

@Test
public void shouldFindRightByName() throws Exception {
    // given//from  w  w w .j av  a2  s .co  m
    String name = "testRight";

    RightDto rightDto = generateInstance();
    rightDto.setName(name);

    RightDto[] rights = new RightDto[] { rightDto };
    RightReferenceDataService service = (RightReferenceDataService) prepareService();
    ResponseEntity<RightDto[]> response = mock(ResponseEntity.class);

    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            eq(service.getArrayResultClass()))).thenReturn(response);
    when(response.getBody()).thenReturn(rights);

    RightDto right = service.findRight(name);

    // then
    verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.GET), entityCaptor.capture(),
            eq(service.getArrayResultClass()));

    URI uri = uriCaptor.getValue();
    String url = service.getServiceUrl() + service.getUrl() + "search?name=" + name;

    assertThat(uri.toString(), is(equalTo(url)));
    assertThat(right.getName(), is(equalTo(name)));

    assertAuthHeader(entityCaptor.getValue());
    assertThat(entityCaptor.getValue().getBody(), is(nullValue()));
}

From source file:gmusic.api.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, final HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(
                address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")) + "&format=jsarray");
    }/*from  w ww . j  a v  a  2  s  .  c o m*/

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay"))
    // && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}

From source file:info.rmapproject.api.auth.ApiUserServiceTest.java

/**
 * Tests retrieval of an Agent that has been set up to synchronize with the database
 * should retrieve an Agent URI//from  w  w w  . j a  v a 2  s .co  m
 */
@Test
@Ignore //see comment at top of page
public void getSystemAgentUriForEventTestSyncAgent() {
    try {
        URI sysAgent = apiUserService.getSystemAgentUri(TEST_USER_TESTSYNC, TEST_PASS_TESTSYNC);
        assertTrue(sysAgent.toString().length() > 0);
    } catch (RMapApiException e) {
        fail("sysAgent not retrieved");
    }
}

From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

public static ObjectNode buildSchemaNode(final ObjectMapper objectMapper, final URI schemaUri,
        final SchemaLoader schemaLoader, final Set<URI> addedBaseSchemaUris) {

    final Prototype prototype = schemaLoader.getPrototype(schemaUri);
    if (prototype == null) {
        return null;
    }//from w w  w. ja  va 2s  .  co  m

    final ObjectNode schemaNode = objectMapper.createObjectNode();
    schemaNode.put(PropertyName.localName.name(), prototype.getUniqueName().getLocalName());
    schemaNode.put(PropertyName.title.name(), prototype.getTitle());
    schemaNode.put(PropertyName.uri.name(), schemaUri.toString());
    schemaNode.put(PropertyName.version.name(), prototype.getVersion());

    String titleSlotName = prototype.getTitleSlotName();
    if (StringUtils.isNotBlank(titleSlotName)) {
        schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName);
    } else {
        titleSlotName = getTitleSlotName(schemaUri, schemaLoader);
        if (StringUtils.isNotBlank(titleSlotName)) {
            schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName);
        }
    }

    final Set<String> allSlotNames = prototype.getAllSlotNames();
    if (allSlotNames != null && !allSlotNames.isEmpty()) {
        final ArrayNode propertyNamesNode = objectMapper.createArrayNode();

        for (final String slotName : allSlotNames) {
            final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
            if (protoSlot instanceof LinkProtoSlot) {
                continue;
            }

            if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                propertyNamesNode.add(slotName);
            }
        }
        if (propertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.propertyNames.name(), propertyNamesNode);
        }
    }

    final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames();
    if (keySlotNames != null && !keySlotNames.isEmpty()) {
        final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode();

        for (final String keySlotName : keySlotNames) {
            keyPropertyNamesNode.add(keySlotName);
        }

        if (keyPropertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode);
        }
    }

    final Set<String> allKeySlotNames = prototype.getAllKeySlotNames();
    final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode();
    schemaNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode);

    for (final String keySlotName : allKeySlotNames) {
        allKeySlotNamesNode.add(keySlotName);
    }

    final Set<String> comparablePropertyNames = prototype.getComparableSlotNames();
    if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) {
        final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode();

        for (final String comparablePropertyName : comparablePropertyNames) {
            comparablePropertyNamesNode.add(comparablePropertyName);
        }

        if (comparablePropertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode);
        }
    }

    final Map<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots();
    if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) {
        final ArrayNode linkNamesNode = objectMapper.createArrayNode();

        for (final LinkProtoSlot linkProtoSlot : linkProtoSlots.values()) {
            if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                linkNamesNode.add(linkProtoSlot.getName());
            }
        }

        if (linkNamesNode.size() > 0) {
            schemaNode.put(PropertyName.linkNames.name(), linkNamesNode);
        }
    }

    final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris();
    if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty() && addedBaseSchemaUris != null) {

        final ArrayNode baseSchemasNode = objectMapper.createArrayNode();
        for (final URI baseSchemaUri : declaredBaseSchemaUris) {
            if (!addedBaseSchemaUris.contains(baseSchemaUri)) {
                final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader,
                        addedBaseSchemaUris);
                baseSchemasNode.add(baseSchemaNode);
                addedBaseSchemaUris.add(baseSchemaUri);
            }
        }

        if (baseSchemasNode.size() > 0) {
            schemaNode.put(PropertyName.baseSchemas.name(), baseSchemasNode);
        }
    }

    return schemaNode;
}

From source file:com.nesscomputing.service.discovery.client.ServiceURI.java

public ServiceURI(final URI uri) throws URISyntaxException {
    if (!"srvc".equals(uri.getScheme())) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }/*from  w  w  w  .j a  va2s  .com*/
    if (!StringUtils.startsWith(uri.getSchemeSpecificPart(), "//")) {
        throw new URISyntaxException(uri.toString(), "ServiceURI only supports srvc:// URIs");
    }

    final String schemeSpecificPart = uri.getSchemeSpecificPart().substring(2);
    final int slashIndex = schemeSpecificPart.indexOf('/');
    if (slashIndex == -1) {
        throw new URISyntaxException(uri.toString(), "ServiceURI requires a slash at the end of the service!");
    }
    final int colonIndex = schemeSpecificPart.indexOf(':');
    if (colonIndex == -1 || colonIndex > slashIndex) {
        serviceName = schemeSpecificPart.substring(0, slashIndex);
        serviceType = null;
    } else {
        serviceName = schemeSpecificPart.substring(0, colonIndex);
        serviceType = schemeSpecificPart.substring(colonIndex + 1, slashIndex);
    }

    path = uri.getRawPath();
    query = uri.getRawQuery();
    fragment = uri.getRawFragment();
}

From source file:info.rmapproject.api.auth.ApiUserServiceTest.java

/**
 * Tests retrieval of a System Agent URI where user has an agent
 * Should return an Agent URI./*from   w  w w. j  a  v a 2s. co m*/
 */
@Test
@Ignore //see comment at top of page
public void getSystemAgentUriForEventTestWithAgent() {
    try {
        URI sysAgent = apiUserService.getSystemAgentUri(TEST_USER_WITHAGENT, TEST_PASS_WITHAGENT);
        assertTrue(sysAgent.toString().equals("rmap:userwithagent"));
    } catch (RMapApiException e) {
        fail("sysAgent not retrieved");
    }
}

From source file:org.jasig.portlet.calendar.adapter.exchange.AutodiscoverRedirectStrategy.java

/**
 * Overrides behavior to follow redirects for POST messages, AND to have the redirect be a POST.  Behavior of
 * <code>DefaultRedirectStrategy</code> is to use a GET for the redirect (though against spec this is the
 * de-facto standard, see http://www.mail-archive.com/httpclient-users@hc.apache.org/msg06327.html and
 * http://www.alanflavell.org.uk/www/post-redirect.html).
 *
 * For our application, we want to follow the redirect for a 302 as long as it is to a safe location and
 * have the redirect be a POST./*  ww  w . j ava2 s .c  o  m*/
 *
 * This code is modified from http-components' http-client 4.2.5.  Since we only use POST the code for the
 * other HTTP methods has been removed to simplify this method.
 *
 * @param request Http request
 * @param response Http response
 * @param context Http context
 * @return Request to issue to the redirected location
 * @throws ProtocolException protocol exception
 */
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    log.info("Following redirect to {}", uri.toString());
    String method = request.getRequestLine().getMethod();
    int status = response.getStatusLine().getStatusCode();

    // Insure location is safe
    if (matchesPatternSet(uri, unsafeUriPatterns)) {
        log.warn("Not following to URI {} - matches a configured unsafe URI pattern", uri.toString());
        throw new CalendarException("Autodiscover redirected to unsafe URI " + uri.toString());
    }

    if (!matchesPatternSet(uri, uriRequirementPatterns) && uriRequirementPatterns.size() > 0) {
        log.warn("Not following to URI {} - URI does not match a required URI pattern", uri.toString());
        throw new CalendarException(
                "Autodiscover redirected to URI not matching required pattern. URI=" + uri.toString());
    }

    // Follow forwards for 301 and 302 in addition to 307, to validate the redirect location,
    // and to use a POST method.
    if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY) {
        if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
            return copyEntity(new HttpPost(uri), request);
        }
    }

    // Should not get here, but return sensible value just in case.  A GET will likely fail.
    return new HttpGet(uri);
}