Example usage for java.net URLEncoder encode

List of usage examples for java.net URLEncoder encode

Introduction

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

Prototype

public static String encode(String s, Charset charset) 

Source Link

Document

Translates a string into application/x-www-form-urlencoded format using a specific java.nio.charset.Charset Charset .

Usage

From source file:jenkins.security.security218.ysoserial.exploit.JSF.java

public static void main(String[] args) {

    if (args.length < 3) {
        System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
        System.exit(-1);//from www. j  a  va2 s .c  o m
    }

    final Object payloadObject = Utils.makePayloadObject(args[1], args[2]);

    try {
        URL u = new URL(args[0]);

        URLConnection c = u.openConnection();
        if (!(c instanceof HttpURLConnection)) {
            throw new IllegalArgumentException("Not a HTTP url");
        }

        HttpURLConnection hc = (HttpURLConnection) c;
        hc.setDoOutput(true);
        hc.setRequestMethod("POST");
        hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream os = hc.getOutputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(payloadObject);
        oos.close();
        byte[] data = bos.toByteArray();
        String requestBody = "javax.faces.ViewState="
                + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
        os.write(requestBody.getBytes("US-ASCII"));
        os.close();

        System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    Utils.releasePayload(args[1], payloadObject);

}

From source file:com.music.tools.SongDBDownloader.java

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpContext ctx = new BasicHttpContext();

    HttpUriRequest req = new HttpGet(
            "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand");
    client.execute(req, ctx);/* www .  j av  a  2  s  . c om*/
    req.abort();

    List<String> urls = getSongUrls(
            "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1",
            client, ctx);
    List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size());
    for (String songUrl : urls) {
        paramsList.addAll(getSongParams(songUrl, client, ctx));
    }
    int i = 0;
    for (List<? extends NameValuePair> params : paramsList) {

        HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML");

        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate");
        request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Origin", "http://www.hooktheory.com");
        request.setHeader("Referer",
                URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8"));

        HttpEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);

        try {
            HttpResponse response = client.execute(request, ctx);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                String xml = CharStreams.toString(new InputStreamReader(is));
                is.close();
                Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8"));
            } else {
                System.out.println(response.getStatusLine());
                System.out.println(params);
            }
            i++;
            request.abort();
        } catch (Exception ex) {
            System.out.println(params);
            ex.printStackTrace();
        }
    }
}

From source file:com.cloud.sample.UserCloudAPIExecutor.java

public static void main(String[] args) {
    // Host//  w  ww  . j  ava 2 s.co m
    String host = null;

    // Fully qualified URL with http(s)://host:port
    String apiUrl = null;

    // ApiKey and secretKey as given by your CloudStack vendor
    String apiKey = null;
    String secretKey = null;

    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("usercloud.properties"));

        // host
        host = prop.getProperty("host");
        if (host == null) {
            System.out.println(
                    "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file.");
        }

        // apiUrl
        apiUrl = prop.getProperty("apiUrl");
        if (apiUrl == null) {
            System.out.println(
                    "Please specify a valid API URL in the format of command=&param1=&param2=... in your usercloud.properties file.");
        }

        // apiKey
        apiKey = prop.getProperty("apiKey");
        if (apiKey == null) {
            System.out.println(
                    "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }

        // secretKey
        secretKey = prop.getProperty("secretKey");
        if (secretKey == null) {
            System.out.println(
                    "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }

        if (apiUrl == null || apiKey == null || secretKey == null) {
            return;
        }

        System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl
                + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'");

        // Step 1: Make sure your APIKey is URL encoded
        String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");

        // Step 2: URL encode each parameter value, then sort the parameters and apiKey in
        // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey.
        // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using
        // '&' to delimit
        // the string
        List<String> sortedParams = new ArrayList<String>();
        sortedParams.add("apikey=" + encodedApiKey.toLowerCase());
        StringTokenizer st = new StringTokenizer(apiUrl, "&");
        String url = null;
        boolean first = true;
        while (st.hasMoreTokens()) {
            String paramValue = st.nextToken();
            String param = paramValue.substring(0, paramValue.indexOf("="));
            String value = URLEncoder
                    .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8");
            if (first) {
                url = param + "=" + value;
                first = false;
            } else {
                url = url + "&" + param + "=" + value;
            }
            sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase());
        }
        Collections.sort(sortedParams);

        System.out.println("Sorted Parameters: " + sortedParams);

        // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key
        String sortedUrl = null;
        first = true;
        for (String param : sortedParams) {
            if (first) {
                sortedUrl = param;
                first = false;
            } else {
                sortedUrl = sortedUrl + "&" + param;
            }
        }
        System.out.println("sorted URL : " + sortedUrl);
        String encodedSignature = signRequest(sortedUrl, secretKey);

        // Step 4: Construct the final URL we want to send to the CloudStack Management Server
        // Final result should look like:
        // http(s)://://client/api?&apiKey=&signature=
        String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature;
        System.out.println("final URL : " + finalUrl);

        // Step 5: Perform a HTTP GET on this URL to execute the command
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(finalUrl);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            // SUCCESS!
            System.out.println("Successfully executed command");
        } else {
            // FAILED!
            System.out.println("Unable to execute command with response code: " + responseCode);
        }

    } catch (Throwable t) {
        System.out.println(t);
    }
}

From source file:net.semanticmetadata.lire.solr.SearchImages.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
    // http://localhost:8080/solr/lire/query?q=hashes%3A1152++hashes%3A605++hashes%3A96++hashes%3A275++&wt=xml
    String hashes = "1152  605  96  275  2057  3579  3950  2831  2367  3169  3292  974  2465  1573  2933  3125  314  2158  3532  974  2198  2315  3013  3302  3316  1467  2213  818  3  1083  18  2604  327  1370  593  3677  464  79  256  984  2496  1124  855  2091  780  1941  1887  1145  1396  4016  2406  2227  1532  2598  215  1375  171  2516  1698  368  2350  3799  223  1471  2083  1051  3015  3789  3374  1442  3991  3575  1452  751  428  3103  1182  2241  474  275  3678  3970  559  3394  2662  2361  2048  1083  181  1483  3903  3331  2363  756  558  2838  3984  1878  2667  3333  1473  2136  3499  3873  1437  3091  1287  948  46  3660  3003  1572  1185  2231  2622  257  3538  3632  3989  1180  3928  3144  1492  3941  3253  3498  2721  1036  22  1020  725  1431  3821  2248  2542  3659  2849  524  2967  1  2493  3620  2951  3584  1641  3873  2087  1506  1489  3064";
    String[] split = hashes.split(" ");
    String query = "";
    for (int i = 0; i < split.length; i++) {
        String s = split[i];//from   ww w .  ja  v  a2 s.c  om
        if (s.trim().length() > 0)
            query += " cl_ha:" + s.trim();
    }
    URL u = new URL(baseURL + "?q=" + URLEncoder.encode(query, "utf-8") + "&wt=xml&rows=500");
    InputStream in = u.openStream();
    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
    SolrResponseHandler dh = new SolrResponseHandler();
    saxParser.parse(in, dh);
    ArrayList<ResultItem> results = dh.getResults();
    // re-rank:

}

From source file:com.cloud.test.utils.SubmitCert.java

public static void main(String[] args) {
    // Parameters
    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    while (iter.hasNext()) {
        String arg = iter.next();

        if (arg.equals("-c")) {
            certFileName = iter.next();//  w w w .  j  a v a 2s .c  o  m
        }

        if (arg.equals("-s")) {
            secretKey = iter.next();
        }

        if (arg.equals("-a")) {
            apiKey = iter.next();
        }

        if (arg.equals("-action")) {
            url = "Action=" + iter.next();
        }
    }

    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream("conf/tool.properties"));
    } catch (IOException ex) {
        s_logger.error("Error reading from conf/tool.properties", ex);
        System.exit(2);
    }

    host = prop.getProperty("host");
    port = prop.getProperty("port");

    if (url.equals("Action=SetCertificate") && certFileName == null) {
        s_logger.error("Please set path to certificate (including file name) with -c option");
        System.exit(1);
    }

    if (secretKey == null) {
        s_logger.error("Please set secretkey  with -s option");
        System.exit(1);
    }

    if (apiKey == null) {
        s_logger.error("Please set apikey with -a option");
        System.exit(1);
    }

    if (host == null) {
        s_logger.error("Please set host in tool.properties file");
        System.exit(1);
    }

    if (port == null) {
        s_logger.error("Please set port in tool.properties file");
        System.exit(1);
    }

    TreeMap<String, String> param = new TreeMap<String, String>();

    String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint")
            + "\n";
    String temp = "";

    if (certFileName != null) {
        cert = readCert(certFileName);
        param.put("cert", cert);
    }

    param.put("AWSAccessKeyId", apiKey);
    param.put("Expires", prop.getProperty("expires"));
    param.put("SignatureMethod", prop.getProperty("signaturemethod"));
    param.put("SignatureVersion", "2");
    param.put("Version", prop.getProperty("version"));

    StringTokenizer str1 = new StringTokenizer(url, "&");
    while (str1.hasMoreTokens()) {
        String newEl = str1.nextToken();
        StringTokenizer str2 = new StringTokenizer(newEl, "=");
        String name = str2.nextToken();
        String value = str2.nextToken();
        param.put(name, value);
    }

    //sort url hash map by key
    Set c = param.entrySet();
    Iterator it = c.iterator();
    while (it.hasNext()) {
        Map.Entry me = (Map.Entry) it.next();
        String key = (String) me.getKey();
        String value = (String) me.getValue();
        try {
            temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
        } catch (Exception ex) {
            s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex);
        }

    }
    temp = temp.substring(0, temp.length() - 1);
    String requestToSign = req + temp;
    String signature = UtilsForTest.signRequest(requestToSign, secretKey);
    String encodedSignature = "";
    try {
        encodedSignature = URLEncoder.encode(signature, "UTF-8");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?"
            + temp + "&Signature=" + encodedSignature;
    s_logger.info("Sending request with url:  " + url + "\n");
    sendRequest(url);
}

From source file:com.mockey.runner.JettyRunner.java

public static void main(String[] args) throws Exception {
    if (args == null)
        args = new String[0];

    // Initialize the argument parser
    SimpleJSAP jsap = new SimpleJSAP("java -jar Mockey.jar", "Starts a Jetty server running Mockey");
    jsap.registerParameter(new FlaggedOption(ARG_PORT, JSAP.INTEGER_PARSER, "8080", JSAP.NOT_REQUIRED, 'p',
            ARG_PORT, "port to run Jetty on"));
    jsap.registerParameter(new FlaggedOption(BSC.FILE, JSAP.STRING_PARSER,
            MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, JSAP.NOT_REQUIRED, 'f', BSC.FILE,
            "Relative path to a mockey-definitions file to initialize Mockey, relative to where you're starting Mockey"));

    jsap.registerParameter(new FlaggedOption(BSC.URL, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'u', BSC.URL,
            "URL to a mockey-definitions file to initialize Mockey"));

    jsap.registerParameter(new FlaggedOption(BSC.TRANSIENT, JSAP.BOOLEAN_PARSER, "true", JSAP.NOT_REQUIRED, 't',
            BSC.TRANSIENT, "Read only mode if set to true, no updates are made to the file system."));

    jsap.registerParameter(new FlaggedOption(BSC.FILTERTAG, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'F',
            BSC.FILTERTAG,/*w ww .  j  av  a2  s  .c  om*/
            "Filter tag for services and scenarios, useful for 'only use information with this tag'. "));
    jsap.registerParameter(
            new Switch(ARG_QUIET, 'q', "quiet", "Runs in quiet mode and does not loads the browser"));

    jsap.registerParameter(new FlaggedOption(BSC.HEADLESS, JSAP.BOOLEAN_PARSER, "false", JSAP.NOT_REQUIRED, 'H',
            BSC.HEADLESS,
            "Headless flag. Default is 'false'. Set to 'true' if you do not want Mockey to spawn a browser thread upon startup."));

    // parse the command line options
    JSAPResult config = jsap.parse(args);

    // Bail out if they asked for the --help
    if (jsap.messagePrinted()) {
        System.exit(1);
    }

    // Construct the new arguments for jetty-runner
    int port = config.getInt(ARG_PORT);
    boolean transientState = true;
    // We can add more things to the quite mode. For now we are just not launching browser
    boolean isQuiteMode = false;

    try {
        transientState = config.getBoolean(BSC.TRANSIENT);
        isQuiteMode = config.getBoolean(ARG_QUIET);
    } catch (Exception e) {
        //
    }

    // Initialize Log4J file roller appender.
    StartUpServlet.getDebugFile();
    InputStream log4jInputStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("WEB-INF/log4j.properties");
    Properties log4JProperties = new Properties();
    log4JProperties.load(log4jInputStream);
    PropertyConfigurator.configure(log4JProperties);

    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setConfigurations(new Configuration[] { new PreCompiledJspConfiguration() });

    ClassPathResourceHandler resourceHandler = new ClassPathResourceHandler();
    resourceHandler.setContextPath("/");

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.addHandler(resourceHandler);

    contexts.addHandler(webapp);

    server.setHandler(contexts);

    server.start();
    // Construct the arguments for Mockey
    String file = String.valueOf(config.getString(BSC.FILE));
    String url = String.valueOf(config.getString(BSC.URL));
    String filterTag = config.getString(BSC.FILTERTAG);
    String fTagParam = "";
    boolean headless = config.getBoolean(BSC.HEADLESS);
    if (filterTag != null) {
        fTagParam = "&" + BSC.FILTERTAG + "=" + URLEncoder.encode(filterTag, "UTF-8");
    }

    // Startup displays a big message and URL redirects after x seconds.
    // Snazzy.
    String initUrl = HOMEURL;
    // BUT...if a file is defined, (which it *should*),
    // then let's initialize with it instead.
    if (url != null && url.trim().length() > 0) {
        URLEncoder.encode(initUrl, "UTF-8");
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.URL + "=" + URLEncoder.encode(url, "UTF-8") + fTagParam;
    } else if (file != null && file.trim().length() > 0) {
        URLEncoder.encode(initUrl, "UTF-8");
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.FILE + "=" + URLEncoder.encode(file, "UTF-8") + fTagParam;
    } else {
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.FILE + "=" + URLEncoder.encode(MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, "UTF-8")
                + fTagParam;

    }

    if (!(headless || isQuiteMode)) {
        new Thread(new BrowserThread("http://127.0.0.1", String.valueOf(port), initUrl, 0)).start();
        server.join();
    } else {
        initializeMockey(new URL("http://127.0.0.1" + ":" + String.valueOf(port) + initUrl));
    }
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {//  w  w  w .  j  a  va2 s  . c  om
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:Main.java

public static String urlToEncode(String url) {
    try {//from   w w  w.ja v a2s  .  c  o  m
        url = URLEncoder.encode(url, "UTF-8");
    } catch (Exception e) {
    }
    return url;
}

From source file:Main.java

public static String getURLEncoded(String s) {
    String s1;/*w w w  . j a va  2  s  . c  o m*/
    try {
        s1 = URLEncoder.encode(s, "UTF-8");
    } catch (Exception exception) {
        return "";
    }
    return s1;
}

From source file:Main.java

public static String getEncoderStr(String str) {
    String utfStr;/*  ww w.  j  a  va  2 s.  co  m*/
    try {
        utfStr = URLEncoder.encode(str, "utf-8").replace("+", "%20");
    } catch (Exception e) {
        utfStr = str;
    }
    return utfStr;
}