Example usage for java.net URL toExternalForm

List of usage examples for java.net URL toExternalForm

Introduction

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

Prototype

public String toExternalForm() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java

@Override
protected void establishUserApps() {
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    if (tcl == null) {
        tcl = getClass().getClassLoader();
    }/*  w  ww. j  av a 2  s.co m*/

    final String WEBAPPDIR = "auth/webapp";

    final String CONTEXTPATH = "/auth";

    // for localhost:port/admin/index.html and whatever else is in the webapp directory
    final URL warUrl = tcl.getResource(WEBAPPDIR);
    final String warUrlString = warUrl.toExternalForm();

    /*
     * Context context = new WebAppContext(warUrlString, CONTEXTPATH); server.setHandler(context);
     */

    WebAppContext webapp = createWebApp(CONTEXTPATH, warUrlString);
    this.server.setHandler(webapp);

    // Thread.currentThread().setContextClassLoader(context.getClassLoader());

    System.setProperty(PicketBoxConstants.USERNAME, "Aladdin");
    System.setProperty(PicketBoxConstants.CREDENTIAL, "Open Sesame");

    FilterHolder filterHolder = new FilterHolder(DelegatingSecurityFilter.class);

    /*
     * Map<String, String> contextParameters = new HashMap<String, String>();
     * contextParameters.put(PicketBoxConstants.AUTHENTICATION_KEY, PicketBoxConstants.HTTP_DIGEST);
     * contextParameters.put(PicketBoxConstants.HTTP_CONFIGURATION_PROVIDER,
     * HTTPDigestConfigurationProvider.class.getName());
     *
     * context.setInitParams(contextParameters);
     *
     * context.addFilter(filterHolder, "/", 1);
     */

    webapp.setInitParameter(PicketBoxConstants.AUTHENTICATION_KEY, PicketBoxConstants.HTTP_DIGEST);
    webapp.setInitParameter(PicketBoxConstants.HTTP_CONFIGURATION_PROVIDER,
            HTTPDigestConfigurationProvider.class.getName());

    ServletHandler servletHandler = new ServletHandler();
    servletHandler.addFilter(filterHolder, createFilterMapping("/", filterHolder));

    webapp.setServletHandler(servletHandler);
}

From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java

private WebResponse produceWebResponseForGAEProcolHack(final URL url) {
    final String externalForm = url.toExternalForm();
    for (String pattern : GAE_URL_HACKS) {
        final int index = externalForm.indexOf(pattern);
        if (index == 0) {
            String contentString = externalForm.substring(pattern.length());
            if (contentString.startsWith("'") && contentString.endsWith("'")) {
                contentString = contentString.substring(1, contentString.length() - 1);
            }//from w ww.  j  ava  2 s .co m
            if (LOG.isDebugEnabled()) {
                LOG.debug("special handling of URL, returning (" + contentString + ") for URL " + url);
            }
            return new StringWebResponse(contentString, url);
        }
    }
    return null;
}

From source file:org.jbpm.formbuilder.server.RESTIoServiceTest.java

public void testSetContextOK() throws Exception {
    RESTIoService restService = new RESTIoService();
    URL pathToClasses = getClass().getResource("/FormBuilder.properties");
    String filePath = pathToClasses.toExternalForm();
    //assumes compilation is in target/classes
    filePath = filePath.replace("target/classes/FormBuilder.properties", "src/main/webapp");
    filePath = filePath + "/WEB-INF/springComponents.xml";
    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(filePath);
    ServiceFactory.getInstance().setBeanFactory(ctx);
    ServletContext context = EasyMock.createMock(ServletContext.class);

    EasyMock.replay(context);//from w  w w  .jav a  2 s  .  com
    restService.setContext(context);
    EasyMock.verify(context);

    TaskDefinitionService service = restService.getTaskService();
    assertNotNull("service shouldn't be null", service);
}

From source file:org.jboss.as.test.integration.security.jaas.JAASIdentityCachingTestCase.java

/**
 * Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the
 * expected one./* w  w  w .  j  av a 2  s.c o m*/
 * 
 * @param webAppURL
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL webAppURL) throws Exception {
    final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1)
            + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "="
            + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8"));
    final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1));
    LOGGER.info("Requesting URL " + greetingUri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        final HttpGet getCounter = new HttpGet(counterUri);
        final HttpGet getGreeting = new HttpGet(greetingUri);
        HttpResponse response = httpClient.execute(getGreeting);
        assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());

        //check if LoginModule #login() counter is initialized correctly
        response = httpClient.execute(getCounter);
        assertEquals("0", EntityUtils.toString(response.getEntity()));

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin",
                CustomLoginModule.PASSWORD);
        httpClient.getCredentialsProvider()
                .setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials);

        //make 2 calls to the servlet
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
        response = httpClient.execute(getGreeting);
        assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));

        //There should be only one call to login() method 
        response = httpClient.execute(getCounter);
        assertEquals("1", EntityUtils.toString(response.getEntity()));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.intuit.tank.agent.AgentStartup.java

public void run() {
    logger.info("Starting up...");
    if (AmazonUtil.usingEip()) {
        try {/*from  www.  j a  v a 2  s  .  c  o m*/
            logger.info("Using EIP. Sleeping for " + WAIT_FOR_RESTART_TIME + " ms.");
            Thread.sleep(WAIT_FOR_RESTART_TIME);
        } catch (InterruptedException e1) {
            logger.info("Exception waiting.");
            System.exit(0);
        }
    }
    try {
        if (controllerBase == null) {
            controllerBase = AmazonUtil.getControllerBaseUrl();
        }

        logger.info("Starting up: ControllerBaseUrl=" + controllerBase);
        URL url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SETTINGS);
        logger.info("Starting up: making call to tank service url to get settings.xml " + url.toExternalForm());
        InputStream settingsStream = url.openStream();
        try {
            String settings = IOUtils.toString(settingsStream);
            FileUtils.writeStringToFile(new File("settings.xml"), settings);
            logger.info("got settings file...");
        } finally {
            IOUtils.closeQuietly(settingsStream);
        }
        url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SUPPORT);
        logger.info("Making call to tank service url to get support files " + url.toExternalForm());
        ZipInputStream zip = new ZipInputStream(url.openStream());
        try {
            ZipEntry entry = zip.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                logger.info("Got file from controller: " + name);
                File f = new File(name);
                FileOutputStream fout = FileUtils.openOutputStream(f);
                try {
                    IOUtils.copy(zip, fout);
                } finally {
                    IOUtils.closeQuietly(fout);
                }
                entry = zip.getNextEntry();
            }
        } finally {
            IOUtils.closeQuietly(zip);
        }
        // now start the harness
        String jvmArgs = AmazonUtil.getUserDataAsMap().get(TankConstants.KEY_JVM_ARGS);
        logger.info("Starting apiharness with command: " + API_HARNESS_COMMAND + " -http=" + controllerBase
                + " " + jvmArgs);
        Runtime.getRuntime().exec(API_HARNESS_COMMAND + " -http=" + controllerBase + " " + jvmArgs);
    } catch (Exception e) {
        logger.error("Error in AgentStartup " + e, e);
    }
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected RemoteReference(URL url, Credential token) {
    try {//from  ww w . ja  v a 2 s. c o m
        if (!url.toString().endsWith("/"))
            url = new URL(url.toExternalForm() + '/'); // normalize
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL:" + url, e);
    }
    this.url = url;
    this.token = token;
}

From source file:com.thinkberg.webdav.PropPatchHandler.java

/**
 * Get a multistatus response for each of the property set/remove requests.
 *
 * @param object              the context object the property requests apply to
 * @param requestedProperties the properties that should be set or removed
 * @param baseUrl             the base url of this server
 * @return an XML document that is the response
 * @throws FileSystemException if there is an error setting or removing a property
 *//*ww  w .ja  v  a  2s  .c om*/
private Document getMultiStatusResponse(FileObject object, List<Element> requestedProperties, URL baseUrl)
        throws FileSystemException {
    Document propDoc = DocumentHelper.createDocument();
    propDoc.setXMLEncoding("UTF-8");

    Element multiStatus = propDoc.addElement(TAG_MULTISTATUS, NAMESPACE_DAV);
    Element responseEl = multiStatus.addElement(TAG_RESPONSE);
    try {
        URL url = new URL(baseUrl, URLEncoder.encode(object.getName().getPath(), "UTF-8"));
        responseEl.addElement(TAG_HREF).addText(url.toExternalForm());
    } catch (Exception e) {
        LOG.error("can't set HREF tag in response", e);
    }
    DavResource resource = DavResourceFactory.getInstance().getDavResource(object);
    resource.setPropertyValues(responseEl, requestedProperties);
    return propDoc;
}

From source file:org.apache.commons.rdf.integrationtests.JSONLDParsingTest.java

private void rdf4jParse(URL url) throws IOException {
    Model model;/*from w  ww.  j  a va  2  s  . co m*/
    try (InputStream in = url.openStream()) {
        model = Rio.parse(in, url.toExternalForm(), RDFFormat.JSONLD);
    }
    RDF4JGraph graph = new RDF4J().asGraph(model);
    checkGraph(graph);
}

From source file:org.jboss.aerogear.test.api.extension.JavaSenderTestRequest.java

public String sendTestMessage(PushApplication application, URL pushServerUrl, String alert) {
    Response response = getSession().given().formParam("pushAppId", application.getPushApplicationID())
            .formParam("secret", application.getMasterSecret())
            .formParam("serverUrl", pushServerUrl.toExternalForm()).formParam("alert", alert)
            .post("/javaSenderTest");

    UnexpectedResponseException.verifyResponse(response, HttpStatus.SC_OK);

    return response.asString();
}

From source file:com.esri.geoportal.commons.robots.BotsParser.java

/**
 * Parses context of the Robots.txt file if available.
 *
 * @param matchingStrategy matching strategy
 * @param winningStrategy winning strategy
 * @param serverUrl url of the server which is expected to have robots.txt
 * present/*from   w ww  .j a  v a 2s.  c o  m*/
 * @return instance of {@link Bots} or <code>null</code> if unable to
 * obtain robots.txt
 */
public Bots readRobotsTxt(MatchingStrategy matchingStrategy, WinningStrategy winningStrategy, URL serverUrl) {
    if (serverUrl != null) {
        LOG.info(formatForLog("Accessing robots.txt for: %s", serverUrl.toExternalForm()));
        try {
            URL robotsTxtUrl = getRobotsTxtUrl(serverUrl);
            if (robotsTxtUrl != null) {
                HttpGet method = new HttpGet(robotsTxtUrl.toExternalForm());
                method.setConfig(DEFAULT_REQUEST_CONFIG);
                method.setHeader("User-Agent", botsConfig.getUserAgent());
                HttpResponse response = httpClient.execute(method);
                if (response.getStatusLine().getStatusCode() < 300) {
                    InputStream responseStream = response.getEntity().getContent();
                    Bots robots = BotsParser.this.readRobotsTxt(matchingStrategy, winningStrategy,
                            responseStream);
                    if (robots != null) {
                        LOG.info(formatForLog("Received Robotx.txt for: %s", serverUrl.toExternalForm()));
                    }
                    return robots;
                }
            }
        } catch (IOException ex) {
            LOG.debug(formatForLog("Unable to access robots.txt for: %s", serverUrl.toExternalForm()));
            LOG.debug("", ex);
        }
    }
    return null;
}