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:HrefMatch.java

public static void main(String[] args) {
    try {/*from ww  w.ja va  2s.co  m*/
        // get URL string from command line or use default
        String urlString;
        if (args.length > 0)
            urlString = args[0];
        else
            urlString = "http://java.sun.com";

        // open reader for URL
        InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());

        // read contents into string builder
        StringBuilder input = new StringBuilder();
        int ch;
        while ((ch = in.read()) != -1)
            input.append((char) ch);

        // search for all occurrences of pattern
        String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String match = input.substring(start, end);
            System.out.println(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (PatternSyntaxException e) {
        e.printStackTrace();
    }
}

From source file:org.jcodec.player.app.PlayerMain.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Syntax: <url>");
        return;/* ww  w .ja v  a 2  s. com*/
    }
    new PlayerMain(new URL(args[0]));
}

From source file:flashcrawler.FlashCrawler.java

/**
 * @param args the command line arguments
 *//*from   w w  w.  j  av  a  2s  .  co m*/
public static void main(String[] args) throws FileNotFoundException {
    Scanner scn = new Scanner(new File("input.txt"));
    ArrayList<String> ins = new ArrayList();
    while (scn.hasNextLine()) {
        String input = scn.nextLine();
        ins.add(input);
    }

    String URL;
    PrintWriter writer = null;
    writer = new PrintWriter(new FileOutputStream(new File("error-log.txt"), true));

    String File;
    for (String name : ins) {
        File offlinePath = new File("/games/" + name + ".swf");
        String onlinePath = "http://wsh.gamib.com/x/" + name + "/" + name + ".swf";
        System.out.println("Downloading " + onlinePath + " into " + offlinePath);
        URL url = null;
        try {
            System.out.println("...");
            url = new URL(onlinePath);
        } catch (MalformedURLException ex) {
            System.out.println("Failed to create url object");
            writer.println("Error when creating url: " + onlinePath + "\tname");
        }
        try {
            System.out.println("...");
            FileUtils.copyURLToFile(url, offlinePath);
            System.out.println("Success.");
        } catch (IOException ex) {
            System.out.println("Error when downloading game: " + offlinePath);
            writer.println("Error when downloading game: " + offlinePath);
        }

    }
    writer.close();
    System.out.println("Process complete!");
}

From source file:ImageSize.java

public static void main(String[] args) throws Exception {
    String url = "http://www.java2s.com/style/logo.png";

    new ImageSize(new URL(url));

}

From source file:SendMail.java

public static void main(String[] args) {
    try {/*from   w w  w. java2 s. c  om*/
        // If the user specified a mailhost, tell the system about it.
        if (args.length >= 1)
            System.getProperties().put("mail.host", args[0]);

        // A Reader stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Ask the user for the from, to, and subject lines
        System.out.print("From: ");
        String from = in.readLine();
        System.out.print("To: ");
        String to = in.readLine();
        System.out.print("Subject: ");
        String subject = in.readLine();

        // Establish a network connection for sending mail
        URL u = new URL("mailto:" + to); // Create a mailto: URL
        URLConnection c = u.openConnection(); // Create its URLConnection
        c.setDoInput(false); // Specify no input from it
        c.setDoOutput(true); // Specify we'll do output
        System.out.println("Connecting..."); // Tell the user
        System.out.flush(); // Tell them right now
        c.connect(); // Connect to mail host
        PrintWriter out = // Get output stream to host
                new PrintWriter(new OutputStreamWriter(c.getOutputStream()));

        // We're talking to the SMTP server now.
        // Write out mail headers. Don't let users fake the From address
        out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@"
                + InetAddress.getLocalHost().getHostName() + ">\r\n");
        out.print("To: " + to + "\r\n");
        out.print("Subject: " + subject + "\r\n");
        out.print("\r\n"); // blank line to end the list of headers

        // Now ask the user to enter the body of the message
        System.out.println("Enter the message. " + "End with a '.' on a line by itself.");
        // Read message line by line and send it out.
        String line;
        for (;;) {
            line = in.readLine();
            if ((line == null) || line.equals("."))
                break;
            out.print(line + "\r\n");
        }

        // Close (and flush) the stream to terminate the message
        out.close();
        // Tell the user it was successfully sent.
        System.out.println("Message sent.");
    } catch (Exception e) { // Handle any exceptions, print error message.
        System.err.println(e);
        System.err.println("Usage: java SendMail [<mailhost>]");
    }
}

From source file:com.zxm.servicemix.examples.cxf.jaxrs.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all customer info

    // Sent HTTP GET request to query customer info
    System.out.println("Sent HTTP GET request to query customer info");
    URL url = new URL("http://localhost:8181/cxf/crm/customerservice/customers/123");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query sub resource product info
    System.out.println("\n");
    System.out.println("Sent HTTP GET request to query sub resource product info");
    url = new URL("http://localhost:8181/cxf/crm/customerservice/orders/223/products/323");
    in = url.openStream();/*from  w  w  w  .  ja  va  2s  .  c o  m*/
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update customer info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update customer info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod("http://localhost:8181/cxf/crm/customerservice/customers");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add customer
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add customer");
    inputFile = client.getClass().getResource("add_customer.xml").getFile();
    input = new File(inputFile);
    PostMethod post = new PostMethod("http://localhost:8181/cxf/crm/customerservice/customers");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}

From source file:me.rgcjonas.portableMinecraftLauncher.Main.java

/**
 * entry point//from   www . j  a  v  a2 s  .c o m
 * @param args
 */
public static void main(String[] args) {
    File workDir = getWorkingDirectory();

    //ensure the working directory exists
    if (!workDir.exists()) {
        workDir.mkdir();
    }
    File launcherJar = new File(workDir, "launcher.jar");

    //download launcher if it doesn't exist
    if (!launcherJar.exists()) {
        try {
            URL launcherurl = new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar");
            FileUtils.copyURLToFile(launcherurl, launcherJar);
        } catch (IOException e) {
            // shouldn't happen
            e.printStackTrace();
        }
    }

    URL[] urls;
    try {
        urls = new URL[] { launcherJar.toURI().toURL() };

        //this class loader mustn't be disposed while the launcher is running
        @SuppressWarnings("resource")
        LauncherClassLoader loader = new LauncherClassLoader(urls);

        //run it      
        Class<?> launcherFrame = loader.loadClass("net.minecraft.LauncherFrame");
        launcherFrame.getMethod("main", String[].class).invoke(null, (Object) args);
    } catch (Exception e) {
        // there's nothing we can do in that case but notify the dev
        e.printStackTrace();
    }
}

From source file:org.apache.infra.reviewboard.ReviewBoard.java

public static void main(String... args) throws IOException {

    URL url = new URL(REVIEW_BOARD_URL);
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD)
            .authPreemptive(host);//from  w w  w .  ja  va 2 s.  c o  m

    Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    Response response = executor.execute(request);

    request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    response = executor.execute(request);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent());

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, json);
}

From source file:com.aj.hangman.HangmanReq.java

public static void main(String[] args) {
    HangmanDict dictionary = new HangmanDict();

    try {//from   ww w .j ava 2  s  .co  m
        BufferedReader input = new BufferedReader(new InputStreamReader(
                new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream()));
        String info = input.readLine();
        JSONParser parser = new JSONParser();

        Object obj;
        try {
            obj = parser.parse(info);
            JSONObject retJson = (JSONObject) obj;

            TOKEN = (String) retJson.get("token");
            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            PREM = REM;
            System.out.println("State:: " + STATE);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while ("ALIVE".equalsIgnoreCase(STATUS)) {
            // call make guess function, returns character
            guess = dictionary.makeGuess(STATE);
            System.out.println("Guessed:: " + guess);
            // call the url to update
            BufferedReader reInput = new BufferedReader(
                    new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu"
                            + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream()));

            // parse the url to get the updated value
            String reInfo = reInput.readLine();
            JSONParser reParser = new JSONParser();

            Object retObj = reParser.parse(reInfo);
            JSONObject retJson = (JSONObject) retObj;

            STATUS = (String) retJson.get("status");
            STATE = (String) retJson.get("state");
            REM = (Long) retJson.get("remaining_guesses");
            System.out.println("State:: " + STATE);
        }

        if ("DEAD".equalsIgnoreCase(STATUS)) {
            // print lost
            System.out.println("You LOOSE: DEAD");
        } else if ("FREE".equalsIgnoreCase(STATUS)) {
            // print free
            System.out.println("You WIN: FREE");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.mycompany.jaxrsexample.client.Client.java

public static void main(String args[]) throws Exception {
    // Sent HTTP GET request to query all students info

    System.out.println("Invoking server through HTTP GET to query all students info");
    URL url = new URL("http://localhost:9000/studentservice/students");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP GET request to query student info
    System.out.println("Sent HTTP GET request to query customer info");
    url = new URL("http://localhost:9000/studentservice/students/1");
    in = url.openStream();// ww  w.  j  ava2 s  . c om
    System.out.println(getStringFromInputStream(in));

    // Sent HTTP PUT request to update student info
    System.out.println("\n");
    System.out.println("Sent HTTP PUT request to update student info");
    Client client = new Client();
    String inputFile = client.getClass().getResource("/update_student.xml").getFile();
    URIResolver resolver = new URIResolver(inputFile);
    File input = new File(resolver.getURI());
    PutMethod put = new PutMethod("http://localhost:9000/studentservice/students");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(put);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }

    // Sent HTTP POST request to add student
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add student");
    inputFile = client.getClass().getResource("/add_student.xml").getFile();
    resolver = new URIResolver(inputFile);
    input = new File(resolver.getURI());
    PostMethod post = new PostMethod("http://localhost:9000/studentservice/students");
    post.addRequestHeader("Accept", "text/xml");
    entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        System.out.println("Response status code: " + result);
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }

    System.out.println("\n");
    System.exit(0);
}