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:com.sap.prd.mobile.ios.ota.lib.OtaPlistGeneratorTest.java

@Test
public void testGenerateURL() throws IOException {
    URL url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service),
            buildMap(KEY_REFERER, long_referer, KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier,
                    KEY_BUNDLE_VERSION, long_version, KEY_IPA_CLASSIFIER, ipaClassifier, KEY_OTA_CLASSIFIER,
                    otaClassifier));//  w ww  .  j  a  v  a 2  s  . c om
    assertEquals(10, StringUtils.countMatches(url.toExternalForm(), "/"));
    System.out.println("Length: " + url.toExternalForm().length() + " - " + url.toExternalForm());
    assertTrue(url.toExternalForm().startsWith(long_service));
    assertContains("/" + LibUtils.encode("Referer=" + long_referer) + "/", url.toExternalForm());
    assertContains("/" + LibUtils.encode("title=" + long_title) + "/", url.toExternalForm());
    assertContains("/" + LibUtils.encode("bundleIdentifier=" + long_identifier) + "/", url.toExternalForm());
    assertContains("/" + LibUtils.encode("bundleVersion=" + long_version), url.toExternalForm());
    assertContains("/" + LibUtils.encode("ipaClassifier=" + ipaClassifier), url.toExternalForm());
    assertContains("/" + LibUtils.encode("otaClassifier=" + otaClassifier), url.toExternalForm());

    url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service), buildMap(KEY_REFERER, long_referer,
            KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier, KEY_BUNDLE_VERSION, long_version));
    assertEquals(8, StringUtils.countMatches(url.toExternalForm(), "/"));

    url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service),
            buildMap(KEY_REFERER, long_referer, KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier,
                    KEY_BUNDLE_VERSION, long_version, KEY_OTA_CLASSIFIER, otaClassifier));
    assertEquals(9, StringUtils.countMatches(url.toExternalForm(), "/"));

}

From source file:com.zimbra.cs.util.SoapCLI.java

/**
 * Authenticates using the username and password from the local config.
 * @throws IOException//  w  ww . jav a2 s.  com
 * @throws com.zimbra.common.soap.SoapFaultException
 * @throws ServiceException
 */
protected LmcSession auth() throws SoapFaultException, IOException, ServiceException {
    URL url = new URL("https", mHost, mPort, AdminConstants.ADMIN_SERVICE_URI);
    mServerUrl = url.toExternalForm();
    SoapTransport trans = getTransport();
    mAuth = false;

    Element authReq = new Element.XMLElement(AdminConstants.AUTH_REQUEST);
    authReq.addAttribute(AdminConstants.E_NAME, mUser, Element.Disposition.CONTENT);
    authReq.addAttribute(AdminConstants.E_PASSWORD, mPassword, Element.Disposition.CONTENT);
    try {
        Element authResp = trans.invokeWithoutSession(authReq);
        String authToken = authResp.getAttribute(AdminConstants.E_AUTH_TOKEN);
        ZAuthToken zat = new ZAuthToken(null, authToken, null);
        trans.setAuthToken(authToken);
        mAuth = true;
        return new LmcSession(zat, null);
    } catch (UnknownHostException e) {
        // UnknownHostException's error message is not clear; rethrow with a more descriptive message
        throw new IOException("Unknown host: " + mHost);
    }
}

From source file:com.zimbra.cs.util.SoapCLI.java

/**
 * Authenticates using the provided ZAuthToken
 * @throws IOException// ww  w  .  j a v  a2  s. c o  m
 * @throws com.zimbra.common.soap.SoapFaultException
 * @throws ServiceException
 */
protected LmcSession auth(ZAuthToken zAuthToken) throws SoapFaultException, IOException, ServiceException {
    if (zAuthToken == null)
        return auth();

    URL url = new URL("https", mHost, mPort, AdminConstants.ADMIN_SERVICE_URI);
    mServerUrl = url.toExternalForm();
    SoapTransport trans = getTransport();
    mAuth = false;

    Element authReq = new Element.XMLElement(AdminConstants.AUTH_REQUEST);
    zAuthToken.encodeAuthReq(authReq, true);
    try {
        Element authResp = trans.invokeWithoutSession(authReq);
        ZAuthToken zat = new ZAuthToken(authResp.getElement(AdminConstants.E_AUTH_TOKEN), true);
        trans.setAuthToken(zat);
        mAuth = true;
        return new LmcSession(zat, null);
    } catch (UnknownHostException e) {
        // UnknownHostException's error message is not clear; rethrow with a more descriptive message
        throw new IOException("Unknown host: " + mHost);
    }
}

From source file:fr.gael.dhus.service.UploadService.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@Transactional(propagation = Propagation.REQUIRED)
public boolean addProduct(URL path, final User owner, final List<Collection> collections)
        throws ProductNotAddedException {
    File product = null;// w w w .  jav a  2  s.  com
    File newProduct = null;
    try {
        logger.info("Reading uploaded product : " + path.toExternalForm());

        product = new File(path.toURI());
        if (product.isFile() && UnZip.supported(product.getPath())) {
            try {
                UnZip.unCompress(product.getPath(), product.getParent());
            } catch (Exception e) {
                logger.error("Failure during decompression.", e);
                DataStoreNotReadableProduct dse = new DataStoreNotReadableProduct();
                dse.initCause(e);
                throw dse;
            }

            newProduct = new File(product.getParent());
            path = newProduct.toURI().toURL();
            product.delete();

            Scanner scanner = scannerFactory.getScanner(path.toExternalForm());
            scanner.setSupportedClasses(scannerFactory.getScannerSupport());
            scanner.getScanList().simulate(false);
            try {
                scanner.scan();
            } catch (InterruptedException e) {
                throw new DataStoreNotReadableProduct("Process stopped by the user");
            }

            if (scanner.getScanList().size() == 0) {
                actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, false);
                throw new DataStoreNotReadableProduct("No product recognized");
            }

            for (URLExt url : scanner.getScanList()) {
                dataStore.addProduct(url.getUrl(), owner, collections, null, scanner, null);
                actionRecordWritterDao.uploadEnd(url.getUrl(), owner.getUsername(), collections, true);
            }
            return true;
        }
        /* Case of one file product i.e. ENVISAT uploaded uncompressed */
        else if (product.isFile()) {
            dataStore.addProduct(path, owner, collections, null, null, null);
            actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, true);
            return true;
        } else {
            actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, false);
            throw new DataStoreNotReadableProduct("Uploaded product media not supported.");
        }
    } catch (DataStoreAlreadyExistException e) {
        // later
        actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, false);
        return false;
    } catch (DataStoreNotReadableProduct e) {
        if (product != null && product.exists()) {
            product.delete();
        }
        if (newProduct != null && newProduct.exists()) {
            deleteDir(newProduct);
        }
        actionRecordWritterDao.uploadFailed(path.toString(), owner.getUsername());
        throw new ProductNotAddedException();
    } catch (MalformedURLException e1) {
        logger.warn("There was a problem accessing \"" + path + "\"");
        actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, false);
        return false;
    } catch (URISyntaxException e1) {
        logger.warn("There was a problem accessing \"" + path + "\"");
        actionRecordWritterDao.uploadEnd(path, owner.getUsername(), collections, false);
        return false;
    }
}

From source file:ch.entwine.weblounge.kernel.security.SecurityFilter.java

/**
 * Registers a security filter for the given site.
 * /*from  w w  w  .ja v  a 2 s.c  om*/
 * @param site
 *          the site
 * @param bundle
 *          the site's bundle
 */
private void registerSecurity(Site site, Bundle bundle) {
    URL securityConfiguration = site.getSecurity();
    if (securityConfiguration != null) {
        // Test availability of the security configuration
        InputStream is = null;
        try {
            String configPath = securityConfiguration.toExternalForm();
            if (configPath.startsWith("file://${bundle.root}")) {
                String bundlePath = configPath.substring(21);
                securityConfiguration = bundle.getResource(bundlePath);
            } else if (configPath.startsWith("file://${site.root}")) {
                String bundlePath = UrlUtils.concat("/site", configPath.substring(19));
                securityConfiguration = bundle.getResource(bundlePath);
            }

            // Is the configuration available?
            if (securityConfiguration == null) {
                throw new IllegalStateException("The security configuration of site '" + site.getIdentifier()
                        + "' cannot be found at " + securityConfiguration);
            }

            // Start reading the configuration
            is = securityConfiguration.openStream();

            // Turn the stream into a Spring Security filter chain
            ConfigurableOsgiBundleApplicationContext springContext = null;
            springContext = new OsgiBundleXmlApplicationContext(
                    new String[] { securityConfiguration.toExternalForm() });
            springContext.setBundleContext(bundle.getBundleContext());
            springContext.refresh();

            // Register the security filter chain
            Filter siteSecurityFilter = (Filter) springContext.getBean("springSecurityFilterChain");
            logger.info("Registering custom security filter for site '{}'", site.getIdentifier());
            siteFilters.put(site, siteSecurityFilter);
        } catch (IOException e) {
            throw new IllegalStateException("Security configuration " + securityConfiguration + " of site '"
                    + site.getIdentifier() + "' cannot be read: " + e.getMessage(), e);
        } catch (Throwable t) {
            throw new IllegalStateException("Error registering security configuration " + securityConfiguration
                    + " of site '" + site.getIdentifier() + "': " + t.getMessage(), t);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:it.geosolutions.httpproxy.RequestTypeChecker.java

public void onRequest(HttpServletRequest request, HttpServletResponse response, URL url) throws IOException {
    Set<String> reqTypes = config.getReqtypeWhitelist();

    // //////////////////////////////////////
    // Check off the request type
    // provided vs. permitted request types
    // //////////////////////////////////////

    if (reqTypes != null && reqTypes.size() > 0) {
        Iterator<String> iterator = reqTypes.iterator();

        String urlExtForm = url.toExternalForm();
        /*if (urlExtForm.indexOf("?") != -1) {
        urlExtForm = urlExtForm.split("\\?")[1];
        }*//*from   w w w  .  jav  a 2s .co m*/

        boolean check = false;
        while (iterator.hasNext()) {
            String regex = iterator.next();

            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(urlExtForm);

            if (matcher.matches()) {
                check = true;
                break;
            }
        }

        if (!check)
            throw new HttpErrorException(403, "Request Type" + " is not among the ones allowed for this proxy");
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.UsersRolesLoginModuleTestCase.java

/**
 * testHashOnlyStorePassword// w  ww . j a va  2s . co m
 *
 * @throws Exception
 */
@OperateOnDeployment(DEP6a)
@Test
public void testHashOnlyStorePassword(@ArquillianResource URL url) throws Exception {
    final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
    //successful authentication and authorization
    assertEquals("Response body is not correct.", SimpleSecuredServlet.RESPONSE_BODY,
            Utils.makeCallWithBasicAuthn(servletUrl, ANIL, Utils.hashMD5(ANIL_PWD, Coding.BASE_64), 200));
    //successful authentication and unsuccessful authorization
    Utils.makeCallWithBasicAuthn(servletUrl, MARCUS, Utils.hashMD5(MARCUS_PWD, Coding.BASE_64), 403);
    //unsuccessful authentication
    Utils.makeCallWithBasicAuthn(servletUrl, ANIL, ANIL_PWD, 401);
    Utils.makeCallWithBasicAuthn(servletUrl, MARCUS, MARCUS_PWD, 401);
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private URL adjustUrl(URL rootUrl) {
    try {/*w ww . jav  a2 s.  c  o  m*/
        return new URL(rootUrl.toExternalForm().replaceAll("/*$", "/"));
    } catch (MalformedURLException ex) {
        return rootUrl;
    }
}

From source file:hudson.remoting.Engine.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
@Override/*  ww w . j  a v a2  s . c  o m*/
public void run() {
    try {
        boolean first = true;
        while (true) {
            if (first) {
                first = false;
            } else {
                if (noReconnect)
                    return; // exit
            }

            listener.status("Locating server among " + candidateUrls);
            Throwable firstError = null;
            String port = null;

            for (URL url : candidateUrls) {
                String s = url.toExternalForm();
                if (!s.endsWith("/"))
                    s += '/';
                URL salURL = new URL(s + "tcpSlaveAgentListener/");

                // find out the TCP port
                HttpURLConnection con = (HttpURLConnection) salURL.openConnection();
                if (con instanceof HttpURLConnection && credentials != null) {
                    String encoding = new String(Base64.encodeBase64(credentials.getBytes()));
                    con.setRequestProperty("Authorization", "Basic " + encoding);
                }
                try {
                    try {
                        con.setConnectTimeout(30000);
                        con.setReadTimeout(60000);
                        con.connect();
                    } catch (IOException x) {
                        if (firstError == null) {
                            firstError = new IOException(
                                    "Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x);
                        }
                        continue;
                    }
                    port = con.getHeaderField("X-Hudson-JNLP-Port");
                    if (con.getResponseCode() != 200) {
                        if (firstError == null)
                            firstError = new Exception(salURL + " is invalid: " + con.getResponseCode() + " "
                                    + con.getResponseMessage());
                        continue;
                    }
                    if (port == null) {
                        if (firstError == null)
                            firstError = new Exception(url + " is not Hudson");
                        continue;
                    }
                } finally {
                    con.disconnect();
                }

                // this URL works. From now on, only try this URL
                hudsonUrl = url;
                firstError = null;
                candidateUrls = Collections.singletonList(hudsonUrl);
                break;
            }

            if (firstError != null) {
                listener.error(firstError);
                return;
            }

            Socket s = connect(port);

            listener.status("Handshaking");

            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(s.getInputStream());

            dos.writeUTF("Protocol:JNLP2-connect");
            Properties props = new Properties();
            props.put("Secret-Key", secretKey);
            props.put("Node-Name", slaveName);
            if (cookie != null)
                props.put("Cookie", cookie);
            ByteArrayOutputStream o = new ByteArrayOutputStream();
            props.store(o, null);
            dos.writeUTF(o.toString("UTF-8"));

            String greeting = readLine(in);
            if (greeting.startsWith("Unknown protocol")) {
                LOGGER.info("The server didn't understand the v2 handshake. Falling back to v1 handshake");
                s.close();
                s = connect(port);
                in = new BufferedInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());

                dos.writeUTF("Protocol:JNLP-connect");
                dos.writeUTF(secretKey);
                dos.writeUTF(slaveName);

                greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network?
                if (!greeting.equals(GREETING_SUCCESS)) {
                    onConnectionRejected(greeting);
                    continue;
                }
            } else {
                if (greeting.equals(GREETING_SUCCESS)) {
                    Properties responses = readResponseHeaders(in);
                    cookie = responses.getProperty("Cookie");
                } else {
                    onConnectionRejected(greeting);
                    continue;
                }
            }

            final Socket socket = s;
            final Channel channel = new Channel("channel", executor, in,
                    new BufferedOutputStream(s.getOutputStream()));
            PingThread t = new PingThread(channel) {
                protected void onDead() {
                    try {
                        if (!channel.isInClosed()) {
                            LOGGER.info("Ping failed. Terminating the socket.");
                            socket.close();
                        }
                    } catch (IOException e) {
                        LOGGER.log(SEVERE, "Failed to terminate the socket", e);
                    }
                }
            };
            t.start();
            listener.status("Connected");
            channel.join();
            listener.status("Terminated");
            t.interrupt(); // make sure the ping thread is terminated
            listener.onDisconnect();

            if (noReconnect)
                return; // exit
            // try to connect back to the server every 10 secs.
            waitForServerToBack();
        }
    } catch (Throwable e) {
        listener.error(e);
    }
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a URL source
 * @param _url  a resource URL/*from ww w  .  j a  v  a2  s .  co m*/
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(URL _url) throws IOException, JDOMException {
    // Create an HttpClient.
    HttpClient client = new HttpClient();

    // Issue a GET HTTP method.
    HttpMethod method = new GetMethod(_url.toExternalForm());
    int status_code = client.executeMethod(method);

    if (status_code != 200) {
        RepInfo representation = new RepInfo(_url.toExternalForm());
        representation
                .setMessage(new ErrorMessage("Status code returned [" + String.valueOf(status_code) + "]."));
        representation.setWellFormed(RepInfo.FALSE);
        return getDocumentFromRepresentation(representation);
    }

    byte[] response = method.getResponseBody();
    return this.getDocument(new ByteArrayInputStream(response), _url.toExternalForm());
}