Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:net.groupbuy.controller.admin.StatisticsController.java

/**
 * // w ww .j  av  a2  s.  c  o m
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword())) {
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/groupbuy.php?domain="
                        + setting.getSiteUrl() + "&key="
                        + DigestUtils.md5Hex(setting.getSiteUrl() + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:com.dp2345.controller.admin.StatisticsController.java

/**
 * // w  w w. j a  v a2s  . co m
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword())) {
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/dp2345.php?domain="
                        + setting.getSiteUrl() + "&key="
                        + DigestUtils.md5Hex(setting.getSiteUrl() + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:gov.guilin.controller.admin.StatisticsController.java

/**
 * /* w ww.j  ava 2  s.c o m*/
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword())) {
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/guilin.php?domain="
                        + setting.getSiteUrl() + "&key="
                        + DigestUtils.md5Hex(setting.getSiteUrl() + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:it.polimi.chansonnier.agent.YoutubeGrabber.java

public InputStream getVideo(String pageUrl) {
    try {//from ww w  .ja v a  2 s  .c o m
        URL video = new URL(getVideoUrl(pageUrl));
        _log.debug("it.polimi.chansonnier.agent.YoutubeGrabber: downloading " + video);
        URLConnection connection = video.openConnection();
        return connection.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:net.osxx.controller.admin.StatisticsController.java

/**
 * //from ww w  .  ja va  2  s  .  c o  m
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword())) {
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/osxx.php?domain="
                        + setting.getSiteUrl() + "&key="
                        + DigestUtils.md5Hex(setting.getSiteUrl() + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:net.shopxx.controller.admin.StatisticsController.java

/**
 * //from   w  w w .  j a v a2s  . c  o m
 */
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String setting(@RequestParam(defaultValue = "false") Boolean isEnabled,
        RedirectAttributes redirectAttributes) {
    Setting setting = SettingUtils.get();
    if (isEnabled) {
        if (StringUtils.isEmpty(setting.getCnzzSiteId()) || StringUtils.isEmpty(setting.getCnzzPassword())) {
            try {
                String createAccountUrl = "http://intf.cnzz.com/user/companion/shopxx.php?domain="
                        + setting.getSiteUrl() + "&key="
                        + DigestUtils.md5Hex(setting.getSiteUrl() + "Lfg4uP0H");
                URLConnection urlConnection = new URL(createAccountUrl).openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.contains("@")) {
                        break;
                    }
                }
                if (line != null) {
                    setting.setCnzzSiteId(StringUtils.substringBefore(line, "@"));
                    setting.setCnzzPassword(StringUtils.substringAfter(line, "@"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    setting.setIsCnzzEnabled(isEnabled);
    SettingUtils.set(setting);
    cacheService.clear();
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:setting.jhtml";
}

From source file:de.codesourcery.geoip.locate.FreeGeoIPLocator.java

@Override
public synchronized GeoLocation<StringSubject> locate(StringSubject ipAddress) throws Exception {
    final long lastTime = lastRequestTime.get();
    if (lastTime != 0) {
        final long delta = System.currentTimeMillis() - lastTime;
        if (delta < 300) {
            try {
                Thread.sleep(THROTTLE_MILLIS);
            } catch (Exception e) {
            }/*from w  w w.  java 2s.c  o  m*/
            ;
        }
    }

    lastRequestTime.compareAndSet(lastTime, System.currentTimeMillis());

    final StringBuilder builder = new StringBuilder();
    System.out.println("Retrieving location data for " + ipAddress + " ...");

    final URL api = new URL("http://freegeoip.net/json/" + ipAddress);
    final URLConnection yc = api.openConnection();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()))) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            builder.append(inputLine);
        }
    }
    // {"ip":"213.191.64.208","country_code":"DE","country_name":"Germany","region_code":"","region_name":"","city":"","zipcode":"","latitude":51,"longitude":9,"metro_code":"","area_code":""}

    final Map<String, Object> params = parseJSON(builder.toString());
    System.out.println("GOT: " + params);

    String city = objToString(params.get("city"));
    String country = objToString(params.get("country_name"));
    double latitude = Double.parseDouble(params.get("latitude").toString());
    double longitude = Double.parseDouble(params.get("longitude").toString());

    if ("Reserved".equals(country)) {
        return new GeoLocation<StringSubject>(ipAddress);
    }
    return new GeoLocation<StringSubject>(ipAddress, latitude, longitude, true)
            .setParameter(GeoLocation.KEY_CITY, city).setParameter(GeoLocation.KEY_COUNTRY, country);
}

From source file:com.puppycrawl.tools.checkstyle.PackageNamesLoaderTest.java

@Test
@SuppressWarnings("unchecked")
public void testPackagesWithSaxException() throws Exception {

    final URLConnection mockConnection = Mockito.mock(URLConnection.class);
    when(mockConnection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_BYTE_ARRAY));

    URL url = getMockUrl(mockConnection);

    Enumeration<URL> enumeration = (Enumeration<URL>) mock(Enumeration.class);
    when(enumeration.hasMoreElements()).thenReturn(true);
    when(enumeration.nextElement()).thenReturn(url);

    ClassLoader classLoader = mock(ClassLoader.class);
    when(classLoader.getResources("checkstyle_packages.xml")).thenReturn(enumeration);

    try {// ww  w.  ja  v  a2  s  .c  o  m
        PackageNamesLoader.getPackageNames(classLoader);
        fail();
    } catch (CheckstyleException ex) {
        assertTrue(ex.getCause() instanceof SAXException);
    }
}

From source file:cz.pchmelar.ddw.homework1.MainServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w  . j  a v  a  2 s  .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Simpsons Episode Analyzer</title>");
        out.println(
                "<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\">");
        out.println(
                "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js\"></script>");
        out.println(
                "<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>");
        out.println("</head>");
        out.println("<body style=\"background-color: #A0D1F5\">");

        out.println("<div class=\"container\">");
        out.println("<br>");
        out.println("<br>");
        out.println(
                "<a href=\"/ddw-homework1/MainServlet\"><img src=\"http://www.returndates.com/backgrounds/simpsons.logo.png\" class=\"img-responsive center-block\" style=\"width: 50%; height: 50%\"></a>");
        out.println("<br>");
        out.println("<br>");

        //GET JSON of all simpsons episodes
        String urlString = "http://api.tvmaze.com/singlesearch/shows?q=simpsons&embed=episodes";
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        String JSON = IOUtils.toString(is, "UTF-8");

        //print season/episode/name for every episode in JSON
        JsonElement jelement = new JsonParser().parse(JSON);
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("_embedded");
        JsonArray jarray = jobject.getAsJsonArray("episodes");
        out.println("<table class=\"table table-bordered table-hover\" style=\"background-color: #FFFFFF\">");
        out.println("<thead><tr><th>Season</th><th>Episode</th><th>Name</th></tr></thead><tbody>");
        for (int i = 0; i < jarray.size(); i++) {

            jobject = jarray.get(i).getAsJsonObject();
            String season = jobject.get("season").toString();
            if (season.length() == 1)
                season = "0" + season;
            String episode = jobject.get("number").toString();
            if (episode.length() == 1)
                episode = "0" + episode;

            out.println("<tr>");
            out.println("<td>" + season + "</td>");
            out.println("<td>" + episode + "</td>");
            out.println("<td><a href=\"/ddw-homework1/DetailServlet?season=" + season + "&episode=" + episode
                    + "\">" + jobject.get("name").toString() + "</a></td>");
            out.println("</tr>");
        }
        out.println("</tbody></table>");
        out.println("</container>");

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:emily.command.fun.JokeCommand.java

private String getJokeFromWeb(String username) {
    try {//from w ww.  j av a  2  s .c om
        URL loginurl = new URL("http://api.icndb.com/jokes/random?firstName=&lastName=" + username);
        URLConnection yc = loginurl.openConnection();
        yc.setConnectTimeout(10 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine = in.readLine();
        JsonParser parser = new JsonParser();
        JsonObject array = parser.parse(inputLine).getAsJsonObject();
        return array.get("value").getAsJsonObject().get("joke").getAsString();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}