Example usage for java.net URL URL

List of usage examples for java.net URL URL

Introduction

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

Prototype

public URL(String spec) throws MalformedURLException 

Source Link

Document

Creates a URL object from the String representation.

Usage

From source file:de.raion.xmppbot.hipchat.HipChatAPIConfig.java

public static void main(String[] args) throws Exception {
    HipChatAPIConfig config = new HipChatAPIConfig();
    config.setAuthenticationToken("b2b1ca1091f0709e60253b76db73ea");
    config.setBaseURL(new URL("https://api.hipchat.com"));
    config.setApiVersion("v1");
    config.setRoomCreatePath("rooms/create");
    config.setRoomDeletePath("rooms/delete");
    config.setRoomHistoryPath("rooms/history");

    ObjectWriter writer = new ObjectMapper().writerWithDefaultPrettyPrinter();

    String filename = config.getClass().getSimpleName().toLowerCase() + ".json";

    writer.writeValue(new File(filename), config);
}

From source file:org.craftercms.cstudio.publishing.StopServiceMain.java

public static void main(String[] args) throws Exception {
    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
            "classpath:spring/shutdown-context.xml");

    ReadablePropertyPlaceholderConfigurer properties = (ReadablePropertyPlaceholderConfigurer) context
            .getBean("cstudioShutdownProperties");
    if (properties != null) {
        String url = getProperty(properties, PROP_URL);
        String path = getProperty(properties, PROP_SERVICE_PATH);
        String port = getProperty(properties, PROP_PORT);
        String password = URLEncoder.encode(getProperty(properties, PROP_PASSWORD), "UTF-8");
        String target = url + ":" + port + path;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending a stop request to " + target);
        }//from ww  w  .  j  av  a 2 s  .  co  m
        target = target + "?" + StopServiceServlet.PARAM_PASSWORD + "=" + password;
        URL serviceUrl = new URL(target);
        HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setReadTimeout(10000);
        connection.connect();
        try {
            connection.getContent();
        } catch (ConnectException e) {
            // ignore this error (server will terminate as soon as the request is sent out)
        }
    } else {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(PROPERTIES_NAME + " is not present in shutdown-context.xml");
        }
    }
    context.close();
}

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {/*from   w ww .j  a  va  2  s .  c o  m*/
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

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 {//from w w w  . ja  v a2 s  . c o  m
        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:geocodingsql.Main.java

/**
 * @param args the command line arguments
 *///  w  w w . j a  va2s.c o m
public static void main(String[] args) throws JSONException {
    Main x = new Main();
    ResultSet rs = null;
    String string = "";

    x.establishConnection();
    rs = x.giveName();

    try {
        while (rs.next()) {
            string += rs.getString(1) + " ";
        }

        JOptionPane.showMessageDialog(null, string, "authors", 1);
    } catch (Exception e) {
        System.out.println("Problem when printing the database.");
    }
    x.closeConnection();

    // Now do Geocoding
    String req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=41.3166662867211,-72.9062497615814&result_type=point_of_interest&key="
            + key;
    try {
        URL url = new URL(req + "&sensor=false");
        URLConnection conn = url.openConnection();
        ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
        IOUtils.copy(conn.getInputStream(), output);
        output.close();
        req = output.toString();
    } catch (Exception e) {
        System.out.println("Geocoding Error");
    }
    JSONObject jObject = new JSONObject(req);
    JSONArray resultArray = jObject.getJSONArray("results");
    //this prints out the neighborhood of the provided coordinates
    System.out.println(resultArray.getJSONObject(0).getJSONArray("address_components")
            .getJSONObject("neighborhood").getString("long_name"));
}

From source file:inf.ufg.br.muralufg.features.push.GcmSender.java

public static void main(String[] args) {
    if (args.length < 1 || args.length > 2 || args[0] == null) {
        Log.d("", "usage: ./gradlew run -Pargs=\"MESSAGE[,DEVICE_TOKEN]\"");
        Log.d("",
                "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n"
                        + "specified, the message will only be sent to that device. Otherwise, the message \n"
                        + "will be sent to all devices subscribed to the \"global\" topic.");
        Log.d("", "Example (Broadcast):\n" + "On Windows:   .\\gradlew.bat run -Pargs=\"<Your_Message>\"\n"
                + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>\"");

        Log.d("",
                "Example (Unicast):\n"
                        + "On Windows:   .\\gradlew.bat run -Pargs=\"<Your_Message>,<Your_Token>\"\n"
                        + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>,<Your_Token>\"");
        System.exit(1);/*  w w  w.  j a  v  a2s. c o  m*/
    }
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", args[0].trim());
        // Where to send GCM message.
        if (args.length > 1 && args[1] != null) {
            jGcmData.put("to", args[1].trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Log.d("", resp);
        Log.d("", "Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        Log.d("", "Unable to send GCM message.");
        Log.d("", "Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        Log.d("", "", e);
    } catch (JSONException e) {
        Log.d("", "", e);
    }
}

From source file:com.yannick.GcmSender.java

public static void main(String[] args) {
    if (args.length < 1 || args.length > 2 || args[0] == null) {
        System.err.println("usage: ./gradlew run -Pargs=\"MESSAGE[,DEVICE_TOKEN]\"");
        System.err.println("");
        System.err.println(/*  w ww  . ja va  2  s.  com*/
                "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n"
                        + "specified, the message will only be sent to that device. Otherwise, the message \n"
                        + "will be sent to all devices subscribed to the \"global\" topic.");
        System.err.println("");
        System.err.println(
                "Example (Broadcast):\n" + "On Windows:   .\\gradlew.bat run -Pargs=\"<Your_Message>\"\n"
                        + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>\"");
        System.err.println("");
        System.err.println("Example (Unicast):\n"
                + "On Windows:   .\\gradlew.bat run -Pargs=\"<Your_Message>,<Your_Token>\"\n"
                + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>,<Your_Token>\"");
        System.exit(1);
    }
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", args[0].trim());
        // Where to send GCM message.
        if (args.length > 1 && args[1] != null) {
            jGcmData.put("to", args[1].trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}

From source file:com.yufei.dataget.dataretriver.HttpDataRetriverUsingFirefoxDriver.java

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

    final long startTime = System.currentTimeMillis();
    mLog.info("calling runWithTimeout!");
    HttpDataRetriverUsingFirefoxDriver hdrufd = new HttpDataRetriverUsingFirefoxDriver(null);

    try {//w  w  w .  ja  v a2  s  .  co m
        String htmlContent = TimeOutUtils.runWithTimeout(new Callable<String>() {

            @Override
            public String call() throws Exception {
                String url = "http://www.baidu.com/tools?url=http%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DO0urTq_fyCkG3Rd2veZDQm7TLJ50XyUOeeoybddPUG6zBjpgh37XHtMM_oXKe4nQxM-q5IEVjldslw0tbkMfvK&jump=http%3A%2F%2Fkoubei.baidu.com%2Fwomc%2Fp%2Fsentry%3Ftitle%3D%012014%01-%012015%01%E5%B9%B4%E5%BA%A6%01QS%01%E4%B8%96%E7%95%8C%01%E6%8E%92%E5%90%8D%01%3A%01%E6%BE%B3%E5%A4%A7%E5%88%A9%E4%BA%9A%01%E5%A4%A7%E5%AD%A6%0123%01%E6%89%80%01%E9%AB%98%E6%A0%A1%01%E8%BF%9B%E5%85%A5%02TOP%01500%03-%01%E7%95%99%E5%AD%A6%01-%01...%26q%3Dtop%20500%20university&key=surl";
                hdrufd.setUrl(new URL(url));
                hdrufd.connect();

                System.out.print(hdrufd.getHtmlContent());
                return hdrufd.getHtmlContent();

            }
        }, 10, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        mLog.info("got timeout!");
    } finally {
        hdrufd.disconnect();

    }
    mLog.info("end of main method!");

}

From source file:edu.scripps.fl.pubchem.app.AssayDownloader.java

public static void main(String[] args) throws Exception {
    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("data_url").withType("").withValueSeparator('=')
                    .hasArg().create());
            options.addOption(//w w  w  .  j  ava2  s. c o m
                    OptionBuilder.withLongOpt("days").withType(0).withValueSeparator('=').hasArg().create());
            options.addOption(OptionBuilder.withLongOpt("mlpcn").withType(false).create());
            options.addOption(OptionBuilder.withLongOpt("notInDb").withType(false).create());
        }
    };
    args = clh.handle(args);
    String data_url = clh.getCommandLine().getOptionValue("data_url");
    if (null == data_url)
        data_url = "ftp://ftp.ncbi.nlm.nih.gov/pubchem/Bioassay/CSV/";
    //         data_url = "file:///C:/Home/temp/PubChemFTP/";

    AssayDownloader main = new AssayDownloader();
    main.dataUrl = new URL(data_url);

    if (clh.getCommandLine().hasOption("days"))
        main.days = Integer.parseInt(clh.getCommandLine().getOptionValue("days"));
    if (clh.getCommandLine().hasOption("mlpcn"))
        main.mlpcn = true;
    if (clh.getCommandLine().hasOption("notInDb"))
        main.notInDb = true;

    if (args.length == 0)
        main.process();
    else {
        Long[] list = (Long[]) ConvertUtils.convert(args, Long[].class);
        List<Long> l = (List<Long>) Arrays.asList(list);
        log.info("AID to process: " + l);
        main.process(new HashSet<Long>(Arrays.asList(list)));
    }
}

From source file:lc.buyplus.gcmsender.GcmSender.java

public static void main(String[] args) throws JSONException {
    if (args.length < 1 || args.length > 2 || args[0] == null) {
        System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]");
        System.err.println("");
        System.err.println(/*from  www  . j  a v  a2s  .c o m*/
                "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n"
                        + "specified, the message will only be sent to that device. Otherwise, the message \n"
                        + "will be sent to all devices subscribed to the \"global\" topic.");
        System.err.println("");
        System.err.println(
                "Example (Broadcast):\n" + "On Windows:   .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n"
                        + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\"");
        System.err.println("");
        System.err.println("Example (Unicast):\n"
                + "On Windows:   .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n"
                + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"");
        System.exit(1);
    }
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", args[0].trim());
        // Where to send GCM message.
        if (args.length > 1 && args[1] != null) {
            jGcmData.put("to", args[1].trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}