Example usage for java.net URI URI

List of usage examples for java.net URI URI

Introduction

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

Prototype

public URI(String str) throws URISyntaxException 

Source Link

Document

Constructs a URI by parsing the given string.

Usage

From source file:at.peppol.smp.client.console.SMPClient.java

public static void main(final String[] args) throws Exception {
    if (false) {/*from  w  ww  .ja v  a2s .c o  m*/
        // Enable this section in development mode, if you want to trust all HTTPS
        // certificates
        final SSLContext aSSLContext = SSLContext.getInstance("SSL");
        aSSLContext.init(null, new TrustManager[] { new DoNothingTrustManager() },
                VerySecureRandom.getInstance());
        HttpsURLConnection.setDefaultSSLSocketFactory(aSSLContext.getSocketFactory());
    }

    final SMPClientOptions aOptions = new SMPClientOptions();
    final CommandLine cmd = new PosixParser().parse(aOptions, args);

    ECommand eAction = null;
    boolean bGoodCmd = true;
    String cert = null;

    if (!cmd.hasOption("h")) {
        s_aLogger.error("No Host specified use -h to specify Host");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("u")) {
        s_aLogger.error("No Username specified use -u to specify username");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("p")) {
        s_aLogger.error("No Password specified use -p to specify password");
        bGoodCmd = false;
    }

    if (!cmd.hasOption("c")) {
        s_aLogger.error("No Action specified please use -c parameter to specify command("
                + ECommand.getAllAsString() + ")");
        bGoodCmd = false;
    } else {
        final String sCommand = cmd.getOptionValue("c");
        eAction = ECommand.getFromNameOrNull(sCommand);
        if (eAction == null) {
            s_aLogger.error("Illegal Action specified:" + sCommand + " allowed commands("
                    + ECommand.getAllAsString() + ")");
            bGoodCmd = false;
        } else
            switch (eAction) {
            case ADDGROUP:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                break;
            case DELGROUP:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                break;
            case ADD:
                if (!cmd.hasOption("a")) {
                    s_aLogger.error("No Accesspoint URL defined use -a to Specifify AP-URL");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("d")) {
                    s_aLogger.error("No DocumentType ID specified use -d to specify Document Type ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("r")) {
                    s_aLogger.error("No Process ID specified use -r to specify Process ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("e")) {
                    s_aLogger.error("No Certificate PEM file specified use -e to specify Certificate PEM file");
                    bGoodCmd = false;
                } else {
                    cert = SimpleFileIO.readFileAsString(new File(cmd.getOptionValue('e')),
                            CCharset.CHARSET_ISO_8859_1);
                }
                break;
            case DEL:
                if (!cmd.hasOption("b")) {
                    s_aLogger.error(
                            "No Business/Participant ID specified use -b to specify Business/Participant ID");
                    bGoodCmd = false;
                }
                if (!cmd.hasOption("d")) {
                    s_aLogger.error("No Document Type ID specified use -d to specify Document Type ID");
                    bGoodCmd = false;
                }
            }
    }

    if (!bGoodCmd) {
        final NonBlockingStringWriter aSW = new NonBlockingStringWriter();
        new HelpFormatter().printHelp(new PrintWriter(aSW), HelpFormatter.DEFAULT_WIDTH,
                CGStringHelper.getClassLocalName(SMPClient.class), null, aOptions,
                HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null);
        s_aLogger.info(aSW.getAsString());
        System.exit(-3);
    }

    final SMPClient client = new SMPClient(new URI(cmd.getOptionValue('h')), cmd.getOptionValue('u'),
            cmd.getOptionValue('p'), cmd.getOptionValue('b'), cmd.getOptionValue('d'), cmd.getOptionValue('r'),
            cmd.getOptionValue('a'), cert);

    switch (eAction) {
    case ADDGROUP:
        client._createServiceGroup();
        break;
    case DELGROUP:
        client._deleteServiceGroup();
        break;
    case ADD:
        client._addDocument();
        break;
    case DEL:
        client._deleteDocument();
        break;
    case LIST:
        client._listDocuments();
        break;
    default:
        throw new IllegalStateException();
    }
}

From source file:ezbake.azkaban.manager.ScheduleManager.java

public static void main(String[] args) throws IOException, InterruptedException, TException {
    final OptionsBean bean = new OptionsBean();
    final CmdLineParser parser = new CmdLineParser(bean);

    try {/*  w w  w.j a  v  a  2s. c  o  m*/
        parser.parseArgument(args);

        String time;
        if (bean.scheduleTime == null) {
            // Need to add 2 minutes because Azkaban won't actually schedule it if it's scheduled to run at the
            // current time or in the past.  If we only added one minute there's a race condition for the code
            // submitting before the clock rolls over to the next minute.
            final LocalTime now = LocalTime.now().plusMinutes(2);
            time = now.getHourOfDay() + "," + now.getMinuteOfHour() + ","
                    + ((now.getHourOfDay() > 12) ? "pm" : "am") + ","
                    + now.getChronology().getZone().toString();

            System.out.println("time option not provided.  Using: " + time);
        } else {
            time = bean.scheduleTime;
        }

        final ScheduleManager azkabanScheduler = new ScheduleManager(new URI(bean.endPoint), bean.username,
                bean.password);
        azkabanScheduler.scheduleDate = bean.scheduleDate;
        azkabanScheduler.scheduleTime = time;

        if (bean.period != null) {
            azkabanScheduler.setPeriod(bean.period);
        }

        final SchedulerResult result = azkabanScheduler.scheduleFlow(bean.name, bean.flow, bean.projectId);

        if (result.hasError()) {
            System.err.println(result.getError());
        } else {
            System.out.println(
                    "Scheduled flow <" + bean.flow + "> :" + result.getStatus() + " | " + result.getMessage());
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
    }
}

From source file:com.blackducksoftware.integration.hub.util.HubUrlParser.java

public static String getBaseUrl(final String url) throws URISyntaxException {
    final URI uri = new URI(url);
    final String derivedUrlPrefix = StringUtils.join(uri.getScheme(), "://", uri.getAuthority(), "/");
    return derivedUrlPrefix;
}

From source file:com.almende.arum.RESTApplication.java

/**
 * Inits the./*from  w w w. j  ava2 s .  co m*/
 */
public static void init() {
    Servlet servlet = new org.apache.wink.server.internal.servlet.RestServlet();
    ObjectNode params = JOM.createObjectNode();
    ArrayNode initParams = JOM.createArrayNode();
    ObjectNode param = JOM.createObjectNode();
    param.put("key", "javax.ws.rs.Application");
    param.put("value", RESTApplication.class.getName());
    initParams.add(param);
    params.set("initParams", initParams);

    JettyLauncher launcher = new JettyLauncher();
    try {

        launcher.add(servlet, new URI("/rs/"), params);
        launcher.addFilter("com.thetransactioncompany.cors.CORSFilter", "/*");

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:ddf.catalog.content.data.impl.ContentItemValidator.java

public static void validate(ContentItem item) throws IllegalArgumentException {
    if (StringUtils.isNotBlank(item.getQualifier())) {
        validateInput(item.getQualifier(), QUALIFIER_PATTERN);
    }//from   w w w. jav a 2  s .  c  o  m

    if (StringUtils.isNotBlank(item.getUri())) {
        try {
            new URI(item.getUri());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Unable to create content URI.", e);
        }
    } else {
        throw new IllegalArgumentException("Cannot have an empty content URI.");
    }

}

From source file:Main.java

/**
 * Extract the UUID part from a MusicBrainz identifier.
 * //from  ww w  . j av a2 s  .co m
 * This function takes a MusicBrainz ID (an absolute URI) as the input
 * and returns the UUID part of the URI, thus turning it into a relative
 * URI. If <code>uriStr</code> is null or a relative URI, then it is
 * returned unchanged.
 * 
 * The <code>resType</code> parameter can be used for error checking.
 * Set it to 'artist', 'release', or 'track' to make sure 
 * <code>uriStr</code> is a syntactically valid MusicBrainz identifier
 * of the given resource type. If it isn't, an 
 * <code>IllegalArgumentException</code> exception is raised. This error
 * checking only works if <code>uriStr</code> is an absolute URI, of course.
 * 
 * Example:
 * >>>  MBUtils.extractUuid('http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5', 'artist')
 * 'c0b2500e-0cef-4130-869d-732b23ed9df5'
 * 
 * @param uriStr A string containing a MusicBrainz ID (an URI), or null
 * @param resType A string containing a resource type
 * @return A String containing a relative URI or null
 * @throws URISyntaxException 
 */
public static String extractUuid(String uriStr, String resType) {
    if (uriStr == null) {
        return null;
    }

    URI uri;
    try {
        uri = new URI(uriStr);
    } catch (URISyntaxException e) {
        return uriStr; // not really a valid URI, probably the UUID
    }
    if (uri.getScheme() == null) {
        return uriStr; // not really a valid URI, probably the UUID
    }

    if (!"http".equals(uri.getScheme()) || !"musicbrainz.org".equals(uri.getHost())) {
        throw new IllegalArgumentException(uri.toString() + " is no MB ID");
    }

    String regex = "^/(label|artist|release-group|release|recording|work|collection)/([^/]*)$";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(uri.getPath());
    if (m.matches()) {
        if (resType == null) {
            return m.group(2);
        } else {
            if (resType.equals(m.group(1))) {
                return m.group(2);
            } else {
                throw new IllegalArgumentException("expected '" + resType + "' Id");
            }
        }
    } else {
        throw new IllegalArgumentException("'" + uriStr + " is no valid MB id");
    }
}

From source file:org.thoughtcrime.securesms.mms.MmsDownloadHelper.java

private static byte[] makeRequest(MmsConnectionParameters connectionParameters, String url)
        throws ClientProtocolException, IOException {
    try {// w ww . j av a  2  s. c  o m
        HttpClient client = constructHttpClient(connectionParameters);
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpRequest request = new HttpGet(url);

        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsDownlader", use);
        throw new IOException("Bad URI syntax");
    }
}

From source file:com.zimbra.common.httpclient.HttpProxyConfig.java

public static ProxyHostConfiguration getProxyConfig(HostConfiguration hc, String uriStr) {
    if (!LC.client_use_system_proxy.booleanValue())
        return null;

    URI uri = null;/*from w w w  . j ava 2s. co  m*/
    try {
        uri = new URI(uriStr);
    } catch (URISyntaxException x) {
        ZimbraLog.net.info(uriStr, x);
        return null;
    }

    //no need to filter out localhost as the DefaultProxySelector will do that.

    List<Proxy> proxies = ProxySelectors.defaultProxySelector().select(uri);
    for (Proxy proxy : proxies) {
        switch (proxy.type()) {
        case DIRECT:
            return null;
        case HTTP:
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            if (ZimbraLog.net.isDebugEnabled()) {
                ZimbraLog.net.debug("URI %s to use HTTP proxy %s", safePrint(uri), addr.toString());
            }
            ProxyHostConfiguration nhc = new ProxyHostConfiguration(hc);
            nhc.setProxy(addr.getHostName(), addr.getPort());
            if (proxy instanceof AuthProxy) {
                nhc.setUsername(((AuthProxy) proxy).getUsername());
                nhc.setPassword(((AuthProxy) proxy).getPassword());
            }
            return nhc;
        case SOCKS: //socks proxy can be handled at socket factory level
        default:
            continue;
        }
    }
    return null;
}

From source file:Main.java

/**
 * Create URL using base URI.//from ww w  .  j a  v a 2 s  . c om
 * 
 * @param url a URL string.
 * @param baseURI a base url string to assist in creating a URL.
 * @return newly created URL.
 * @throws MalformedURLException if a malformed URL has occurred.
 */
public static URL createURL(String url, String baseURI) throws MalformedURLException {
    URL returnURL = null;
    URI uri = null;
    try {
        returnURL = new URL(url);
        uri = new URI(url);
        uri = uri.normalize();
        returnURL = new URL(uri.toString());
    }

    catch (Exception mue) {
        int i = baseURI.lastIndexOf('/');
        int j = baseURI.lastIndexOf('\\');
        if (j > i)
            i = j;
        try {
            uri = new URI(baseURI.substring(0, i + 1) + url);
            uri = uri.normalize();
            returnURL = uri.toURL();
        } catch (Exception e) {
            return new URL(baseURI.substring(0, i + 1) + url);
        }
    }
    return returnURL;
}

From source file:org.fdroid.enigtext.mms.MmsDownloadHelper.java

private static byte[] makeRequest(Context context, MmsConnectionParameters connectionParameters, String url)
        throws IOException {
    AndroidHttpClient client = null;//from   ww w . j av a2 s . c o  m

    try {
        client = constructHttpClient(context, connectionParameters);
        URI targetUrl = new URI(url.trim());
        HttpHost target = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpGet request = new HttpGet(url.trim());

        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsDownloadHelper", use);
        throw new IOException("Couldn't parse URI");
    } finally {
        if (client != null)
            client.close();
    }
}