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:io.lavagna.config.DataSourceConfig.java

/**
 * for supporting heroku style url:// w  w w. jav  a2  s . 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:com.tinyhydra.botd.BotdServerOperations.java

public static void CastVote(final Activity activity, final Handler handler, final String email,
        final String shopId, final String shopRef) {
    new Thread() {
        @Override//from   w  w w  .  j a v a  2  s. co  m
        public void run() {
            try {
                URI uri = new URI(activity.getResources().getString(R.string.server_url));
                HttpClient client = new DefaultHttpClient();
                HttpPut put = new HttpPut(uri);

                JSONObject voteObj = new JSONObject();

                // user's phone-account-email-address is used to prevent multiple votes
                // the server will validate. 'shopId' is a consistent id for a specific location
                // but can't be used to get more data. 'shopRef' is an id that changes based on
                // some criteria that google places has imposed, but will let us grab data later on
                // and various Ref codes with the same id will always resolve to the same location.
                voteObj.put(JSONvalues.email.toString(), email);
                voteObj.put(JSONvalues.shopId.toString(), shopId);
                voteObj.put(JSONvalues.shopRef.toString(), shopRef);
                put.setEntity(new StringEntity(voteObj.toString()));

                HttpResponse response = client.execute(put);
                InputStream is = response.getEntity().getContent();
                int ch;
                StringBuffer sb = new StringBuffer();
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }
                if (sb.toString().equals("0")) {
                    Utils.PostToastMessageToHandler(handler, "Vote cast!", Toast.LENGTH_SHORT);
                    // Set a local flag to prevent duplicate voting
                    SharedPreferences settings = activity.getSharedPreferences(Const.GenPrefs, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong(Const.LastVoteDate, Utils.GetDate());
                    editor.commit();
                } else {
                    // The user shouldn't see this. The above SharedPreferences code will be evaluated
                    // when the user hits the Vote button. If the user gets sneaky and deletes local data though,
                    // the server will catch the duplicate vote based on the user's email address and send back a '1'.
                    Utils.PostToastMessageToHandler(handler,
                            "Vote refused. You've probably already voted today.", Toast.LENGTH_LONG);
                }
                GetTopTen(activity, handler, true);
                // Catch blocks. Return a generic error if anything goes wrong.
                //TODO: implement some better/more appropriate error handling.
            } catch (URISyntaxException usex) {
                usex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (UnsupportedEncodingException ueex) {
                ueex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (ClientProtocolException cpex) {
                cpex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (IOException ioex) {
                ioex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (JSONException jex) {
                jex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            }
        }
    }.start();
}

From source file:edu.uci.ics.crawler4j.url.URLCanonicalizer.java

public static String getCanonicalURL(String href, String context) {

    try {/*w  w  w  . j a va2  s.c  o m*/
        URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));

        String host = canonicalURL.getHost().toLowerCase();
        if (StringUtils.isBlank(host)) {
            // This is an invalid Url.
            return null;
        }

        String path = canonicalURL.getPath();

        /*
         * Normalize: no empty segments (i.e., "//"), no segments equal to
         * ".", and no segments equal to ".." that are preceded by a segment
         * not equal to "..".
         */
        path = new URI(path).normalize().toString();

        /*
         * Convert '//' -> '/'
         */
        int idx = path.indexOf("//");
        while (idx >= 0) {
            path = path.replace("//", "/");
            idx = path.indexOf("//");
        }

        /*
         * Drop starting '/../'
         */
        while (path.startsWith("/../")) {
            path = path.substring(3);
        }

        /*
         * Trim
         */
        path = path.trim();

        final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
        final String queryString;

        if (params != null && params.size() > 0) {
            String canonicalParams = canonicalize(params);
            queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
        } else {
            queryString = "";
        }

        /*
         * Add starting slash if needed
         */
        if (path.length() == 0) {
            path = "/" + path;
        }

        /*
         * Drop default port: example.com:80 -> example.com
         */
        int port = canonicalURL.getPort();
        if (port == canonicalURL.getDefaultPort()) {
            port = -1;
        }

        String protocol = canonicalURL.getProtocol().toLowerCase();
        String pathAndQueryString = normalizePath(path) + queryString;

        URL result = new URL(protocol, host, port, pathAndQueryString);
        return result.toExternalForm();

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

From source file:org.mule.tools.rhinodo.impl.NodeModuleImplBuilder.java

private static NodeModuleImpl extractFromPackageJson(URI root) {
    if (root == null) {
        throw new IllegalArgumentException("Error validating rootDirectory");
    }//from ww  w.  j a va  2s  . c  o m

    URI packageJson;
    try {
        packageJson = new URI(root.toString() + "/" + "package.json");
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    boolean exists;
    if ("file".equals(packageJson.getScheme())) {
        exists = new File(packageJson).exists();
    } else {
        throw new IllegalStateException(
                String.format("Error: scheme [%s] not supported.", packageJson.getScheme()));
    }

    if (!exists) {
        throw new IllegalStateException(String.format("Error: package.json not found at [%s].", packageJson));
    }

    return NodeModuleImpl.create(root,
            NodeModuleImplBuilder.<String, String>getPackageJSONMap(new File(packageJson.getPath())));
}

From source file:com.subgraph.vega.ui.http.requestviewer.HttpViewLabelProvider.java

@Override
public String getColumnText(Object element, int columnIndex) {
    if (!(element instanceof IRequestLogRecord))
        return null;
    final IRequestLogRecord record = (IRequestLogRecord) element;
    URI uri;//from  w  w w  . j  a v a 2  s.c  om
    try {
        uri = new URI(record.getRequest().getRequestLine().getUri());

    } catch (URISyntaxException e) {
        return null;
    }
    switch (columnIndex) {
    case 0:
        return Long.toString(record.getRequestId());
    case 1:
        return record.getHttpHost().toURI();
    case 2:
        return record.getRequest().getRequestLine().getMethod();
    case 3:
        if (uri.getRawQuery() != null)
            return uri.getRawPath() + "?" + uri.getRawQuery();
        else
            return uri.getRawPath();
    case 4:
        return Integer.valueOf(record.getResponse().getStatusLine().getStatusCode()).toString();
    case 5:
        return getResponseLength(record.getResponse());
    case 6:
        return Long.toString(record.getRequestMilliseconds());
    }
    return null;
}

From source file:bova.rtmapi.RestClient.java

JSONResponse execute() throws ServerException, RtmApiException, IOException {
    // Execute HTTP Post Request
    HttpClient httpclient = new DefaultHttpClient();
    URI uri;//www.j a v a 2s  . com
    try {
        uri = new URI(this.request.getUrl());
        HttpPost httppost = new HttpPost(uri);
        HttpResponse response = httpclient.execute(httppost);
        // Get string from response
        InputStream is = response.getEntity().getContent();
        try {
            StringBuilder sb = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is)));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sb.append(line);
            }
            // get JSON Response from string and return it
            return new JSONResponse(sb.toString());
        } finally {
            is.close();
        }
    } catch (URISyntaxException e) {
        throw new RtmApiException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new RtmApiException(e.getMessage());
    }
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

public static File getFile(URL url) throws IOException {
    if (url == null) {
        return null;
    }//  w ww . j  ava 2  s.c  om
    if (PROTOCOL_FILE.equals(url.getProtocol()) || PROTOCOL_PLATFORM.equalsIgnoreCase(url.getProtocol())) {
        File file;
        try {
            file = new File(new URI(url.toExternalForm()));
        } catch (Exception e) {
            file = new File(url.getFile());
        }
        if (!file.exists()) {
            return null;
        }
        return file;
    }
    File file = getCachedFile(url);
    long urlLastModified = getLastModified(url);
    if (file.exists()) {
        long lastModified = file.lastModified();
        if (urlLastModified > lastModified) {
            file = download(file, url);
            if (file != null) {
                file.setLastModified(urlLastModified);
            }
        }
    } else {
        file = download(file, url);
        if (file != null && urlLastModified > -1) {
            file.setLastModified(urlLastModified);
        }
    }
    return file;
}

From source file:com.lukasz.chat.pusher.PusherConnection.java

public void connect() {
    try {// w w w  .j  a va  2 s . co m
        URI url = new URI(mPusher.getUrl());
        Log.d(LOG_TAG, "Connecting to " + url.toString());

        mWebSocket = new WebSocketConnection(url);
        mWebSocket.setEventHandler(new WebSocketEventHandler() {
            public void onOpen() {
                Log.d(LOG_TAG, "Successfully opened Websocket");
            }

            public void onMessage(WebSocketMessage message) {

                try {
                    JSONObject parsed = new JSONObject(message.getText());
                    String eventName = parsed.getString("event");
                    String channelName = parsed.optString("channel", null);
                    String eventData = parsed.getString("data");

                    if (eventName.equals(Pusher.PUSHER_EVENT_CONNECTION_ESTABLISHED)) {
                        JSONObject parsedEventData = new JSONObject(eventData);
                        String socketId = parsedEventData.getString("socket_id");
                        mPusher.onConnected(socketId);
                    } else {
                        mPusher.dispatchEvents(eventName, eventData, channelName);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onClose() {
                Log.d(LOG_TAG, "Successfully closed Websocket");
            }
        });

        mWebSocket.connect();

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

From source file:org.httplog4j.client.HTTPLog4jAppender.java

public HTTPLog4jAppender(String remoteURI) {
    try {//  w  w  w. j a va 2 s.  c o m
        this.remoteURI = new URI(remoteURI);
    } catch (URISyntaxException uriSyntaxException) {
        errorHandler.error("could not configure HTTP Log4j Appender, malformed URL provided",
                uriSyntaxException, ErrorCode.ADDRESS_PARSE_FAILURE);
        LogLog.error("malformed URL provided on initialization", uriSyntaxException);
    }
    httpClient = new DefaultHttpClient();
}

From source file:com.emorym.android_pusher.PusherConnection.java

public void connect() {
    try {//from   w w w  . ja v  a 2s  .co m
        URI url = new URI(mPusher.getUrl());
        Log.d(LOG_TAG, "Connecting to " + url.toString());

        mWebSocket = new WebSocketConnection(url);
        mWebSocket.setEventHandler(new WebSocketEventHandler() {
            public void onOpen() {
                Log.d(LOG_TAG, "Successfully opened Websocket");
            }

            public void onMessage(WebSocketMessage message) {
                Log.d(LOG_TAG, "Received from Websocket " + message.getText());

                try {
                    JSONObject parsed = new JSONObject(message.getText());
                    String eventName = parsed.getString("event");
                    String channelName = parsed.optString("channel", null);
                    String eventData = parsed.getString("data");

                    if (eventName.equals(Pusher.PUSHER_EVENT_CONNECTION_ESTABLISHED)) {
                        JSONObject parsedEventData = new JSONObject(eventData);
                        String socketId = parsedEventData.getString("socket_id");
                        mPusher.onConnected(socketId);
                    } else {
                        mPusher.dispatchEvents(eventName, eventData, channelName);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onClose() {
                Log.d(LOG_TAG, "Successfully closed Websocket");
            }
        });
        mWebSocket.connect();

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