Example usage for org.apache.http.client.utils URIUtils createURI

List of usage examples for org.apache.http.client.utils URIUtils createURI

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIUtils createURI.

Prototype

@Deprecated
public static URI createURI(final String scheme, final String host, final int port, final String path,
        final String query, final String fragment) throws URISyntaxException 

Source Link

Document

Constructs a URI using all the parameters.

Usage

From source file:com.healthcit.cacure.dao.CouchDBDao.java

private String getCouchDbRevisionNumber(String databaseName, String designDocName)
        throws IOException, URISyntaxException {
    // Prepare a request object
    URI uri = URIUtils.createURI("http", host, port,
            "/" + databaseName + "/" + DESIGN_DOC_PREFIX + "/" + designDocName, null, null);
    HttpGet httpGet = new HttpGet(uri);

    // response is a JSON object with one array in it
    String response = doHttp(httpGet);

    JSONObject doc = JSONObject.fromObject(response);

    return (doc.containsKey("_rev") ? doc.getString("_rev") : null);
}

From source file:com.healthcit.cacure.dao.CouchDBDao.java

public String writeToDb(JSONObject jsonDoc) throws IOException, URISyntaxException {
    String jsonStr = jsonDoc.toString();
    URI uri = URIUtils.createURI("http", host, port, "/" + getDbName() + "/" + getDocId(), null, null);

    // Prepare a request object
    HttpPut httpPut = new HttpPut(uri);
    httpPut.setHeader("Content-Type", "application/json");
    StringEntity body = new StringEntity(jsonStr);
    httpPut.setEntity(body);/*  w w w .  j  a va2 s. c o  m*/

    String response = doHttp(httpPut);
    return response;
}

From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java

/**
 * Remove the query part from URI./*  ww  w .ja  va  2 s . com*/
 * 
 * @param uri
 * @return URI after remove the query part.
 */
public static URI removeQueryPart(URI uri) {
    try {
        return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), null, null);
    } catch (URISyntaxException e) {
        Logger.error("Remove query part from uri failed.", e);
        return uri;
    }
}

From source file:com.healthcit.cacure.dao.CouchDBDao.java

private void batchGetDocumentIDs() throws IOException, URISyntaxException {

    // retrieve a set of IDs from DB
    URI uri = URIUtils.createURI("http", host, port, "/_uuids", "count=" + batchSize, null);

    // Prepare a request object
    HttpGet httpGet = new HttpGet(uri);

    // response is a JSON object with one array in it
    String response = doHttp(httpGet);
    //      Object obj=JSONValue.parse(response);
    JSONObject doc = JSONObject.fromObject(response);
    List<String> idList = (List<String>) (doc.get("uuids"));

    if (docIdSet == null) {
        docIdSet = new LinkedList<String>();
    }/*from   ww w . ja v a 2s  . c o m*/
    for (String id : idList) {
        docIdSet.add(id);
    }

}

From source file:com.healthcit.cacure.dao.CouchDBDao.java

/**
 * Generates the full URL from the CouchDB view name and "key" parameters.
 * @param viewName/*from  ww  w .ja  va2  s  . c  o m*/
 * @param key
 * @return
 */
public JSONObject getDataForView(String viewName, String parameterList) throws URISyntaxException {
    JSONObject obj = null;
    URI uri = null;
    try {
        String viewURI = constructViewURL(viewName);

        // Construct the full URL
        uri = URIUtils.createURI("http", host, port, viewURI, parameterList, null);
        HttpGet httpGet = new HttpGet(uri);
        String response = doHttp(httpGet);
        obj = JSONObject.fromObject(response);
    } catch (IOException ex) {
        log.error("Could not read from CouchDB: " + uri);
        ex.printStackTrace();
    }
    return obj;
}

From source file:org.openstack.burrow.backend.http.BaseHttp.java

/**
 * Generates a URI object from the passed in account name, queue name, message
 * id, and a List of Name/Value pairs//from   www  .  j av  a 2  s . c  om
 * 
 * @param account An Account name as a String
 * @param queue A Queue name as a String
 * @param message A Message id as a String
 * @param params A List of Name/Value pairs
 * @return A URI object as requested
 * @throws URISyntaxException Thrown if an issue arises with creating the URI
 */
private URI getUri(String account, String queue, String message, List<NameValuePair> params)
        throws URISyntaxException {
    String path = "/v1.0";
    if (account != null)
        path += "/" + account;
    if (queue != null)
        path += "/" + queue;
    if (message != null)
        path += "/" + message;
    String encodedParams = null;
    if (params != null)
        encodedParams = URLEncodedUtils.format(params, "UTF-8");
    return URIUtils.createURI(scheme, host, port, path, encodedParams, null);
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

private HttpGet createGetByBaseUrl(String baseUrl, String relativePath, List<NameValuePair> queryParameters)
        throws AppFactoryException {
    String query = null;//www.  j av  a2  s .  co  m
    HttpGet get;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(baseUrl);
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), relativePath, query,
                null);

        get = new HttpGet(uri);
        if (authenticate) {
            get.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }

    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + baseUrl
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for url : " + baseUrl
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }

    return get;
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * Util method to create a http get method
 *
 * @param urlFragment     the url fragment
 * @param queryParameters query parameters
 * @param tenantDomain    tenant domain, to which the application is belongs
 * @return a {@link HttpGet}//from  www .  ja  v a2  s . co  m
 */
private HttpGet createGet(String urlFragment, List<NameValuePair> queryParameters, String tenantDomain)
        throws AppFactoryException {

    String query = null;
    HttpGet get;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(getJenkinsUrl(tenantDomain));
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), urlFragment, query, null);
        get = new HttpGet(uri);
        if (authenticate) {
            get.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }

    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + urlFragment + " in tenant : " + tenantDomain
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for url fragment " + urlFragment + " in tenant : "
                + tenantDomain + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
    return get;
}

From source file:org.wso2.carbon.appfactory.jenkins.build.RestBasedJenkinsCIConnector.java

/**
 * Util method to create a POST method/*from   w w  w . ja  v  a 2s  .co m*/
 *
 * @param urlFragment     Url fragments.
 * @param queryParameters Query parameters.
 * @param httpEntity
 * @param tenantDomain    Tenant Domain of application
 * @return a {@link HttpPost}
 */
private HttpPost createPost(String urlFragment, List<NameValuePair> queryParameters, HttpEntity httpEntity,
        String tenantDomain) throws AppFactoryException {

    String query = "";
    HttpPost post;

    if (queryParameters != null) {
        query = URLEncodedUtils.format(queryParameters, HTTP.UTF_8);
    }
    try {
        URL url = new URL(getJenkinsUrl(tenantDomain));
        URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), urlFragment, query, null);
        post = new HttpPost(uri);

        if (httpEntity != null) {
            post.setEntity(httpEntity);
        }

        if (authenticate) {
            post.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials(this.username, this.apiKeyOrPassword), HTTP.UTF_8, false));
        }
    } catch (MalformedURLException e) {
        String msg = "Error while generating URL for the path : " + urlFragment + " in tenant : " + tenantDomain
                + " during the creation of HttpGet method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    } catch (URISyntaxException e) {
        String msg = "Error while constructing the URI for tenant : " + tenantDomain
                + " during the creation of " + "HttpPosts method";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }
    return post;
}

From source file:org.b3log.latke.client.LatkeClient.java

/**
 * Main entry./*from   www  . j  a v  a2 s  .c o m*/
 * 
 * @param args the specified command line arguments
 * @throws Exception exception 
 */
public static void main(String[] args) throws Exception {
    // Backup Test:      
    // args = new String[] {
    // "-h", "-backup", "-repository_names", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir",
    // "C:/b3log_backup", "-w", "true"};

    //        args = new String[] {
    //            "-h", "-restore", "-create_tables", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir",
    //            "C:/b3log_backup"};

    final Options options = getOptions();

    final CommandLineParser parser = new PosixParser();

    try {
        final CommandLine cmd = parser.parse(options, args);

        serverAddress = cmd.getOptionValue("s");

        backupDir = new File(cmd.getOptionValue("backup_dir"));
        if (!backupDir.exists()) {
            backupDir.mkdir();
        }

        userName = cmd.getOptionValue("u");

        if (cmd.hasOption("verbose")) {
            verbose = true;
        }

        password = cmd.getOptionValue("p");

        if (verbose) {
            System.out.println("Requesting server[" + serverAddress + "]");
        }

        final HttpClient httpClient = new DefaultHttpClient();

        if (cmd.hasOption("repository_names")) {
            getRepositoryNames();
        }

        if (cmd.hasOption("create_tables")) {
            final List<NameValuePair> qparams = new ArrayList<NameValuePair>();

            qparams.add(new BasicNameValuePair("userName", userName));
            qparams.add(new BasicNameValuePair("password", password));

            final URI uri = URIUtils.createURI("http", serverAddress, -1, CREATE_TABLES,
                    URLEncodedUtils.format(qparams, "UTF-8"), null);
            final HttpPut request = new HttpPut();

            request.setURI(uri);

            if (verbose) {
                System.out.println("Starting create tables");
            }

            final HttpResponse httpResponse = httpClient.execute(request);
            final InputStream contentStream = httpResponse.getEntity().getContent();
            final String content = IOUtils.toString(contentStream).trim();

            if (verbose) {
                printResponse(content);
            }
        }

        if (cmd.hasOption("w")) {
            final String writable = cmd.getOptionValue("w");
            final List<NameValuePair> qparams = new ArrayList<NameValuePair>();

            qparams.add(new BasicNameValuePair("userName", userName));
            qparams.add(new BasicNameValuePair("password", password));

            qparams.add(new BasicNameValuePair("writable", writable));
            final URI uri = URIUtils.createURI("http", serverAddress, -1, SET_REPOSITORIES_WRITABLE,
                    URLEncodedUtils.format(qparams, "UTF-8"), null);
            final HttpPut request = new HttpPut();

            request.setURI(uri);

            if (verbose) {
                System.out.println("Setting repository writable[" + writable + "]");
            }

            final HttpResponse httpResponse = httpClient.execute(request);
            final InputStream contentStream = httpResponse.getEntity().getContent();
            final String content = IOUtils.toString(contentStream).trim();

            if (verbose) {
                printResponse(content);
            }
        }

        if (cmd.hasOption("backup")) {
            System.out.println("Make sure you have disabled repository writes with [-w false], continue? (y)");
            final Scanner scanner = new Scanner(System.in);
            final String input = scanner.next();

            scanner.close();

            if (!"y".equals(input)) {
                return;
            }

            if (verbose) {
                System.out.println("Starting backup data");
            }

            final Set<String> repositoryNames = getRepositoryNames();

            for (final String repositoryName : repositoryNames) {
                // You could specify repository manually 
                // if (!"archiveDate_article".equals(repositoryName)) {
                // continue;
                // }

                int requestPageNum = 1;

                // Backup interrupt recovery
                final List<File> backupFiles = getBackupFiles(repositoryName);

                if (!backupFiles.isEmpty()) {
                    final File latestBackup = backupFiles.get(backupFiles.size() - 1);

                    final String latestPageSize = getBackupFileNameField(latestBackup.getName(), "${pageSize}");

                    if (!PAGE_SIZE.equals(latestPageSize)) {
                        // The 'latestPageSize' should be less or equal to 'PAGE_SIZE', if they are not the same that indicates 
                        // the latest backup file is the last of this repository, the repository backup had completed

                        if (verbose) {
                            System.out.println("Repository [" + repositoryName + "] backup have completed");
                        }

                        continue;
                    }

                    final String latestPageNum = getBackupFileNameField(latestBackup.getName(), "${pageNum}");

                    // Prepare for the next page to request
                    requestPageNum = Integer.parseInt(latestPageNum) + 1;

                    if (verbose) {
                        System.out.println(
                                "Start tot backup interrupt recovery [pageNum=" + requestPageNum + "]");
                    }
                }

                int totalPageCount = requestPageNum + 1;

                for (; requestPageNum <= totalPageCount; requestPageNum++) {
                    final List<NameValuePair> params = new ArrayList<NameValuePair>();

                    params.add(new BasicNameValuePair("userName", userName));
                    params.add(new BasicNameValuePair("password", password));
                    params.add(new BasicNameValuePair("repositoryName", repositoryName));
                    params.add(new BasicNameValuePair("pageNum", String.valueOf(requestPageNum)));
                    params.add(new BasicNameValuePair("pageSize", PAGE_SIZE));
                    final URI uri = URIUtils.createURI("http", serverAddress, -1, GET_DATA,
                            URLEncodedUtils.format(params, "UTF-8"), null);
                    final HttpGet request = new HttpGet(uri);

                    if (verbose) {
                        System.out.println("Getting data from repository [" + repositoryName
                                + "] with pagination [pageNum=" + requestPageNum + ", pageSize=" + PAGE_SIZE
                                + "]");
                    }

                    final HttpResponse httpResponse = httpClient.execute(request);
                    final InputStream contentStream = httpResponse.getEntity().getContent();
                    final String content = IOUtils.toString(contentStream, "UTF-8").trim();

                    contentStream.close();

                    if (verbose) {
                        printResponse(content);
                    }

                    final JSONObject resp = new JSONObject(content);
                    final JSONObject pagination = resp.getJSONObject("pagination");

                    totalPageCount = pagination.getInt("paginationPageCount");
                    final JSONArray results = resp.getJSONArray("rslts");

                    final String backupPath = backupDir.getPath() + File.separatorChar + repositoryName
                            + File.separatorChar + requestPageNum + '_' + results.length() + '_'
                            + System.currentTimeMillis() + ".json";
                    final File backup = new File(backupPath);
                    final FileWriter fileWriter = new FileWriter(backup);

                    IOUtils.write(results.toString(), fileWriter);
                    fileWriter.close();

                    if (verbose) {
                        System.out.println("Backup file[path=" + backupPath + "]");
                    }
                }
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println("Make sure you have enabled repository writes with [-w true], continue? (y)");
            final Scanner scanner = new Scanner(System.in);
            final String input = scanner.next();

            scanner.close();

            if (!"y".equals(input)) {
                return;
            }

            if (verbose) {
                System.out.println("Starting restore data");
            }

            final Set<String> repositoryNames = getRepositoryNamesFromBackupDir();

            for (final String repositoryName : repositoryNames) {
                // You could specify repository manually 
                // if (!"archiveDate_article".equals(repositoryName)) {
                // continue;
                // }

                final List<File> backupFiles = getBackupFiles(repositoryName);

                if (verbose) {
                    System.out.println("Restoring repository[" + repositoryName + ']');
                }

                for (final File backupFile : backupFiles) {
                    final FileReader backupFileReader = new FileReader(backupFile);
                    final String dataContent = IOUtils.toString(backupFileReader);

                    backupFileReader.close();

                    final List<NameValuePair> params = new ArrayList<NameValuePair>();

                    params.add(new BasicNameValuePair("userName", userName));
                    params.add(new BasicNameValuePair("password", password));
                    params.add(new BasicNameValuePair("repositoryName", repositoryName));
                    final URI uri = URIUtils.createURI("http", serverAddress, -1, PUT_DATA,
                            URLEncodedUtils.format(params, "UTF-8"), null);
                    final HttpPost request = new HttpPost(uri);

                    final List<NameValuePair> data = new ArrayList<NameValuePair>();

                    data.add(new BasicNameValuePair("data", dataContent));
                    final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8");

                    request.setEntity(entity);

                    if (verbose) {
                        System.out.println("Data[" + dataContent + "]");
                    }

                    final HttpResponse httpResponse = httpClient.execute(request);
                    final InputStream contentStream = httpResponse.getEntity().getContent();
                    final String content = IOUtils.toString(contentStream, "UTF-8").trim();

                    contentStream.close();

                    if (verbose) {
                        printResponse(content);
                    }

                    final String pageNum = getBackupFileNameField(backupFile.getName(), "${pageNum}");
                    final String pageSize = getBackupFileNameField(backupFile.getName(), "${pageSize}");
                    final String backupTime = getBackupFileNameField(backupFile.getName(), "${backupTime}");

                    final String restoredPath = backupDir.getPath() + File.separatorChar + repositoryName
                            + File.separatorChar + pageNum + '_' + pageSize + '_' + backupTime + '_'
                            + System.currentTimeMillis() + ".json";
                    final File restoredFile = new File(restoredPath);

                    backupFile.renameTo(restoredFile);

                    if (verbose) {
                        System.out.println("Backup file[path=" + restoredPath + "]");
                    }
                }
            }
        }

        if (cmd.hasOption("v")) {
            System.out.println(VERSION);
        }

        if (cmd.hasOption("h")) {
            printHelp(options);
        }

        // final File backup = new File(backupDir.getPath() + File.separatorChar + repositoryName + pageNum + '_' + pageSize + '_'
        // + System.currentTimeMillis() + ".json");
        // final FileEntity fileEntity = new FileEntity(backup, "application/json; charset=\"UTF-8\"");

    } catch (final ParseException e) {
        System.err.println("Parsing args failed, caused by: " + e.getMessage());
        printHelp(options);
    } catch (final ConnectException e) {
        System.err.println("Connection refused");
    }
}