Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

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

Prototype

public String toASCIIString() 

Source Link

Document

Returns the content of this URI as a US-ASCII string.

Usage

From source file:Main.java

public static void main(String[] args) throws NullPointerException, URISyntaxException {
    URI uri = new URI("http://www.java2s.com");
    System.out.println("URI      : " + uri);
    System.out.println(uri.toASCIIString());
}

From source file:org.apache.metron.dataservices.Main.java

public static void main(String[] args) throws Exception {

    Options options = new Options();

    options.addOption("homeDir", true, "Home directory for the service");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    Properties configProps = new Properties();

    String homeDir = cmd.getOptionValue("homeDir");

    if (homeDir.endsWith("/")) {
        homeDir = homeDir.substring(0, homeDir.length() - 1);
    }/*  w  w w.  java 2  s .co m*/

    DOMConfigurator.configure(homeDir + "/log4j.xml");

    logger.warn("DataServices Server starting...");

    File configFile = new File(homeDir + "/config.properties");
    FileReader configFileReader = new FileReader(configFile);
    try {
        configProps.load(configFileReader);

        Option[] cmdOptions = cmd.getOptions();
        for (Option opt : cmdOptions) {
            String argName = opt.getOpt();
            String argValue = opt.getValue();

            configProps.put(argName, argValue);
        }

    } finally {
        if (configFileReader != null) {
            configFileReader.close();
        }
    }

    WebAppContext context = new WebAppContext();

    Injector injector = Guice.createInjector(new DefaultServletModule(configProps),
            new AlertsServerModule(configProps),
            new DefaultShiroWebModule(configProps, context.getServletContext()), new AbstractModule() {

                @Override
                protected void configure() {
                    binder().requireExplicitBindings();
                    bind(GuiceFilter.class);
                    bind(GuiceResteasyBootstrapServletContextListener.class);
                    bind(EnvironmentLoaderListener.class);

                }
            });

    injector.getAllBindings();
    injector.createChildInjector().getAllBindings();

    Server server = new Server(port);

    /***************************************************
     *************** enable SSL ************************
     ***************************************************/

    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);
    http_config.setRequestHeaderSize(8192);
    http_config.setResponseHeaderSize(8192);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);
    // httpConfig.addCustomizer(new ForwardedRequestCustomizer())
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    String sslKeystorePath = configProps.getProperty("sslKeystorePath", "/keystore");
    logger.debug("sslKeystorePath: " + sslKeystorePath);
    sslContextFactory.setKeyStorePath(homeDir + sslKeystorePath);

    String sslKeystorePassword = configProps.getProperty("sslKeystorePassword");
    sslContextFactory.setKeyStorePassword(sslKeystorePassword);

    String sslKeyManagerPassword = configProps.getProperty("sslKeyManagerPassword");
    if (sslKeyManagerPassword != null && !sslKeyManagerPassword.isEmpty()) {
        sslContextFactory.setKeyManagerPassword(sslKeyManagerPassword);
    }

    String sslTruststorePath = configProps.getProperty("sslTruststorePath");
    if (sslTruststorePath != null && !sslTruststorePath.isEmpty()) {
        sslContextFactory.setTrustStorePath(homeDir + sslTruststorePath);
    }

    String sslTruststorePassword = configProps.getProperty("sslTruststorePassword");
    if (sslTruststorePassword != null && !sslTruststorePassword.isEmpty()) {
        sslContextFactory.setTrustStorePassword(sslTruststorePassword);
    }

    sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");

    // SSL HTTP Configuration
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
    sslConnector.setPort(8443);
    server.addConnector(sslConnector);

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));

    /** For JSP support.  Used only for testing and debugging for now.  This came come out
     * once the real consumers for this service are in place
     */
    URL indexUri = Main.class.getResource(WEBROOT_INDEX);
    if (indexUri == null) {
        throw new FileNotFoundException("Unable to find resource " + WEBROOT_INDEX);
    }

    // Points to wherever /webroot/ (the resource) is
    URI baseUri = indexUri.toURI();

    // Establish Scratch directory for the servlet context (used by JSP compilation)
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    File scratchDir = new File(tempDir.toString(), "embedded-jetty-jsp");

    if (!scratchDir.exists()) {
        if (!scratchDir.mkdirs()) {
            throw new IOException("Unable to create scratch directory: " + scratchDir);
        }
    }

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    context.setAttribute("javax.servlet.context.tempdir", scratchDir);
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());

    //Ensure the jsp engine is initialized correctly
    JettyJasperInitializer sci = new JettyJasperInitializer();
    ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(context);
    ContainerInitializer initializer = new ContainerInitializer(sci, null);
    List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
    initializers.add(initializer);

    context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
    context.addBean(sciStarter, true);

    // Set Classloader of Context to be sane (needed for JSTL)
    // JSP requires a non-System classloader, this simply wraps the
    // embedded System classloader in a way that makes it suitable
    // for JSP to use
    // new URL( "file:///home/prhodes/.m2/repository/javax/servlet/jsp/javax.servlet.jsp-api/2.3.1/javax.servlet.jsp-api-2.3.1.jar" ) 
    ClassLoader jspClassLoader = new URLClassLoader(new URL[] {},
            Thread.currentThread().getContextClassLoader());
    context.setClassLoader(jspClassLoader);

    // Add JSP Servlet (must be named "jsp")
    ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class);
    holderJsp.setInitOrder(0);
    holderJsp.setInitParameter("logVerbosityLevel", "DEBUG");
    holderJsp.setInitParameter("fork", "false");
    holderJsp.setInitParameter("xpoweredBy", "false");
    holderJsp.setInitParameter("compilerTargetVM", "1.7");
    holderJsp.setInitParameter("compilerSourceVM", "1.7");
    holderJsp.setInitParameter("keepgenerated", "true");
    context.addServlet(holderJsp, "*.jsp");
    //context.addServlet(holderJsp,"*.jspf");
    //context.addServlet(holderJsp,"*.jspx");

    // Add Default Servlet (must be named "default")
    ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
    holderDefault.setInitParameter("resourceBase", baseUri.toASCIIString());
    holderDefault.setInitParameter("dirAllowed", "true");
    context.addServlet(holderDefault, "/");

    /** end "for JSP support */

    context.setResourceBase(baseUri.toASCIIString());

    context.setInitParameter("resteasy.guice.modules",
            "org.apache.metron.dataservices.modules.guice.RestEasyModule");
    context.setInitParameter("resteasy.servlet.mapping.prefix", "/rest");

    context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
    context.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    server.setHandler(context);
    server.start();

    AlertsProcessingServer alertsServer = injector.getInstance(AlertsProcessingServer.class);

    alertsServer.startProcessing();

    server.join();
}

From source file:org.opendatakit.aggregate.odktables.Util.java

public static String buildUri(String base, String... path) {
    String pathElts = StringUtils.join(path, "/");
    URI uri = URI.create(base + "/" + pathElts).normalize();
    return uri.toASCIIString();
}

From source file:net.erdfelt.android.sdkfido.util.PathUtil.java

public static String toRelativePath(File basedir, File destpath) {
    URI baseuri = basedir.toURI();
    URI otheruri = destpath.toURI();
    URI reluri = baseuri.relativize(otheruri);
    return FilenameUtils.separatorsToSystem(reluri.toASCIIString());
}

From source file:talend.ext.images.server.util.ImagePathUtil.java

/**
 * Encode an URL path according to RFC 2396
 * @param path Absolute uri path//from   w  w  w.  ja v a 2s.  co m
 * @return
 */
public static String encodeURL(String path) {
    try {
        // Don't use java.net.URLEncoder as it is meant for application/x-www-form-urlencoded content, such as the
        // query string. Use java.net.URI to encode URL image path
        URI uri = new URI("f", null, path, null); //$NON-NLS-1$
        return StringUtils.substringAfter(uri.toASCIIString(), "f:"); //$NON-NLS-1$
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:Main.java

public static String encodeDocumentUrl(String urlString) {
    try {//  w  ww. j a  v a 2  s .  c  om

        URL url = new URL(urlString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());

        return uri.toASCIIString();

    } catch (MalformedURLException e) {
        return null;
    } catch (URISyntaxException e) {
        return null;
    }

}

From source file:io.pivotal.strepsirrhini.chaosloris.web.ChaosController.java

private static Schedule getSchedule(URI uri, ScheduleRepository scheduleRepository) {
    Matcher matcher = SCHEDULE.matcher(uri.toASCIIString());
    if (matcher.find()) {
        return scheduleRepository.getOne(Long.valueOf(matcher.group(1)));
    } else {//from  www .  j av  a2  s.c  om
        throw new IllegalArgumentException();
    }
}

From source file:org.apache.bigtop.bigpetstore.qstream.Utils.java

public static HttpResponse get(String hostname, String resource, List<? extends NameValuePair> params)
        throws Exception {
    System.out.println("getting http " + hostname);
    //URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
    URI uri = URIUtils.createURI("http", hostname, -1, resource, URLEncodedUtils.format(params, "UTF-8"), null);
    System.out.println(uri.toASCIIString());
    HttpResponse respo = get(uri);/*w w w .  j  a  v  a 2 s  .  c  o m*/
    return respo;
}

From source file:org.apache.maven.wagon.shared.http.HtmlFileListParser.java

private static String cleanLink(URI baseURI, String link) {
    if (StringUtils.isEmpty(link)) {
        return "";
    }//from www . j  a  v a 2 s .com

    String ret = link;

    try {
        URI linkuri = new URI(ret);
        if (link.startsWith("/")) {
            linkuri = baseURI.resolve(linkuri);
        }
        URI relativeURI = baseURI.relativize(linkuri).normalize();
        ret = relativeURI.toASCIIString();
        if (ret.startsWith(baseURI.getPath())) {
            ret = ret.substring(baseURI.getPath().length());
        }

        ret = URLDecoder.decode(ret, "UTF-8");
    } catch (URISyntaxException e) {
    } catch (UnsupportedEncodingException e) {
    }

    return ret;
}

From source file:io.pivotal.strepsirrhini.chaosloris.web.ChaosController.java

private static Application getApplication(URI uri, ApplicationRepository applicationRepository) {
    Matcher matcher = APPLICATION.matcher(uri.toASCIIString());
    if (matcher.find()) {
        return applicationRepository.getOne(Long.valueOf(matcher.group(1)));
    } else {/*from   w  w w  .  j a  v a2  s  . com*/
        throw new IllegalArgumentException();
    }
}