Example usage for java.net URI getUserInfo

List of usage examples for java.net URI getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Returns the decoded user-information component of this URI.

Usage

From source file:Main.java

public static void main(String[] args) {
    URI uri = URI.create("http://java2s.com/query.php?name=value");
    System.out.println(uri.getUserInfo());
}

From source file:sitekit.tutorial.TutorialSiteMain.java

/**
 * Main method for running DefaultSiteUI.
 *
 * @param args the commandline arguments
 * @throws Exception if exception occurs in jetty startup.
 *//*from w  w w . ja  va 2s .c o  m*/
public static void main(final String[] args) throws Exception {
    // Configure logging.
    DOMConfigurator.configure("./log4j.xml");

    // Configuration loading with HEROKU support.
    final String environmentDatabaseString = System.getenv("DATABASE_URL");
    if (StringUtils.isNotEmpty(environmentDatabaseString)) {
        final URI dbUri = new URI(environmentDatabaseString);

        final String dbUser = dbUri.getUserInfo().split(":")[0];
        final String dbPassword = dbUri.getUserInfo().split(":")[1];
        final String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.url", dbUrl);
        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.user", dbUser);
        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.password", dbPassword);
        LOGGER.info("Environment variable defined database URL: " + environmentDatabaseString);
    }

    final String environmentPortString = System.getenv().get("PORT");
    final int port;
    if (StringUtils.isNotEmpty(environmentPortString)) {
        port = Integer.parseInt(environmentPortString);
        LOGGER.info("Environment variable defined HTTP port: " + port);
    } else {
        port = Integer.parseInt(PropertiesUtil.getProperty("site", "http-port"));
        LOGGER.info("Configuration defined HTTP port: " + port);
    }

    // Configure Java Persistence API.
    DefaultSiteUI.setEntityManagerFactory(
            PersistenceUtil.getEntityManagerFactory(PERSISTENCE_UNIT, PROPERTIES_CATEGORY));
    // Configure security provider.
    DefaultSiteUI.setSecurityProvider(new SecurityProviderSessionImpl("administrator", "user"));
    // Configure content provider.
    DefaultSiteUI.setContentProvider(new DefaultContentProvider());
    // Configure localization provider.
    DefaultSiteUI.setLocalizationProvider(
            new LocalizationProviderBundleImpl(LOCALIZATION_BUNDLE, "custom-localization"));

    // Get default site descriptor.
    final SiteDescriptor siteDescriptor = DefaultSiteUI.getContentProvider().getSiteDescriptor();
    // Describe custom view.
    final ViewDescriptor customDescriptor = new ViewDescriptor("custom", "Custom Title", DefaultView.class);
    customDescriptor.setViewletClass("content", HelloWorldViewlet.class);
    siteDescriptor.getViewDescriptors().add(customDescriptor);
    // Add custom view to navigation.
    final NavigationVersion navigationVersion = siteDescriptor.getNavigation().getProductionVersion();
    navigationVersion.setDefaultPageName("custom");
    navigationVersion.addRootPage(0, "custom");

    // Configure Embedded jetty.
    // -------------------------
    final boolean developmentEnvironment = TutorialSiteMain.class.getClassLoader().getResource("webapp/")
            .toExternalForm().startsWith("file:");

    final String webappUrl;
    if (developmentEnvironment) {
        webappUrl = DefaultSiteUI.class.getClassLoader().getResource("webapp/").toExternalForm()
                .replace("target/classes", "src/main/resources");
    } else {
        webappUrl = DefaultSiteUI.class.getClassLoader().getResource("webapp/").toExternalForm();
    }

    final Server server = new Server(port);

    final WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setDescriptor(webappUrl + "/WEB-INF/web.xml");
    context.setResourceBase(webappUrl);
    context.setParentLoaderPriority(true);
    if (developmentEnvironment) {
        context.setInitParameter("cacheControl", "no-cache");
        context.setInitParameter("useFileMappedBuffer", "false");
        context.setInitParameter("maxCachedFiles", "0");
    }
    server.setHandler(context);
    try {
        server.start();
    } catch (final BindException e) {
        LOGGER.warn("Jetty port (" + port + ") binding failed: " + e.getMessage());
        return;
    }
    server.join();
}

From source file:org.vaadin.addons.sitekit.example.ExampleSiteMain.java

/**
 * Main method for running DefaultSiteUI.
 * @param args the commandline arguments
 * @throws Exception if exception occurs in jetty startup.
 *///w  w w .  j a va2 s.  c  o  m
public static void main(final String[] args) throws Exception {
    // Configure logging.
    // ------------------
    DOMConfigurator.configure("./log4j.xml");

    // Configuration loading with HEROKU support.
    final String environmentDatabaseString = System.getenv("DATABASE_URL");
    if (StringUtils.isNotEmpty(environmentDatabaseString)) {
        final URI dbUri = new URI(environmentDatabaseString);

        final String dbUser = dbUri.getUserInfo().split(":")[0];
        final String dbPassword = dbUri.getUserInfo().split(":")[1];
        final String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();

        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.url", dbUrl);
        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.user", dbUser);
        PropertiesUtil.setProperty(PROPERTIES_CATEGORY, "javax.persistence.jdbc.password", dbPassword);
        LOGGER.info("Environment variable defined database URL: " + environmentDatabaseString);
    }

    final String environmentPortString = System.getenv().get("PORT");
    final int port;
    if (StringUtils.isNotEmpty(environmentPortString)) {
        port = Integer.parseInt(environmentPortString);
        LOGGER.info("Environment variable defined HTTP port: " + port);
    } else {
        port = Integer.parseInt(PropertiesUtil.getProperty("site", "http-port"));
        LOGGER.info("Configuration defined HTTP port: " + port);
    }

    // Configure Java Persistence API.
    // -------------------------------
    DefaultSiteUI.setEntityManagerFactory(
            PersistenceUtil.getEntityManagerFactory(PERSISTENCE_UNIT, PROPERTIES_CATEGORY));

    // Configure providers.
    // --------------------
    // Configure security provider.
    DefaultSiteUI.setSecurityProvider(new SecurityProviderSessionImpl("administrator", "user"));
    // Configure content provider.
    DefaultSiteUI.setContentProvider(new DefaultContentProvider());
    // Configure localization provider.
    DefaultSiteUI.setLocalizationProvider(new LocalizationProviderBundleImpl(LOCALIZATION_BUNDLE));

    // Initialize modules
    SiteModuleManager.initializeModule(AuditModule.class);
    SiteModuleManager.initializeModule(ContentModule.class);

    // Add feedback view and set it default.
    // -----------------------------------
    final SiteDescriptor siteDescriptor = DefaultSiteUI.getContentProvider().getSiteDescriptor();

    // Customize navigation tree.
    final NavigationVersion navigationVersion = siteDescriptor.getNavigation().getProductionVersion();
    navigationVersion.setDefaultPageName("feedback");
    navigationVersion.addRootPage(0, "feedback");

    // Describe feedback view.
    final ViewDescriptor feedback = new ViewDescriptor("feedback", "Feedback", DefaultView.class);
    feedback.setViewletClass("content", FeedbackViewlet.class);
    siteDescriptor.getViewDescriptors().add(feedback);

    // Describe feedback view fields.
    final FieldSetDescriptor feedbackFieldSetDescriptor = new FieldSetDescriptor(Feedback.class);
    feedbackFieldSetDescriptor.setVisibleFieldIds(new String[] { "title", "description", "emailAddress",
            "firstName", "lastName", "organizationName", "organizationSize" });
    FieldSetDescriptorRegister.registerFieldSetDescriptor("feedback", feedbackFieldSetDescriptor);

    // Configure Embedded jetty.
    // -------------------------
    final boolean developmentEnvironment = ExampleSiteMain.class.getClassLoader().getResource("webapp/")
            .toExternalForm().startsWith("file:");

    final String webappUrl;
    if (developmentEnvironment) {
        webappUrl = DefaultSiteUI.class.getClassLoader().getResource("webapp/").toExternalForm()
                .replace("target/classes", "src/main/resources");
    } else {
        webappUrl = DefaultSiteUI.class.getClassLoader().getResource("webapp/").toExternalForm();
    }

    final Server server = new Server(port);

    final WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setDescriptor(webappUrl + "/WEB-INF/web.xml");
    context.setResourceBase(webappUrl);
    context.setParentLoaderPriority(true);
    if (developmentEnvironment) {
        context.setInitParameter("cacheControl", "no-cache");
        context.setInitParameter("useFileMappedBuffer", "false");
        context.setInitParameter("maxCachedFiles", "0");
    }
    server.setHandler(context);
    try {
        server.start();
    } catch (final BindException e) {
        LOGGER.warn("Jetty port (" + port + ") binding failed: " + e.getMessage());
        return;
    }
    server.join();
}

From source file:MainClass.java

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

    URI u = new URI("http://www.java2s.com");
    System.out.println("The URI is " + u);
    if (u.isOpaque()) {
        System.out.println("This is an opaque URI.");
        System.out.println("The scheme is " + u.getScheme());
        System.out.println("The scheme specific part is " + u.getSchemeSpecificPart());
        System.out.println("The fragment ID is " + u.getFragment());
    } else {//from  ww  w .  j a v  a  2s  .c  om
        System.out.println("This is a hierarchical URI.");
        System.out.println("The scheme is " + u.getScheme());

        u = u.parseServerAuthority();
        System.out.println("The host is " + u.getUserInfo());
        System.out.println("The user info is " + u.getUserInfo());
        System.out.println("The port is " + u.getPort());
        System.out.println("The path is " + u.getPath());
        System.out.println("The query string is " + u.getQuery());
        System.out.println("The fragment ID is " + u.getFragment());
    }

}

From source file:io.gravitee.gateway.standalone.DynamicRoutingGatewayTest.java

private static URI create(URI uri, int port) {
    try {/*from w  ww .ja  v a2s. com*/
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());
    } catch (URISyntaxException e) {
        return uri;
    }
}

From source file:io.lavagna.config.DataSourceConfig.java

/**
 * for supporting heroku style url:/*from w w w . j  a va2s  .  c  o m*/
 *
 * <pre>
 * [database type]://[username]:[password]@[host]:[port]/[database name]
 * </pre>
 *
 * @param dataSource
 * @param env
 * @throws URISyntaxException
 */
private static void urlWithCredentials(HikariDataSource dataSource, Environment env) throws URISyntaxException {
    URI dbUri = new URI(env.getRequiredProperty("datasource.url"));
    dataSource.setUsername(dbUri.getUserInfo().split(":")[0]);
    dataSource.setPassword(dbUri.getUserInfo().split(":")[1]);
    dataSource.setJdbcUrl(
            String.format("%s://%s:%s%s", scheme(dbUri), dbUri.getHost(), dbUri.getPort(), dbUri.getPath()));
}

From source file:Main.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *///ww  w.java 2s . c o  m
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userpass + "'");
    }

    String username = userpass[0];
    String password = userpass[1]; // TODO enable reading this secretly

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:org.mule.module.pubsubhubbub.VerificationType.java

private static URI buildVerificationUrl(final AbstractVerifiableRequest request,
        final String verificationChallenge) throws URISyntaxException {
    final StringBuilder queryBuilder = new StringBuilder(
            StringUtils.defaultString(request.getCallbackUrl().getQuery()));

    Utils.appendToQuery(Constants.HUB_MODE_PARAM, request.getMode(), queryBuilder);

    for (final URI topicUrl : request.getTopicUrls()) {
        Utils.appendToQuery(Constants.HUB_TOPIC_PARAM, topicUrl.toString(), queryBuilder);
    }/*from ww w . ja  va  2s .  com*/

    Utils.appendToQuery(Constants.HUB_CHALLENGE_PARAM, verificationChallenge, queryBuilder);
    Utils.appendToQuery(Constants.HUB_LEASE_SECONDS_PARAM, Long.toString(request.getLeaseSeconds()),
            queryBuilder);

    if (StringUtils.isNotBlank(request.getVerificationToken())) {
        Utils.appendToQuery(Constants.HUB_VERIFY_TOKEN_PARAM, request.getVerificationToken(), queryBuilder);
    }

    final URI callbackUrl = request.getCallbackUrl();
    return new URI(callbackUrl.getScheme(), callbackUrl.getUserInfo(), callbackUrl.getHost(),
            callbackUrl.getPort(), callbackUrl.getPath(), queryBuilder.toString(), null);
}

From source file:org.apache.commons.net.examples.mail.IMAPUtils.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *///from www  . j  a v a  2  s  .com
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userInfo + "'");
    }

    String username = userpass[0];
    String password = userpass[1];
    // prompt for the password if necessary
    password = Utils.getPassword(username, password);

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:URIUtil.java

/**
 * Get the parent URI of the supplied URI
 * @param uri The input URI for which the parent URI is being requrested.
 * @return The parent URI.  Returns a URI instance equivalent to "../" if
 * the supplied URI path has no parent.//from ww  w.jav  a2  s . co  m
 * @throws URISyntaxException Failed to reconstruct the parent URI.
 */
public static URI getParent(URI uri) throws URISyntaxException {

    String parentPath = new File(uri.getPath()).getParent();

    if (parentPath == null) {
        return new URI("../");
    }

    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
            parentPath.replace('\\', '/'), uri.getQuery(), uri.getFragment());
}