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:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/* ww  w  .  j a  v  a  2  s . c  o m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    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.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<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @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));
    WebHdfsHaDispatch dispatch = new WebHdfsHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    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:org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "OOZIE";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//w w  w.ja  v  a  2  s  .co m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    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.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<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @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));
    DefaultHaDispatch dispatch = new DefaultHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.setServiceRole(serviceName);
    dispatch.init();
    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:se.vgregion.urlservice.controllers.RedirectController.java

/**
 * Handle redirects//ww w .  ja v a  2  s .  com
 */
@RequestMapping("/{path}")
public ModelAndView redirect(@PathVariable("path") String path, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    log.info("Redirecting");

    // TODO clean up domain handling
    String domain = "http://" + request.getServerName();
    if (request.getServerPort() != 80) {
        domain += ":" + request.getServerPort();
    }
    domain += request.getContextPath();
    URI uri = urlServiceService.redirect(domain, path);

    if (uri != null) {
        ModelAndView mav = new ModelAndView("redirect");
        response.setStatus(301);
        response.setHeader("Location", uri.toString());

        mav.addObject("longUrl", uri.toString());

        if (statsTracker != null) {
            try {
                statsTracker.track(uri.toString(), domain + path, path, request.getHeader("User-agent"));
            } catch (Exception e) {
                log.warn("Error on tracking to Piwik", e);
            }
        }

        return mav;
    } else {
        response.sendError(404);
        return null;
    }
}

From source file:won.protocol.rest.LinkedDataRestClientHttps.java

@Override
public Dataset readResourceData(URI resourceURI, final URI requesterWebID) {

    HttpMessageConverter datasetConverter = new RdfDatasetConverter();
    RestTemplate restTemplate;//from  w w  w  . j  av a 2s.  c  o  m
    try {
        restTemplate = getRestTemplateForReadingLinkedData(requesterWebID.toString());
    } catch (Exception e) {
        logger.error("Failed to create ssl tofu rest template", e);
        throw new RuntimeException(e);
    }
    restTemplate.getMessageConverters().add(datasetConverter);

    return super.readResourceData(resourceURI, restTemplate, entity);
}

From source file:fr.cls.atoll.motu.library.cas.util.AssertionUtils.java

/**
 * Adds the cas ticket.//from w  w w.  ja  v  a  2 s .  co m
 * 
 * @param targetService the target service
 * @param data the data
 * @param user the user
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MotuCasException the motu cas exception
 */
public static String addCASTicket(URI targetService, MultivaluedMap<String, String> data, UserBase user)
        throws IOException, MotuCasException {
    return AssertionUtils.addCASTicket(targetService.toString(), data, user.getLogin(), user.getPwd(),
            user.getCasRestSuffURL());
}

From source file:org.fcrepo.apix.jena.impl.LdpContainerRegistry.java

@Override
public boolean hasInDomain(final URI uri) {
    return uri.toString().startsWith(containerId.toString());
}

From source file:com.bittorrent.mpetazzoni.common.Torrent.java

/**
 * Helper method to create a {@link Torrent} object for a set of files.
 *
 * <p>//from   w w w .  jav  a  2  s  . c om
 * Hash the given files to create the multi-file {@link Torrent} object
 * representing the Torrent meta-info about them, needed for announcing
 * and/or sharing these files. Since we created the torrent, we're
 * considering we'll be a full initial seeder for it.
 * </p>
 *
 * @param parent The parent directory or location of the torrent files,
 * also used as the torrent's name.
 * @param files The files to add into this torrent.
 * @param announce The announce URI that will be used for this torrent.
 * @param announceList The announce URIs organized as tiers that will 
 * be used for this torrent
 * @param createdBy The creator's name, or any string identifying the
 * torrent's creator.
 */
private static Torrent create(File parent, List<File> files, URI announce, List<List<URI>> announceList,
        String createdBy) throws InterruptedException, IOException {
    if (files == null || files.isEmpty()) {
        logger.info("Creating single-file torrent for {}...", parent.getName());
    } else {
        logger.info("Creating {}-file torrent {}...", files.size(), parent.getName());
    }

    Map<String, BEValue> torrent = new HashMap<String, BEValue>();

    if (announce != null) {
        torrent.put("announce", new BEValue(announce.toString()));
    }
    if (announceList != null) {
        List<BEValue> tiers = new LinkedList<BEValue>();
        for (List<URI> trackers : announceList) {
            List<BEValue> tierInfo = new LinkedList<BEValue>();
            for (URI trackerURI : trackers) {
                tierInfo.add(new BEValue(trackerURI.toString()));
            }
            tiers.add(new BEValue(tierInfo));
        }
        torrent.put("announce-list", new BEValue(tiers));
    }

    torrent.put("creation date", new BEValue(new Date().getTime() / 1000));
    torrent.put("created by", new BEValue(createdBy));

    Map<String, BEValue> info = new TreeMap<String, BEValue>();
    info.put("name", new BEValue(parent.getName()));
    info.put("piece length", new BEValue(Torrent.PIECE_LENGTH));

    if (files == null || files.isEmpty()) {
        info.put("length", new BEValue(parent.length()));
        info.put("pieces", new BEValue(Torrent.hashFile(parent), Torrent.BYTE_ENCODING));
    } else {
        List<BEValue> fileInfo = new LinkedList<BEValue>();
        for (File file : files) {
            Map<String, BEValue> fileMap = new HashMap<String, BEValue>();
            fileMap.put("length", new BEValue(file.length()));

            LinkedList<BEValue> filePath = new LinkedList<BEValue>();
            while (file != null) {
                if (file.equals(parent)) {
                    break;
                }

                filePath.addFirst(new BEValue(file.getName()));
                file = file.getParentFile();
            }

            fileMap.put("path", new BEValue(filePath));
            fileInfo.add(new BEValue(fileMap));
        }
        info.put("files", new BEValue(fileInfo));
        info.put("pieces", new BEValue(Torrent.hashFiles(files), Torrent.BYTE_ENCODING));
    }
    torrent.put("info", new BEValue(info));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BEncoder.bencode(new BEValue(torrent), baos);
    return new Torrent(baos.toByteArray(), true);
}

From source file:info.magnolia.ui.admincentral.shellapp.favorites.FavoritesPresenter.java

String getUrlFragmentFromURI(URI location) {
    final String url = location.toString();
    String instancePrefix = getWebAppRootURI();

    final String urlFragment = url.contains(instancePrefix)
            ? url.substring(url.indexOf(instancePrefix) + instancePrefix.length(), url.length())
            : url;/*from   w w w  .j a v a  2 s .  c om*/
    return urlFragment;
}

From source file:org.fcrepo.importexport.integration.ImporterIT.java

@Test
public void testImport() throws FcrepoOperationFailedException, IOException {
    final String exportPath = TARGET_DIR + "/" + UUID.randomUUID() + "/testPeartreeAmbiguity";
    final String parentTitle = "parent";
    final String childTitle = "child";
    final String binaryText = "binary";

    final URI parent = URI.create(serverAddress + UUID.randomUUID());
    final URI child = URI.create(parent.toString() + "/child");
    final URI binary = URI.create(child + "/binary");
    assertEquals(SC_CREATED, create(parent).getStatusCode());
    assertEquals(SC_CREATED, create(child).getStatusCode());
    assertEquals(SC_NO_CONTENT, client.patch(parent).body(insertTitle(parentTitle)).perform().getStatusCode());
    assertEquals(SC_NO_CONTENT, client.patch(child).body(insertTitle(childTitle)).perform().getStatusCode());
    assertEquals(SC_CREATED,/*from w  w  w .  jav  a  2  s  .c  o m*/
            client.put(binary).body(new ByteArrayInputStream(binaryText.getBytes("UTF-8")), "text/plain")
                    .perform().getStatusCode());

    // Run an export process
    final Config config = new Config();
    config.setMode("export");
    config.setDescriptionDirectory(exportPath);
    config.setBinaryDirectory(exportPath);
    config.setRdfExtension(DEFAULT_RDF_EXT);
    config.setRdfLanguage(DEFAULT_RDF_LANG);
    config.setResource(parent.toString());
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);

    final Exporter exporter = new Exporter(config, clientBuilder);
    exporter.run();

    // Verify
    resourceExists(parent);

    // Remove the resources
    client.delete(parent).perform();
    final FcrepoResponse getResponse = client.get(parent).perform();
    assertEquals("Resource should have been deleted!", SC_GONE, getResponse.getStatusCode());
    assertEquals("Failed to delete the tombstone!", SC_NO_CONTENT,
            client.delete(getResponse.getLinkHeaders("hasTombstone").get(0)).perform().getStatusCode());

    // Run the import process
    config.setMode("import");

    final Importer importer = new Importer(config, clientBuilder);
    importer.run();

    // Verify
    assertHasTitle(parent, parentTitle);
    assertHasTitle(child, childTitle);
    assertEquals("Binary should have been imported!", binaryText,
            IOUtils.toString(client.get(binary).perform().getBody(), "UTF-8"));
}